1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kstandarditemlistwidget.h"
22 #include "kfileitemlistview.h"
23 #include "kfileitemmodel.h"
26 #include <KIconEffect>
27 #include <KIconLoader>
29 #include <kratingpainter.h>
30 #include <KStringHandler>
33 #include "private/kfileitemclipboard.h"
34 #include "private/kitemlistroleeditor.h"
35 #include "private/kpixmapmodifier.h"
37 #include <QFontMetricsF>
38 #include <QGraphicsScene>
39 #include <QGraphicsSceneResizeEvent>
40 #include <QGraphicsView>
42 #include <QStyleOption>
43 #include <QTextLayout>
45 #include <QPixmapCache>
47 // #define KSTANDARDITEMLISTWIDGET_DEBUG
49 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
50 KItemListWidgetInformant()
54 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
58 QSizeF
KStandardItemListWidgetInformant::itemSizeHint(int index
, const KItemListView
* view
) const
60 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
61 const KItemListStyleOption
& option
= view
->styleOption();
62 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
64 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
65 case KStandardItemListWidget::IconsLayout
: {
66 const QString text
= KStringHandler::preProcessWrap(values
["text"].toString());
68 const qreal itemWidth
= view
->itemSize().width();
69 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
72 // Calculate the number of lines required for wrapping the name
73 QTextOption
textOption(Qt::AlignHCenter
);
74 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
77 QTextLayout
layout(text
, option
.font
);
78 layout
.setTextOption(textOption
);
80 while ((line
= layout
.createLine()).isValid()) {
81 line
.setLineWidth(maxWidth
);
82 line
.naturalTextWidth();
83 textHeight
+= line
.height();
87 // Add one line for each additional information
88 textHeight
+= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
90 const qreal maxTextHeight
= option
.maxTextSize
.height();
91 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
92 textHeight
= maxTextHeight
;
95 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
98 case KStandardItemListWidget::CompactLayout
: {
99 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
100 // to show all roles without horizontal clipping.
101 qreal maximumRequiredWidth
= 0.0;
103 foreach (const QByteArray
& role
, view
->visibleRoles()) {
104 const QString text
= roleText(role
, values
);
105 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
106 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
109 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
110 const qreal maxWidth
= option
.maxTextSize
.width();
111 if (maxWidth
> 0 && width
> maxWidth
) {
114 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
115 return QSizeF(width
, height
);
118 case KStandardItemListWidget::DetailsLayout
: {
119 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
120 return QSizeF(-1, height
);
131 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
133 const KItemListView
* view
) const
135 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
136 const KItemListStyleOption
& option
= view
->styleOption();
138 const QString text
= roleText(role
, values
);
139 qreal width
= KStandardItemListWidget::columnPadding(option
);
141 if (role
== "rating") {
142 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
144 width
+= option
.fontMetrics
.width(text
);
146 if (role
== "text") {
147 if (view
->supportsItemExpanding()) {
148 // Increase the width by the expansion-toggle and the current expansion level
149 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
150 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
151 width
+= (expandedParentsCount
+ 1) * height
;
154 // Increase the width by the required space for the icon
155 width
+= option
.padding
* 2 + option
.iconSize
;
162 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
163 const QHash
<QByteArray
, QVariant
>& values
) const
165 if (role
== "rating") {
166 // Always use an empty text, as the rating is shown by the image m_rating.
169 return values
.value(role
).toString();
172 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
173 KItemListWidget(informant
, parent
),
177 m_customizedFontMetrics(m_customizedFont
),
178 m_isExpandable(false),
179 m_supportsItemExpanding(false),
181 m_dirtyContent(true),
182 m_dirtyContentRoles(),
183 m_layout(IconsLayout
),
186 m_scaledPixmapSize(),
191 m_sortedVisibleRoles(),
194 m_additionalInfoTextColor(),
202 KStandardItemListWidget::~KStandardItemListWidget()
204 qDeleteAll(m_textInfo
);
208 delete m_oldRoleEditor
;
211 void KStandardItemListWidget::setLayout(Layout layout
)
213 if (m_layout
!= layout
) {
215 m_dirtyLayout
= true;
216 updateAdditionalInfoTextColor();
221 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
226 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
228 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
229 m_supportsItemExpanding
= supportsItemExpanding
;
230 m_dirtyLayout
= true;
235 bool KStandardItemListWidget::supportsItemExpanding() const
237 return m_supportsItemExpanding
;
240 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
242 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
244 KItemListWidget::paint(painter
, option
, widget
);
246 if (!m_expansionArea
.isEmpty()) {
247 drawSiblingsInformation(painter
);
250 const KItemListStyleOption
& itemListStyleOption
= styleOption();
252 const qreal opacity
= painter
->opacity();
253 // Blend the unhovered and hovered pixmap if the hovering
254 // animation is ongoing
255 if (hoverOpacity() < 1.0) {
256 painter
->setOpacity((1.0 - hoverOpacity()) * opacity
);
257 drawPixmap(painter
, m_pixmap
);
260 painter
->setOpacity(hoverOpacity() * opacity
);
261 drawPixmap(painter
, m_hoverPixmap
);
262 painter
->setOpacity(opacity
);
264 drawPixmap(painter
, m_pixmap
);
267 painter
->setFont(m_customizedFont
);
268 painter
->setPen(m_isHidden
? m_additionalInfoTextColor
: textColor());
269 const TextInfo
* textInfo
= m_textInfo
.value("text");
272 // It seems that we can end up here even if m_textInfo does not contain
273 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
274 // this can only happen if the index is negative. This can happen when
275 // the item is about to be removed, see KItemListView::slotItemsRemoved().
276 // TODO: try to reproduce the crash and find a better fix.
280 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
282 bool clipAdditionalInfoBounds
= false;
283 if (m_supportsItemExpanding
) {
284 // Prevent a possible overlapping of the additional-information texts
285 // with the icon. This can happen if the user has minimized the width
286 // of the name-column to a very small value.
287 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
288 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
289 clipAdditionalInfoBounds
= true;
291 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
295 painter
->setPen(m_additionalInfoTextColor
);
296 painter
->setFont(m_customizedFont
);
298 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
299 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
300 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
303 if (!m_rating
.isNull()) {
304 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
305 QPointF pos
= ratingTextInfo
->pos
;
306 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
307 if (align
& Qt::AlignHCenter
) {
308 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
310 painter
->drawPixmap(pos
, m_rating
);
313 if (clipAdditionalInfoBounds
) {
317 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
318 painter
->setBrush(Qt::NoBrush
);
319 painter
->setPen(Qt::green
);
320 painter
->drawRect(m_iconRect
);
322 painter
->setPen(Qt::red
);
323 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
324 painter
->drawRect(rect());
328 QRectF
KStandardItemListWidget::iconRect() const
330 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
334 QRectF
KStandardItemListWidget::textRect() const
336 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
340 QRectF
KStandardItemListWidget::textFocusRect() const
342 // In the compact- and details-layout a larger textRect() is returned to be aligned
343 // with the iconRect(). This is useful to have a larger selection/hover-area
344 // when having a quite large icon size but only one line of text. Still the
345 // focus rectangle should be shown as narrow as possible around the text.
347 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
350 case CompactLayout
: {
351 QRectF rect
= m_textRect
;
352 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
353 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
354 rect
.setTop(topText
->pos
.y());
355 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
359 case DetailsLayout
: {
360 QRectF rect
= m_textRect
;
361 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
362 rect
.setTop(textInfo
->pos
.y());
363 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
365 const KItemListStyleOption
& option
= styleOption();
366 if (option
.extendedSelectionRegion
) {
367 const QString text
= textInfo
->staticText
.text();
368 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
381 QRectF
KStandardItemListWidget::expansionToggleRect() const
383 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
384 return m_isExpandable
? m_expansionArea
: QRectF();
387 QRectF
KStandardItemListWidget::selectionToggleRect() const
389 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
391 const int iconHeight
= styleOption().iconSize
;
393 int toggleSize
= KIconLoader::SizeSmall
;
394 if (iconHeight
>= KIconLoader::SizeEnormous
) {
395 toggleSize
= KIconLoader::SizeMedium
;
396 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
397 toggleSize
= KIconLoader::SizeSmallMedium
;
400 QPointF pos
= iconRect().topLeft();
402 // If the selection toggle has a very small distance to the
403 // widget borders, the size of the selection toggle will get
404 // increased to prevent an accidental clicking of the item
405 // when trying to hit the toggle.
406 const int widgetHeight
= size().height();
407 const int widgetWidth
= size().width();
408 const int minMargin
= 2;
410 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
411 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
412 toggleSize
= widgetHeight
;
415 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
416 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
417 toggleSize
= widgetWidth
;
421 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
424 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
427 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
428 if (m_layout
!= DetailsLayout
) {
432 // Only return the content of the text-column as pixmap
433 const int leftClip
= m_pixmapPos
.x();
435 const TextInfo
* textInfo
= m_textInfo
.value("text");
436 const int rightClip
= textInfo
->pos
.x() +
437 textInfo
->staticText
.size().width() +
438 2 * styleOption().padding
;
440 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
441 clippedPixmap
.fill(Qt::transparent
);
443 QPainter
painter(&clippedPixmap
);
444 painter
.drawPixmap(-leftClip
, 0, pixmap
);
446 return clippedPixmap
;
450 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
452 return new KStandardItemListWidgetInformant();
455 void KStandardItemListWidget::invalidateCache()
457 m_dirtyLayout
= true;
458 m_dirtyContent
= true;
461 void KStandardItemListWidget::refreshCache()
465 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
471 bool KStandardItemListWidget::isHidden() const
476 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
481 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
483 return QPalette::Text
;
486 void KStandardItemListWidget::setTextColor(const QColor
& color
)
488 if (color
!= m_customTextColor
) {
489 m_customTextColor
= color
;
490 updateAdditionalInfoTextColor();
495 QColor
KStandardItemListWidget::textColor() const
497 if (m_customTextColor
.isValid() && !isSelected()) {
498 return m_customTextColor
;
501 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
502 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
503 return styleOption().palette
.color(group
, role
);
506 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
509 m_dirtyContent
= true;
513 QPixmap
KStandardItemListWidget::overlay() const
519 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
520 const QHash
<QByteArray
, QVariant
>& values
) const
522 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
525 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
526 const QSet
<QByteArray
>& roles
)
530 m_dirtyContent
= true;
532 QSet
<QByteArray
> dirtyRoles
;
533 if (roles
.isEmpty()) {
534 dirtyRoles
= visibleRoles().toSet();
539 // The icon-state might depend from other roles and hence is
540 // marked as dirty whenever a role has been changed
541 dirtyRoles
.insert("iconPixmap");
542 dirtyRoles
.insert("iconName");
544 QSetIterator
<QByteArray
> it(dirtyRoles
);
545 while (it
.hasNext()) {
546 const QByteArray
& role
= it
.next();
547 m_dirtyContentRoles
.insert(role
);
551 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
552 const QList
<QByteArray
>& previous
)
555 m_sortedVisibleRoles
= current
;
556 m_dirtyLayout
= true;
559 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
566 m_dirtyLayout
= true;
569 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
570 const KItemListStyleOption
& previous
)
574 updateAdditionalInfoTextColor();
575 m_dirtyLayout
= true;
578 void KStandardItemListWidget::hoveredChanged(bool hovered
)
581 m_dirtyLayout
= true;
584 void KStandardItemListWidget::selectedChanged(bool selected
)
587 updateAdditionalInfoTextColor();
588 m_dirtyContent
= true;
591 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
595 m_dirtyLayout
= true;
598 int KStandardItemListWidget::selectionLength(const QString
& text
) const
600 return text
.length();
603 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
607 QGraphicsView
* parent
= scene()->views()[0];
608 if (current
.isEmpty() || !parent
|| current
!= "text") {
610 emit
roleEditingCanceled(index(), current
, data().value(current
));
612 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
613 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
614 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
615 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
616 m_oldRoleEditor
= m_roleEditor
;
617 m_roleEditor
->hide();
621 } else if (m_oldRoleEditor
) {
622 // Delete the old editor before constructing the new one to
623 // prevent a memory leak.
624 m_oldRoleEditor
->deleteLater();
628 Q_ASSERT(!m_roleEditor
);
630 const TextInfo
* textInfo
= m_textInfo
.value("text");
632 m_roleEditor
= new KItemListRoleEditor(parent
);
633 m_roleEditor
->setIndex(index());
634 m_roleEditor
->setRole(current
);
635 m_roleEditor
->setFont(styleOption().font
);
637 const QString text
= data().value(current
).toString();
638 m_roleEditor
->setPlainText(text
);
640 QTextOption textOption
= textInfo
->staticText
.textOption();
641 m_roleEditor
->document()->setDefaultTextOption(textOption
);
643 const int textSelectionLength
= selectionLength(text
);
645 if (textSelectionLength
> 0) {
646 QTextCursor cursor
= m_roleEditor
->textCursor();
647 cursor
.movePosition(QTextCursor::StartOfBlock
);
648 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
649 m_roleEditor
->setTextCursor(cursor
);
652 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
653 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
654 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
655 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
657 // Adjust the geometry of the editor
658 QRectF rect
= roleEditingRect(current
);
659 const int frameWidth
= m_roleEditor
->frameWidth();
660 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
661 rect
.translate(pos());
662 if (rect
.right() > parent
->width()) {
663 rect
.setWidth(parent
->width() - rect
.left());
665 m_roleEditor
->setGeometry(rect
.toRect());
666 m_roleEditor
->show();
667 m_roleEditor
->setFocus();
670 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
673 setEditedRole(QByteArray());
674 Q_ASSERT(!m_roleEditor
);
677 KItemListWidget::resizeEvent(event
);
679 m_dirtyLayout
= true;
682 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
684 KItemListWidget::showEvent(event
);
686 // Listen to changes of the clipboard to mark the item as cut/uncut
687 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
689 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
690 m_isCut
= clipboard
->isCut(itemUrl
);
692 connect(clipboard
, SIGNAL(cutItemsChanged()),
693 this, SLOT(slotCutItemsChanged()));
696 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
698 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
699 this, SLOT(slotCutItemsChanged()));
701 KItemListWidget::hideEvent(event
);
704 void KStandardItemListWidget::slotCutItemsChanged()
706 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
707 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
708 if (m_isCut
!= isCut
) {
710 m_pixmap
= QPixmap();
711 m_dirtyContent
= true;
716 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
717 const QByteArray
& role
,
718 const QVariant
& value
)
721 emit
roleEditingCanceled(index
, role
, value
);
722 setEditedRole(QByteArray());
725 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
726 const QByteArray
& role
,
727 const QVariant
& value
)
730 emit
roleEditingFinished(index
, role
, value
);
731 setEditedRole(QByteArray());
734 void KStandardItemListWidget::triggerCacheRefreshing()
736 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
742 const QHash
<QByteArray
, QVariant
> values
= data();
743 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
744 m_isHidden
= isHidden();
745 m_customizedFont
= customizedFont(styleOption().font
);
746 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
748 updateExpansionArea();
752 m_dirtyLayout
= false;
753 m_dirtyContent
= false;
754 m_dirtyContentRoles
.clear();
757 void KStandardItemListWidget::updateExpansionArea()
759 if (m_supportsItemExpanding
) {
760 const QHash
<QByteArray
, QVariant
> values
= data();
761 Q_ASSERT(values
.contains("expandedParentsCount"));
762 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
763 if (expandedParentsCount
>= 0) {
764 const qreal widgetHeight
= size().height();
765 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
766 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
768 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
773 m_expansionArea
= QRectF();
776 void KStandardItemListWidget::updatePixmapCache()
778 // Precondition: Requires already updated m_textPos values to calculate
779 // the remaining height when the alignment is vertical.
781 const QSizeF widgetSize
= size();
782 const bool iconOnTop
= (m_layout
== IconsLayout
);
783 const KItemListStyleOption
& option
= styleOption();
784 const qreal padding
= option
.padding
;
786 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
787 const int maxIconHeight
= option
.iconSize
;
789 const QHash
<QByteArray
, QVariant
> values
= data();
791 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
792 if (!updatePixmap
&& m_dirtyContent
) {
793 updatePixmap
= m_dirtyContentRoles
.isEmpty()
794 || m_dirtyContentRoles
.contains("iconPixmap")
795 || m_dirtyContentRoles
.contains("iconName")
796 || m_dirtyContentRoles
.contains("iconOverlays");
800 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
801 if (m_pixmap
.isNull()) {
802 // Use the icon that fits to the MIME-type
803 QString iconName
= values
["iconName"].toString();
804 if (iconName
.isEmpty()) {
805 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
806 // use a generic icon as fallback
807 iconName
= QLatin1String("unknown");
809 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
810 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
811 // A custom pixmap has been applied. Assure that the pixmap
812 // is scaled to the maximum available size.
813 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
816 const QStringList overlays
= values
["iconOverlays"].toStringList();
818 // Strangely KFileItem::overlays() returns empty string-values, so
819 // we need to check first whether an overlay must be drawn at all.
820 // It is more efficient to do it here, as KIconLoader::drawOverlays()
821 // assumes that an overlay will be drawn and has some additional
823 foreach (const QString
& overlay
, overlays
) {
824 if (!overlay
.isEmpty()) {
825 // There is at least one overlay, draw all overlays above m_pixmap
826 // and cancel the check
827 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
833 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
834 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
838 KIconEffect::semiTransparent(m_pixmap
);
842 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
843 QImage image
= m_pixmap
.toImage();
844 KIconEffect::colorize(image
, color
, 0.8f
);
845 m_pixmap
= QPixmap::fromImage(image
);
849 if (!m_overlay
.isNull()) {
850 QPainter
painter(&m_pixmap
);
851 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
854 int scaledIconSize
= 0;
856 const TextInfo
* textInfo
= m_textInfo
.value("text");
857 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
859 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
860 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
861 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
862 widgetSize
.height() - 2 * padding
: maxIconHeight
;
865 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
866 const int maxScaledIconHeight
= scaledIconSize
;
868 m_scaledPixmapSize
= m_pixmap
.size();
869 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
872 // Center horizontally and align on bottom within the icon-area
873 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
874 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
876 // Center horizontally and vertically within the icon-area
877 const TextInfo
* textInfo
= m_textInfo
.value("text");
878 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
879 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
880 m_pixmapPos
.setY(padding
881 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
884 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
886 // Prepare the pixmap that is used when the item gets hovered
888 m_hoverPixmap
= m_pixmap
;
889 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
890 // In the KIconLoader terminology, active = hover.
891 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
892 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
894 m_hoverPixmap
= m_pixmap
;
896 } else if (hoverOpacity() <= 0.0) {
897 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
898 m_hoverPixmap
= QPixmap();
902 void KStandardItemListWidget::updateTextsCache()
904 QTextOption textOption
;
907 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
908 textOption
.setAlignment(Qt::AlignHCenter
);
912 textOption
.setAlignment(Qt::AlignLeft
);
913 textOption
.setWrapMode(QTextOption::NoWrap
);
920 qDeleteAll(m_textInfo
);
922 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
923 TextInfo
* textInfo
= new TextInfo();
924 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
925 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
926 textInfo
->staticText
.setTextOption(textOption
);
927 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
931 case IconsLayout
: updateIconsLayoutTextCache(); break;
932 case CompactLayout
: updateCompactLayoutTextCache(); break;
933 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
934 default: Q_ASSERT(false); break;
937 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
938 if (ratingTextInfo
) {
939 // The text of the rating-role has been set to empty to get
940 // replaced by a rating-image showing the rating as stars.
941 const KItemListStyleOption
& option
= styleOption();
942 QSizeF ratingSize
= preferredRatingSize(option
);
944 const qreal availableWidth
= (m_layout
== DetailsLayout
)
945 ? columnWidth("rating") - columnPadding(option
)
947 if (ratingSize
.width() > availableWidth
) {
948 ratingSize
.rwidth() = availableWidth
;
950 m_rating
= QPixmap(ratingSize
.toSize());
951 m_rating
.fill(Qt::transparent
);
953 QPainter
painter(&m_rating
);
954 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
955 const int rating
= data().value("rating").toInt();
956 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
957 } else if (!m_rating
.isNull()) {
958 m_rating
= QPixmap();
962 void KStandardItemListWidget::updateIconsLayoutTextCache()
969 // might get wrapped above
974 const QHash
<QByteArray
, QVariant
> values
= data();
976 const KItemListStyleOption
& option
= styleOption();
977 const qreal padding
= option
.padding
;
978 const qreal maxWidth
= size().width() - 2 * padding
;
979 const qreal widgetHeight
= size().height();
980 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
982 // Initialize properties for the "text" role. It will be used as anchor
983 // for initializing the position of the other roles.
984 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
985 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
986 nameTextInfo
->staticText
.setText(nameText
);
988 // Calculate the number of lines required for the name and the required width
990 qreal nameHeight
= 0;
993 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
994 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
996 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
997 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
998 layout
.beginLayout();
999 int nameLineIndex
= 0;
1000 while ((line
= layout
.createLine()).isValid()) {
1001 line
.setLineWidth(maxWidth
);
1002 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1003 nameHeight
+= line
.height();
1006 if (nameLineIndex
== maxNameLines
) {
1007 // The maximum number of textlines has been reached. If this is
1008 // the case provide an elided text if necessary.
1009 const int textLength
= line
.textStart() + line
.textLength();
1010 if (textLength
< nameText
.length()) {
1011 // Elide the last line of the text
1012 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1013 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1015 line
.naturalTextWidth() - 1);
1016 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1017 nameTextInfo
->staticText
.setText(elidedText
);
1024 // Use one line for each additional information
1025 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1026 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1028 additionalRolesCount
* lineSpacing
-
1030 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1031 nameTextInfo
->pos
.y(),
1035 // Calculate the position for each additional information
1036 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1037 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1038 if (role
== "text") {
1042 const QString text
= roleText(role
, values
);
1043 TextInfo
* textInfo
= m_textInfo
.value(role
);
1044 textInfo
->staticText
.setText(text
);
1046 qreal requiredWidth
= 0;
1048 QTextLayout
layout(text
, m_customizedFont
);
1049 QTextOption textOption
;
1050 textOption
.setWrapMode(QTextOption::NoWrap
);
1051 layout
.setTextOption(textOption
);
1053 layout
.beginLayout();
1054 QTextLine textLine
= layout
.createLine();
1055 if (textLine
.isValid()) {
1056 textLine
.setLineWidth(maxWidth
);
1057 requiredWidth
= textLine
.naturalTextWidth();
1058 if (requiredWidth
> maxWidth
) {
1059 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1060 textInfo
->staticText
.setText(elidedText
);
1061 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1062 } else if (role
== "rating") {
1063 // Use the width of the rating pixmap, because the rating text is empty.
1064 requiredWidth
= m_rating
.width();
1069 textInfo
->pos
= QPointF(padding
, y
);
1070 textInfo
->staticText
.setTextWidth(maxWidth
);
1072 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1073 m_textRect
|= textRect
;
1078 // Add a padding to the text rectangle
1079 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1082 void KStandardItemListWidget::updateCompactLayoutTextCache()
1084 // +------+ Name role
1085 // | Icon | Additional role 1
1086 // +------+ Additional role 2
1088 const QHash
<QByteArray
, QVariant
> values
= data();
1090 const KItemListStyleOption
& option
= styleOption();
1091 const qreal widgetHeight
= size().height();
1092 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1093 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1094 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1096 qreal maximumRequiredTextWidth
= 0;
1097 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1098 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1099 const qreal maxWidth
= size().width() - x
- option
.padding
;
1100 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1101 const QString text
= roleText(role
, values
);
1102 TextInfo
* textInfo
= m_textInfo
.value(role
);
1103 textInfo
->staticText
.setText(text
);
1105 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1106 if (requiredWidth
> maxWidth
) {
1107 requiredWidth
= maxWidth
;
1108 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1109 textInfo
->staticText
.setText(elidedText
);
1112 textInfo
->pos
= QPointF(x
, y
);
1113 textInfo
->staticText
.setTextWidth(maxWidth
);
1115 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1120 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1123 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1125 // Precondition: Requires already updated m_expansionArea
1126 // to determine the left position.
1129 // | Icon | Name role Additional role 1 Additional role 2
1131 m_textRect
= QRectF();
1133 const KItemListStyleOption
& option
= styleOption();
1134 const QHash
<QByteArray
, QVariant
> values
= data();
1136 const qreal widgetHeight
= size().height();
1137 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1138 const int fontHeight
= m_customizedFontMetrics
.height();
1140 const qreal columnWidthInc
= columnPadding(option
);
1141 qreal firstColumnInc
= scaledIconSize
;
1142 if (m_supportsItemExpanding
) {
1143 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1145 firstColumnInc
+= option
.padding
;
1148 qreal x
= firstColumnInc
;
1149 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1151 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1152 QString text
= roleText(role
, values
);
1154 // Elide the text in case it does not fit into the available column-width
1155 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1156 const qreal roleWidth
= columnWidth(role
);
1157 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1159 const bool isTextRole
= (role
== "text");
1161 availableTextWidth
-= firstColumnInc
;
1164 if (requiredWidth
> availableTextWidth
) {
1165 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1166 requiredWidth
= m_customizedFontMetrics
.width(text
);
1169 TextInfo
* textInfo
= m_textInfo
.value(role
);
1170 textInfo
->staticText
.setText(text
);
1171 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1175 const qreal textWidth
= option
.extendedSelectionRegion
1176 ? size().width() - textInfo
->pos
.x()
1177 : requiredWidth
+ 2 * option
.padding
;
1178 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1179 textWidth
, size().height());
1181 // The column after the name should always be aligned on the same x-position independent
1182 // from the expansion-level shown in the name column
1183 x
-= firstColumnInc
;
1184 } else if (isRoleRightAligned(role
)) {
1185 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1190 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1193 if (m_customTextColor
.isValid()) {
1194 c1
= m_customTextColor
;
1195 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1196 c1
= styleOption().palette
.highlightedText().color();
1198 c1
= styleOption().palette
.text().color();
1201 // For the color of the additional info the inactive text color
1202 // is not used as this might lead to unreadable text for some color schemes. Instead
1203 // the text color c1 is slightly mixed with the background color.
1204 const QColor c2
= styleOption().palette
.base().color();
1206 const int p2
= 100 - p1
;
1207 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1208 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1209 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1212 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1214 if (m_scaledPixmapSize
!= pixmap
.size()) {
1215 QPixmap scaledPixmap
= pixmap
;
1216 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1217 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1219 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1220 painter
->setPen(Qt::blue
);
1221 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1224 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1228 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1230 const int siblingSize
= size().height();
1231 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1232 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1234 QStyleOption option
;
1235 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1236 bool isItemSibling
= true;
1238 const QBitArray siblings
= siblingsInformation();
1239 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1240 option
.rect
= siblingRect
;
1241 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1243 if (isItemSibling
) {
1244 option
.state
|= QStyle::State_Item
;
1245 if (m_isExpandable
) {
1246 option
.state
|= QStyle::State_Children
;
1248 if (data()["isExpanded"].toBool()) {
1249 option
.state
|= QStyle::State_Open
;
1251 isItemSibling
= false;
1254 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1256 siblingRect
.translate(-siblingRect
.width(), 0);
1260 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1262 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1267 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1268 if (m_layout
== DetailsLayout
) {
1269 rect
.setWidth(columnWidth(role
) - rect
.x());
1275 void KStandardItemListWidget::closeRoleEditor()
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 if (m_roleEditor
->hasFocus()) {
1283 // If the editing was not ended by a FocusOut event, we have
1284 // to transfer the keyboard focus back to the KItemListContainer.
1285 scene()->views()[0]->parentWidget()->setFocus();
1288 m_oldRoleEditor
= m_roleEditor
;
1289 m_roleEditor
->hide();
1293 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1295 const QString key
= "KStandardItemListWidget:" % name
% ":" % QString::number(size
);
1298 if (!QPixmapCache::find(key
, pixmap
)) {
1299 const KIcon
icon(name
);
1302 if (size
<= KIconLoader::SizeSmall
) {
1303 requestedSize
= KIconLoader::SizeSmall
;
1304 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1305 requestedSize
= KIconLoader::SizeSmallMedium
;
1306 } else if (size
<= KIconLoader::SizeMedium
) {
1307 requestedSize
= KIconLoader::SizeMedium
;
1308 } else if (size
<= KIconLoader::SizeLarge
) {
1309 requestedSize
= KIconLoader::SizeLarge
;
1310 } else if (size
<= KIconLoader::SizeHuge
) {
1311 requestedSize
= KIconLoader::SizeHuge
;
1312 } else if (size
<= KIconLoader::SizeEnormous
) {
1313 requestedSize
= KIconLoader::SizeEnormous
;
1314 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1315 requestedSize
= KIconLoader::SizeEnormous
* 2;
1317 requestedSize
= size
;
1320 pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1321 if (requestedSize
!= size
) {
1322 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1325 QPixmapCache::insert(key
, pixmap
);
1331 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1333 const qreal height
= option
.fontMetrics
.ascent();
1334 return QSizeF(height
* 5, height
);
1337 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1339 return option
.padding
* 6;
1342 #include "kstandarditemlistwidget.moc"