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 "kfileitemclipboard_p.h"
23 #include "kfileitemlistview.h"
24 #include "kfileitemmodel.h"
25 #include "kpixmapmodifier_p.h"
28 #include <KIconEffect>
29 #include <KIconLoader>
31 #include <kratingpainter.h>
32 #include <KStringHandler>
35 #include <QFontMetricsF>
36 #include <QGraphicsSceneResizeEvent>
38 #include <QStyleOption>
39 #include <QTextLayout>
42 // #define KFILEITEMLISTWIDGET_DEBUG
44 KFileItemListWidget::KFileItemListWidget(QGraphicsItem
* parent
) :
45 KItemListWidget(parent
),
48 m_isExpandable(false),
49 m_supportsItemExpanding(false),
52 m_dirtyContentRoles(),
53 m_layout(IconsLayout
),
61 m_sortedVisibleRoles(),
64 m_additionalInfoTextColor(),
70 KFileItemListWidget::~KFileItemListWidget()
72 qDeleteAll(m_textInfo
);
76 void KFileItemListWidget::setLayout(Layout layout
)
78 if (m_layout
!= layout
) {
81 updateAdditionalInfoTextColor();
86 KFileItemListWidget::Layout
KFileItemListWidget::layout() const
91 void KFileItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
93 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
94 m_supportsItemExpanding
= supportsItemExpanding
;
100 bool KFileItemListWidget::supportsItemExpanding() const
102 return m_supportsItemExpanding
;
105 void KFileItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
107 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
109 KItemListWidget::paint(painter
, option
, widget
);
111 if (!m_expansionArea
.isEmpty()) {
112 drawSiblingsInformation(painter
);
115 const KItemListStyleOption
& itemListStyleOption
= styleOption();
117 // Blend the unhovered and hovered pixmap if the hovering
118 // animation is ongoing
119 if (hoverOpacity() < 1.0) {
120 drawPixmap(painter
, m_pixmap
);
123 const qreal opacity
= painter
->opacity();
124 painter
->setOpacity(hoverOpacity() * opacity
);
125 drawPixmap(painter
, m_hoverPixmap
);
126 painter
->setOpacity(opacity
);
128 drawPixmap(painter
, m_pixmap
);
131 painter
->setFont(itemListStyleOption
.font
);
132 painter
->setPen(textColor());
133 const TextInfo
* textInfo
= m_textInfo
.value("name");
134 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
136 bool clipAdditionalInfoBounds
= false;
137 if (m_supportsItemExpanding
) {
138 // Prevent a possible overlapping of the additional-information texts
139 // with the icon. This can happen if the user has minimized the width
140 // of the name-column to a very small value.
141 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
142 if (textInfo
->pos
.x() + columnWidth("name") > minX
) {
143 clipAdditionalInfoBounds
= true;
145 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
149 painter
->setPen(m_additionalInfoTextColor
);
150 painter
->setFont(itemListStyleOption
.font
);
152 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
153 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
154 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
157 if (!m_rating
.isNull()) {
158 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
159 QPointF pos
= ratingTextInfo
->pos
;
160 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
161 if (align
& Qt::AlignHCenter
) {
162 pos
.rx() += (size().width() - m_rating
.width()) / 2;
164 painter
->drawPixmap(pos
, m_rating
);
167 if (clipAdditionalInfoBounds
) {
171 #ifdef KFILEITEMLISTWIDGET_DEBUG
172 painter
->setBrush(Qt::NoBrush
);
173 painter
->setPen(Qt::green
);
174 painter
->drawRect(m_iconRect
);
176 painter
->setPen(Qt::red
);
177 painter
->drawText(QPointF(0, itemListStyleOption
.fontMetrics
.height()), QString::number(index()));
178 painter
->drawRect(rect());
182 QRectF
KFileItemListWidget::iconRect() const
184 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
188 QRectF
KFileItemListWidget::textRect() const
190 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
194 QRectF
KFileItemListWidget::textFocusRect() const
196 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
197 if (m_layout
== CompactLayout
) {
198 // In the compact layout a larger textRect() is returned to be aligned
199 // with the iconRect(). This is useful to have a larger selection/hover-area
200 // when having a quite large icon size but only one line of text. Still the
201 // focus rectangle should be shown as narrow as possible around the text.
202 QRectF rect
= m_textRect
;
203 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
204 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
205 rect
.setTop(topText
->pos
.y());
206 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
212 QRectF
KFileItemListWidget::expansionToggleRect() const
214 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
215 return m_isExpandable
? m_expansionArea
: QRectF();
218 QRectF
KFileItemListWidget::selectionToggleRect() const
220 const_cast<KFileItemListWidget
*>(this)->triggerCacheRefreshing();
222 const int iconHeight
= styleOption().iconSize
;
224 int toggleSize
= KIconLoader::SizeSmall
;
225 if (iconHeight
>= KIconLoader::SizeEnormous
) {
226 toggleSize
= KIconLoader::SizeMedium
;
227 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
228 toggleSize
= KIconLoader::SizeSmallMedium
;
231 QPointF pos
= iconRect().topLeft();
233 // If the selection toggle has a very small distance to the
234 // widget borders, the size of the selection toggle will get
235 // increased to prevent an accidental clicking of the item
236 // when trying to hit the toggle.
237 const int widgetHeight
= size().height();
238 const int widgetWidth
= size().width();
239 const int minMargin
= 2;
241 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
242 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
243 toggleSize
= widgetHeight
;
246 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
247 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
248 toggleSize
= widgetWidth
;
252 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
255 QSizeF
KFileItemListWidget::itemSizeHint(int index
, const KItemListView
* view
)
257 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
258 const KItemListStyleOption
& option
= view
->styleOption();
259 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
261 switch (static_cast<const KFileItemListView
*>(view
)->itemLayout()) {
263 const QString text
= KStringHandler::preProcessWrap(values
["name"].toString());
265 const qreal maxWidth
= view
->itemSize().width() - 2 * option
.padding
;
268 // Calculate the number of lines required for wrapping the name
269 QTextOption
textOption(Qt::AlignHCenter
);
270 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
272 qreal textHeight
= 0;
273 QTextLayout
layout(text
, option
.font
);
274 layout
.setTextOption(textOption
);
275 layout
.beginLayout();
276 while ((line
= layout
.createLine()).isValid()) {
277 line
.setLineWidth(maxWidth
);
278 line
.naturalTextWidth();
279 textHeight
+= line
.height();
283 // Add one line for each additional information
284 const qreal height
= textHeight
+
285 additionalRolesCount
* option
.fontMetrics
.lineSpacing() +
288 return QSizeF(view
->itemSize().width(), height
);
291 case CompactLayout
: {
292 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
293 // to show all roles without horizontal clipping.
294 qreal maximumRequiredWidth
= 0.0;
296 foreach (const QByteArray
& role
, view
->visibleRoles()) {
297 const QString text
= KFileItemListWidget::roleText(role
, values
);
298 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
299 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
302 const qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
303 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
304 return QSizeF(width
, height
);
307 case DetailsLayout
: {
308 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
309 return QSizeF(-1, height
);
320 qreal
KFileItemListWidget::preferredRoleColumnWidth(const QByteArray
& role
,
322 const KItemListView
* view
)
325 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
326 const KItemListStyleOption
& option
= view
->styleOption();
328 const QString text
= KFileItemListWidget::roleText(role
, values
);
329 qreal width
= columnPadding(option
);
331 if (role
== "rating") {
332 width
+= preferredRatingSize(option
).width();
334 width
+= option
.fontMetrics
.width(text
);
336 if (role
== "name") {
337 // Increase the width by the expansion-toggle and the current expansion level
338 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
339 width
+= option
.padding
+ (expandedParentsCount
+ 1) * view
->itemSize().height() + KIconLoader::SizeSmall
;
341 // Increase the width by the required space for the icon
342 width
+= option
.padding
* 2 + option
.iconSize
;
349 void KFileItemListWidget::invalidateCache()
351 m_dirtyLayout
= true;
352 m_dirtyContent
= true;
355 void KFileItemListWidget::refreshCache()
359 void KFileItemListWidget::setTextColor(const QColor
& color
)
361 if (color
!= m_customTextColor
) {
362 m_customTextColor
= color
;
363 updateAdditionalInfoTextColor();
368 QColor
KFileItemListWidget::textColor() const
370 if (m_customTextColor
.isValid() && !isSelected()) {
371 return m_customTextColor
;
374 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
375 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: QPalette::Text
;
376 return styleOption().palette
.brush(group
, role
).color();
379 void KFileItemListWidget::setOverlay(const QPixmap
& overlay
)
382 m_dirtyContent
= true;
386 QPixmap
KFileItemListWidget::overlay() const
391 void KFileItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
392 const QSet
<QByteArray
>& roles
)
396 m_dirtyContent
= true;
398 QSet
<QByteArray
> dirtyRoles
;
399 if (roles
.isEmpty()) {
400 dirtyRoles
= visibleRoles().toSet();
401 dirtyRoles
.insert("iconPixmap");
402 dirtyRoles
.insert("iconName");
407 QSetIterator
<QByteArray
> it(dirtyRoles
);
408 while (it
.hasNext()) {
409 const QByteArray
& role
= it
.next();
410 m_dirtyContentRoles
.insert(role
);
414 void KFileItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
415 const QList
<QByteArray
>& previous
)
418 m_sortedVisibleRoles
= current
;
419 m_dirtyLayout
= true;
422 void KFileItemListWidget::columnWidthChanged(const QByteArray
& role
,
429 m_dirtyLayout
= true;
432 void KFileItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
433 const KItemListStyleOption
& previous
)
437 updateAdditionalInfoTextColor();
438 m_dirtyLayout
= true;
441 void KFileItemListWidget::hoveredChanged(bool hovered
)
444 m_dirtyLayout
= true;
447 void KFileItemListWidget::selectedChanged(bool selected
)
450 updateAdditionalInfoTextColor();
453 void KFileItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
457 m_dirtyLayout
= true;
461 void KFileItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
463 KItemListWidget::resizeEvent(event
);
464 m_dirtyLayout
= true;
467 void KFileItemListWidget::showEvent(QShowEvent
* event
)
469 KItemListWidget::showEvent(event
);
471 // Listen to changes of the clipboard to mark the item as cut/uncut
472 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
474 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
475 m_isCut
= clipboard
->isCut(itemUrl
);
477 connect(clipboard
, SIGNAL(cutItemsChanged()),
478 this, SLOT(slotCutItemsChanged()));
481 void KFileItemListWidget::hideEvent(QHideEvent
* event
)
483 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
484 this, SLOT(slotCutItemsChanged()));
486 KItemListWidget::hideEvent(event
);
489 void KFileItemListWidget::slotCutItemsChanged()
491 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
492 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
493 if (m_isCut
!= isCut
) {
495 m_pixmap
= QPixmap();
496 m_dirtyContent
= true;
501 void KFileItemListWidget::triggerCacheRefreshing()
503 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
509 const QHash
<QByteArray
, QVariant
> values
= data();
510 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
511 m_isHidden
= values
["name"].toString().startsWith(QLatin1Char('.'));
513 updateExpansionArea();
517 m_dirtyLayout
= false;
518 m_dirtyContent
= false;
519 m_dirtyContentRoles
.clear();
522 void KFileItemListWidget::updateExpansionArea()
524 if (m_supportsItemExpanding
) {
525 const QHash
<QByteArray
, QVariant
> values
= data();
526 Q_ASSERT(values
.contains("expandedParentsCount"));
527 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
528 if (expandedParentsCount
>= 0) {
529 const qreal widgetHeight
= size().height();
530 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
531 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
533 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
538 m_expansionArea
= QRectF();
541 void KFileItemListWidget::updatePixmapCache()
543 // Precondition: Requires already updated m_textPos values to calculate
544 // the remaining height when the alignment is vertical.
546 const QSizeF widgetSize
= size();
547 const bool iconOnTop
= (m_layout
== IconsLayout
);
548 const KItemListStyleOption
& option
= styleOption();
549 const qreal padding
= option
.padding
;
551 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
552 const int maxIconHeight
= option
.iconSize
;
554 const QHash
<QByteArray
, QVariant
> values
= data();
556 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
557 if (!updatePixmap
&& m_dirtyContent
) {
558 updatePixmap
= m_dirtyContentRoles
.isEmpty()
559 || m_dirtyContentRoles
.contains("iconPixmap")
560 || m_dirtyContentRoles
.contains("iconName")
561 || m_dirtyContentRoles
.contains("iconOverlays");
565 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
566 if (m_pixmap
.isNull()) {
567 // Use the icon that fits to the MIME-type
568 QString iconName
= values
["iconName"].toString();
569 if (iconName
.isEmpty()) {
570 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
571 // use a generic icon as fallback
572 iconName
= QLatin1String("unknown");
574 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
575 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
576 // A custom pixmap has been applied. Assure that the pixmap
577 // is scaled to the maximum available size.
578 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
581 const QStringList overlays
= values
["iconOverlays"].toStringList();
583 // Strangely KFileItem::overlays() returns empty string-values, so
584 // we need to check first whether an overlay must be drawn at all.
585 // It is more efficient to do it here, as KIconLoader::drawOverlays()
586 // assumes that an overlay will be drawn and has some additional
588 foreach (const QString
& overlay
, overlays
) {
589 if (!overlay
.isEmpty()) {
590 // There is at least one overlay, draw all overlays above m_pixmap
591 // and cancel the check
592 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
598 applyCutEffect(m_pixmap
);
602 applyHiddenEffect(m_pixmap
);
606 if (!m_overlay
.isNull()) {
607 QPainter
painter(&m_pixmap
);
608 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
611 int scaledIconSize
= 0;
613 const TextInfo
* textInfo
= m_textInfo
.value("name");
614 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
616 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
617 const qreal requiredTextHeight
= textRowsCount
* option
.fontMetrics
.height();
618 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
619 widgetSize
.height() - 2 * padding
: maxIconHeight
;
622 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
623 const int maxScaledIconHeight
= scaledIconSize
;
625 m_scaledPixmapSize
= m_pixmap
.size();
626 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
629 // Center horizontally and align on bottom within the icon-area
630 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
631 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
633 // Center horizontally and vertically within the icon-area
634 const TextInfo
* textInfo
= m_textInfo
.value("name");
635 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
636 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
637 m_pixmapPos
.setY(padding
638 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
641 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
643 // Prepare the pixmap that is used when the item gets hovered
645 m_hoverPixmap
= m_pixmap
;
646 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
647 // In the KIconLoader terminology, active = hover.
648 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
649 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
651 m_hoverPixmap
= m_pixmap
;
653 } else if (hoverOpacity() <= 0.0) {
654 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
655 m_hoverPixmap
= QPixmap();
659 void KFileItemListWidget::updateTextsCache()
661 QTextOption textOption
;
664 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
665 textOption
.setAlignment(Qt::AlignHCenter
);
669 textOption
.setAlignment(Qt::AlignLeft
);
670 textOption
.setWrapMode(QTextOption::NoWrap
);
677 qDeleteAll(m_textInfo
);
679 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
680 TextInfo
* textInfo
= new TextInfo();
681 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
682 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
683 textInfo
->staticText
.setTextOption(textOption
);
684 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
688 case IconsLayout
: updateIconsLayoutTextCache(); break;
689 case CompactLayout
: updateCompactLayoutTextCache(); break;
690 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
691 default: Q_ASSERT(false); break;
694 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
695 if (ratingTextInfo
) {
696 // The text of the rating-role has been set to empty to get
697 // replaced by a rating-image showing the rating as stars.
698 const KItemListStyleOption
& option
= styleOption();
699 QSizeF ratingSize
= preferredRatingSize(option
);
701 const qreal availableWidth
= (m_layout
== DetailsLayout
)
702 ? columnWidth("rating") - columnPadding(option
)
703 : m_textRect
.width();
704 if (ratingSize
.width() > availableWidth
) {
705 ratingSize
.rwidth() = availableWidth
;
707 m_rating
= QPixmap(ratingSize
.toSize());
708 m_rating
.fill(Qt::transparent
);
710 QPainter
painter(&m_rating
);
711 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
712 const int rating
= data().value("rating").toInt();
713 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
714 } else if (!m_rating
.isNull()) {
715 m_rating
= QPixmap();
719 void KFileItemListWidget::updateIconsLayoutTextCache()
726 // might get wrapped above
731 const QHash
<QByteArray
, QVariant
> values
= data();
733 const KItemListStyleOption
& option
= styleOption();
734 const qreal padding
= option
.padding
;
735 const qreal maxWidth
= size().width() - 2 * padding
;
736 const qreal widgetHeight
= size().height();
737 const qreal lineSpacing
= option
.fontMetrics
.lineSpacing();
739 // Initialize properties for the "name" role. It will be used as anchor
740 // for initializing the position of the other roles.
741 TextInfo
* nameTextInfo
= m_textInfo
.value("name");
742 nameTextInfo
->staticText
.setText(KStringHandler::preProcessWrap(values
["name"].toString()));
744 // Calculate the number of lines required for the name and the required width
746 qreal nameHeight
= 0;
749 QTextLayout
layout(nameTextInfo
->staticText
.text(), option
.font
);
750 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
751 layout
.beginLayout();
752 while ((line
= layout
.createLine()).isValid()) {
753 line
.setLineWidth(maxWidth
);
754 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
755 nameHeight
+= line
.height();
759 // Use one line for each additional information
760 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
761 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
762 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
764 additionalRolesCount
* lineSpacing
-
766 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
767 nameTextInfo
->pos
.y(),
771 // Calculate the position for each additional information
772 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
773 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
774 if (role
== "name") {
778 const QString text
= roleText(role
, values
);
779 TextInfo
* textInfo
= m_textInfo
.value(role
);
780 textInfo
->staticText
.setText(text
);
782 qreal requiredWidth
= 0;
784 QTextLayout
layout(text
, option
.font
);
785 QTextOption textOption
;
786 textOption
.setWrapMode(QTextOption::NoWrap
);
787 layout
.setTextOption(textOption
);
789 layout
.beginLayout();
790 QTextLine textLine
= layout
.createLine();
791 if (textLine
.isValid()) {
792 textLine
.setLineWidth(maxWidth
);
793 requiredWidth
= textLine
.naturalTextWidth();
794 if (requiredWidth
> maxWidth
) {
795 const QString elidedText
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
796 textInfo
->staticText
.setText(elidedText
);
797 requiredWidth
= option
.fontMetrics
.width(elidedText
);
802 textInfo
->pos
= QPointF(padding
, y
);
803 textInfo
->staticText
.setTextWidth(maxWidth
);
805 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
806 m_textRect
|= textRect
;
811 // Add a padding to the text rectangle
812 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
815 void KFileItemListWidget::updateCompactLayoutTextCache()
817 // +------+ Name role
818 // | Icon | Additional role 1
819 // +------+ Additional role 2
821 const QHash
<QByteArray
, QVariant
> values
= data();
823 const KItemListStyleOption
& option
= styleOption();
824 const qreal widgetHeight
= size().height();
825 const qreal lineSpacing
= option
.fontMetrics
.lineSpacing();
826 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
827 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
829 qreal maximumRequiredTextWidth
= 0;
830 const qreal x
= option
.padding
* 3 + scaledIconSize
;
831 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
832 const qreal maxWidth
= size().width() - x
- option
.padding
;
833 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
834 const QString text
= roleText(role
, values
);
835 TextInfo
* textInfo
= m_textInfo
.value(role
);
836 textInfo
->staticText
.setText(text
);
838 qreal requiredWidth
= option
.fontMetrics
.width(text
);
839 if (requiredWidth
> maxWidth
) {
840 requiredWidth
= maxWidth
;
841 const QString elidedText
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
842 textInfo
->staticText
.setText(elidedText
);
845 textInfo
->pos
= QPointF(x
, y
);
846 textInfo
->staticText
.setTextWidth(maxWidth
);
848 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
853 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
856 void KFileItemListWidget::updateDetailsLayoutTextCache()
858 // Precondition: Requires already updated m_expansionArea
859 // to determine the left position.
862 // | Icon | Name role Additional role 1 Additional role 2
864 m_textRect
= QRectF();
866 const KItemListStyleOption
& option
= styleOption();
867 const QHash
<QByteArray
, QVariant
> values
= data();
869 const qreal widgetHeight
= size().height();
870 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
871 const int fontHeight
= option
.fontMetrics
.height();
873 const qreal columnWidthInc
= columnPadding(option
);
874 qreal firstColumnInc
= scaledIconSize
;
875 if (m_supportsItemExpanding
) {
876 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
878 firstColumnInc
+= option
.padding
;
881 qreal x
= firstColumnInc
;
882 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
884 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
885 const RoleType type
= roleType(role
);
887 QString text
= roleText(role
, values
);
889 // Elide the text in case it does not fit into the available column-width
890 qreal requiredWidth
= option
.fontMetrics
.width(text
);
891 const qreal roleWidth
= columnWidth(role
);
892 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
894 availableTextWidth
-= firstColumnInc
;
897 if (requiredWidth
> availableTextWidth
) {
898 text
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
899 requiredWidth
= option
.fontMetrics
.width(text
);
902 TextInfo
* textInfo
= m_textInfo
.value(role
);
903 textInfo
->staticText
.setText(text
);
904 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
909 const qreal textWidth
= option
.extendedSelectionRegion
910 ? size().width() - textInfo
->pos
.x()
911 : requiredWidth
+ 2 * option
.padding
;
912 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
913 textWidth
, size().height());
915 // The column after the name should always be aligned on the same x-position independent
916 // from the expansion-level shown in the name column
921 // The values for the size should be right aligned
922 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
931 void KFileItemListWidget::updateAdditionalInfoTextColor()
934 if (m_customTextColor
.isValid()) {
935 c1
= m_customTextColor
;
936 } else if (isSelected() && m_layout
!= DetailsLayout
) {
937 c1
= styleOption().palette
.highlightedText().color();
939 c1
= styleOption().palette
.text().color();
942 // For the color of the additional info the inactive text color
943 // is not used as this might lead to unreadable text for some color schemes. Instead
944 // the text color c1 is slightly mixed with the background color.
945 const QColor c2
= styleOption().palette
.base().color();
947 const int p2
= 100 - p1
;
948 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
949 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
950 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
953 void KFileItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
955 if (m_scaledPixmapSize
!= pixmap
.size()) {
956 QPixmap scaledPixmap
= pixmap
;
957 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
958 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
960 #ifdef KFILEITEMLISTWIDGET_DEBUG
961 painter
->setPen(Qt::blue
);
962 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
965 painter
->drawPixmap(m_pixmapPos
, pixmap
);
969 void KFileItemListWidget::drawSiblingsInformation(QPainter
* painter
)
971 const int siblingSize
= size().height();
972 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
973 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
976 bool isItemSibling
= true;
978 const QBitArray siblings
= siblingsInformation();
979 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
980 option
.rect
= siblingRect
;
981 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
984 option
.state
|= QStyle::State_Item
;
985 if (m_isExpandable
) {
986 option
.state
|= QStyle::State_Children
;
988 if (data()["isExpanded"].toBool()) {
989 option
.state
|= QStyle::State_Open
;
991 isItemSibling
= false;
994 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
996 siblingRect
.translate(-siblingRect
.width(), 0);
1000 QPixmap
KFileItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1002 const KIcon
icon(name
);
1005 if (size
<= KIconLoader::SizeSmall
) {
1006 requestedSize
= KIconLoader::SizeSmall
;
1007 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1008 requestedSize
= KIconLoader::SizeSmallMedium
;
1009 } else if (size
<= KIconLoader::SizeMedium
) {
1010 requestedSize
= KIconLoader::SizeMedium
;
1011 } else if (size
<= KIconLoader::SizeLarge
) {
1012 requestedSize
= KIconLoader::SizeLarge
;
1013 } else if (size
<= KIconLoader::SizeHuge
) {
1014 requestedSize
= KIconLoader::SizeHuge
;
1015 } else if (size
<= KIconLoader::SizeEnormous
) {
1016 requestedSize
= KIconLoader::SizeEnormous
;
1017 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1018 requestedSize
= KIconLoader::SizeEnormous
* 2;
1020 requestedSize
= size
;
1023 QPixmap pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1024 if (requestedSize
!= size
) {
1025 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1031 void KFileItemListWidget::applyCutEffect(QPixmap
& pixmap
)
1033 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1034 pixmap
= effect
->apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1037 void KFileItemListWidget::applyHiddenEffect(QPixmap
& pixmap
)
1039 KIconEffect::semiTransparent(pixmap
);
1042 KFileItemListWidget::RoleType
KFileItemListWidget::roleType(const QByteArray
& role
)
1044 static QHash
<QByteArray
, RoleType
> rolesHash
;
1045 if (rolesHash
.isEmpty()) {
1046 rolesHash
.insert("name", Name
);
1047 rolesHash
.insert("size", Size
);
1048 rolesHash
.insert("date", Date
);
1049 rolesHash
.insert("rating", Rating
);
1052 return rolesHash
.value(role
, Generic
);
1055 QString
KFileItemListWidget::roleText(const QByteArray
& role
, const QHash
<QByteArray
, QVariant
>& values
)
1058 const QVariant roleValue
= values
.value(role
);
1060 switch (roleType(role
)) {
1062 if (values
.value("isDir").toBool()) {
1063 // The item represents a directory. Show the number of sub directories
1064 // instead of the file size of the directory.
1065 if (!roleValue
.isNull()) {
1066 const int count
= roleValue
.toInt();
1068 text
= i18nc("@item:intable", "Unknown");
1070 text
= i18ncp("@item:intable", "%1 item", "%1 items", count
);
1074 // Show the size in kilobytes (always round up)
1075 const KLocale
* locale
= KGlobal::locale();
1076 const int roundInc
= (locale
->binaryUnitDialect() == KLocale::MetricBinaryDialect
) ? 499 : 511;
1077 const KIO::filesize_t size
= roleValue
.value
<KIO::filesize_t
>() + roundInc
;
1078 text
= locale
->formatByteSize(size
, 0, KLocale::DefaultBinaryDialect
, KLocale::UnitKiloByte
);
1084 const QDateTime dateTime
= roleValue
.toDateTime();
1085 text
= KGlobal::locale()->formatDateTime(dateTime
);
1090 // Always use an empty text, as the rating is shown by the image m_rating.
1095 text
= roleValue
.toString();
1106 QSizeF
KFileItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1108 const qreal height
= option
.fontMetrics
.ascent();
1109 return QSizeF(height
* 5, height
);
1112 qreal
KFileItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1114 return option
.padding
* 6;
1117 #include "kfileitemlistwidget.moc"