]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemlistwidget.cpp
Icons view: Layout optimizations
[dolphin.git] / src / kitemviews / kfileitemlistwidget.cpp
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * *
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. *
8 * *
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. *
13 * *
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 ***************************************************************************/
19
20 #include "kfileitemlistwidget.h"
21
22 #include "kfileitemclipboard_p.h"
23 #include "kfileitemmodel.h"
24 #include "kitemlistview.h"
25 #include "kpixmapmodifier_p.h"
26
27 #include <KIcon>
28 #include <KIconEffect>
29 #include <KIconLoader>
30 #include <KLocale>
31 #include <KStringHandler>
32 #include <KDebug>
33
34 #include <QFontMetricsF>
35 #include <QGraphicsSceneResizeEvent>
36 #include <QPainter>
37 #include <QStyleOption>
38 #include <QTextLayout>
39 #include <QTextLine>
40
41 // #define KFILEITEMLISTWIDGET_DEBUG
42
43 KFileItemListWidget::KFileItemListWidget(QGraphicsItem* parent) :
44 KItemListWidget(parent),
45 m_isCut(false),
46 m_isHidden(false),
47 m_isExpandable(false),
48 m_dirtyLayout(true),
49 m_dirtyContent(true),
50 m_dirtyContentRoles(),
51 m_layout(IconsLayout),
52 m_pixmapPos(),
53 m_pixmap(),
54 m_scaledPixmapSize(),
55 m_iconRect(),
56 m_hoverPixmap(),
57 m_textPos(),
58 m_text(),
59 m_textRect(),
60 m_sortedVisibleRoles(),
61 m_expansionArea(),
62 m_customTextColor(),
63 m_additionalInfoTextColor(),
64 m_overlay()
65 {
66 for (int i = 0; i < TextIdCount; ++i) {
67 m_text[i].setTextFormat(Qt::PlainText);
68 m_text[i].setPerformanceHint(QStaticText::AggressiveCaching);
69 }
70 }
71
72 KFileItemListWidget::~KFileItemListWidget()
73 {
74 }
75
76 void KFileItemListWidget::setLayout(Layout layout)
77 {
78 if (m_layout != layout) {
79 m_layout = layout;
80 m_dirtyLayout = true;
81 updateAdditionalInfoTextColor();
82 update();
83 }
84 }
85
86 KFileItemListWidget::Layout KFileItemListWidget::layout() const
87 {
88 return m_layout;
89 }
90
91 void KFileItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
92 {
93 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
94
95 KItemListWidget::paint(painter, option, widget);
96
97 // Draw expansion toggle '>' or 'V'
98 if (m_isExpandable && !m_expansionArea.isEmpty()) {
99 QStyleOption arrowOption;
100 arrowOption.rect = m_expansionArea.toRect();
101 const QStyle::PrimitiveElement arrow = data()["isExpanded"].toBool()
102 ? QStyle::PE_IndicatorArrowDown : QStyle::PE_IndicatorArrowRight;
103 style()->drawPrimitive(arrow, &arrowOption, painter);
104 }
105
106 const KItemListStyleOption& itemListStyleOption = styleOption();
107 if (isHovered()) {
108 // Blend the unhovered and hovered pixmap if the hovering
109 // animation is ongoing
110 if (hoverOpacity() < 1.0) {
111 drawPixmap(painter, m_pixmap);
112 }
113
114 const qreal opacity = painter->opacity();
115 painter->setOpacity(hoverOpacity() * opacity);
116 drawPixmap(painter, m_hoverPixmap);
117 painter->setOpacity(opacity);
118 } else {
119 drawPixmap(painter, m_pixmap);
120 }
121
122 painter->setFont(itemListStyleOption.font);
123 painter->setPen(textColor());
124 painter->drawStaticText(m_textPos[Name], m_text[Name]);
125
126 bool clipAdditionalInfoBounds = false;
127 if (m_layout == DetailsLayout) {
128 // Prevent a possible overlapping of the additional-information texts
129 // with the icon. This can happen if the user has minimized the width
130 // of the name-column to a very small value.
131 const qreal minX = m_pixmapPos.x() + m_pixmap.width() + 4 * itemListStyleOption.margin;
132 if (m_textPos[Name + 1].x() < minX) {
133 clipAdditionalInfoBounds = true;
134 painter->save();
135 painter->setClipRect(minX, 0, size().width() - minX, size().height(), Qt::IntersectClip);
136 }
137 }
138
139 painter->setPen(m_additionalInfoTextColor);
140 painter->setFont(itemListStyleOption.font);
141 for (int i = Name + 1; i < TextIdCount; ++i) {
142 painter->drawStaticText(m_textPos[i], m_text[i]);
143 }
144
145 if (clipAdditionalInfoBounds) {
146 painter->restore();
147 }
148
149 #ifdef KFILEITEMLISTWIDGET_DEBUG
150 painter->setBrush(Qt::NoBrush);
151 painter->setPen(Qt::green);
152 painter->drawRect(m_iconRect);
153
154 painter->setPen(Qt::red);
155 painter->drawText(QPointF(0, itemListStyleOption.fontMetrics.height()), QString::number(index()));
156 painter->drawRect(rect());
157 #endif
158 }
159
160 QRectF KFileItemListWidget::iconRect() const
161 {
162 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
163 return m_iconRect;
164 }
165
166 QRectF KFileItemListWidget::textRect() const
167 {
168 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
169 return m_textRect;
170 }
171
172 QRectF KFileItemListWidget::expansionToggleRect() const
173 {
174 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
175 return m_isExpandable ? m_expansionArea : QRectF();
176 }
177
178 QRectF KFileItemListWidget::selectionToggleRect() const
179 {
180 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
181
182 const int iconHeight = m_pixmap.height();
183
184 int toggleSize = KIconLoader::SizeSmall;
185 if (iconHeight >= KIconLoader::SizeEnormous) {
186 toggleSize = KIconLoader::SizeMedium;
187 } else if (iconHeight >= KIconLoader::SizeLarge) {
188 toggleSize = KIconLoader::SizeSmallMedium;
189 }
190
191 QPointF pos = iconRect().topLeft();
192
193 // If the selection toggle has a very small distance to the
194 // widget borders, the size of the selection toggle will get
195 // increased to prevent an accidental clicking of the item
196 // when trying to hit the toggle.
197 const int widgetHeight = size().height();
198 const int widgetWidth = size().width();
199 const int minMargin = 2;
200
201 if (toggleSize + minMargin * 2 >= widgetHeight) {
202 toggleSize = widgetHeight;
203 pos.setY(0);
204 }
205 if (toggleSize + minMargin * 2 >= widgetWidth) {
206 toggleSize = widgetWidth;
207 pos.setX(0);
208 }
209
210 return QRectF(pos, QSizeF(toggleSize, toggleSize));
211 }
212
213 QString KFileItemListWidget::roleText(const QByteArray& role, const QHash<QByteArray, QVariant>& values)
214 {
215 QString text;
216 const QVariant roleValue = values.value(role);
217
218 switch (roleTextId(role)) {
219 case Name:
220 case Permissions:
221 case Owner:
222 case Group:
223 case Type:
224 case Destination:
225 case Path:
226 text = roleValue.toString();
227 break;
228
229 case Size: {
230 if (values.value("isDir").toBool()) {
231 // The item represents a directory. Show the number of sub directories
232 // instead of the file size of the directory.
233 if (!roleValue.isNull()) {
234 const int count = roleValue.toInt();
235 if (count < 0) {
236 text = i18nc("@item:intable", "Unknown");
237 } else {
238 text = i18ncp("@item:intable", "%1 item", "%1 items", count);
239 }
240 }
241 } else {
242 // Show the size in kilobytes (always round up)
243 const KLocale* locale = KGlobal::locale();
244 const int roundInc = (locale->binaryUnitDialect() == KLocale::MetricBinaryDialect) ? 499 : 511;
245 const KIO::filesize_t size = roleValue.value<KIO::filesize_t>() + roundInc;
246 text = locale->formatByteSize(size, 0, KLocale::DefaultBinaryDialect, KLocale::UnitKiloByte);
247 }
248 break;
249 }
250
251 case Date: {
252 const QDateTime dateTime = roleValue.toDateTime();
253 text = KGlobal::locale()->formatDateTime(dateTime);
254 break;
255 }
256
257 default:
258 Q_ASSERT(false);
259 break;
260 }
261
262 return text;
263 }
264
265 void KFileItemListWidget::invalidateCache()
266 {
267 m_dirtyLayout = true;
268 m_dirtyContent = true;
269 }
270
271 void KFileItemListWidget::refreshCache()
272 {
273 }
274
275 void KFileItemListWidget::setTextColor(const QColor& color)
276 {
277 if (color != m_customTextColor) {
278 m_customTextColor = color;
279 updateAdditionalInfoTextColor();
280 update();
281 }
282 }
283
284 QColor KFileItemListWidget::textColor() const
285 {
286 if (m_customTextColor.isValid() && !isSelected()) {
287 return m_customTextColor;
288 }
289
290 const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive;
291 const QPalette::ColorRole role = isSelected() ? QPalette::HighlightedText : QPalette::Text;
292 return styleOption().palette.brush(group, role).color();
293 }
294
295 void KFileItemListWidget::setOverlay(const QPixmap& overlay)
296 {
297 m_overlay = overlay;
298 m_dirtyContent = true;
299 update();
300 }
301
302 QPixmap KFileItemListWidget::overlay() const
303 {
304 return m_overlay;
305 }
306
307 void KFileItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
308 const QSet<QByteArray>& roles)
309 {
310 KItemListWidget::dataChanged(current, roles);
311 m_dirtyContent = true;
312
313 QSet<QByteArray> dirtyRoles;
314 if (roles.isEmpty()) {
315 dirtyRoles = visibleRoles().toSet();
316 dirtyRoles.insert("iconPixmap");
317 dirtyRoles.insert("iconName");
318 } else {
319 dirtyRoles = roles;
320 }
321
322 QSetIterator<QByteArray> it(dirtyRoles);
323 while (it.hasNext()) {
324 const QByteArray& role = it.next();
325 m_dirtyContentRoles.insert(role);
326 }
327 }
328
329 void KFileItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
330 const QList<QByteArray>& previous)
331 {
332 KItemListWidget::visibleRolesChanged(current, previous);
333 m_sortedVisibleRoles = current;
334 m_dirtyLayout = true;
335 }
336
337 void KFileItemListWidget::visibleRolesSizesChanged(const QHash<QByteArray, QSizeF>& current,
338 const QHash<QByteArray, QSizeF>& previous)
339 {
340 KItemListWidget::visibleRolesSizesChanged(current, previous);
341 m_dirtyLayout = true;
342 }
343
344 void KFileItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
345 const KItemListStyleOption& previous)
346 {
347 KItemListWidget::styleOptionChanged(current, previous);
348 updateAdditionalInfoTextColor();
349 m_dirtyLayout = true;
350 }
351
352 void KFileItemListWidget::hoveredChanged(bool hovered)
353 {
354 Q_UNUSED(hovered);
355 m_dirtyLayout = true;
356 }
357
358 void KFileItemListWidget::selectedChanged(bool selected)
359 {
360 Q_UNUSED(selected);
361 updateAdditionalInfoTextColor();
362 }
363
364 void KFileItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
365 {
366 KItemListWidget::resizeEvent(event);
367 m_dirtyLayout = true;
368 }
369
370 void KFileItemListWidget::showEvent(QShowEvent* event)
371 {
372 KItemListWidget::showEvent(event);
373
374 // Listen to changes of the clipboard to mark the item as cut/uncut
375 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
376
377 const KUrl itemUrl = data().value("url").value<KUrl>();
378 m_isCut = clipboard->isCut(itemUrl);
379
380 connect(clipboard, SIGNAL(cutItemsChanged()),
381 this, SLOT(slotCutItemsChanged()));
382 }
383
384 void KFileItemListWidget::hideEvent(QHideEvent* event)
385 {
386 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
387 this, SLOT(slotCutItemsChanged()));
388
389 KItemListWidget::hideEvent(event);
390 }
391
392 void KFileItemListWidget::slotCutItemsChanged()
393 {
394 const KUrl itemUrl = data().value("url").value<KUrl>();
395 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
396 if (m_isCut != isCut) {
397 m_isCut = isCut;
398 m_pixmap = QPixmap();
399 m_dirtyContent = true;
400 update();
401 }
402 }
403
404 void KFileItemListWidget::triggerCacheRefreshing()
405 {
406 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
407 return;
408 }
409
410 refreshCache();
411
412 const QHash<QByteArray, QVariant> values = data();
413 m_isExpandable = values["isExpandable"].toBool();
414 m_isHidden = values["name"].toString().startsWith(QLatin1Char('.'));
415
416 updateExpansionArea();
417 updateTextsCache();
418 updatePixmapCache();
419
420 m_dirtyLayout = false;
421 m_dirtyContent = false;
422 m_dirtyContentRoles.clear();
423 }
424
425 void KFileItemListWidget::updateExpansionArea()
426 {
427 if (m_layout == DetailsLayout) {
428 const QHash<QByteArray, QVariant> values = data();
429 Q_ASSERT(values.contains("expansionLevel"));
430 const KItemListStyleOption& option = styleOption();
431 const int expansionLevel = values.value("expansionLevel", 0).toInt();
432 if (expansionLevel >= 0) {
433 const qreal widgetHeight = size().height();
434 const qreal expansionLevelSize = KIconLoader::SizeSmall;
435 const qreal x = option.margin + expansionLevel * widgetHeight;
436 const qreal y = (widgetHeight - expansionLevelSize) / 2;
437 m_expansionArea = QRectF(x, y, expansionLevelSize, expansionLevelSize);
438 return;
439 }
440 }
441
442 m_expansionArea = QRectF();
443 }
444
445 void KFileItemListWidget::updatePixmapCache()
446 {
447 // Precondition: Requires already updated m_textPos values to calculate
448 // the remaining height when the alignment is vertical.
449
450 const QSizeF widgetSize = size();
451 const bool iconOnTop = (m_layout == IconsLayout);
452 const KItemListStyleOption& option = styleOption();
453 const qreal margin = option.margin;
454
455 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * margin : option.iconSize;
456 const int maxIconHeight = option.iconSize;
457
458 const QHash<QByteArray, QVariant> values = data();
459
460 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
461 if (!updatePixmap && m_dirtyContent) {
462 updatePixmap = m_dirtyContentRoles.isEmpty()
463 || m_dirtyContentRoles.contains("iconPixmap")
464 || m_dirtyContentRoles.contains("iconName")
465 || m_dirtyContentRoles.contains("iconOverlays");
466 }
467
468 if (updatePixmap) {
469 m_pixmap = values["iconPixmap"].value<QPixmap>();
470 if (m_pixmap.isNull()) {
471 // Use the icon that fits to the MIME-type
472 QString iconName = values["iconName"].toString();
473 if (iconName.isEmpty()) {
474 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
475 // use a generic icon as fallback
476 iconName = QLatin1String("unknown");
477 }
478 m_pixmap = pixmapForIcon(iconName, maxIconHeight);
479 } else if (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight) {
480 // A custom pixmap has been applied. Assure that the pixmap
481 // is scaled to the maximum available size.
482 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight));
483 }
484
485 const QStringList overlays = values["iconOverlays"].toStringList();
486
487 // Strangely KFileItem::overlays() returns empty string-values, so
488 // we need to check first whether an overlay must be drawn at all.
489 // It is more efficient to do it here, as KIconLoader::drawOverlays()
490 // assumes that an overlay will be drawn and has some additional
491 // setup time.
492 foreach (const QString& overlay, overlays) {
493 if (!overlay.isEmpty()) {
494 // There is at least one overlay, draw all overlays above m_pixmap
495 // and cancel the check
496 KIconLoader::global()->drawOverlays(overlays, m_pixmap, KIconLoader::Desktop);
497 break;
498 }
499 }
500
501 if (m_isCut) {
502 applyCutEffect(m_pixmap);
503 }
504
505 if (m_isHidden) {
506 applyHiddenEffect(m_pixmap);
507 }
508 }
509
510 if (!m_overlay.isNull()) {
511 QPainter painter(&m_pixmap);
512 painter.drawPixmap(0, m_pixmap.height() - m_overlay.height(), m_overlay);
513 }
514
515 int scaledIconSize = 0;
516 if (iconOnTop) {
517 scaledIconSize = static_cast<int>(m_textPos[Name].y() - 2 * margin);
518 } else {
519 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
520 const qreal requiredTextHeight = textRowsCount * option.fontMetrics.height();
521 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
522 widgetSize.height() - 2 * margin : maxIconHeight;
523 }
524
525 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * margin : scaledIconSize;
526 const int maxScaledIconHeight = scaledIconSize;
527
528 m_scaledPixmapSize = m_pixmap.size();
529 m_scaledPixmapSize.scale(maxScaledIconWidth, maxScaledIconHeight, Qt::KeepAspectRatio);
530
531 if (iconOnTop) {
532 // Center horizontally and align on bottom within the icon-area
533 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2);
534 m_pixmapPos.setY(margin + scaledIconSize - m_scaledPixmapSize.height());
535 } else {
536 // Center horizontally and vertically within the icon-area
537 m_pixmapPos.setX(m_textPos[Name].x() - 2 * margin
538 - (scaledIconSize + m_scaledPixmapSize.width()) / 2);
539 m_pixmapPos.setY(margin
540 + (scaledIconSize - m_scaledPixmapSize.height()) / 2);
541 }
542
543 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
544 m_iconRect.adjust(-margin, -margin, margin, margin);
545
546 // Prepare the pixmap that is used when the item gets hovered
547 if (isHovered()) {
548 m_hoverPixmap = m_pixmap;
549 KIconEffect* effect = KIconLoader::global()->iconEffect();
550 // In the KIconLoader terminology, active = hover.
551 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
552 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
553 } else {
554 m_hoverPixmap = m_pixmap;
555 }
556 } else if (hoverOpacity() <= 0.0) {
557 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
558 m_hoverPixmap = QPixmap();
559 }
560 }
561
562 void KFileItemListWidget::updateTextsCache()
563 {
564 QTextOption textOption;
565 switch (m_layout) {
566 case IconsLayout:
567 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
568 textOption.setAlignment(Qt::AlignHCenter);
569 break;
570 case CompactLayout:
571 case DetailsLayout:
572 textOption.setAlignment(Qt::AlignLeft);
573 textOption.setWrapMode(QTextOption::NoWrap);
574 break;
575 default:
576 Q_ASSERT(false);
577 break;
578 }
579
580 for (int i = 0; i < TextIdCount; ++i) {
581 m_text[i].setText(QString());
582 m_text[i].setTextOption(textOption);
583 }
584
585 switch (m_layout) {
586 case IconsLayout: updateIconsLayoutTextCache(); break;
587 case CompactLayout: updateCompactLayoutTextCache(); break;
588 case DetailsLayout: updateDetailsLayoutTextCache(); break;
589 default: Q_ASSERT(false); break;
590 }
591 }
592
593 void KFileItemListWidget::updateIconsLayoutTextCache()
594 {
595 // +------+
596 // | Icon |
597 // +------+
598 //
599 // Name role that
600 // might get wrapped above
601 // several lines.
602 // Additional role 1
603 // Additional role 2
604
605 const QHash<QByteArray, QVariant> values = data();
606
607 const KItemListStyleOption& option = styleOption();
608 const qreal margin = option.margin;
609 const qreal maxWidth = size().width() - 2 * margin;
610 const qreal widgetHeight = size().height();
611 const qreal fontHeight = option.fontMetrics.height();
612
613 // Initialize properties for the "name" role. It will be used as anchor
614 // for initializing the position of the other roles.
615 m_text[Name].setText(KStringHandler::preProcessWrap(values["name"].toString()));
616
617 // Calculate the number of lines required for the name and the required width
618 int textLinesCountForName = 0;
619 qreal requiredWidthForName = 0;
620 QTextLine line;
621
622 QTextLayout layout(m_text[Name].text(), option.font);
623 layout.setTextOption(m_text[Name].textOption());
624 layout.beginLayout();
625 while ((line = layout.createLine()).isValid()) {
626 line.setLineWidth(maxWidth);
627 requiredWidthForName = qMax(requiredWidthForName, line.naturalTextWidth());
628 ++textLinesCountForName;
629 }
630 layout.endLayout();
631
632 // Use one line for each additional information
633 int textLinesCount = textLinesCountForName;
634 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
635 textLinesCount += additionalRolesCount;
636
637 m_text[Name].setTextWidth(maxWidth);
638 m_textPos[Name] = QPointF(margin, widgetHeight - textLinesCount * fontHeight - margin);
639 m_textRect = QRectF(margin + (maxWidth - requiredWidthForName) / 2,
640 m_textPos[Name].y(),
641 requiredWidthForName,
642 textLinesCountForName * fontHeight);
643
644 // Calculate the position for each additional information
645 qreal y = m_textPos[Name].y() + textLinesCountForName * fontHeight;
646 foreach (const QByteArray& role, m_sortedVisibleRoles) {
647 const TextId textId = roleTextId(role);
648 if (textId == Name) {
649 continue;
650 }
651
652 const QString text = roleText(role, values);
653 m_text[textId].setText(text);
654
655 qreal requiredWidth = 0;
656
657 QTextLayout layout(text, option.font);
658 layout.setTextOption(m_text[textId].textOption());
659 layout.beginLayout();
660 QTextLine textLine = layout.createLine();
661 if (textLine.isValid()) {
662 textLine.setLineWidth(maxWidth);
663 requiredWidth = textLine.naturalTextWidth();
664 if (textLine.textLength() < text.length()) {
665 // TODO: QFontMetrics::elidedText() works different regarding the given width
666 // in comparison to QTextLine::setLineWidth(). It might happen that the text does
667 // not get elided although it does not fit into the given width. As workaround
668 // the margin is substracted.
669 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth - margin);
670 m_text[textId].setText(elidedText);
671 }
672 }
673 layout.endLayout();
674
675 m_textPos[textId] = QPointF(margin, y);
676 m_text[textId].setTextWidth(maxWidth);
677
678 const QRectF textRect(margin + (maxWidth - requiredWidth) / 2, y, requiredWidth, fontHeight);
679 m_textRect |= textRect;
680
681 y += fontHeight;
682 }
683
684 // Add a margin to the text rectangle
685 m_textRect.adjust(-margin, -margin, margin, margin);
686 }
687
688 void KFileItemListWidget::updateCompactLayoutTextCache()
689 {
690 // +------+ Name role
691 // | Icon | Additional role 1
692 // +------+ Additional role 2
693
694 const QHash<QByteArray, QVariant> values = data();
695
696 const KItemListStyleOption& option = styleOption();
697 const qreal widgetHeight = size().height();
698 const qreal fontHeight = option.fontMetrics.height();
699 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * fontHeight;
700 const int scaledIconSize = (textLinesHeight < option.iconSize) ? widgetHeight - 2 * option.margin : option.iconSize;
701
702 qreal maximumRequiredTextWidth = 0;
703 const qreal x = option.margin * 3 + scaledIconSize;
704 qreal y = (widgetHeight - textLinesHeight) / 2;
705 const qreal maxWidth = size().width() - x - option.margin;
706 foreach (const QByteArray& role, m_sortedVisibleRoles) {
707 const TextId textId = roleTextId(role);
708
709 const QString text = roleText(role, values);
710 m_text[textId].setText(text);
711
712 qreal requiredWidth = option.fontMetrics.width(text);
713 if (requiredWidth > maxWidth) {
714 requiredWidth = maxWidth;
715 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
716 m_text[textId].setText(elidedText);
717 }
718
719 m_textPos[textId] = QPointF(x, y);
720 m_text[textId].setTextWidth(maxWidth);
721
722 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
723
724 y += fontHeight;
725 }
726
727 m_textRect = QRectF(x - option.margin, 0, maximumRequiredTextWidth + 2 * option.margin, widgetHeight);
728 }
729
730 void KFileItemListWidget::updateDetailsLayoutTextCache()
731 {
732 // Precondition: Requires already updated m_expansionArea
733 // to determine the left position.
734
735 // +------+
736 // | Icon | Name role Additional role 1 Additional role 2
737 // +------+
738 m_textRect = QRectF();
739
740 const KItemListStyleOption& option = styleOption();
741 const QHash<QByteArray, QVariant> values = data();
742
743 const qreal widgetHeight = size().height();
744 const int scaledIconSize = widgetHeight - 2 * option.margin;
745 const int fontHeight = option.fontMetrics.height();
746
747 const qreal columnMargin = option.margin * 3;
748 const qreal firstColumnInc = m_expansionArea.right() + option.margin * 2 + scaledIconSize;
749 qreal x = firstColumnInc;
750 const qreal y = qMax(qreal(option.margin), (widgetHeight - fontHeight) / 2);
751
752 foreach (const QByteArray& role, m_sortedVisibleRoles) {
753 const TextId textId = roleTextId(role);
754
755 QString text = roleText(role, values);
756
757 // Elide the text in case it does not fit into the available column-width
758 qreal requiredWidth = option.fontMetrics.width(text);
759 const qreal columnWidth = visibleRolesSizes().value(role, QSizeF(0, 0)).width();
760 qreal availableTextWidth = columnWidth - 2 * columnMargin;
761 if (textId == Name) {
762 availableTextWidth -= firstColumnInc;
763 }
764
765 if (requiredWidth > availableTextWidth) {
766 text = option.fontMetrics.elidedText(text, Qt::ElideRight, availableTextWidth);
767 requiredWidth = option.fontMetrics.width(text);
768 }
769
770 m_text[textId].setText(text);
771 m_textPos[textId] = QPointF(x + columnMargin, y);
772 x += columnWidth;
773
774 switch (textId) {
775 case Name: {
776 m_textRect = QRectF(m_textPos[textId].x() - option.margin, 0,
777 requiredWidth + 2 * option.margin, size().height());
778
779 // The column after the name should always be aligned on the same x-position independent
780 // from the expansion-level shown in the name column
781 x -= firstColumnInc;
782 break;
783 }
784 case Size:
785 // The values for the size should be right aligned
786 m_textPos[textId].rx() += columnWidth - requiredWidth - 2 * columnMargin;
787 break;
788
789 default:
790 break;
791 }
792 }
793 }
794
795 void KFileItemListWidget::updateAdditionalInfoTextColor()
796 {
797 QColor c1;
798 if (m_customTextColor.isValid()) {
799 c1 = m_customTextColor;
800 } else if (isSelected() && m_layout != DetailsLayout) {
801 c1 = styleOption().palette.highlightedText().color();
802 } else {
803 c1 = styleOption().palette.text().color();
804 }
805
806 // For the color of the additional info the inactive text color
807 // is not used as this might lead to unreadable text for some color schemes. Instead
808 // the text color c1 is slightly mixed with the background color.
809 const QColor c2 = styleOption().palette.base().color();
810 const int p1 = 70;
811 const int p2 = 100 - p1;
812 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
813 (c1.green() * p1 + c2.green() * p2) / 100,
814 (c1.blue() * p1 + c2.blue() * p2) / 100);
815 }
816
817 void KFileItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
818 {
819 if (m_scaledPixmapSize != pixmap.size()) {
820 QPixmap scaledPixmap = pixmap;
821 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize);
822 painter->drawPixmap(m_pixmapPos, scaledPixmap);
823
824 #ifdef KFILEITEMLISTWIDGET_DEBUG
825 painter->setPen(Qt::blue);
826 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
827 #endif
828 } else {
829 painter->drawPixmap(m_pixmapPos, pixmap);
830 }
831 }
832
833 QPixmap KFileItemListWidget::pixmapForIcon(const QString& name, int size)
834 {
835 const KIcon icon(name);
836
837 int requestedSize;
838 if (size <= KIconLoader::SizeSmall) {
839 requestedSize = KIconLoader::SizeSmall;
840 } else if (size <= KIconLoader::SizeSmallMedium) {
841 requestedSize = KIconLoader::SizeSmallMedium;
842 } else if (size <= KIconLoader::SizeMedium) {
843 requestedSize = KIconLoader::SizeMedium;
844 } else if (size <= KIconLoader::SizeLarge) {
845 requestedSize = KIconLoader::SizeLarge;
846 } else if (size <= KIconLoader::SizeHuge) {
847 requestedSize = KIconLoader::SizeHuge;
848 } else if (size <= KIconLoader::SizeEnormous) {
849 requestedSize = KIconLoader::SizeEnormous;
850 } else if (size <= KIconLoader::SizeEnormous * 2) {
851 requestedSize = KIconLoader::SizeEnormous * 2;
852 } else {
853 requestedSize = size;
854 }
855
856 QPixmap pixmap = icon.pixmap(requestedSize, requestedSize);
857 if (requestedSize != size) {
858 KPixmapModifier::scale(pixmap, QSize(size, size));
859 }
860
861 return pixmap;
862 }
863
864 KFileItemListWidget::TextId KFileItemListWidget::roleTextId(const QByteArray& role)
865 {
866 static QHash<QByteArray, TextId> rolesHash;
867 if (rolesHash.isEmpty()) {
868 rolesHash.insert("name", Name);
869 rolesHash.insert("size", Size);
870 rolesHash.insert("date", Date);
871 rolesHash.insert("permissions", Permissions);
872 rolesHash.insert("owner", Owner);
873 rolesHash.insert("group", Group);
874 rolesHash.insert("type", Type);
875 rolesHash.insert("destination", Destination);
876 rolesHash.insert("path", Path);
877 }
878
879 return rolesHash.value(role);
880 }
881
882 void KFileItemListWidget::applyCutEffect(QPixmap& pixmap)
883 {
884 KIconEffect* effect = KIconLoader::global()->iconEffect();
885 pixmap = effect->apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
886 }
887
888 void KFileItemListWidget::applyHiddenEffect(QPixmap& pixmap)
889 {
890 KIconEffect::semiTransparent(pixmap);
891 }
892
893 #include "kfileitemlistwidget.moc"