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(),
201 KStandardItemListWidget::~KStandardItemListWidget()
203 qDeleteAll(m_textInfo
);
209 void KStandardItemListWidget::setLayout(Layout layout
)
211 if (m_layout
!= layout
) {
213 m_dirtyLayout
= true;
214 updateAdditionalInfoTextColor();
219 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
224 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
226 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
227 m_supportsItemExpanding
= supportsItemExpanding
;
228 m_dirtyLayout
= true;
233 bool KStandardItemListWidget::supportsItemExpanding() const
235 return m_supportsItemExpanding
;
238 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
240 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
242 KItemListWidget::paint(painter
, option
, widget
);
244 if (!m_expansionArea
.isEmpty()) {
245 drawSiblingsInformation(painter
);
248 const KItemListStyleOption
& itemListStyleOption
= styleOption();
250 // Blend the unhovered and hovered pixmap if the hovering
251 // animation is ongoing
252 if (hoverOpacity() < 1.0) {
253 drawPixmap(painter
, m_pixmap
);
256 const qreal opacity
= painter
->opacity();
257 painter
->setOpacity(hoverOpacity() * opacity
);
258 drawPixmap(painter
, m_hoverPixmap
);
259 painter
->setOpacity(opacity
);
261 drawPixmap(painter
, m_pixmap
);
264 painter
->setFont(m_customizedFont
);
265 painter
->setPen(m_isHidden
? m_additionalInfoTextColor
: textColor());
266 const TextInfo
* textInfo
= m_textInfo
.value("text");
269 // It seems that we can end up here even if m_textInfo does not contain
270 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
271 // this can only happen if the index is negative. This can happen when
272 // the item is about to be removed, see KItemListView::slotItemsRemoved().
273 // TODO: try to reproduce the crash and find a better fix.
277 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
279 bool clipAdditionalInfoBounds
= false;
280 if (m_supportsItemExpanding
) {
281 // Prevent a possible overlapping of the additional-information texts
282 // with the icon. This can happen if the user has minimized the width
283 // of the name-column to a very small value.
284 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
285 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
286 clipAdditionalInfoBounds
= true;
288 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
292 painter
->setPen(m_additionalInfoTextColor
);
293 painter
->setFont(m_customizedFont
);
295 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
296 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
297 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
300 if (!m_rating
.isNull()) {
301 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
302 QPointF pos
= ratingTextInfo
->pos
;
303 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
304 if (align
& Qt::AlignHCenter
) {
305 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
307 painter
->drawPixmap(pos
, m_rating
);
310 if (clipAdditionalInfoBounds
) {
314 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
315 painter
->setBrush(Qt::NoBrush
);
316 painter
->setPen(Qt::green
);
317 painter
->drawRect(m_iconRect
);
319 painter
->setPen(Qt::red
);
320 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
321 painter
->drawRect(rect());
325 QRectF
KStandardItemListWidget::iconRect() const
327 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
331 QRectF
KStandardItemListWidget::textRect() const
333 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
337 QRectF
KStandardItemListWidget::textFocusRect() const
339 // In the compact- and details-layout a larger textRect() is returned to be aligned
340 // with the iconRect(). This is useful to have a larger selection/hover-area
341 // when having a quite large icon size but only one line of text. Still the
342 // focus rectangle should be shown as narrow as possible around the text.
344 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
347 case CompactLayout
: {
348 QRectF rect
= m_textRect
;
349 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
350 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
351 rect
.setTop(topText
->pos
.y());
352 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
356 case DetailsLayout
: {
357 QRectF rect
= m_textRect
;
358 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
359 rect
.setTop(textInfo
->pos
.y());
360 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
362 const KItemListStyleOption
& option
= styleOption();
363 if (option
.extendedSelectionRegion
) {
364 const QString text
= textInfo
->staticText
.text();
365 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
378 QRectF
KStandardItemListWidget::expansionToggleRect() const
380 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
381 return m_isExpandable
? m_expansionArea
: QRectF();
384 QRectF
KStandardItemListWidget::selectionToggleRect() const
386 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
388 const int iconHeight
= styleOption().iconSize
;
390 int toggleSize
= KIconLoader::SizeSmall
;
391 if (iconHeight
>= KIconLoader::SizeEnormous
) {
392 toggleSize
= KIconLoader::SizeMedium
;
393 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
394 toggleSize
= KIconLoader::SizeSmallMedium
;
397 QPointF pos
= iconRect().topLeft();
399 // If the selection toggle has a very small distance to the
400 // widget borders, the size of the selection toggle will get
401 // increased to prevent an accidental clicking of the item
402 // when trying to hit the toggle.
403 const int widgetHeight
= size().height();
404 const int widgetWidth
= size().width();
405 const int minMargin
= 2;
407 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
408 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
409 toggleSize
= widgetHeight
;
412 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
413 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
414 toggleSize
= widgetWidth
;
418 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
421 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
424 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
425 if (m_layout
!= DetailsLayout
) {
429 // Only return the content of the text-column as pixmap
430 const int leftClip
= m_pixmapPos
.x();
432 const TextInfo
* textInfo
= m_textInfo
.value("text");
433 const int rightClip
= textInfo
->pos
.x() +
434 textInfo
->staticText
.size().width() +
435 2 * styleOption().padding
;
437 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
438 clippedPixmap
.fill(Qt::transparent
);
440 QPainter
painter(&clippedPixmap
);
441 painter
.drawPixmap(-leftClip
, 0, pixmap
);
443 return clippedPixmap
;
447 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
449 return new KStandardItemListWidgetInformant();
452 void KStandardItemListWidget::invalidateCache()
454 m_dirtyLayout
= true;
455 m_dirtyContent
= true;
458 void KStandardItemListWidget::refreshCache()
462 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
468 bool KStandardItemListWidget::isHidden() const
473 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
478 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
480 return QPalette::Text
;
483 void KStandardItemListWidget::setTextColor(const QColor
& color
)
485 if (color
!= m_customTextColor
) {
486 m_customTextColor
= color
;
487 updateAdditionalInfoTextColor();
492 QColor
KStandardItemListWidget::textColor() const
494 if (m_customTextColor
.isValid() && !isSelected()) {
495 return m_customTextColor
;
498 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
499 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
500 return styleOption().palette
.color(group
, role
);
503 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
506 m_dirtyContent
= true;
510 QPixmap
KStandardItemListWidget::overlay() const
516 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
517 const QHash
<QByteArray
, QVariant
>& values
) const
519 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
522 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
523 const QSet
<QByteArray
>& roles
)
527 m_dirtyContent
= true;
529 QSet
<QByteArray
> dirtyRoles
;
530 if (roles
.isEmpty()) {
531 dirtyRoles
= visibleRoles().toSet();
536 // The icon-state might depend from other roles and hence is
537 // marked as dirty whenever a role has been changed
538 dirtyRoles
.insert("iconPixmap");
539 dirtyRoles
.insert("iconName");
541 QSetIterator
<QByteArray
> it(dirtyRoles
);
542 while (it
.hasNext()) {
543 const QByteArray
& role
= it
.next();
544 m_dirtyContentRoles
.insert(role
);
548 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
549 const QList
<QByteArray
>& previous
)
552 m_sortedVisibleRoles
= current
;
553 m_dirtyLayout
= true;
556 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
563 m_dirtyLayout
= true;
566 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
567 const KItemListStyleOption
& previous
)
571 updateAdditionalInfoTextColor();
572 m_dirtyLayout
= true;
575 void KStandardItemListWidget::hoveredChanged(bool hovered
)
578 m_dirtyLayout
= true;
581 void KStandardItemListWidget::selectedChanged(bool selected
)
584 updateAdditionalInfoTextColor();
585 m_dirtyContent
= true;
588 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
592 m_dirtyLayout
= true;
595 int KStandardItemListWidget::selectionLength(const QString
& text
) const
597 return text
.length();
600 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
604 QGraphicsView
* parent
= scene()->views()[0];
605 if (current
.isEmpty() || !parent
|| current
!= "text") {
607 emit
roleEditingCanceled(index(), current
, data().value(current
));
609 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
610 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
611 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
612 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
613 // Do not delete the role editor using deleteLater() because we might be
614 // inside a nested event loop which has been started by one of its event
615 // handlers (contextMenuEvent() or drag&drop inside mouseMoveEvent()).
616 m_roleEditor
->deleteWhenIdle();
622 Q_ASSERT(!m_roleEditor
);
624 const TextInfo
* textInfo
= m_textInfo
.value("text");
626 m_roleEditor
= new KItemListRoleEditor(parent
);
627 m_roleEditor
->setIndex(index());
628 m_roleEditor
->setRole(current
);
629 m_roleEditor
->setFont(styleOption().font
);
631 const QString text
= data().value(current
).toString();
632 m_roleEditor
->setPlainText(text
);
634 QTextOption textOption
= textInfo
->staticText
.textOption();
635 m_roleEditor
->document()->setDefaultTextOption(textOption
);
637 const int textSelectionLength
= selectionLength(text
);
639 if (textSelectionLength
> 0) {
640 QTextCursor cursor
= m_roleEditor
->textCursor();
641 cursor
.movePosition(QTextCursor::StartOfBlock
);
642 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
643 m_roleEditor
->setTextCursor(cursor
);
646 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
647 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
648 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
649 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
651 // Adjust the geometry of the editor
652 QRectF rect
= roleEditingRect(current
);
653 const int frameWidth
= m_roleEditor
->frameWidth();
654 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
655 rect
.translate(pos());
656 if (rect
.right() > parent
->width()) {
657 rect
.setWidth(parent
->width() - rect
.left());
659 m_roleEditor
->setGeometry(rect
.toRect());
660 m_roleEditor
->show();
661 m_roleEditor
->setFocus();
664 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
667 setEditedRole(QByteArray());
668 Q_ASSERT(!m_roleEditor
);
671 KItemListWidget::resizeEvent(event
);
673 m_dirtyLayout
= true;
676 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
678 KItemListWidget::showEvent(event
);
680 // Listen to changes of the clipboard to mark the item as cut/uncut
681 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
683 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
684 m_isCut
= clipboard
->isCut(itemUrl
);
686 connect(clipboard
, SIGNAL(cutItemsChanged()),
687 this, SLOT(slotCutItemsChanged()));
690 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
692 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
693 this, SLOT(slotCutItemsChanged()));
695 KItemListWidget::hideEvent(event
);
698 void KStandardItemListWidget::slotCutItemsChanged()
700 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
701 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
702 if (m_isCut
!= isCut
) {
704 m_pixmap
= QPixmap();
705 m_dirtyContent
= true;
710 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
711 const QByteArray
& role
,
712 const QVariant
& value
)
715 emit
roleEditingCanceled(index
, role
, value
);
716 setEditedRole(QByteArray());
719 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
720 const QByteArray
& role
,
721 const QVariant
& value
)
724 emit
roleEditingFinished(index
, role
, value
);
725 setEditedRole(QByteArray());
728 void KStandardItemListWidget::triggerCacheRefreshing()
730 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
736 const QHash
<QByteArray
, QVariant
> values
= data();
737 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
738 m_isHidden
= isHidden();
739 m_customizedFont
= customizedFont(styleOption().font
);
740 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
742 updateExpansionArea();
746 m_dirtyLayout
= false;
747 m_dirtyContent
= false;
748 m_dirtyContentRoles
.clear();
751 void KStandardItemListWidget::updateExpansionArea()
753 if (m_supportsItemExpanding
) {
754 const QHash
<QByteArray
, QVariant
> values
= data();
755 Q_ASSERT(values
.contains("expandedParentsCount"));
756 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
757 if (expandedParentsCount
>= 0) {
758 const qreal widgetHeight
= size().height();
759 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
760 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
762 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
767 m_expansionArea
= QRectF();
770 void KStandardItemListWidget::updatePixmapCache()
772 // Precondition: Requires already updated m_textPos values to calculate
773 // the remaining height when the alignment is vertical.
775 const QSizeF widgetSize
= size();
776 const bool iconOnTop
= (m_layout
== IconsLayout
);
777 const KItemListStyleOption
& option
= styleOption();
778 const qreal padding
= option
.padding
;
780 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
781 const int maxIconHeight
= option
.iconSize
;
783 const QHash
<QByteArray
, QVariant
> values
= data();
785 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
786 if (!updatePixmap
&& m_dirtyContent
) {
787 updatePixmap
= m_dirtyContentRoles
.isEmpty()
788 || m_dirtyContentRoles
.contains("iconPixmap")
789 || m_dirtyContentRoles
.contains("iconName")
790 || m_dirtyContentRoles
.contains("iconOverlays");
794 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
795 if (m_pixmap
.isNull()) {
796 // Use the icon that fits to the MIME-type
797 QString iconName
= values
["iconName"].toString();
798 if (iconName
.isEmpty()) {
799 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
800 // use a generic icon as fallback
801 iconName
= QLatin1String("unknown");
803 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
804 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
805 // A custom pixmap has been applied. Assure that the pixmap
806 // is scaled to the maximum available size.
807 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
810 const QStringList overlays
= values
["iconOverlays"].toStringList();
812 // Strangely KFileItem::overlays() returns empty string-values, so
813 // we need to check first whether an overlay must be drawn at all.
814 // It is more efficient to do it here, as KIconLoader::drawOverlays()
815 // assumes that an overlay will be drawn and has some additional
817 foreach (const QString
& overlay
, overlays
) {
818 if (!overlay
.isEmpty()) {
819 // There is at least one overlay, draw all overlays above m_pixmap
820 // and cancel the check
821 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
827 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
828 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
832 KIconEffect::semiTransparent(m_pixmap
);
836 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
837 QImage image
= m_pixmap
.toImage();
838 KIconEffect::colorize(image
, color
, 1.0f
);
839 m_pixmap
= QPixmap::fromImage(image
);
843 if (!m_overlay
.isNull()) {
844 QPainter
painter(&m_pixmap
);
845 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
848 int scaledIconSize
= 0;
850 const TextInfo
* textInfo
= m_textInfo
.value("text");
851 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
853 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
854 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
855 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
856 widgetSize
.height() - 2 * padding
: maxIconHeight
;
859 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
860 const int maxScaledIconHeight
= scaledIconSize
;
862 m_scaledPixmapSize
= m_pixmap
.size();
863 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
866 // Center horizontally and align on bottom within the icon-area
867 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
868 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
870 // Center horizontally and vertically within the icon-area
871 const TextInfo
* textInfo
= m_textInfo
.value("text");
872 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
873 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
874 m_pixmapPos
.setY(padding
875 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
878 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
880 // Prepare the pixmap that is used when the item gets hovered
882 m_hoverPixmap
= m_pixmap
;
883 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
884 // In the KIconLoader terminology, active = hover.
885 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
886 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
888 m_hoverPixmap
= m_pixmap
;
890 } else if (hoverOpacity() <= 0.0) {
891 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
892 m_hoverPixmap
= QPixmap();
896 void KStandardItemListWidget::updateTextsCache()
898 QTextOption textOption
;
901 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
902 textOption
.setAlignment(Qt::AlignHCenter
);
906 textOption
.setAlignment(Qt::AlignLeft
);
907 textOption
.setWrapMode(QTextOption::NoWrap
);
914 qDeleteAll(m_textInfo
);
916 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
917 TextInfo
* textInfo
= new TextInfo();
918 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
919 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
920 textInfo
->staticText
.setTextOption(textOption
);
921 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
925 case IconsLayout
: updateIconsLayoutTextCache(); break;
926 case CompactLayout
: updateCompactLayoutTextCache(); break;
927 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
928 default: Q_ASSERT(false); break;
931 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
932 if (ratingTextInfo
) {
933 // The text of the rating-role has been set to empty to get
934 // replaced by a rating-image showing the rating as stars.
935 const KItemListStyleOption
& option
= styleOption();
936 QSizeF ratingSize
= preferredRatingSize(option
);
938 const qreal availableWidth
= (m_layout
== DetailsLayout
)
939 ? columnWidth("rating") - columnPadding(option
)
941 if (ratingSize
.width() > availableWidth
) {
942 ratingSize
.rwidth() = availableWidth
;
944 m_rating
= QPixmap(ratingSize
.toSize());
945 m_rating
.fill(Qt::transparent
);
947 QPainter
painter(&m_rating
);
948 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
949 const int rating
= data().value("rating").toInt();
950 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
951 } else if (!m_rating
.isNull()) {
952 m_rating
= QPixmap();
956 void KStandardItemListWidget::updateIconsLayoutTextCache()
963 // might get wrapped above
968 const QHash
<QByteArray
, QVariant
> values
= data();
970 const KItemListStyleOption
& option
= styleOption();
971 const qreal padding
= option
.padding
;
972 const qreal maxWidth
= size().width() - 2 * padding
;
973 const qreal widgetHeight
= size().height();
974 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
976 // Initialize properties for the "text" role. It will be used as anchor
977 // for initializing the position of the other roles.
978 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
979 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
980 nameTextInfo
->staticText
.setText(nameText
);
982 // Calculate the number of lines required for the name and the required width
984 qreal nameHeight
= 0;
987 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
988 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
990 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
991 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
992 layout
.beginLayout();
993 int nameLineIndex
= 0;
994 while ((line
= layout
.createLine()).isValid()) {
995 line
.setLineWidth(maxWidth
);
996 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
997 nameHeight
+= line
.height();
1000 if (nameLineIndex
== maxNameLines
) {
1001 // The maximum number of textlines has been reached. If this is
1002 // the case provide an elided text if necessary.
1003 const int textLength
= line
.textStart() + line
.textLength();
1004 if (textLength
< nameText
.length()) {
1005 // Elide the last line of the text
1006 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1007 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1009 line
.naturalTextWidth() - 1);
1010 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1011 nameTextInfo
->staticText
.setText(elidedText
);
1018 // Use one line for each additional information
1019 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1020 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1022 additionalRolesCount
* lineSpacing
-
1024 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1025 nameTextInfo
->pos
.y(),
1029 // Calculate the position for each additional information
1030 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1031 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1032 if (role
== "text") {
1036 const QString text
= roleText(role
, values
);
1037 TextInfo
* textInfo
= m_textInfo
.value(role
);
1038 textInfo
->staticText
.setText(text
);
1040 qreal requiredWidth
= 0;
1042 QTextLayout
layout(text
, m_customizedFont
);
1043 QTextOption textOption
;
1044 textOption
.setWrapMode(QTextOption::NoWrap
);
1045 layout
.setTextOption(textOption
);
1047 layout
.beginLayout();
1048 QTextLine textLine
= layout
.createLine();
1049 if (textLine
.isValid()) {
1050 textLine
.setLineWidth(maxWidth
);
1051 requiredWidth
= textLine
.naturalTextWidth();
1052 if (requiredWidth
> maxWidth
) {
1053 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1054 textInfo
->staticText
.setText(elidedText
);
1055 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1056 } else if (role
== "rating") {
1057 // Use the width of the rating pixmap, because the rating text is empty.
1058 requiredWidth
= m_rating
.width();
1063 textInfo
->pos
= QPointF(padding
, y
);
1064 textInfo
->staticText
.setTextWidth(maxWidth
);
1066 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1067 m_textRect
|= textRect
;
1072 // Add a padding to the text rectangle
1073 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1076 void KStandardItemListWidget::updateCompactLayoutTextCache()
1078 // +------+ Name role
1079 // | Icon | Additional role 1
1080 // +------+ Additional role 2
1082 const QHash
<QByteArray
, QVariant
> values
= data();
1084 const KItemListStyleOption
& option
= styleOption();
1085 const qreal widgetHeight
= size().height();
1086 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1087 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1088 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1090 qreal maximumRequiredTextWidth
= 0;
1091 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1092 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1093 const qreal maxWidth
= size().width() - x
- option
.padding
;
1094 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1095 const QString text
= roleText(role
, values
);
1096 TextInfo
* textInfo
= m_textInfo
.value(role
);
1097 textInfo
->staticText
.setText(text
);
1099 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1100 if (requiredWidth
> maxWidth
) {
1101 requiredWidth
= maxWidth
;
1102 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1103 textInfo
->staticText
.setText(elidedText
);
1106 textInfo
->pos
= QPointF(x
, y
);
1107 textInfo
->staticText
.setTextWidth(maxWidth
);
1109 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1114 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1117 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1119 // Precondition: Requires already updated m_expansionArea
1120 // to determine the left position.
1123 // | Icon | Name role Additional role 1 Additional role 2
1125 m_textRect
= QRectF();
1127 const KItemListStyleOption
& option
= styleOption();
1128 const QHash
<QByteArray
, QVariant
> values
= data();
1130 const qreal widgetHeight
= size().height();
1131 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1132 const int fontHeight
= m_customizedFontMetrics
.height();
1134 const qreal columnWidthInc
= columnPadding(option
);
1135 qreal firstColumnInc
= scaledIconSize
;
1136 if (m_supportsItemExpanding
) {
1137 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1139 firstColumnInc
+= option
.padding
;
1142 qreal x
= firstColumnInc
;
1143 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1145 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1146 QString text
= roleText(role
, values
);
1148 // Elide the text in case it does not fit into the available column-width
1149 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1150 const qreal roleWidth
= columnWidth(role
);
1151 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1153 const bool isTextRole
= (role
== "text");
1155 availableTextWidth
-= firstColumnInc
;
1158 if (requiredWidth
> availableTextWidth
) {
1159 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1160 requiredWidth
= m_customizedFontMetrics
.width(text
);
1163 TextInfo
* textInfo
= m_textInfo
.value(role
);
1164 textInfo
->staticText
.setText(text
);
1165 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1169 const qreal textWidth
= option
.extendedSelectionRegion
1170 ? size().width() - textInfo
->pos
.x()
1171 : requiredWidth
+ 2 * option
.padding
;
1172 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1173 textWidth
, size().height());
1175 // The column after the name should always be aligned on the same x-position independent
1176 // from the expansion-level shown in the name column
1177 x
-= firstColumnInc
;
1178 } else if (isRoleRightAligned(role
)) {
1179 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1184 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1187 if (m_customTextColor
.isValid()) {
1188 c1
= m_customTextColor
;
1189 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1190 c1
= styleOption().palette
.highlightedText().color();
1192 c1
= styleOption().palette
.text().color();
1195 // For the color of the additional info the inactive text color
1196 // is not used as this might lead to unreadable text for some color schemes. Instead
1197 // the text color c1 is slightly mixed with the background color.
1198 const QColor c2
= styleOption().palette
.base().color();
1200 const int p2
= 100 - p1
;
1201 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1202 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1203 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1206 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1208 if (m_scaledPixmapSize
!= pixmap
.size()) {
1209 QPixmap scaledPixmap
= pixmap
;
1210 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1211 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1213 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1214 painter
->setPen(Qt::blue
);
1215 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1218 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1222 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1224 const int siblingSize
= size().height();
1225 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1226 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1228 QStyleOption option
;
1229 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1230 bool isItemSibling
= true;
1232 const QBitArray siblings
= siblingsInformation();
1233 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1234 option
.rect
= siblingRect
;
1235 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1237 if (isItemSibling
) {
1238 option
.state
|= QStyle::State_Item
;
1239 if (m_isExpandable
) {
1240 option
.state
|= QStyle::State_Children
;
1242 if (data()["isExpanded"].toBool()) {
1243 option
.state
|= QStyle::State_Open
;
1245 isItemSibling
= false;
1248 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1250 siblingRect
.translate(-siblingRect
.width(), 0);
1254 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1256 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1261 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1262 if (m_layout
== DetailsLayout
) {
1263 rect
.setWidth(columnWidth(role
) - rect
.x());
1269 void KStandardItemListWidget::closeRoleEditor()
1271 if (m_roleEditor
->hasFocus()) {
1272 // If the editing was not ended by a FocusOut event, we have
1273 // to transfer the keyboard focus back to the KItemListContainer.
1274 scene()->views()[0]->parentWidget()->setFocus();
1277 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
1278 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
1279 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
1280 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
1282 // Do not delete the role editor using deleteLater() because we might be
1283 // inside a nested event loop which has been started by one of its event
1284 // handlers (contextMenuEvent() or drag&drop inside mouseMoveEvent()).
1285 m_roleEditor
->deleteWhenIdle();
1289 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1291 const QString key
= "KStandardItemListWidget:" % name
% ":" % QString::number(size
);
1294 if (!QPixmapCache::find(key
, pixmap
)) {
1295 const KIcon
icon(name
);
1298 if (size
<= KIconLoader::SizeSmall
) {
1299 requestedSize
= KIconLoader::SizeSmall
;
1300 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1301 requestedSize
= KIconLoader::SizeSmallMedium
;
1302 } else if (size
<= KIconLoader::SizeMedium
) {
1303 requestedSize
= KIconLoader::SizeMedium
;
1304 } else if (size
<= KIconLoader::SizeLarge
) {
1305 requestedSize
= KIconLoader::SizeLarge
;
1306 } else if (size
<= KIconLoader::SizeHuge
) {
1307 requestedSize
= KIconLoader::SizeHuge
;
1308 } else if (size
<= KIconLoader::SizeEnormous
) {
1309 requestedSize
= KIconLoader::SizeEnormous
;
1310 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1311 requestedSize
= KIconLoader::SizeEnormous
* 2;
1313 requestedSize
= size
;
1316 pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1317 if (requestedSize
!= size
) {
1318 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1321 QPixmapCache::insert(key
, pixmap
);
1327 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1329 const qreal height
= option
.fontMetrics
.ascent();
1330 return QSizeF(height
* 5, height
);
1333 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1335 return option
.padding
* 6;
1338 #include "kstandarditemlistwidget.moc"