1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kstandarditemlistwidget.h"
22 #include "kfileitemlistview.h"
23 #include "kfileitemmodel.h"
26 #include <KIconEffect>
27 #include <KIconLoader>
29 #include <kratingpainter.h>
30 #include <KStringHandler>
33 #include "private/kfileitemclipboard.h"
34 #include "private/kitemlistroleeditor.h"
35 #include "private/kpixmapmodifier.h"
37 #include <QFontMetricsF>
38 #include <QGraphicsScene>
39 #include <QGraphicsSceneResizeEvent>
40 #include <QGraphicsView>
42 #include <QStyleOption>
43 #include <QTextLayout>
46 // #define KSTANDARDITEMLISTWIDGET_DEBUG
48 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
49 KItemListWidgetInformant()
53 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
57 QSizeF
KStandardItemListWidgetInformant::itemSizeHint(int index
, const KItemListView
* view
) const
59 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
60 const KItemListStyleOption
& option
= view
->styleOption();
61 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
63 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
64 case KStandardItemListWidget::IconsLayout
: {
65 const QString text
= KStringHandler::preProcessWrap(values
["text"].toString());
67 const qreal itemWidth
= view
->itemSize().width();
68 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
71 // Calculate the number of lines required for wrapping the name
72 QTextOption
textOption(Qt::AlignHCenter
);
73 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
76 QTextLayout
layout(text
, option
.font
);
77 layout
.setTextOption(textOption
);
79 while ((line
= layout
.createLine()).isValid()) {
80 line
.setLineWidth(maxWidth
);
81 line
.naturalTextWidth();
82 textHeight
+= line
.height();
86 // Add one line for each additional information
87 textHeight
+= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
89 const qreal maxTextHeight
= option
.maxTextSize
.height();
90 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
91 textHeight
= maxTextHeight
;
94 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
97 case KStandardItemListWidget::CompactLayout
: {
98 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
99 // to show all roles without horizontal clipping.
100 qreal maximumRequiredWidth
= 0.0;
102 foreach (const QByteArray
& role
, view
->visibleRoles()) {
103 const QString text
= roleText(role
, values
);
104 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
105 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
108 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
109 const qreal maxWidth
= option
.maxTextSize
.width();
110 if (maxWidth
> 0 && width
> maxWidth
) {
113 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
114 return QSizeF(width
, height
);
117 case KStandardItemListWidget::DetailsLayout
: {
118 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
119 return QSizeF(-1, height
);
130 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
132 const KItemListView
* view
) const
134 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
135 const KItemListStyleOption
& option
= view
->styleOption();
137 const QString text
= roleText(role
, values
);
138 qreal width
= KStandardItemListWidget::columnPadding(option
);
140 if (role
== "rating") {
141 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
143 width
+= option
.fontMetrics
.width(text
);
145 if (role
== "text") {
146 if (view
->supportsItemExpanding()) {
147 // Increase the width by the expansion-toggle and the current expansion level
148 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
149 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
150 width
+= (expandedParentsCount
+ 1) * height
;
153 // Increase the width by the required space for the icon
154 width
+= option
.padding
* 2 + option
.iconSize
;
161 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
162 const QHash
<QByteArray
, QVariant
>& values
) const
164 if (role
== "rating") {
165 // Always use an empty text, as the rating is shown by the image m_rating.
168 return values
.value(role
).toString();
171 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
172 KItemListWidget(informant
, parent
),
176 m_customizedFontMetrics(m_customizedFont
),
177 m_isExpandable(false),
178 m_supportsItemExpanding(false),
180 m_dirtyContent(true),
181 m_dirtyContentRoles(),
182 m_layout(IconsLayout
),
185 m_scaledPixmapSize(),
190 m_sortedVisibleRoles(),
193 m_additionalInfoTextColor(),
200 KStandardItemListWidget::~KStandardItemListWidget()
202 qDeleteAll(m_textInfo
);
208 void KStandardItemListWidget::setLayout(Layout layout
)
210 if (m_layout
!= layout
) {
212 m_dirtyLayout
= true;
213 updateAdditionalInfoTextColor();
218 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
223 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
225 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
226 m_supportsItemExpanding
= supportsItemExpanding
;
227 m_dirtyLayout
= true;
232 bool KStandardItemListWidget::supportsItemExpanding() const
234 return m_supportsItemExpanding
;
237 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
239 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
241 KItemListWidget::paint(painter
, option
, widget
);
243 if (!m_expansionArea
.isEmpty()) {
244 drawSiblingsInformation(painter
);
247 const KItemListStyleOption
& itemListStyleOption
= styleOption();
249 // Blend the unhovered and hovered pixmap if the hovering
250 // animation is ongoing
251 if (hoverOpacity() < 1.0) {
252 drawPixmap(painter
, m_pixmap
);
255 const qreal opacity
= painter
->opacity();
256 painter
->setOpacity(hoverOpacity() * opacity
);
257 drawPixmap(painter
, m_hoverPixmap
);
258 painter
->setOpacity(opacity
);
260 drawPixmap(painter
, m_pixmap
);
263 painter
->setFont(m_customizedFont
);
264 painter
->setPen(m_isHidden
? m_additionalInfoTextColor
: textColor());
265 const TextInfo
* textInfo
= m_textInfo
.value("text");
268 // It seems that we can end up here even if m_textInfo does not contain
269 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
270 // this can only happen if the index is negative. This can happen when
271 // the item is about to be removed, see KItemListView::slotItemsRemoved().
272 // TODO: try to reproduce the crash and find a better fix.
276 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
278 bool clipAdditionalInfoBounds
= false;
279 if (m_supportsItemExpanding
) {
280 // Prevent a possible overlapping of the additional-information texts
281 // with the icon. This can happen if the user has minimized the width
282 // of the name-column to a very small value.
283 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
284 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
285 clipAdditionalInfoBounds
= true;
287 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
291 painter
->setPen(m_additionalInfoTextColor
);
292 painter
->setFont(m_customizedFont
);
294 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
295 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
296 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
299 if (!m_rating
.isNull()) {
300 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
301 QPointF pos
= ratingTextInfo
->pos
;
302 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
303 if (align
& Qt::AlignHCenter
) {
304 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
306 painter
->drawPixmap(pos
, m_rating
);
309 if (clipAdditionalInfoBounds
) {
313 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
314 painter
->setBrush(Qt::NoBrush
);
315 painter
->setPen(Qt::green
);
316 painter
->drawRect(m_iconRect
);
318 painter
->setPen(Qt::red
);
319 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
320 painter
->drawRect(rect());
324 QRectF
KStandardItemListWidget::iconRect() const
326 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
330 QRectF
KStandardItemListWidget::textRect() const
332 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
336 QRectF
KStandardItemListWidget::textFocusRect() const
338 // In the compact- and details-layout a larger textRect() is returned to be aligned
339 // with the iconRect(). This is useful to have a larger selection/hover-area
340 // when having a quite large icon size but only one line of text. Still the
341 // focus rectangle should be shown as narrow as possible around the text.
343 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
346 case CompactLayout
: {
347 QRectF rect
= m_textRect
;
348 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
349 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
350 rect
.setTop(topText
->pos
.y());
351 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
355 case DetailsLayout
: {
356 QRectF rect
= m_textRect
;
357 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
358 rect
.setTop(textInfo
->pos
.y());
359 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
361 const KItemListStyleOption
& option
= styleOption();
362 if (option
.extendedSelectionRegion
) {
363 const QString text
= textInfo
->staticText
.text();
364 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
377 QRectF
KStandardItemListWidget::expansionToggleRect() const
379 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
380 return m_isExpandable
? m_expansionArea
: QRectF();
383 QRectF
KStandardItemListWidget::selectionToggleRect() const
385 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
387 const int iconHeight
= styleOption().iconSize
;
389 int toggleSize
= KIconLoader::SizeSmall
;
390 if (iconHeight
>= KIconLoader::SizeEnormous
) {
391 toggleSize
= KIconLoader::SizeMedium
;
392 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
393 toggleSize
= KIconLoader::SizeSmallMedium
;
396 QPointF pos
= iconRect().topLeft();
398 // If the selection toggle has a very small distance to the
399 // widget borders, the size of the selection toggle will get
400 // increased to prevent an accidental clicking of the item
401 // when trying to hit the toggle.
402 const int widgetHeight
= size().height();
403 const int widgetWidth
= size().width();
404 const int minMargin
= 2;
406 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
407 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
408 toggleSize
= widgetHeight
;
411 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
412 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
413 toggleSize
= widgetWidth
;
417 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
420 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
423 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
424 if (m_layout
!= DetailsLayout
) {
428 // Only return the content of the text-column as pixmap
429 const int leftClip
= m_pixmapPos
.x();
431 const TextInfo
* textInfo
= m_textInfo
.value("text");
432 const int rightClip
= textInfo
->pos
.x() +
433 textInfo
->staticText
.size().width() +
434 2 * styleOption().padding
;
436 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
437 clippedPixmap
.fill(Qt::transparent
);
439 QPainter
painter(&clippedPixmap
);
440 painter
.drawPixmap(-leftClip
, 0, pixmap
);
442 return clippedPixmap
;
446 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
448 return new KStandardItemListWidgetInformant();
451 void KStandardItemListWidget::invalidateCache()
453 m_dirtyLayout
= true;
454 m_dirtyContent
= true;
457 void KStandardItemListWidget::refreshCache()
461 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
467 bool KStandardItemListWidget::isHidden() const
472 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
477 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
479 return QPalette::Text
;
482 void KStandardItemListWidget::setTextColor(const QColor
& color
)
484 if (color
!= m_customTextColor
) {
485 m_customTextColor
= color
;
486 updateAdditionalInfoTextColor();
491 QColor
KStandardItemListWidget::textColor() const
493 if (m_customTextColor
.isValid() && !isSelected()) {
494 return m_customTextColor
;
497 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
498 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
499 return styleOption().palette
.color(group
, role
);
502 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
505 m_dirtyContent
= true;
509 QPixmap
KStandardItemListWidget::overlay() const
515 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
516 const QHash
<QByteArray
, QVariant
>& values
) const
518 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
521 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
522 const QSet
<QByteArray
>& roles
)
526 m_dirtyContent
= true;
528 QSet
<QByteArray
> dirtyRoles
;
529 if (roles
.isEmpty()) {
530 dirtyRoles
= visibleRoles().toSet();
535 // The icon-state might depend from other roles and hence is
536 // marked as dirty whenever a role has been changed
537 dirtyRoles
.insert("iconPixmap");
538 dirtyRoles
.insert("iconName");
540 QSetIterator
<QByteArray
> it(dirtyRoles
);
541 while (it
.hasNext()) {
542 const QByteArray
& role
= it
.next();
543 m_dirtyContentRoles
.insert(role
);
547 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
548 const QList
<QByteArray
>& previous
)
551 m_sortedVisibleRoles
= current
;
552 m_dirtyLayout
= true;
555 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
562 m_dirtyLayout
= true;
565 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
566 const KItemListStyleOption
& previous
)
570 updateAdditionalInfoTextColor();
571 m_dirtyLayout
= true;
574 void KStandardItemListWidget::hoveredChanged(bool hovered
)
577 m_dirtyLayout
= true;
580 void KStandardItemListWidget::selectedChanged(bool selected
)
583 updateAdditionalInfoTextColor();
584 m_dirtyContent
= true;
587 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
591 m_dirtyLayout
= true;
594 int KStandardItemListWidget::selectionLength(const QString
& text
) const
596 return text
.length();
599 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
603 QGraphicsView
* parent
= scene()->views()[0];
604 if (current
.isEmpty() || !parent
|| current
!= "text") {
606 emit
roleEditingCanceled(index(), current
, data().value(current
));
608 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
609 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
610 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
611 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
612 m_roleEditor
->deleteLater();
618 Q_ASSERT(!m_roleEditor
);
620 const TextInfo
* textInfo
= m_textInfo
.value("text");
622 m_roleEditor
= new KItemListRoleEditor(parent
);
623 m_roleEditor
->setIndex(index());
624 m_roleEditor
->setRole(current
);
625 m_roleEditor
->setFont(styleOption().font
);
627 const QString text
= data().value(current
).toString();
628 m_roleEditor
->setPlainText(text
);
630 QTextOption textOption
= textInfo
->staticText
.textOption();
631 m_roleEditor
->document()->setDefaultTextOption(textOption
);
633 const int textSelectionLength
= selectionLength(text
);
635 if (textSelectionLength
> 0) {
636 QTextCursor cursor
= m_roleEditor
->textCursor();
637 cursor
.movePosition(QTextCursor::StartOfBlock
);
638 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
639 m_roleEditor
->setTextCursor(cursor
);
642 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
643 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
644 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
645 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
647 // Adjust the geometry of the editor
648 QRectF rect
= roleEditingRect(current
);
649 const int frameWidth
= m_roleEditor
->frameWidth();
650 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
651 rect
.translate(pos());
652 if (rect
.right() > parent
->width()) {
653 rect
.setWidth(parent
->width() - rect
.left());
655 m_roleEditor
->setGeometry(rect
.toRect());
656 m_roleEditor
->show();
657 m_roleEditor
->setFocus();
660 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
663 setEditedRole(QByteArray());
664 Q_ASSERT(!m_roleEditor
);
667 KItemListWidget::resizeEvent(event
);
669 m_dirtyLayout
= true;
672 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
674 KItemListWidget::showEvent(event
);
676 // Listen to changes of the clipboard to mark the item as cut/uncut
677 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
679 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
680 m_isCut
= clipboard
->isCut(itemUrl
);
682 connect(clipboard
, SIGNAL(cutItemsChanged()),
683 this, SLOT(slotCutItemsChanged()));
686 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
688 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
689 this, SLOT(slotCutItemsChanged()));
691 KItemListWidget::hideEvent(event
);
694 void KStandardItemListWidget::slotCutItemsChanged()
696 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
697 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
698 if (m_isCut
!= isCut
) {
700 m_pixmap
= QPixmap();
701 m_dirtyContent
= true;
706 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
707 const QByteArray
& role
,
708 const QVariant
& value
)
711 emit
roleEditingCanceled(index
, role
, value
);
712 setEditedRole(QByteArray());
715 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
716 const QByteArray
& role
,
717 const QVariant
& value
)
720 emit
roleEditingFinished(index
, role
, value
);
721 setEditedRole(QByteArray());
724 void KStandardItemListWidget::triggerCacheRefreshing()
726 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
732 const QHash
<QByteArray
, QVariant
> values
= data();
733 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
734 m_isHidden
= isHidden();
735 m_customizedFont
= customizedFont(styleOption().font
);
736 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
738 updateExpansionArea();
742 m_dirtyLayout
= false;
743 m_dirtyContent
= false;
744 m_dirtyContentRoles
.clear();
747 void KStandardItemListWidget::updateExpansionArea()
749 if (m_supportsItemExpanding
) {
750 const QHash
<QByteArray
, QVariant
> values
= data();
751 Q_ASSERT(values
.contains("expandedParentsCount"));
752 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
753 if (expandedParentsCount
>= 0) {
754 const qreal widgetHeight
= size().height();
755 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
756 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
758 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
763 m_expansionArea
= QRectF();
766 void KStandardItemListWidget::updatePixmapCache()
768 // Precondition: Requires already updated m_textPos values to calculate
769 // the remaining height when the alignment is vertical.
771 const QSizeF widgetSize
= size();
772 const bool iconOnTop
= (m_layout
== IconsLayout
);
773 const KItemListStyleOption
& option
= styleOption();
774 const qreal padding
= option
.padding
;
776 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
777 const int maxIconHeight
= option
.iconSize
;
779 const QHash
<QByteArray
, QVariant
> values
= data();
781 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
782 if (!updatePixmap
&& m_dirtyContent
) {
783 updatePixmap
= m_dirtyContentRoles
.isEmpty()
784 || m_dirtyContentRoles
.contains("iconPixmap")
785 || m_dirtyContentRoles
.contains("iconName")
786 || m_dirtyContentRoles
.contains("iconOverlays");
790 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
791 if (m_pixmap
.isNull()) {
792 // Use the icon that fits to the MIME-type
793 QString iconName
= values
["iconName"].toString();
794 if (iconName
.isEmpty()) {
795 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
796 // use a generic icon as fallback
797 iconName
= QLatin1String("unknown");
799 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
800 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
801 // A custom pixmap has been applied. Assure that the pixmap
802 // is scaled to the maximum available size.
803 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
806 const QStringList overlays
= values
["iconOverlays"].toStringList();
808 // Strangely KFileItem::overlays() returns empty string-values, so
809 // we need to check first whether an overlay must be drawn at all.
810 // It is more efficient to do it here, as KIconLoader::drawOverlays()
811 // assumes that an overlay will be drawn and has some additional
813 foreach (const QString
& overlay
, overlays
) {
814 if (!overlay
.isEmpty()) {
815 // There is at least one overlay, draw all overlays above m_pixmap
816 // and cancel the check
817 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
823 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
824 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
828 KIconEffect::semiTransparent(m_pixmap
);
832 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
833 QImage image
= m_pixmap
.toImage();
834 KIconEffect::colorize(image
, color
, 1.0f
);
835 m_pixmap
= QPixmap::fromImage(image
);
839 if (!m_overlay
.isNull()) {
840 QPainter
painter(&m_pixmap
);
841 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
844 int scaledIconSize
= 0;
846 const TextInfo
* textInfo
= m_textInfo
.value("text");
847 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
849 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
850 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
851 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
852 widgetSize
.height() - 2 * padding
: maxIconHeight
;
855 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
856 const int maxScaledIconHeight
= scaledIconSize
;
858 m_scaledPixmapSize
= m_pixmap
.size();
859 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
862 // Center horizontally and align on bottom within the icon-area
863 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
864 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
866 // Center horizontally and vertically within the icon-area
867 const TextInfo
* textInfo
= m_textInfo
.value("text");
868 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
869 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
870 m_pixmapPos
.setY(padding
871 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
874 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
876 // Prepare the pixmap that is used when the item gets hovered
878 m_hoverPixmap
= m_pixmap
;
879 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
880 // In the KIconLoader terminology, active = hover.
881 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
882 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
884 m_hoverPixmap
= m_pixmap
;
886 } else if (hoverOpacity() <= 0.0) {
887 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
888 m_hoverPixmap
= QPixmap();
892 void KStandardItemListWidget::updateTextsCache()
894 QTextOption textOption
;
897 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
898 textOption
.setAlignment(Qt::AlignHCenter
);
902 textOption
.setAlignment(Qt::AlignLeft
);
903 textOption
.setWrapMode(QTextOption::NoWrap
);
910 qDeleteAll(m_textInfo
);
912 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
913 TextInfo
* textInfo
= new TextInfo();
914 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
915 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
916 textInfo
->staticText
.setTextOption(textOption
);
917 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
921 case IconsLayout
: updateIconsLayoutTextCache(); break;
922 case CompactLayout
: updateCompactLayoutTextCache(); break;
923 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
924 default: Q_ASSERT(false); break;
927 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
928 if (ratingTextInfo
) {
929 // The text of the rating-role has been set to empty to get
930 // replaced by a rating-image showing the rating as stars.
931 const KItemListStyleOption
& option
= styleOption();
932 QSizeF ratingSize
= preferredRatingSize(option
);
934 const qreal availableWidth
= (m_layout
== DetailsLayout
)
935 ? columnWidth("rating") - columnPadding(option
)
937 if (ratingSize
.width() > availableWidth
) {
938 ratingSize
.rwidth() = availableWidth
;
940 m_rating
= QPixmap(ratingSize
.toSize());
941 m_rating
.fill(Qt::transparent
);
943 QPainter
painter(&m_rating
);
944 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
945 const int rating
= data().value("rating").toInt();
946 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
947 } else if (!m_rating
.isNull()) {
948 m_rating
= QPixmap();
952 void KStandardItemListWidget::updateIconsLayoutTextCache()
959 // might get wrapped above
964 const QHash
<QByteArray
, QVariant
> values
= data();
966 const KItemListStyleOption
& option
= styleOption();
967 const qreal padding
= option
.padding
;
968 const qreal maxWidth
= size().width() - 2 * padding
;
969 const qreal widgetHeight
= size().height();
970 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
972 // Initialize properties for the "text" role. It will be used as anchor
973 // for initializing the position of the other roles.
974 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
975 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
976 nameTextInfo
->staticText
.setText(nameText
);
978 // Calculate the number of lines required for the name and the required width
980 qreal nameHeight
= 0;
983 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
984 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
986 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
987 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
988 layout
.beginLayout();
989 int nameLineIndex
= 0;
990 while ((line
= layout
.createLine()).isValid()) {
991 line
.setLineWidth(maxWidth
);
992 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
993 nameHeight
+= line
.height();
996 if (nameLineIndex
== maxNameLines
) {
997 // The maximum number of textlines has been reached. If this is
998 // the case provide an elided text if necessary.
999 const int textLength
= line
.textStart() + line
.textLength();
1000 if (textLength
< nameText
.length()) {
1001 // Elide the last line of the text
1002 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1003 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1005 line
.naturalTextWidth() - 1);
1006 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1007 nameTextInfo
->staticText
.setText(elidedText
);
1014 // Use one line for each additional information
1015 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1016 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1018 additionalRolesCount
* lineSpacing
-
1020 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1021 nameTextInfo
->pos
.y(),
1025 // Calculate the position for each additional information
1026 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1027 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1028 if (role
== "text") {
1032 const QString text
= roleText(role
, values
);
1033 TextInfo
* textInfo
= m_textInfo
.value(role
);
1034 textInfo
->staticText
.setText(text
);
1036 qreal requiredWidth
= 0;
1038 QTextLayout
layout(text
, m_customizedFont
);
1039 QTextOption textOption
;
1040 textOption
.setWrapMode(QTextOption::NoWrap
);
1041 layout
.setTextOption(textOption
);
1043 layout
.beginLayout();
1044 QTextLine textLine
= layout
.createLine();
1045 if (textLine
.isValid()) {
1046 textLine
.setLineWidth(maxWidth
);
1047 requiredWidth
= textLine
.naturalTextWidth();
1048 if (requiredWidth
> maxWidth
) {
1049 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1050 textInfo
->staticText
.setText(elidedText
);
1051 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1052 } else if (role
== "rating") {
1053 // Use the width of the rating pixmap, because the rating text is empty.
1054 requiredWidth
= m_rating
.width();
1059 textInfo
->pos
= QPointF(padding
, y
);
1060 textInfo
->staticText
.setTextWidth(maxWidth
);
1062 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1063 m_textRect
|= textRect
;
1068 // Add a padding to the text rectangle
1069 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1072 void KStandardItemListWidget::updateCompactLayoutTextCache()
1074 // +------+ Name role
1075 // | Icon | Additional role 1
1076 // +------+ Additional role 2
1078 const QHash
<QByteArray
, QVariant
> values
= data();
1080 const KItemListStyleOption
& option
= styleOption();
1081 const qreal widgetHeight
= size().height();
1082 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1083 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1084 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1086 qreal maximumRequiredTextWidth
= 0;
1087 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1088 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1089 const qreal maxWidth
= size().width() - x
- option
.padding
;
1090 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1091 const QString text
= roleText(role
, values
);
1092 TextInfo
* textInfo
= m_textInfo
.value(role
);
1093 textInfo
->staticText
.setText(text
);
1095 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1096 if (requiredWidth
> maxWidth
) {
1097 requiredWidth
= maxWidth
;
1098 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1099 textInfo
->staticText
.setText(elidedText
);
1102 textInfo
->pos
= QPointF(x
, y
);
1103 textInfo
->staticText
.setTextWidth(maxWidth
);
1105 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1110 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1113 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1115 // Precondition: Requires already updated m_expansionArea
1116 // to determine the left position.
1119 // | Icon | Name role Additional role 1 Additional role 2
1121 m_textRect
= QRectF();
1123 const KItemListStyleOption
& option
= styleOption();
1124 const QHash
<QByteArray
, QVariant
> values
= data();
1126 const qreal widgetHeight
= size().height();
1127 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1128 const int fontHeight
= m_customizedFontMetrics
.height();
1130 const qreal columnWidthInc
= columnPadding(option
);
1131 qreal firstColumnInc
= scaledIconSize
;
1132 if (m_supportsItemExpanding
) {
1133 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1135 firstColumnInc
+= option
.padding
;
1138 qreal x
= firstColumnInc
;
1139 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1141 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1142 QString text
= roleText(role
, values
);
1144 // Elide the text in case it does not fit into the available column-width
1145 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1146 const qreal roleWidth
= columnWidth(role
);
1147 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1149 const bool isTextRole
= (role
== "text");
1151 availableTextWidth
-= firstColumnInc
;
1154 if (requiredWidth
> availableTextWidth
) {
1155 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1156 requiredWidth
= m_customizedFontMetrics
.width(text
);
1159 TextInfo
* textInfo
= m_textInfo
.value(role
);
1160 textInfo
->staticText
.setText(text
);
1161 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1165 const qreal textWidth
= option
.extendedSelectionRegion
1166 ? size().width() - textInfo
->pos
.x()
1167 : requiredWidth
+ 2 * option
.padding
;
1168 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1169 textWidth
, size().height());
1171 // The column after the name should always be aligned on the same x-position independent
1172 // from the expansion-level shown in the name column
1173 x
-= firstColumnInc
;
1174 } else if (isRoleRightAligned(role
)) {
1175 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1180 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1183 if (m_customTextColor
.isValid()) {
1184 c1
= m_customTextColor
;
1185 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1186 c1
= styleOption().palette
.highlightedText().color();
1188 c1
= styleOption().palette
.text().color();
1191 // For the color of the additional info the inactive text color
1192 // is not used as this might lead to unreadable text for some color schemes. Instead
1193 // the text color c1 is slightly mixed with the background color.
1194 const QColor c2
= styleOption().palette
.base().color();
1196 const int p2
= 100 - p1
;
1197 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1198 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1199 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1202 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1204 if (m_scaledPixmapSize
!= pixmap
.size()) {
1205 QPixmap scaledPixmap
= pixmap
;
1206 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1207 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1209 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1210 painter
->setPen(Qt::blue
);
1211 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1214 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1218 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1220 const int siblingSize
= size().height();
1221 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1222 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1224 QStyleOption option
;
1225 bool isItemSibling
= true;
1227 const QBitArray siblings
= siblingsInformation();
1228 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1229 option
.rect
= siblingRect
;
1230 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1232 if (isItemSibling
) {
1233 option
.state
|= QStyle::State_Item
;
1234 if (m_isExpandable
) {
1235 option
.state
|= QStyle::State_Children
;
1237 if (data()["isExpanded"].toBool()) {
1238 option
.state
|= QStyle::State_Open
;
1240 isItemSibling
= false;
1243 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1245 siblingRect
.translate(-siblingRect
.width(), 0);
1249 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1251 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1256 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1257 if (m_layout
== DetailsLayout
) {
1258 rect
.setWidth(columnWidth(role
) - rect
.x());
1264 void KStandardItemListWidget::closeRoleEditor()
1266 if (m_roleEditor
->hasFocus()) {
1267 // If the editing was not ended by a FocusOut event, we have
1268 // to transfer the keyboard focus back to the KItemListContainer.
1269 scene()->views()[0]->parentWidget()->setFocus();
1272 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
1273 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
1274 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
1275 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
1276 m_roleEditor
->deleteLater();
1280 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1282 const KIcon
icon(name
);
1285 if (size
<= KIconLoader::SizeSmall
) {
1286 requestedSize
= KIconLoader::SizeSmall
;
1287 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1288 requestedSize
= KIconLoader::SizeSmallMedium
;
1289 } else if (size
<= KIconLoader::SizeMedium
) {
1290 requestedSize
= KIconLoader::SizeMedium
;
1291 } else if (size
<= KIconLoader::SizeLarge
) {
1292 requestedSize
= KIconLoader::SizeLarge
;
1293 } else if (size
<= KIconLoader::SizeHuge
) {
1294 requestedSize
= KIconLoader::SizeHuge
;
1295 } else if (size
<= KIconLoader::SizeEnormous
) {
1296 requestedSize
= KIconLoader::SizeEnormous
;
1297 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1298 requestedSize
= KIconLoader::SizeEnormous
* 2;
1300 requestedSize
= size
;
1303 QPixmap pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1304 if (requestedSize
!= size
) {
1305 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1311 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1313 const qreal height
= option
.fontMetrics
.ascent();
1314 return QSizeF(height
* 5, height
);
1317 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1319 return option
.padding
* 6;
1322 #include "kstandarditemlistwidget.moc"