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