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 m_roleEditor
->deleteLater();
619 Q_ASSERT(!m_roleEditor
);
621 const TextInfo
* textInfo
= m_textInfo
.value("text");
623 m_roleEditor
= new KItemListRoleEditor(parent
);
624 m_roleEditor
->setIndex(index());
625 m_roleEditor
->setRole(current
);
626 m_roleEditor
->setFont(styleOption().font
);
628 const QString text
= data().value(current
).toString();
629 m_roleEditor
->setPlainText(text
);
631 QTextOption textOption
= textInfo
->staticText
.textOption();
632 m_roleEditor
->document()->setDefaultTextOption(textOption
);
634 const int textSelectionLength
= selectionLength(text
);
636 if (textSelectionLength
> 0) {
637 QTextCursor cursor
= m_roleEditor
->textCursor();
638 cursor
.movePosition(QTextCursor::StartOfBlock
);
639 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
640 m_roleEditor
->setTextCursor(cursor
);
643 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
644 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
645 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
646 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
648 // Adjust the geometry of the editor
649 QRectF rect
= roleEditingRect(current
);
650 const int frameWidth
= m_roleEditor
->frameWidth();
651 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
652 rect
.translate(pos());
653 if (rect
.right() > parent
->width()) {
654 rect
.setWidth(parent
->width() - rect
.left());
656 m_roleEditor
->setGeometry(rect
.toRect());
657 m_roleEditor
->show();
658 m_roleEditor
->setFocus();
661 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
664 setEditedRole(QByteArray());
665 Q_ASSERT(!m_roleEditor
);
668 KItemListWidget::resizeEvent(event
);
670 m_dirtyLayout
= true;
673 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
675 KItemListWidget::showEvent(event
);
677 // Listen to changes of the clipboard to mark the item as cut/uncut
678 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
680 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
681 m_isCut
= clipboard
->isCut(itemUrl
);
683 connect(clipboard
, SIGNAL(cutItemsChanged()),
684 this, SLOT(slotCutItemsChanged()));
687 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
689 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
690 this, SLOT(slotCutItemsChanged()));
692 KItemListWidget::hideEvent(event
);
695 void KStandardItemListWidget::slotCutItemsChanged()
697 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
698 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
699 if (m_isCut
!= isCut
) {
701 m_pixmap
= QPixmap();
702 m_dirtyContent
= true;
707 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
708 const QByteArray
& role
,
709 const QVariant
& value
)
712 emit
roleEditingCanceled(index
, role
, value
);
713 setEditedRole(QByteArray());
716 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
717 const QByteArray
& role
,
718 const QVariant
& value
)
721 emit
roleEditingFinished(index
, role
, value
);
722 setEditedRole(QByteArray());
725 void KStandardItemListWidget::triggerCacheRefreshing()
727 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
733 const QHash
<QByteArray
, QVariant
> values
= data();
734 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
735 m_isHidden
= isHidden();
736 m_customizedFont
= customizedFont(styleOption().font
);
737 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
739 updateExpansionArea();
743 m_dirtyLayout
= false;
744 m_dirtyContent
= false;
745 m_dirtyContentRoles
.clear();
748 void KStandardItemListWidget::updateExpansionArea()
750 if (m_supportsItemExpanding
) {
751 const QHash
<QByteArray
, QVariant
> values
= data();
752 Q_ASSERT(values
.contains("expandedParentsCount"));
753 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
754 if (expandedParentsCount
>= 0) {
755 const qreal widgetHeight
= size().height();
756 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
757 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
759 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
764 m_expansionArea
= QRectF();
767 void KStandardItemListWidget::updatePixmapCache()
769 // Precondition: Requires already updated m_textPos values to calculate
770 // the remaining height when the alignment is vertical.
772 const QSizeF widgetSize
= size();
773 const bool iconOnTop
= (m_layout
== IconsLayout
);
774 const KItemListStyleOption
& option
= styleOption();
775 const qreal padding
= option
.padding
;
777 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
778 const int maxIconHeight
= option
.iconSize
;
780 const QHash
<QByteArray
, QVariant
> values
= data();
782 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
783 if (!updatePixmap
&& m_dirtyContent
) {
784 updatePixmap
= m_dirtyContentRoles
.isEmpty()
785 || m_dirtyContentRoles
.contains("iconPixmap")
786 || m_dirtyContentRoles
.contains("iconName")
787 || m_dirtyContentRoles
.contains("iconOverlays");
791 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
792 if (m_pixmap
.isNull()) {
793 // Use the icon that fits to the MIME-type
794 QString iconName
= values
["iconName"].toString();
795 if (iconName
.isEmpty()) {
796 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
797 // use a generic icon as fallback
798 iconName
= QLatin1String("unknown");
800 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
801 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
802 // A custom pixmap has been applied. Assure that the pixmap
803 // is scaled to the maximum available size.
804 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
807 const QStringList overlays
= values
["iconOverlays"].toStringList();
809 // Strangely KFileItem::overlays() returns empty string-values, so
810 // we need to check first whether an overlay must be drawn at all.
811 // It is more efficient to do it here, as KIconLoader::drawOverlays()
812 // assumes that an overlay will be drawn and has some additional
814 foreach (const QString
& overlay
, overlays
) {
815 if (!overlay
.isEmpty()) {
816 // There is at least one overlay, draw all overlays above m_pixmap
817 // and cancel the check
818 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
824 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
825 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
829 KIconEffect::semiTransparent(m_pixmap
);
833 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
834 QImage image
= m_pixmap
.toImage();
835 KIconEffect::colorize(image
, color
, 1.0f
);
836 m_pixmap
= QPixmap::fromImage(image
);
840 if (!m_overlay
.isNull()) {
841 QPainter
painter(&m_pixmap
);
842 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
845 int scaledIconSize
= 0;
847 const TextInfo
* textInfo
= m_textInfo
.value("text");
848 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
850 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
851 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
852 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
853 widgetSize
.height() - 2 * padding
: maxIconHeight
;
856 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
857 const int maxScaledIconHeight
= scaledIconSize
;
859 m_scaledPixmapSize
= m_pixmap
.size();
860 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
863 // Center horizontally and align on bottom within the icon-area
864 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
865 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
867 // Center horizontally and vertically within the icon-area
868 const TextInfo
* textInfo
= m_textInfo
.value("text");
869 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
870 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
871 m_pixmapPos
.setY(padding
872 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
875 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
877 // Prepare the pixmap that is used when the item gets hovered
879 m_hoverPixmap
= m_pixmap
;
880 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
881 // In the KIconLoader terminology, active = hover.
882 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
883 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
885 m_hoverPixmap
= m_pixmap
;
887 } else if (hoverOpacity() <= 0.0) {
888 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
889 m_hoverPixmap
= QPixmap();
893 void KStandardItemListWidget::updateTextsCache()
895 QTextOption textOption
;
898 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
899 textOption
.setAlignment(Qt::AlignHCenter
);
903 textOption
.setAlignment(Qt::AlignLeft
);
904 textOption
.setWrapMode(QTextOption::NoWrap
);
911 qDeleteAll(m_textInfo
);
913 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
914 TextInfo
* textInfo
= new TextInfo();
915 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
916 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
917 textInfo
->staticText
.setTextOption(textOption
);
918 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
922 case IconsLayout
: updateIconsLayoutTextCache(); break;
923 case CompactLayout
: updateCompactLayoutTextCache(); break;
924 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
925 default: Q_ASSERT(false); break;
928 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
929 if (ratingTextInfo
) {
930 // The text of the rating-role has been set to empty to get
931 // replaced by a rating-image showing the rating as stars.
932 const KItemListStyleOption
& option
= styleOption();
933 QSizeF ratingSize
= preferredRatingSize(option
);
935 const qreal availableWidth
= (m_layout
== DetailsLayout
)
936 ? columnWidth("rating") - columnPadding(option
)
938 if (ratingSize
.width() > availableWidth
) {
939 ratingSize
.rwidth() = availableWidth
;
941 m_rating
= QPixmap(ratingSize
.toSize());
942 m_rating
.fill(Qt::transparent
);
944 QPainter
painter(&m_rating
);
945 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
946 const int rating
= data().value("rating").toInt();
947 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
948 } else if (!m_rating
.isNull()) {
949 m_rating
= QPixmap();
953 void KStandardItemListWidget::updateIconsLayoutTextCache()
960 // might get wrapped above
965 const QHash
<QByteArray
, QVariant
> values
= data();
967 const KItemListStyleOption
& option
= styleOption();
968 const qreal padding
= option
.padding
;
969 const qreal maxWidth
= size().width() - 2 * padding
;
970 const qreal widgetHeight
= size().height();
971 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
973 // Initialize properties for the "text" role. It will be used as anchor
974 // for initializing the position of the other roles.
975 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
976 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
977 nameTextInfo
->staticText
.setText(nameText
);
979 // Calculate the number of lines required for the name and the required width
981 qreal nameHeight
= 0;
984 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
985 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
987 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
988 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
989 layout
.beginLayout();
990 int nameLineIndex
= 0;
991 while ((line
= layout
.createLine()).isValid()) {
992 line
.setLineWidth(maxWidth
);
993 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
994 nameHeight
+= line
.height();
997 if (nameLineIndex
== maxNameLines
) {
998 // The maximum number of textlines has been reached. If this is
999 // the case provide an elided text if necessary.
1000 const int textLength
= line
.textStart() + line
.textLength();
1001 if (textLength
< nameText
.length()) {
1002 // Elide the last line of the text
1003 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1004 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1006 line
.naturalTextWidth() - 1);
1007 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1008 nameTextInfo
->staticText
.setText(elidedText
);
1015 // Use one line for each additional information
1016 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1017 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1019 additionalRolesCount
* lineSpacing
-
1021 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1022 nameTextInfo
->pos
.y(),
1026 // Calculate the position for each additional information
1027 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1028 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1029 if (role
== "text") {
1033 const QString text
= roleText(role
, values
);
1034 TextInfo
* textInfo
= m_textInfo
.value(role
);
1035 textInfo
->staticText
.setText(text
);
1037 qreal requiredWidth
= 0;
1039 QTextLayout
layout(text
, m_customizedFont
);
1040 QTextOption textOption
;
1041 textOption
.setWrapMode(QTextOption::NoWrap
);
1042 layout
.setTextOption(textOption
);
1044 layout
.beginLayout();
1045 QTextLine textLine
= layout
.createLine();
1046 if (textLine
.isValid()) {
1047 textLine
.setLineWidth(maxWidth
);
1048 requiredWidth
= textLine
.naturalTextWidth();
1049 if (requiredWidth
> maxWidth
) {
1050 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1051 textInfo
->staticText
.setText(elidedText
);
1052 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1053 } else if (role
== "rating") {
1054 // Use the width of the rating pixmap, because the rating text is empty.
1055 requiredWidth
= m_rating
.width();
1060 textInfo
->pos
= QPointF(padding
, y
);
1061 textInfo
->staticText
.setTextWidth(maxWidth
);
1063 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1064 m_textRect
|= textRect
;
1069 // Add a padding to the text rectangle
1070 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1073 void KStandardItemListWidget::updateCompactLayoutTextCache()
1075 // +------+ Name role
1076 // | Icon | Additional role 1
1077 // +------+ Additional role 2
1079 const QHash
<QByteArray
, QVariant
> values
= data();
1081 const KItemListStyleOption
& option
= styleOption();
1082 const qreal widgetHeight
= size().height();
1083 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1084 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1085 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1087 qreal maximumRequiredTextWidth
= 0;
1088 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1089 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1090 const qreal maxWidth
= size().width() - x
- option
.padding
;
1091 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1092 const QString text
= roleText(role
, values
);
1093 TextInfo
* textInfo
= m_textInfo
.value(role
);
1094 textInfo
->staticText
.setText(text
);
1096 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1097 if (requiredWidth
> maxWidth
) {
1098 requiredWidth
= maxWidth
;
1099 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1100 textInfo
->staticText
.setText(elidedText
);
1103 textInfo
->pos
= QPointF(x
, y
);
1104 textInfo
->staticText
.setTextWidth(maxWidth
);
1106 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1111 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1114 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1116 // Precondition: Requires already updated m_expansionArea
1117 // to determine the left position.
1120 // | Icon | Name role Additional role 1 Additional role 2
1122 m_textRect
= QRectF();
1124 const KItemListStyleOption
& option
= styleOption();
1125 const QHash
<QByteArray
, QVariant
> values
= data();
1127 const qreal widgetHeight
= size().height();
1128 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1129 const int fontHeight
= m_customizedFontMetrics
.height();
1131 const qreal columnWidthInc
= columnPadding(option
);
1132 qreal firstColumnInc
= scaledIconSize
;
1133 if (m_supportsItemExpanding
) {
1134 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1136 firstColumnInc
+= option
.padding
;
1139 qreal x
= firstColumnInc
;
1140 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1142 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1143 QString text
= roleText(role
, values
);
1145 // Elide the text in case it does not fit into the available column-width
1146 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1147 const qreal roleWidth
= columnWidth(role
);
1148 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1150 const bool isTextRole
= (role
== "text");
1152 availableTextWidth
-= firstColumnInc
;
1155 if (requiredWidth
> availableTextWidth
) {
1156 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1157 requiredWidth
= m_customizedFontMetrics
.width(text
);
1160 TextInfo
* textInfo
= m_textInfo
.value(role
);
1161 textInfo
->staticText
.setText(text
);
1162 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1166 const qreal textWidth
= option
.extendedSelectionRegion
1167 ? size().width() - textInfo
->pos
.x()
1168 : requiredWidth
+ 2 * option
.padding
;
1169 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1170 textWidth
, size().height());
1172 // The column after the name should always be aligned on the same x-position independent
1173 // from the expansion-level shown in the name column
1174 x
-= firstColumnInc
;
1175 } else if (isRoleRightAligned(role
)) {
1176 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1181 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1184 if (m_customTextColor
.isValid()) {
1185 c1
= m_customTextColor
;
1186 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1187 c1
= styleOption().palette
.highlightedText().color();
1189 c1
= styleOption().palette
.text().color();
1192 // For the color of the additional info the inactive text color
1193 // is not used as this might lead to unreadable text for some color schemes. Instead
1194 // the text color c1 is slightly mixed with the background color.
1195 const QColor c2
= styleOption().palette
.base().color();
1197 const int p2
= 100 - p1
;
1198 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1199 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1200 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1203 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1205 if (m_scaledPixmapSize
!= pixmap
.size()) {
1206 QPixmap scaledPixmap
= pixmap
;
1207 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1208 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1210 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1211 painter
->setPen(Qt::blue
);
1212 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1215 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1219 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1221 const int siblingSize
= size().height();
1222 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1223 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1225 QStyleOption option
;
1226 bool isItemSibling
= true;
1228 const QBitArray siblings
= siblingsInformation();
1229 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1230 option
.rect
= siblingRect
;
1231 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1233 if (isItemSibling
) {
1234 option
.state
|= QStyle::State_Item
;
1235 if (m_isExpandable
) {
1236 option
.state
|= QStyle::State_Children
;
1238 if (data()["isExpanded"].toBool()) {
1239 option
.state
|= QStyle::State_Open
;
1241 isItemSibling
= false;
1244 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1246 siblingRect
.translate(-siblingRect
.width(), 0);
1250 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1252 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1257 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1258 if (m_layout
== DetailsLayout
) {
1259 rect
.setWidth(columnWidth(role
) - rect
.x());
1265 void KStandardItemListWidget::closeRoleEditor()
1267 if (m_roleEditor
->hasFocus()) {
1268 // If the editing was not ended by a FocusOut event, we have
1269 // to transfer the keyboard focus back to the KItemListContainer.
1270 scene()->views()[0]->parentWidget()->setFocus();
1273 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
1274 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
1275 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
1276 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
1277 m_roleEditor
->deleteLater();
1281 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1283 const QString key
= "KStandardItemListWidget:" % name
% ":" % QString::number(size
);
1286 if (!QPixmapCache::find(key
, pixmap
)) {
1287 const KIcon
icon(name
);
1290 if (size
<= KIconLoader::SizeSmall
) {
1291 requestedSize
= KIconLoader::SizeSmall
;
1292 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1293 requestedSize
= KIconLoader::SizeSmallMedium
;
1294 } else if (size
<= KIconLoader::SizeMedium
) {
1295 requestedSize
= KIconLoader::SizeMedium
;
1296 } else if (size
<= KIconLoader::SizeLarge
) {
1297 requestedSize
= KIconLoader::SizeLarge
;
1298 } else if (size
<= KIconLoader::SizeHuge
) {
1299 requestedSize
= KIconLoader::SizeHuge
;
1300 } else if (size
<= KIconLoader::SizeEnormous
) {
1301 requestedSize
= KIconLoader::SizeEnormous
;
1302 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1303 requestedSize
= KIconLoader::SizeEnormous
* 2;
1305 requestedSize
= size
;
1308 pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1309 if (requestedSize
!= size
) {
1310 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1313 QPixmapCache::insert(key
, pixmap
);
1319 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1321 const qreal height
= option
.fontMetrics
.ascent();
1322 return QSizeF(height
* 5, height
);
1325 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1327 return option
.padding
* 6;
1330 #include "kstandarditemlistwidget.moc"