1 /***************************************************************************
2 * Copyright (C) 2011 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 "kfileitemlistwidget.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 KFILEITEMLISTWIDGET_DEBUG
48 KFileItemListWidget::KFileItemListWidget(QGraphicsItem
* parent
) :
49 KItemListWidget(parent
),
52 m_isExpandable(false),
53 m_supportsItemExpanding(false),
56 m_dirtyContentRoles(),
57 m_layout(IconsLayout
),
65 m_sortedVisibleRoles(),
68 m_additionalInfoTextColor(),
75 KFileItemListWidget::~KFileItemListWidget()
77 qDeleteAll(m_textInfo
);
83 void KFileItemListWidget::setLayout(Layout layout
)
85 if (m_layout
!= layout
) {
88 updateAdditionalInfoTextColor();
93 KFileItemListWidget::Layout
KFileItemListWidget::layout() const
98 void KFileItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
100 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
101 m_supportsItemExpanding
= supportsItemExpanding
;
102 m_dirtyLayout
= true;
107 bool KFileItemListWidget::supportsItemExpanding() const
109 return m_supportsItemExpanding
;
112 void KFileItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
114 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
116 KItemListWidget::paint(painter
, option
, widget
);
118 if (!m_expansionArea
.isEmpty()) {
119 drawSiblingsInformation(painter
);
122 const KItemListStyleOption
& itemListStyleOption
= styleOption();
124 // Blend the unhovered and hovered pixmap if the hovering
125 // animation is ongoing
126 if (hoverOpacity() < 1.0) {
127 drawPixmap(painter
, m_pixmap
);
130 const qreal opacity
= painter
->opacity();
131 painter
->setOpacity(hoverOpacity() * opacity
);
132 drawPixmap(painter
, m_hoverPixmap
);
133 painter
->setOpacity(opacity
);
135 drawPixmap(painter
, m_pixmap
);
138 painter
->setFont(itemListStyleOption
.font
);
139 painter
->setPen(textColor());
140 const TextInfo
* textInfo
= m_textInfo
.value("name");
141 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
143 bool clipAdditionalInfoBounds
= false;
144 if (m_supportsItemExpanding
) {
145 // Prevent a possible overlapping of the additional-information texts
146 // with the icon. This can happen if the user has minimized the width
147 // of the name-column to a very small value.
148 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
149 if (textInfo
->pos
.x() + columnWidth("name") > minX
) {
150 clipAdditionalInfoBounds
= true;
152 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
156 painter
->setPen(m_additionalInfoTextColor
);
157 painter
->setFont(itemListStyleOption
.font
);
159 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
160 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
161 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
164 if (!m_rating
.isNull()) {
165 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
166 QPointF pos
= ratingTextInfo
->pos
;
167 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
168 if (align
& Qt::AlignHCenter
) {
169 pos
.rx() += (size().width() - m_rating
.width()) / 2;
171 painter
->drawPixmap(pos
, m_rating
);
174 if (clipAdditionalInfoBounds
) {
178 #ifdef KFILEITEMLISTWIDGET_DEBUG
179 painter
->setBrush(Qt::NoBrush
);
180 painter
->setPen(Qt::green
);
181 painter
->drawRect(m_iconRect
);
183 painter
->setPen(Qt::red
);
184 painter
->drawText(QPointF(0, itemListStyleOption
.fontMetrics
.height()), QString::number(index()));
185 painter
->drawRect(rect());
189 QRectF
KFileItemListWidget::iconRect() const
191 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
195 QRectF
KFileItemListWidget::textRect() const
197 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
201 QRectF
KFileItemListWidget::textFocusRect() const
203 // In the compact- and details-layout a larger textRect() is returned to be aligned
204 // with the iconRect(). This is useful to have a larger selection/hover-area
205 // when having a quite large icon size but only one line of text. Still the
206 // focus rectangle should be shown as narrow as possible around the text.
208 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
211 case CompactLayout
: {
212 QRectF rect
= m_textRect
;
213 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
214 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
215 rect
.setTop(topText
->pos
.y());
216 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
220 case DetailsLayout
: {
221 QRectF rect
= m_textRect
;
222 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
223 rect
.setTop(textInfo
->pos
.y());
224 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
235 QRectF
KFileItemListWidget::expansionToggleRect() const
237 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
238 return m_isExpandable
? m_expansionArea
: QRectF();
241 QRectF
KFileItemListWidget::selectionToggleRect() const
243 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
245 const int iconHeight
= styleOption().iconSize
;
247 int toggleSize
= KIconLoader::SizeSmall
;
248 if (iconHeight
>= KIconLoader::SizeEnormous
) {
249 toggleSize
= KIconLoader::SizeMedium
;
250 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
251 toggleSize
= KIconLoader::SizeSmallMedium
;
254 QPointF pos
= iconRect().topLeft();
256 // If the selection toggle has a very small distance to the
257 // widget borders, the size of the selection toggle will get
258 // increased to prevent an accidental clicking of the item
259 // when trying to hit the toggle.
260 const int widgetHeight
= size().height();
261 const int widgetWidth
= size().width();
262 const int minMargin
= 2;
264 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
265 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
266 toggleSize
= widgetHeight
;
269 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
270 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
271 toggleSize
= widgetWidth
;
275 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
278 QSizeF
KFileItemListWidget::itemSizeHint(int index
, const KItemListView
* view
)
280 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
281 const KItemListStyleOption
& option
= view
->styleOption();
282 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
284 switch (static_cast<const KFileItemListView
*>(view
)->itemLayout()) {
286 const QString text
= KStringHandler::preProcessWrap(values
["name"].toString());
288 const qreal itemWidth
= view
->itemSize().width();
289 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
292 // Calculate the number of lines required for wrapping the name
293 QTextOption
textOption(Qt::AlignHCenter
);
294 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
296 qreal textHeight
= 0;
297 QTextLayout
layout(text
, option
.font
);
298 layout
.setTextOption(textOption
);
299 layout
.beginLayout();
300 while ((line
= layout
.createLine()).isValid()) {
301 line
.setLineWidth(maxWidth
);
302 line
.naturalTextWidth();
303 textHeight
+= line
.height();
307 // Add one line for each additional information
308 textHeight
+= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
310 const qreal maxTextHeight
= option
.maxTextSize
.height();
311 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
312 textHeight
= maxTextHeight
;
315 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
318 case CompactLayout
: {
319 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
320 // to show all roles without horizontal clipping.
321 qreal maximumRequiredWidth
= 0.0;
323 foreach (const QByteArray
& role
, view
->visibleRoles()) {
324 const QString text
= KFileItemListWidget::roleText(role
, values
);
325 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
326 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
329 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
330 const qreal maxWidth
= option
.maxTextSize
.width();
331 if (maxWidth
> 0 && width
> maxWidth
) {
334 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
335 return QSizeF(width
, height
);
338 case DetailsLayout
: {
339 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
340 return QSizeF(-1, height
);
351 qreal
KFileItemListWidget::preferredRoleColumnWidth(const QByteArray
& role
,
353 const KItemListView
* view
)
356 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
357 const KItemListStyleOption
& option
= view
->styleOption();
359 const QString text
= KFileItemListWidget::roleText(role
, values
);
360 qreal width
= columnPadding(option
);
362 if (role
== "rating") {
363 width
+= preferredRatingSize(option
).width();
365 width
+= option
.fontMetrics
.width(text
);
367 if (role
== "name") {
368 // Increase the width by the expansion-toggle and the current expansion level
369 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
370 width
+= option
.padding
+ (expandedParentsCount
+ 1) * view
->itemSize().height() + KIconLoader::SizeSmall
;
372 // Increase the width by the required space for the icon
373 width
+= option
.padding
* 2 + option
.iconSize
;
380 void KFileItemListWidget::invalidateCache()
382 m_dirtyLayout
= true;
383 m_dirtyContent
= true;
386 void KFileItemListWidget::refreshCache()
390 void KFileItemListWidget::setTextColor(const QColor
& color
)
392 if (color
!= m_customTextColor
) {
393 m_customTextColor
= color
;
394 updateAdditionalInfoTextColor();
399 QColor
KFileItemListWidget::textColor() const
401 if (m_customTextColor
.isValid() && !isSelected()) {
402 return m_customTextColor
;
405 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
406 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: QPalette::Text
;
407 return styleOption().palette
.brush(group
, role
).color();
410 void KFileItemListWidget::setOverlay(const QPixmap
& overlay
)
413 m_dirtyContent
= true;
417 QPixmap
KFileItemListWidget::overlay() const
422 void KFileItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
423 const QSet
<QByteArray
>& roles
)
427 m_dirtyContent
= true;
429 QSet
<QByteArray
> dirtyRoles
;
430 if (roles
.isEmpty()) {
431 dirtyRoles
= visibleRoles().toSet();
432 dirtyRoles
.insert("iconPixmap");
433 dirtyRoles
.insert("iconName");
438 QSetIterator
<QByteArray
> it(dirtyRoles
);
439 while (it
.hasNext()) {
440 const QByteArray
& role
= it
.next();
441 m_dirtyContentRoles
.insert(role
);
445 void KFileItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
446 const QList
<QByteArray
>& previous
)
449 m_sortedVisibleRoles
= current
;
450 m_dirtyLayout
= true;
453 void KFileItemListWidget::columnWidthChanged(const QByteArray
& role
,
460 m_dirtyLayout
= true;
463 void KFileItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
464 const KItemListStyleOption
& previous
)
468 updateAdditionalInfoTextColor();
469 m_dirtyLayout
= true;
472 void KFileItemListWidget::hoveredChanged(bool hovered
)
475 m_dirtyLayout
= true;
478 void KFileItemListWidget::selectedChanged(bool selected
)
481 updateAdditionalInfoTextColor();
484 void KFileItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
488 m_dirtyLayout
= true;
491 void KFileItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
495 QGraphicsView
* parent
= scene()->views()[0];
496 if (current
.isEmpty() || !parent
|| current
!= "name") {
498 emit
roleEditingCanceled(index(), current
, data().value(current
));
499 m_roleEditor
->deleteLater();
505 Q_ASSERT(!m_roleEditor
);
507 const TextInfo
* textInfo
= m_textInfo
.value("name");
509 m_roleEditor
= new KItemListRoleEditor(parent
);
510 m_roleEditor
->setIndex(index());
511 m_roleEditor
->setRole(current
);
513 const QString text
= data().value(current
).toString();
514 m_roleEditor
->setPlainText(text
);
516 QTextOption textOption
= textInfo
->staticText
.textOption();
517 m_roleEditor
->document()->setDefaultTextOption(textOption
);
519 // Select the text without MIME-type extension
520 int selectionLength
= text
.length();
522 const QString extension
= KMimeType::extractKnownExtension(text
);
523 if (!extension
.isEmpty()) {
524 selectionLength
-= extension
.length() + 1;
527 if (selectionLength
> 0) {
528 QTextCursor cursor
= m_roleEditor
->textCursor();
529 cursor
.movePosition(QTextCursor::StartOfBlock
);
530 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, selectionLength
);
531 m_roleEditor
->setTextCursor(cursor
);
534 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
535 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
536 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
537 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
539 // Adjust the geometry of the editor
540 QRectF rect
= roleEditingRect(current
);
541 const int frameWidth
= m_roleEditor
->frameWidth();
542 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
543 rect
.translate(pos());
544 if (rect
.right() > parent
->width()) {
545 rect
.setWidth(parent
->width() - rect
.left());
547 m_roleEditor
->setGeometry(rect
.toRect());
548 m_roleEditor
->show();
549 m_roleEditor
->setFocus();
552 void KFileItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
555 setEditedRole(QByteArray());
556 Q_ASSERT(!m_roleEditor
);
559 KItemListWidget::resizeEvent(event
);
561 m_dirtyLayout
= true;
564 void KFileItemListWidget::showEvent(QShowEvent
* event
)
566 KItemListWidget::showEvent(event
);
568 // Listen to changes of the clipboard to mark the item as cut/uncut
569 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
571 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
572 m_isCut
= clipboard
->isCut(itemUrl
);
574 connect(clipboard
, SIGNAL(cutItemsChanged()),
575 this, SLOT(slotCutItemsChanged()));
578 void KFileItemListWidget::hideEvent(QHideEvent
* event
)
580 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
581 this, SLOT(slotCutItemsChanged()));
583 KItemListWidget::hideEvent(event
);
586 void KFileItemListWidget::slotCutItemsChanged()
588 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
589 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
590 if (m_isCut
!= isCut
) {
592 m_pixmap
= QPixmap();
593 m_dirtyContent
= true;
598 void KFileItemListWidget::slotRoleEditingCanceled(int index
,
599 const QByteArray
& role
,
600 const QVariant
& value
)
602 m_roleEditor
->deleteLater();
604 emit
roleEditingCanceled(index
, role
, value
);
605 setEditedRole(QByteArray());
608 void KFileItemListWidget::slotRoleEditingFinished(int index
,
609 const QByteArray
& role
,
610 const QVariant
& value
)
612 m_roleEditor
->deleteLater();
614 emit
roleEditingFinished(index
, role
, value
);
615 setEditedRole(QByteArray());
618 void KFileItemListWidget::triggerCacheRefreshing()
620 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
626 const QHash
<QByteArray
, QVariant
> values
= data();
627 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
628 m_isHidden
= values
["name"].toString().startsWith(QLatin1Char('.'));
630 updateExpansionArea();
634 m_dirtyLayout
= false;
635 m_dirtyContent
= false;
636 m_dirtyContentRoles
.clear();
639 void KFileItemListWidget::updateExpansionArea()
641 if (m_supportsItemExpanding
) {
642 const QHash
<QByteArray
, QVariant
> values
= data();
643 Q_ASSERT(values
.contains("expandedParentsCount"));
644 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
645 if (expandedParentsCount
>= 0) {
646 const qreal widgetHeight
= size().height();
647 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
648 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
650 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
655 m_expansionArea
= QRectF();
658 void KFileItemListWidget::updatePixmapCache()
660 // Precondition: Requires already updated m_textPos values to calculate
661 // the remaining height when the alignment is vertical.
663 const QSizeF widgetSize
= size();
664 const bool iconOnTop
= (m_layout
== IconsLayout
);
665 const KItemListStyleOption
& option
= styleOption();
666 const qreal padding
= option
.padding
;
668 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
669 const int maxIconHeight
= option
.iconSize
;
671 const QHash
<QByteArray
, QVariant
> values
= data();
673 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
674 if (!updatePixmap
&& m_dirtyContent
) {
675 updatePixmap
= m_dirtyContentRoles
.isEmpty()
676 || m_dirtyContentRoles
.contains("iconPixmap")
677 || m_dirtyContentRoles
.contains("iconName")
678 || m_dirtyContentRoles
.contains("iconOverlays");
682 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
683 if (m_pixmap
.isNull()) {
684 // Use the icon that fits to the MIME-type
685 QString iconName
= values
["iconName"].toString();
686 if (iconName
.isEmpty()) {
687 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
688 // use a generic icon as fallback
689 iconName
= QLatin1String("unknown");
691 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
692 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
693 // A custom pixmap has been applied. Assure that the pixmap
694 // is scaled to the maximum available size.
695 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
698 const QStringList overlays
= values
["iconOverlays"].toStringList();
700 // Strangely KFileItem::overlays() returns empty string-values, so
701 // we need to check first whether an overlay must be drawn at all.
702 // It is more efficient to do it here, as KIconLoader::drawOverlays()
703 // assumes that an overlay will be drawn and has some additional
705 foreach (const QString
& overlay
, overlays
) {
706 if (!overlay
.isEmpty()) {
707 // There is at least one overlay, draw all overlays above m_pixmap
708 // and cancel the check
709 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
715 applyCutEffect(m_pixmap
);
719 applyHiddenEffect(m_pixmap
);
723 if (!m_overlay
.isNull()) {
724 QPainter
painter(&m_pixmap
);
725 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
728 int scaledIconSize
= 0;
730 const TextInfo
* textInfo
= m_textInfo
.value("name");
731 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
733 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
734 const qreal requiredTextHeight
= textRowsCount
* option
.fontMetrics
.height();
735 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
736 widgetSize
.height() - 2 * padding
: maxIconHeight
;
739 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
740 const int maxScaledIconHeight
= scaledIconSize
;
742 m_scaledPixmapSize
= m_pixmap
.size();
743 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
746 // Center horizontally and align on bottom within the icon-area
747 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
748 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
750 // Center horizontally and vertically within the icon-area
751 const TextInfo
* textInfo
= m_textInfo
.value("name");
752 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
753 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
754 m_pixmapPos
.setY(padding
755 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
758 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
760 // Prepare the pixmap that is used when the item gets hovered
762 m_hoverPixmap
= m_pixmap
;
763 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
764 // In the KIconLoader terminology, active = hover.
765 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
766 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
768 m_hoverPixmap
= m_pixmap
;
770 } else if (hoverOpacity() <= 0.0) {
771 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
772 m_hoverPixmap
= QPixmap();
776 void KFileItemListWidget::updateTextsCache()
778 QTextOption textOption
;
781 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
782 textOption
.setAlignment(Qt::AlignHCenter
);
786 textOption
.setAlignment(Qt::AlignLeft
);
787 textOption
.setWrapMode(QTextOption::NoWrap
);
794 qDeleteAll(m_textInfo
);
796 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
797 TextInfo
* textInfo
= new TextInfo();
798 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
799 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
800 textInfo
->staticText
.setTextOption(textOption
);
801 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
805 case IconsLayout
: updateIconsLayoutTextCache(); break;
806 case CompactLayout
: updateCompactLayoutTextCache(); break;
807 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
808 default: Q_ASSERT(false); break;
811 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
812 if (ratingTextInfo
) {
813 // The text of the rating-role has been set to empty to get
814 // replaced by a rating-image showing the rating as stars.
815 const KItemListStyleOption
& option
= styleOption();
816 QSizeF ratingSize
= preferredRatingSize(option
);
818 const qreal availableWidth
= (m_layout
== DetailsLayout
)
819 ? columnWidth("rating") - columnPadding(option
)
820 : m_textRect
.width();
821 if (ratingSize
.width() > availableWidth
) {
822 ratingSize
.rwidth() = availableWidth
;
824 m_rating
= QPixmap(ratingSize
.toSize());
825 m_rating
.fill(Qt::transparent
);
827 QPainter
painter(&m_rating
);
828 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
829 const int rating
= data().value("rating").toInt();
830 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
831 } else if (!m_rating
.isNull()) {
832 m_rating
= QPixmap();
836 void KFileItemListWidget::updateIconsLayoutTextCache()
843 // might get wrapped above
848 const QHash
<QByteArray
, QVariant
> values
= data();
850 const KItemListStyleOption
& option
= styleOption();
851 const qreal padding
= option
.padding
;
852 const qreal maxWidth
= size().width() - 2 * padding
;
853 const qreal widgetHeight
= size().height();
854 const qreal lineSpacing
= option
.fontMetrics
.lineSpacing();
856 // Initialize properties for the "name" role. It will be used as anchor
857 // for initializing the position of the other roles.
858 TextInfo
* nameTextInfo
= m_textInfo
.value("name");
859 const QString nameText
= KStringHandler::preProcessWrap(values
["name"].toString());
860 nameTextInfo
->staticText
.setText(nameText
);
862 // Calculate the number of lines required for the name and the required width
864 qreal nameHeight
= 0;
867 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
868 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
870 QTextLayout
layout(nameTextInfo
->staticText
.text(), option
.font
);
871 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
872 layout
.beginLayout();
873 int nameLineIndex
= 0;
874 while ((line
= layout
.createLine()).isValid()) {
875 line
.setLineWidth(maxWidth
);
876 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
877 nameHeight
+= line
.height();
880 if (nameLineIndex
== maxNameLines
) {
881 // The maximum number of textlines has been reached. If this is
882 // the case provide an elided text if necessary.
883 const int textLength
= line
.textStart() + line
.textLength();
884 if (textLength
< nameText
.length()) {
885 // Elide the last line of the text
886 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
887 lastTextLine
= option
.fontMetrics
.elidedText(lastTextLine
,
889 line
.naturalTextWidth() - 1);
890 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
891 nameTextInfo
->staticText
.setText(elidedText
);
898 // Use one line for each additional information
899 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
900 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
902 additionalRolesCount
* lineSpacing
-
904 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
905 nameTextInfo
->pos
.y(),
909 // Calculate the position for each additional information
910 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
911 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
912 if (role
== "name") {
916 const QString text
= roleText(role
, values
);
917 TextInfo
* textInfo
= m_textInfo
.value(role
);
918 textInfo
->staticText
.setText(text
);
920 qreal requiredWidth
= 0;
922 QTextLayout
layout(text
, option
.font
);
923 QTextOption textOption
;
924 textOption
.setWrapMode(QTextOption::NoWrap
);
925 layout
.setTextOption(textOption
);
927 layout
.beginLayout();
928 QTextLine textLine
= layout
.createLine();
929 if (textLine
.isValid()) {
930 textLine
.setLineWidth(maxWidth
);
931 requiredWidth
= textLine
.naturalTextWidth();
932 if (requiredWidth
> maxWidth
) {
933 const QString elidedText
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
934 textInfo
->staticText
.setText(elidedText
);
935 requiredWidth
= option
.fontMetrics
.width(elidedText
);
940 textInfo
->pos
= QPointF(padding
, y
);
941 textInfo
->staticText
.setTextWidth(maxWidth
);
943 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
944 m_textRect
|= textRect
;
949 // Add a padding to the text rectangle
950 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
953 void KFileItemListWidget::updateCompactLayoutTextCache()
955 // +------+ Name role
956 // | Icon | Additional role 1
957 // +------+ Additional role 2
959 const QHash
<QByteArray
, QVariant
> values
= data();
961 const KItemListStyleOption
& option
= styleOption();
962 const qreal widgetHeight
= size().height();
963 const qreal lineSpacing
= option
.fontMetrics
.lineSpacing();
964 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
965 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
967 qreal maximumRequiredTextWidth
= 0;
968 const qreal x
= option
.padding
* 3 + scaledIconSize
;
969 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
970 const qreal maxWidth
= size().width() - x
- option
.padding
;
971 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
972 const QString text
= roleText(role
, values
);
973 TextInfo
* textInfo
= m_textInfo
.value(role
);
974 textInfo
->staticText
.setText(text
);
976 qreal requiredWidth
= option
.fontMetrics
.width(text
);
977 if (requiredWidth
> maxWidth
) {
978 requiredWidth
= maxWidth
;
979 const QString elidedText
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
980 textInfo
->staticText
.setText(elidedText
);
983 textInfo
->pos
= QPointF(x
, y
);
984 textInfo
->staticText
.setTextWidth(maxWidth
);
986 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
991 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
994 void KFileItemListWidget::updateDetailsLayoutTextCache()
996 // Precondition: Requires already updated m_expansionArea
997 // to determine the left position.
1000 // | Icon | Name role Additional role 1 Additional role 2
1002 m_textRect
= QRectF();
1004 const KItemListStyleOption
& option
= styleOption();
1005 const QHash
<QByteArray
, QVariant
> values
= data();
1007 const qreal widgetHeight
= size().height();
1008 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1009 const int fontHeight
= option
.fontMetrics
.height();
1011 const qreal columnWidthInc
= columnPadding(option
);
1012 qreal firstColumnInc
= scaledIconSize
;
1013 if (m_supportsItemExpanding
) {
1014 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1016 firstColumnInc
+= option
.padding
;
1019 qreal x
= firstColumnInc
;
1020 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1022 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1023 const RoleType type
= roleType(role
);
1025 QString text
= roleText(role
, values
);
1027 // Elide the text in case it does not fit into the available column-width
1028 qreal requiredWidth
= option
.fontMetrics
.width(text
);
1029 const qreal roleWidth
= columnWidth(role
);
1030 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1032 availableTextWidth
-= firstColumnInc
;
1035 if (requiredWidth
> availableTextWidth
) {
1036 text
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1037 requiredWidth
= option
.fontMetrics
.width(text
);
1040 TextInfo
* textInfo
= m_textInfo
.value(role
);
1041 textInfo
->staticText
.setText(text
);
1042 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1047 const qreal textWidth
= option
.extendedSelectionRegion
1048 ? size().width() - textInfo
->pos
.x()
1049 : requiredWidth
+ 2 * option
.padding
;
1050 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1051 textWidth
, size().height());
1053 // The column after the name should always be aligned on the same x-position independent
1054 // from the expansion-level shown in the name column
1055 x
-= firstColumnInc
;
1059 // The values for the size should be right aligned
1060 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1069 void KFileItemListWidget::updateAdditionalInfoTextColor()
1072 if (m_customTextColor
.isValid()) {
1073 c1
= m_customTextColor
;
1074 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1075 c1
= styleOption().palette
.highlightedText().color();
1077 c1
= styleOption().palette
.text().color();
1080 // For the color of the additional info the inactive text color
1081 // is not used as this might lead to unreadable text for some color schemes. Instead
1082 // the text color c1 is slightly mixed with the background color.
1083 const QColor c2
= styleOption().palette
.base().color();
1085 const int p2
= 100 - p1
;
1086 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1087 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1088 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1091 void KFileItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1093 if (m_scaledPixmapSize
!= pixmap
.size()) {
1094 QPixmap scaledPixmap
= pixmap
;
1095 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1096 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1098 #ifdef KFILEITEMLISTWIDGET_DEBUG
1099 painter
->setPen(Qt::blue
);
1100 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1103 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1107 void KFileItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1109 const int siblingSize
= size().height();
1110 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1111 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1113 QStyleOption option
;
1114 bool isItemSibling
= true;
1116 const QBitArray siblings
= siblingsInformation();
1117 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1118 option
.rect
= siblingRect
;
1119 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1121 if (isItemSibling
) {
1122 option
.state
|= QStyle::State_Item
;
1123 if (m_isExpandable
) {
1124 option
.state
|= QStyle::State_Children
;
1126 if (data()["isExpanded"].toBool()) {
1127 option
.state
|= QStyle::State_Open
;
1129 isItemSibling
= false;
1132 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1134 siblingRect
.translate(-siblingRect
.width(), 0);
1138 QRectF
KFileItemListWidget::roleEditingRect(const QByteArray
& role
) const
1140 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1145 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1146 if (m_layout
== DetailsLayout
) {
1147 rect
.setWidth(columnWidth(role
) - rect
.x());
1153 QPixmap
KFileItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1155 const KIcon
icon(name
);
1158 if (size
<= KIconLoader::SizeSmall
) {
1159 requestedSize
= KIconLoader::SizeSmall
;
1160 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1161 requestedSize
= KIconLoader::SizeSmallMedium
;
1162 } else if (size
<= KIconLoader::SizeMedium
) {
1163 requestedSize
= KIconLoader::SizeMedium
;
1164 } else if (size
<= KIconLoader::SizeLarge
) {
1165 requestedSize
= KIconLoader::SizeLarge
;
1166 } else if (size
<= KIconLoader::SizeHuge
) {
1167 requestedSize
= KIconLoader::SizeHuge
;
1168 } else if (size
<= KIconLoader::SizeEnormous
) {
1169 requestedSize
= KIconLoader::SizeEnormous
;
1170 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1171 requestedSize
= KIconLoader::SizeEnormous
* 2;
1173 requestedSize
= size
;
1176 QPixmap pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1177 if (requestedSize
!= size
) {
1178 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1184 void KFileItemListWidget::applyCutEffect(QPixmap
& pixmap
)
1186 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1187 pixmap
= effect
->apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1190 void KFileItemListWidget::applyHiddenEffect(QPixmap
& pixmap
)
1192 KIconEffect::semiTransparent(pixmap
);
1195 KFileItemListWidget::RoleType
KFileItemListWidget::roleType(const QByteArray
& role
)
1197 static QHash
<QByteArray
, RoleType
> rolesHash
;
1198 if (rolesHash
.isEmpty()) {
1199 rolesHash
.insert("name", Name
);
1200 rolesHash
.insert("size", Size
);
1201 rolesHash
.insert("date", Date
);
1202 rolesHash
.insert("rating", Rating
);
1205 return rolesHash
.value(role
, Generic
);
1208 QString
KFileItemListWidget::roleText(const QByteArray
& role
, const QHash
<QByteArray
, QVariant
>& values
)
1211 const QVariant roleValue
= values
.value(role
);
1213 switch (roleType(role
)) {
1215 if (values
.value("isDir").toBool()) {
1216 // The item represents a directory. Show the number of sub directories
1217 // instead of the file size of the directory.
1218 if (!roleValue
.isNull()) {
1219 const int count
= roleValue
.toInt();
1221 text
= i18nc("@item:intable", "Unknown");
1223 text
= i18ncp("@item:intable", "%1 item", "%1 items", count
);
1227 const KIO::filesize_t size
= roleValue
.value
<KIO::filesize_t
>();
1228 text
= KGlobal::locale()->formatByteSize(size
);
1234 const QDateTime dateTime
= roleValue
.toDateTime();
1235 text
= KGlobal::locale()->formatDateTime(dateTime
);
1240 // Always use an empty text, as the rating is shown by the image m_rating.
1245 text
= roleValue
.toString();
1256 QSizeF
KFileItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1258 const qreal height
= option
.fontMetrics
.ascent();
1259 return QSizeF(height
* 5, height
);
1262 qreal
KFileItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1264 return option
.padding
* 6;
1267 #include "kfileitemlistwidget.moc"