]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kstandarditemlistwidget.cpp
Enable basic drag and drop support for the Places Panel
[dolphin.git] / src / kitemviews / kstandarditemlistwidget.cpp
1 /***************************************************************************
2 * Copyright (C) 2012 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 "kstandarditemlistwidget.h"
21
22 #include "kfileitemlistview.h"
23 #include "kfileitemmodel.h"
24
25 #include <KIcon>
26 #include <KIconEffect>
27 #include <KIconLoader>
28 #include <KLocale>
29 #include <kratingpainter.h>
30 #include <KStringHandler>
31 #include <KDebug>
32
33 #include "private/kfileitemclipboard.h"
34 #include "private/kitemlistroleeditor.h"
35 #include "private/kpixmapmodifier.h"
36
37 #include <QFontMetricsF>
38 #include <QGraphicsScene>
39 #include <QGraphicsSceneResizeEvent>
40 #include <QGraphicsView>
41 #include <QPainter>
42 #include <QStyleOption>
43 #include <QTextLayout>
44 #include <QTextLine>
45
46 // #define KSTANDARDITEMLISTWIDGET_DEBUG
47
48 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
49 KItemListWidgetInformant()
50 {
51 }
52
53 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
54 {
55 }
56
57 QSizeF KStandardItemListWidgetInformant::itemSizeHint(int index, const KItemListView* view) const
58 {
59 const QHash<QByteArray, QVariant> values = view->model()->data(index);
60 const KItemListStyleOption& option = view->styleOption();
61 const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0);
62
63 switch (static_cast<const KStandardItemListView*>(view)->itemLayout()) {
64 case KStandardItemListWidget::IconsLayout: {
65 const QString text = KStringHandler::preProcessWrap(values["text"].toString());
66
67 const qreal itemWidth = view->itemSize().width();
68 const qreal maxWidth = itemWidth - 2 * option.padding;
69 QTextLine line;
70
71 // Calculate the number of lines required for wrapping the name
72 QTextOption textOption(Qt::AlignHCenter);
73 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
74
75 qreal textHeight = 0;
76 QTextLayout layout(text, option.font);
77 layout.setTextOption(textOption);
78 layout.beginLayout();
79 while ((line = layout.createLine()).isValid()) {
80 line.setLineWidth(maxWidth);
81 line.naturalTextWidth();
82 textHeight += line.height();
83 }
84 layout.endLayout();
85
86 // Add one line for each additional information
87 textHeight += additionalRolesCount * option.fontMetrics.lineSpacing();
88
89 const qreal maxTextHeight = option.maxTextSize.height();
90 if (maxTextHeight > 0 && textHeight > maxTextHeight) {
91 textHeight = maxTextHeight;
92 }
93
94 return QSizeF(itemWidth, textHeight + option.iconSize + option.padding * 3);
95 }
96
97 case KStandardItemListWidget::CompactLayout: {
98 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
99 // to show all roles without horizontal clipping.
100 qreal maximumRequiredWidth = 0.0;
101
102 foreach (const QByteArray& role, view->visibleRoles()) {
103 const QString text = roleText(role, values);
104 const qreal requiredWidth = option.fontMetrics.width(text);
105 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
106 }
107
108 qreal width = option.padding * 4 + option.iconSize + maximumRequiredWidth;
109 const qreal maxWidth = option.maxTextSize.width();
110 if (maxWidth > 0 && width > maxWidth) {
111 width = maxWidth;
112 }
113 const qreal height = option.padding * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * option.fontMetrics.lineSpacing());
114 return QSizeF(width, height);
115 }
116
117 case KStandardItemListWidget::DetailsLayout: {
118 const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height());
119 return QSizeF(-1, height);
120 }
121
122 default:
123 Q_ASSERT(false);
124 break;
125 }
126
127 return QSize();
128 }
129
130 qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray& role,
131 int index,
132 const KItemListView* view) const
133 {
134 const QHash<QByteArray, QVariant> values = view->model()->data(index);
135 const KItemListStyleOption& option = view->styleOption();
136
137 const QString text = roleText(role, values);
138 qreal width = KStandardItemListWidget::columnPadding(option);
139
140 if (role == "rating") {
141 width += KStandardItemListWidget::preferredRatingSize(option).width();
142 } else {
143 width += option.fontMetrics.width(text);
144
145 if (role == "text") {
146 if (view->supportsItemExpanding()) {
147 // Increase the width by the expansion-toggle and the current expansion level
148 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
149 const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height());
150 width += (expandedParentsCount + 1) * height;
151 }
152
153 // Increase the width by the required space for the icon
154 width += option.padding * 2 + option.iconSize;
155 }
156 }
157
158 return width;
159 }
160
161 QString KStandardItemListWidgetInformant::roleText(const QByteArray& role,
162 const QHash<QByteArray, QVariant>& values) const
163 {
164 if (role == "rating") {
165 // Always use an empty text, as the rating is shown by the image m_rating.
166 return QString();
167 }
168 return values.value(role).toString();
169 }
170
171 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) :
172 KItemListWidget(informant, parent),
173 m_isCut(false),
174 m_isHidden(false),
175 m_isExpandable(false),
176 m_supportsItemExpanding(false),
177 m_dirtyLayout(true),
178 m_dirtyContent(true),
179 m_dirtyContentRoles(),
180 m_layout(IconsLayout),
181 m_pixmapPos(),
182 m_pixmap(),
183 m_scaledPixmapSize(),
184 m_iconRect(),
185 m_hoverPixmap(),
186 m_textInfo(),
187 m_textRect(),
188 m_sortedVisibleRoles(),
189 m_expansionArea(),
190 m_customTextColor(),
191 m_additionalInfoTextColor(),
192 m_overlay(),
193 m_rating(),
194 m_roleEditor(0)
195 {
196 }
197
198 KStandardItemListWidget::~KStandardItemListWidget()
199 {
200 qDeleteAll(m_textInfo);
201 m_textInfo.clear();
202
203 delete m_roleEditor;
204 }
205
206 void KStandardItemListWidget::setLayout(Layout layout)
207 {
208 if (m_layout != layout) {
209 m_layout = layout;
210 m_dirtyLayout = true;
211 updateAdditionalInfoTextColor();
212 update();
213 }
214 }
215
216 KStandardItemListWidget::Layout KStandardItemListWidget::layout() const
217 {
218 return m_layout;
219 }
220
221 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding)
222 {
223 if (m_supportsItemExpanding != supportsItemExpanding) {
224 m_supportsItemExpanding = supportsItemExpanding;
225 m_dirtyLayout = true;
226 update();
227 }
228 }
229
230 bool KStandardItemListWidget::supportsItemExpanding() const
231 {
232 return m_supportsItemExpanding;
233 }
234
235 void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
236 {
237 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
238
239 KItemListWidget::paint(painter, option, widget);
240
241 if (!m_expansionArea.isEmpty()) {
242 drawSiblingsInformation(painter);
243 }
244
245 const KItemListStyleOption& itemListStyleOption = styleOption();
246 if (isHovered()) {
247 // Blend the unhovered and hovered pixmap if the hovering
248 // animation is ongoing
249 if (hoverOpacity() < 1.0) {
250 drawPixmap(painter, m_pixmap);
251 }
252
253 const qreal opacity = painter->opacity();
254 painter->setOpacity(hoverOpacity() * opacity);
255 drawPixmap(painter, m_hoverPixmap);
256 painter->setOpacity(opacity);
257 } else {
258 drawPixmap(painter, m_pixmap);
259 }
260
261 painter->setFont(itemListStyleOption.font);
262 painter->setPen(m_isHidden ? m_additionalInfoTextColor : textColor());
263 const TextInfo* textInfo = m_textInfo.value("text");
264 painter->drawStaticText(textInfo->pos, textInfo->staticText);
265
266 bool clipAdditionalInfoBounds = false;
267 if (m_supportsItemExpanding) {
268 // Prevent a possible overlapping of the additional-information texts
269 // with the icon. This can happen if the user has minimized the width
270 // of the name-column to a very small value.
271 const qreal minX = m_pixmapPos.x() + m_pixmap.width() + 4 * itemListStyleOption.padding;
272 if (textInfo->pos.x() + columnWidth("text") > minX) {
273 clipAdditionalInfoBounds = true;
274 painter->save();
275 painter->setClipRect(minX, 0, size().width() - minX, size().height(), Qt::IntersectClip);
276 }
277 }
278
279 painter->setPen(m_additionalInfoTextColor);
280 painter->setFont(itemListStyleOption.font);
281
282 for (int i = 1; i < m_sortedVisibleRoles.count(); ++i) {
283 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles[i]);
284 painter->drawStaticText(textInfo->pos, textInfo->staticText);
285 }
286
287 if (!m_rating.isNull()) {
288 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
289 QPointF pos = ratingTextInfo->pos;
290 const Qt::Alignment align = ratingTextInfo->staticText.textOption().alignment();
291 if (align & Qt::AlignHCenter) {
292 pos.rx() += (size().width() - m_rating.width()) / 2;
293 }
294 painter->drawPixmap(pos, m_rating);
295 }
296
297 if (clipAdditionalInfoBounds) {
298 painter->restore();
299 }
300
301 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
302 painter->setBrush(Qt::NoBrush);
303 painter->setPen(Qt::green);
304 painter->drawRect(m_iconRect);
305
306 painter->setPen(Qt::red);
307 painter->drawText(QPointF(0, itemListStyleOption.fontMetrics.height()), QString::number(index()));
308 painter->drawRect(rect());
309 #endif
310 }
311
312 QRectF KStandardItemListWidget::iconRect() const
313 {
314 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
315 return m_iconRect;
316 }
317
318 QRectF KStandardItemListWidget::textRect() const
319 {
320 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
321 return m_textRect;
322 }
323
324 QRectF KStandardItemListWidget::textFocusRect() const
325 {
326 // In the compact- and details-layout a larger textRect() is returned to be aligned
327 // with the iconRect(). This is useful to have a larger selection/hover-area
328 // when having a quite large icon size but only one line of text. Still the
329 // focus rectangle should be shown as narrow as possible around the text.
330
331 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
332
333 switch (m_layout) {
334 case CompactLayout: {
335 QRectF rect = m_textRect;
336 const TextInfo* topText = m_textInfo.value(m_sortedVisibleRoles.first());
337 const TextInfo* bottomText = m_textInfo.value(m_sortedVisibleRoles.last());
338 rect.setTop(topText->pos.y());
339 rect.setBottom(bottomText->pos.y() + bottomText->staticText.size().height());
340 return rect;
341 }
342
343 case DetailsLayout: {
344 QRectF rect = m_textRect;
345 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles.first());
346 rect.setTop(textInfo->pos.y());
347 rect.setBottom(textInfo->pos.y() + textInfo->staticText.size().height());
348
349 const KItemListStyleOption& option = styleOption();
350 if (option.extendedSelectionRegion) {
351 const QString text = textInfo->staticText.text();
352 rect.setWidth(option.fontMetrics.width(text) + 2 * option.padding);
353 }
354
355 return rect;
356 }
357
358 default:
359 break;
360 }
361
362 return m_textRect;
363 }
364
365 QRectF KStandardItemListWidget::expansionToggleRect() const
366 {
367 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
368 return m_isExpandable ? m_expansionArea : QRectF();
369 }
370
371 QRectF KStandardItemListWidget::selectionToggleRect() const
372 {
373 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
374
375 const int iconHeight = styleOption().iconSize;
376
377 int toggleSize = KIconLoader::SizeSmall;
378 if (iconHeight >= KIconLoader::SizeEnormous) {
379 toggleSize = KIconLoader::SizeMedium;
380 } else if (iconHeight >= KIconLoader::SizeLarge) {
381 toggleSize = KIconLoader::SizeSmallMedium;
382 }
383
384 QPointF pos = iconRect().topLeft();
385
386 // If the selection toggle has a very small distance to the
387 // widget borders, the size of the selection toggle will get
388 // increased to prevent an accidental clicking of the item
389 // when trying to hit the toggle.
390 const int widgetHeight = size().height();
391 const int widgetWidth = size().width();
392 const int minMargin = 2;
393
394 if (toggleSize + minMargin * 2 >= widgetHeight) {
395 pos.rx() -= (widgetHeight - toggleSize) / 2;
396 toggleSize = widgetHeight;
397 pos.setY(0);
398 }
399 if (toggleSize + minMargin * 2 >= widgetWidth) {
400 pos.ry() -= (widgetWidth - toggleSize) / 2;
401 toggleSize = widgetWidth;
402 pos.setX(0);
403 }
404
405 return QRectF(pos, QSizeF(toggleSize, toggleSize));
406 }
407
408 QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem* option,
409 QWidget* widget)
410 {
411 QPixmap pixmap = KItemListWidget::createDragPixmap(option, widget);
412 if (m_layout != DetailsLayout || styleOption().extendedSelectionRegion) {
413 return pixmap;
414 }
415
416 // Only return the content of the text-column as pixmap
417 const int leftClip = m_pixmapPos.x();
418
419 const TextInfo* textInfo = m_textInfo.value("text");
420 const int rightClip = textInfo->pos.x() +
421 textInfo->staticText.size().width() +
422 2 * styleOption().padding;
423
424 QPixmap clippedPixmap(rightClip - leftClip + 1, pixmap.height());
425 clippedPixmap.fill(Qt::transparent);
426
427 QPainter painter(&clippedPixmap);
428 painter.drawPixmap(-leftClip, 0, pixmap);
429
430 return clippedPixmap;
431 }
432
433
434 KItemListWidgetInformant* KStandardItemListWidget::createInformant()
435 {
436 return new KStandardItemListWidgetInformant();
437 }
438
439 void KStandardItemListWidget::invalidateCache()
440 {
441 m_dirtyLayout = true;
442 m_dirtyContent = true;
443 }
444
445 void KStandardItemListWidget::refreshCache()
446 {
447 }
448
449 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray& role) const
450 {
451 Q_UNUSED(role);
452 return false;
453 }
454
455 bool KStandardItemListWidget::isHidden() const
456 {
457 return false;
458 }
459
460 void KStandardItemListWidget::setTextColor(const QColor& color)
461 {
462 if (color != m_customTextColor) {
463 m_customTextColor = color;
464 updateAdditionalInfoTextColor();
465 update();
466 }
467 }
468
469 QColor KStandardItemListWidget::textColor() const
470 {
471 if (m_customTextColor.isValid() && !isSelected()) {
472 return m_customTextColor;
473 }
474
475 const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive;
476 const QPalette::ColorRole role = isSelected() ? QPalette::HighlightedText : QPalette::Text;
477 return styleOption().palette.brush(group, role).color();
478 }
479
480 void KStandardItemListWidget::setOverlay(const QPixmap& overlay)
481 {
482 m_overlay = overlay;
483 m_dirtyContent = true;
484 update();
485 }
486
487 QPixmap KStandardItemListWidget::overlay() const
488 {
489 return m_overlay;
490 }
491
492
493 QString KStandardItemListWidget::roleText(const QByteArray& role,
494 const QHash<QByteArray, QVariant>& values) const
495 {
496 return static_cast<const KStandardItemListWidgetInformant*>(informant())->roleText(role, values);
497 }
498
499 void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
500 const QSet<QByteArray>& roles)
501 {
502 Q_UNUSED(current);
503
504 m_dirtyContent = true;
505
506 QSet<QByteArray> dirtyRoles;
507 if (roles.isEmpty()) {
508 dirtyRoles = visibleRoles().toSet();
509 } else {
510 dirtyRoles = roles;
511 }
512
513 // The icon-state might depend from other roles and hence is
514 // marked as dirty whenever a role has been changed
515 dirtyRoles.insert("iconPixmap");
516 dirtyRoles.insert("iconName");
517
518 QSetIterator<QByteArray> it(dirtyRoles);
519 while (it.hasNext()) {
520 const QByteArray& role = it.next();
521 m_dirtyContentRoles.insert(role);
522 }
523 }
524
525 void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
526 const QList<QByteArray>& previous)
527 {
528 Q_UNUSED(previous);
529 m_sortedVisibleRoles = current;
530 m_dirtyLayout = true;
531 }
532
533 void KStandardItemListWidget::columnWidthChanged(const QByteArray& role,
534 qreal current,
535 qreal previous)
536 {
537 Q_UNUSED(role);
538 Q_UNUSED(current);
539 Q_UNUSED(previous);
540 m_dirtyLayout = true;
541 }
542
543 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
544 const KItemListStyleOption& previous)
545 {
546 Q_UNUSED(current);
547 Q_UNUSED(previous);
548 updateAdditionalInfoTextColor();
549 m_dirtyLayout = true;
550 }
551
552 void KStandardItemListWidget::hoveredChanged(bool hovered)
553 {
554 Q_UNUSED(hovered);
555 m_dirtyLayout = true;
556 }
557
558 void KStandardItemListWidget::selectedChanged(bool selected)
559 {
560 Q_UNUSED(selected);
561 updateAdditionalInfoTextColor();
562 }
563
564 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
565 {
566 Q_UNUSED(current);
567 Q_UNUSED(previous);
568 m_dirtyLayout = true;
569 }
570
571 void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
572 {
573 Q_UNUSED(previous);
574
575 QGraphicsView* parent = scene()->views()[0];
576 if (current.isEmpty() || !parent || current != "text") {
577 if (m_roleEditor) {
578 emit roleEditingCanceled(index(), current, data().value(current));
579 m_roleEditor->deleteLater();
580 m_roleEditor = 0;
581 }
582 return;
583 }
584
585 Q_ASSERT(!m_roleEditor);
586
587 const TextInfo* textInfo = m_textInfo.value("text");
588
589 m_roleEditor = new KItemListRoleEditor(parent);
590 m_roleEditor->setIndex(index());
591 m_roleEditor->setRole(current);
592
593 const QString text = data().value(current).toString();
594 m_roleEditor->setPlainText(text);
595
596 QTextOption textOption = textInfo->staticText.textOption();
597 m_roleEditor->document()->setDefaultTextOption(textOption);
598
599 // Select the text without MIME-type extension
600 int selectionLength = text.length();
601
602 const QString extension = KMimeType::extractKnownExtension(text);
603 if (!extension.isEmpty()) {
604 selectionLength -= extension.length() + 1;
605 }
606
607 if (selectionLength > 0) {
608 QTextCursor cursor = m_roleEditor->textCursor();
609 cursor.movePosition(QTextCursor::StartOfBlock);
610 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, selectionLength);
611 m_roleEditor->setTextCursor(cursor);
612 }
613
614 connect(m_roleEditor, SIGNAL(roleEditingCanceled(int,QByteArray,QVariant)),
615 this, SLOT(slotRoleEditingCanceled(int,QByteArray,QVariant)));
616 connect(m_roleEditor, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
617 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
618
619 // Adjust the geometry of the editor
620 QRectF rect = roleEditingRect(current);
621 const int frameWidth = m_roleEditor->frameWidth();
622 rect.adjust(-frameWidth, -frameWidth, frameWidth, frameWidth);
623 rect.translate(pos());
624 if (rect.right() > parent->width()) {
625 rect.setWidth(parent->width() - rect.left());
626 }
627 m_roleEditor->setGeometry(rect.toRect());
628 m_roleEditor->show();
629 m_roleEditor->setFocus();
630 }
631
632 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
633 {
634 if (m_roleEditor) {
635 setEditedRole(QByteArray());
636 Q_ASSERT(!m_roleEditor);
637 }
638
639 KItemListWidget::resizeEvent(event);
640
641 m_dirtyLayout = true;
642 }
643
644 void KStandardItemListWidget::showEvent(QShowEvent* event)
645 {
646 KItemListWidget::showEvent(event);
647
648 // Listen to changes of the clipboard to mark the item as cut/uncut
649 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
650
651 const KUrl itemUrl = data().value("url").value<KUrl>();
652 m_isCut = clipboard->isCut(itemUrl);
653
654 connect(clipboard, SIGNAL(cutItemsChanged()),
655 this, SLOT(slotCutItemsChanged()));
656 }
657
658 void KStandardItemListWidget::hideEvent(QHideEvent* event)
659 {
660 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
661 this, SLOT(slotCutItemsChanged()));
662
663 KItemListWidget::hideEvent(event);
664 }
665
666 void KStandardItemListWidget::slotCutItemsChanged()
667 {
668 const KUrl itemUrl = data().value("url").value<KUrl>();
669 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
670 if (m_isCut != isCut) {
671 m_isCut = isCut;
672 m_pixmap = QPixmap();
673 m_dirtyContent = true;
674 update();
675 }
676 }
677
678 void KStandardItemListWidget::slotRoleEditingCanceled(int index,
679 const QByteArray& role,
680 const QVariant& value)
681 {
682 m_roleEditor->deleteLater();
683 m_roleEditor = 0;
684 emit roleEditingCanceled(index, role, value);
685 setEditedRole(QByteArray());
686 }
687
688 void KStandardItemListWidget::slotRoleEditingFinished(int index,
689 const QByteArray& role,
690 const QVariant& value)
691 {
692 m_roleEditor->deleteLater();
693 m_roleEditor = 0;
694 emit roleEditingFinished(index, role, value);
695 setEditedRole(QByteArray());
696 }
697
698 void KStandardItemListWidget::triggerCacheRefreshing()
699 {
700 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
701 return;
702 }
703
704 refreshCache();
705
706 const QHash<QByteArray, QVariant> values = data();
707 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
708 m_isHidden = isHidden();
709
710 updateExpansionArea();
711 updateTextsCache();
712 updatePixmapCache();
713
714 m_dirtyLayout = false;
715 m_dirtyContent = false;
716 m_dirtyContentRoles.clear();
717 }
718
719 void KStandardItemListWidget::updateExpansionArea()
720 {
721 if (m_supportsItemExpanding) {
722 const QHash<QByteArray, QVariant> values = data();
723 Q_ASSERT(values.contains("expandedParentsCount"));
724 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
725 if (expandedParentsCount >= 0) {
726 const qreal widgetHeight = size().height();
727 const qreal inc = (widgetHeight - KIconLoader::SizeSmall) / 2;
728 const qreal x = expandedParentsCount * widgetHeight + inc;
729 const qreal y = inc;
730 m_expansionArea = QRectF(x, y, KIconLoader::SizeSmall, KIconLoader::SizeSmall);
731 return;
732 }
733 }
734
735 m_expansionArea = QRectF();
736 }
737
738 void KStandardItemListWidget::updatePixmapCache()
739 {
740 // Precondition: Requires already updated m_textPos values to calculate
741 // the remaining height when the alignment is vertical.
742
743 const QSizeF widgetSize = size();
744 const bool iconOnTop = (m_layout == IconsLayout);
745 const KItemListStyleOption& option = styleOption();
746 const qreal padding = option.padding;
747
748 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : option.iconSize;
749 const int maxIconHeight = option.iconSize;
750
751 const QHash<QByteArray, QVariant> values = data();
752
753 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
754 if (!updatePixmap && m_dirtyContent) {
755 updatePixmap = m_dirtyContentRoles.isEmpty()
756 || m_dirtyContentRoles.contains("iconPixmap")
757 || m_dirtyContentRoles.contains("iconName")
758 || m_dirtyContentRoles.contains("iconOverlays");
759 }
760
761 if (updatePixmap) {
762 m_pixmap = values["iconPixmap"].value<QPixmap>();
763 if (m_pixmap.isNull()) {
764 // Use the icon that fits to the MIME-type
765 QString iconName = values["iconName"].toString();
766 if (iconName.isEmpty()) {
767 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
768 // use a generic icon as fallback
769 iconName = QLatin1String("unknown");
770 }
771 m_pixmap = pixmapForIcon(iconName, maxIconHeight);
772 } else if (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight) {
773 // A custom pixmap has been applied. Assure that the pixmap
774 // is scaled to the maximum available size.
775 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight));
776 }
777
778 const QStringList overlays = values["iconOverlays"].toStringList();
779
780 // Strangely KFileItem::overlays() returns empty string-values, so
781 // we need to check first whether an overlay must be drawn at all.
782 // It is more efficient to do it here, as KIconLoader::drawOverlays()
783 // assumes that an overlay will be drawn and has some additional
784 // setup time.
785 foreach (const QString& overlay, overlays) {
786 if (!overlay.isEmpty()) {
787 // There is at least one overlay, draw all overlays above m_pixmap
788 // and cancel the check
789 KIconLoader::global()->drawOverlays(overlays, m_pixmap, KIconLoader::Desktop);
790 break;
791 }
792 }
793
794 if (m_isCut) {
795 applyCutEffect(m_pixmap);
796 }
797
798 if (m_isHidden) {
799 applyHiddenEffect(m_pixmap);
800 }
801 }
802
803 if (!m_overlay.isNull()) {
804 QPainter painter(&m_pixmap);
805 painter.drawPixmap(0, m_pixmap.height() - m_overlay.height(), m_overlay);
806 }
807
808 int scaledIconSize = 0;
809 if (iconOnTop) {
810 const TextInfo* textInfo = m_textInfo.value("text");
811 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
812 } else {
813 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
814 const qreal requiredTextHeight = textRowsCount * option.fontMetrics.height();
815 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
816 widgetSize.height() - 2 * padding : maxIconHeight;
817 }
818
819 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
820 const int maxScaledIconHeight = scaledIconSize;
821
822 m_scaledPixmapSize = m_pixmap.size();
823 m_scaledPixmapSize.scale(maxScaledIconWidth, maxScaledIconHeight, Qt::KeepAspectRatio);
824
825 if (iconOnTop) {
826 // Center horizontally and align on bottom within the icon-area
827 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2);
828 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
829 } else {
830 // Center horizontally and vertically within the icon-area
831 const TextInfo* textInfo = m_textInfo.value("text");
832 m_pixmapPos.setX(textInfo->pos.x() - 2 * padding
833 - (scaledIconSize + m_scaledPixmapSize.width()) / 2);
834 m_pixmapPos.setY(padding
835 + (scaledIconSize - m_scaledPixmapSize.height()) / 2);
836 }
837
838 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
839
840 // Prepare the pixmap that is used when the item gets hovered
841 if (isHovered()) {
842 m_hoverPixmap = m_pixmap;
843 KIconEffect* effect = KIconLoader::global()->iconEffect();
844 // In the KIconLoader terminology, active = hover.
845 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
846 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
847 } else {
848 m_hoverPixmap = m_pixmap;
849 }
850 } else if (hoverOpacity() <= 0.0) {
851 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
852 m_hoverPixmap = QPixmap();
853 }
854 }
855
856 void KStandardItemListWidget::updateTextsCache()
857 {
858 QTextOption textOption;
859 switch (m_layout) {
860 case IconsLayout:
861 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
862 textOption.setAlignment(Qt::AlignHCenter);
863 break;
864 case CompactLayout:
865 case DetailsLayout:
866 textOption.setAlignment(Qt::AlignLeft);
867 textOption.setWrapMode(QTextOption::NoWrap);
868 break;
869 default:
870 Q_ASSERT(false);
871 break;
872 }
873
874 qDeleteAll(m_textInfo);
875 m_textInfo.clear();
876 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
877 TextInfo* textInfo = new TextInfo();
878 textInfo->staticText.setTextFormat(Qt::PlainText);
879 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
880 textInfo->staticText.setTextOption(textOption);
881 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
882 }
883
884 switch (m_layout) {
885 case IconsLayout: updateIconsLayoutTextCache(); break;
886 case CompactLayout: updateCompactLayoutTextCache(); break;
887 case DetailsLayout: updateDetailsLayoutTextCache(); break;
888 default: Q_ASSERT(false); break;
889 }
890
891 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
892 if (ratingTextInfo) {
893 // The text of the rating-role has been set to empty to get
894 // replaced by a rating-image showing the rating as stars.
895 const KItemListStyleOption& option = styleOption();
896 QSizeF ratingSize = preferredRatingSize(option);
897
898 const qreal availableWidth = (m_layout == DetailsLayout)
899 ? columnWidth("rating") - columnPadding(option)
900 : m_textRect.width();
901 if (ratingSize.width() > availableWidth) {
902 ratingSize.rwidth() = availableWidth;
903 }
904 m_rating = QPixmap(ratingSize.toSize());
905 m_rating.fill(Qt::transparent);
906
907 QPainter painter(&m_rating);
908 const QRect rect(0, 0, m_rating.width(), m_rating.height());
909 const int rating = data().value("rating").toInt();
910 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
911 } else if (!m_rating.isNull()) {
912 m_rating = QPixmap();
913 }
914 }
915
916 void KStandardItemListWidget::updateIconsLayoutTextCache()
917 {
918 // +------+
919 // | Icon |
920 // +------+
921 //
922 // Name role that
923 // might get wrapped above
924 // several lines.
925 // Additional role 1
926 // Additional role 2
927
928 const QHash<QByteArray, QVariant> values = data();
929
930 const KItemListStyleOption& option = styleOption();
931 const qreal padding = option.padding;
932 const qreal maxWidth = size().width() - 2 * padding;
933 const qreal widgetHeight = size().height();
934 const qreal lineSpacing = option.fontMetrics.lineSpacing();
935
936 // Initialize properties for the "text" role. It will be used as anchor
937 // for initializing the position of the other roles.
938 TextInfo* nameTextInfo = m_textInfo.value("text");
939 const QString nameText = KStringHandler::preProcessWrap(values["text"].toString());
940 nameTextInfo->staticText.setText(nameText);
941
942 // Calculate the number of lines required for the name and the required width
943 qreal nameWidth = 0;
944 qreal nameHeight = 0;
945 QTextLine line;
946
947 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
948 const int maxNameLines = (option.maxTextSize.height() / int(lineSpacing)) - additionalRolesCount;
949
950 QTextLayout layout(nameTextInfo->staticText.text(), option.font);
951 layout.setTextOption(nameTextInfo->staticText.textOption());
952 layout.beginLayout();
953 int nameLineIndex = 0;
954 while ((line = layout.createLine()).isValid()) {
955 line.setLineWidth(maxWidth);
956 nameWidth = qMax(nameWidth, line.naturalTextWidth());
957 nameHeight += line.height();
958
959 ++nameLineIndex;
960 if (nameLineIndex == maxNameLines) {
961 // The maximum number of textlines has been reached. If this is
962 // the case provide an elided text if necessary.
963 const int textLength = line.textStart() + line.textLength();
964 if (textLength < nameText.length()) {
965 // Elide the last line of the text
966 QString lastTextLine = nameText.mid(line.textStart(), line.textLength());
967 lastTextLine = option.fontMetrics.elidedText(lastTextLine,
968 Qt::ElideRight,
969 line.naturalTextWidth() - 1);
970 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
971 nameTextInfo->staticText.setText(elidedText);
972 }
973 break;
974 }
975 }
976 layout.endLayout();
977
978 // Use one line for each additional information
979 nameTextInfo->staticText.setTextWidth(maxWidth);
980 nameTextInfo->pos = QPointF(padding, widgetHeight -
981 nameHeight -
982 additionalRolesCount * lineSpacing -
983 padding);
984 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
985 nameTextInfo->pos.y(),
986 nameWidth,
987 nameHeight);
988
989 // Calculate the position for each additional information
990 qreal y = nameTextInfo->pos.y() + nameHeight;
991 foreach (const QByteArray& role, m_sortedVisibleRoles) {
992 if (role == "text") {
993 continue;
994 }
995
996 const QString text = roleText(role, values);
997 TextInfo* textInfo = m_textInfo.value(role);
998 textInfo->staticText.setText(text);
999
1000 qreal requiredWidth = 0;
1001
1002 QTextLayout layout(text, option.font);
1003 QTextOption textOption;
1004 textOption.setWrapMode(QTextOption::NoWrap);
1005 layout.setTextOption(textOption);
1006
1007 layout.beginLayout();
1008 QTextLine textLine = layout.createLine();
1009 if (textLine.isValid()) {
1010 textLine.setLineWidth(maxWidth);
1011 requiredWidth = textLine.naturalTextWidth();
1012 if (requiredWidth > maxWidth) {
1013 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
1014 textInfo->staticText.setText(elidedText);
1015 requiredWidth = option.fontMetrics.width(elidedText);
1016 }
1017 }
1018 layout.endLayout();
1019
1020 textInfo->pos = QPointF(padding, y);
1021 textInfo->staticText.setTextWidth(maxWidth);
1022
1023 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
1024 m_textRect |= textRect;
1025
1026 y += lineSpacing;
1027 }
1028
1029 // Add a padding to the text rectangle
1030 m_textRect.adjust(-padding, -padding, padding, padding);
1031 }
1032
1033 void KStandardItemListWidget::updateCompactLayoutTextCache()
1034 {
1035 // +------+ Name role
1036 // | Icon | Additional role 1
1037 // +------+ Additional role 2
1038
1039 const QHash<QByteArray, QVariant> values = data();
1040
1041 const KItemListStyleOption& option = styleOption();
1042 const qreal widgetHeight = size().height();
1043 const qreal lineSpacing = option.fontMetrics.lineSpacing();
1044 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
1045 const int scaledIconSize = (textLinesHeight < option.iconSize) ? widgetHeight - 2 * option.padding : option.iconSize;
1046
1047 qreal maximumRequiredTextWidth = 0;
1048 const qreal x = option.padding * 3 + scaledIconSize;
1049 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
1050 const qreal maxWidth = size().width() - x - option.padding;
1051 foreach (const QByteArray& role, m_sortedVisibleRoles) {
1052 const QString text = roleText(role, values);
1053 TextInfo* textInfo = m_textInfo.value(role);
1054 textInfo->staticText.setText(text);
1055
1056 qreal requiredWidth = option.fontMetrics.width(text);
1057 if (requiredWidth > maxWidth) {
1058 requiredWidth = maxWidth;
1059 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
1060 textInfo->staticText.setText(elidedText);
1061 }
1062
1063 textInfo->pos = QPointF(x, y);
1064 textInfo->staticText.setTextWidth(maxWidth);
1065
1066 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
1067
1068 y += lineSpacing;
1069 }
1070
1071 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
1072 }
1073
1074 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1075 {
1076 // Precondition: Requires already updated m_expansionArea
1077 // to determine the left position.
1078
1079 // +------+
1080 // | Icon | Name role Additional role 1 Additional role 2
1081 // +------+
1082 m_textRect = QRectF();
1083
1084 const KItemListStyleOption& option = styleOption();
1085 const QHash<QByteArray, QVariant> values = data();
1086
1087 const qreal widgetHeight = size().height();
1088 const int scaledIconSize = widgetHeight - 2 * option.padding;
1089 const int fontHeight = option.fontMetrics.height();
1090
1091 const qreal columnWidthInc = columnPadding(option);
1092 qreal firstColumnInc = scaledIconSize;
1093 if (m_supportsItemExpanding) {
1094 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1095 } else {
1096 firstColumnInc += option.padding;
1097 }
1098
1099 qreal x = firstColumnInc;
1100 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1101
1102 foreach (const QByteArray& role, m_sortedVisibleRoles) {
1103 QString text = roleText(role, values);
1104
1105 // Elide the text in case it does not fit into the available column-width
1106 qreal requiredWidth = option.fontMetrics.width(text);
1107 const qreal roleWidth = columnWidth(role);
1108 qreal availableTextWidth = roleWidth - columnWidthInc;
1109
1110 const bool isTextRole = (role == "text");
1111 if (isTextRole) {
1112 availableTextWidth -= firstColumnInc;
1113 }
1114
1115 if (requiredWidth > availableTextWidth) {
1116 text = option.fontMetrics.elidedText(text, Qt::ElideRight, availableTextWidth);
1117 requiredWidth = option.fontMetrics.width(text);
1118 }
1119
1120 TextInfo* textInfo = m_textInfo.value(role);
1121 textInfo->staticText.setText(text);
1122 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1123 x += roleWidth;
1124
1125 if (isTextRole) {
1126 const qreal textWidth = option.extendedSelectionRegion
1127 ? size().width() - textInfo->pos.x()
1128 : requiredWidth + 2 * option.padding;
1129 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
1130 textWidth, size().height());
1131
1132 // The column after the name should always be aligned on the same x-position independent
1133 // from the expansion-level shown in the name column
1134 x -= firstColumnInc;
1135 } else if (isRoleRightAligned(role)) {
1136 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1137 }
1138 }
1139 }
1140
1141 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1142 {
1143 QColor c1;
1144 if (m_customTextColor.isValid()) {
1145 c1 = m_customTextColor;
1146 } else if (isSelected() && m_layout != DetailsLayout) {
1147 c1 = styleOption().palette.highlightedText().color();
1148 } else {
1149 c1 = styleOption().palette.text().color();
1150 }
1151
1152 // For the color of the additional info the inactive text color
1153 // is not used as this might lead to unreadable text for some color schemes. Instead
1154 // the text color c1 is slightly mixed with the background color.
1155 const QColor c2 = styleOption().palette.base().color();
1156 const int p1 = 70;
1157 const int p2 = 100 - p1;
1158 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
1159 (c1.green() * p1 + c2.green() * p2) / 100,
1160 (c1.blue() * p1 + c2.blue() * p2) / 100);
1161 }
1162
1163 void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
1164 {
1165 if (m_scaledPixmapSize != pixmap.size()) {
1166 QPixmap scaledPixmap = pixmap;
1167 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize);
1168 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1169
1170 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1171 painter->setPen(Qt::blue);
1172 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1173 #endif
1174 } else {
1175 painter->drawPixmap(m_pixmapPos, pixmap);
1176 }
1177 }
1178
1179 void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter)
1180 {
1181 const int siblingSize = size().height();
1182 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1183 QRect siblingRect(x, 0, siblingSize, siblingSize);
1184
1185 QStyleOption option;
1186 bool isItemSibling = true;
1187
1188 const QBitArray siblings = siblingsInformation();
1189 for (int i = siblings.count() - 1; i >= 0; --i) {
1190 option.rect = siblingRect;
1191 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1192
1193 if (isItemSibling) {
1194 option.state |= QStyle::State_Item;
1195 if (m_isExpandable) {
1196 option.state |= QStyle::State_Children;
1197 }
1198 if (data()["isExpanded"].toBool()) {
1199 option.state |= QStyle::State_Open;
1200 }
1201 isItemSibling = false;
1202 }
1203
1204 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1205
1206 siblingRect.translate(-siblingRect.width(), 0);
1207 }
1208 }
1209
1210 QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const
1211 {
1212 const TextInfo* textInfo = m_textInfo.value(role);
1213 if (!textInfo) {
1214 return QRectF();
1215 }
1216
1217 QRectF rect(textInfo->pos, textInfo->staticText.size());
1218 if (m_layout == DetailsLayout) {
1219 rect.setWidth(columnWidth(role) - rect.x());
1220 }
1221
1222 return rect;
1223 }
1224
1225 QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, int size)
1226 {
1227 const KIcon icon(name);
1228
1229 int requestedSize;
1230 if (size <= KIconLoader::SizeSmall) {
1231 requestedSize = KIconLoader::SizeSmall;
1232 } else if (size <= KIconLoader::SizeSmallMedium) {
1233 requestedSize = KIconLoader::SizeSmallMedium;
1234 } else if (size <= KIconLoader::SizeMedium) {
1235 requestedSize = KIconLoader::SizeMedium;
1236 } else if (size <= KIconLoader::SizeLarge) {
1237 requestedSize = KIconLoader::SizeLarge;
1238 } else if (size <= KIconLoader::SizeHuge) {
1239 requestedSize = KIconLoader::SizeHuge;
1240 } else if (size <= KIconLoader::SizeEnormous) {
1241 requestedSize = KIconLoader::SizeEnormous;
1242 } else if (size <= KIconLoader::SizeEnormous * 2) {
1243 requestedSize = KIconLoader::SizeEnormous * 2;
1244 } else {
1245 requestedSize = size;
1246 }
1247
1248 QPixmap pixmap = icon.pixmap(requestedSize, requestedSize);
1249 if (requestedSize != size) {
1250 KPixmapModifier::scale(pixmap, QSize(size, size));
1251 }
1252
1253 return pixmap;
1254 }
1255
1256 void KStandardItemListWidget::applyCutEffect(QPixmap& pixmap)
1257 {
1258 KIconEffect* effect = KIconLoader::global()->iconEffect();
1259 pixmap = effect->apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1260 }
1261
1262 void KStandardItemListWidget::applyHiddenEffect(QPixmap& pixmap)
1263 {
1264 KIconEffect::semiTransparent(pixmap);
1265 }
1266
1267 QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1268 {
1269 const qreal height = option.fontMetrics.ascent();
1270 return QSizeF(height * 5, height);
1271 }
1272
1273 qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption& option)
1274 {
1275 return option.padding * 6;
1276 }
1277
1278 #include "kstandarditemlistwidget.moc"