]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemlistview.cpp
Implement group-header layouting
[dolphin.git] / src / kitemviews / kfileitemlistview.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 "kfileitemlistview.h"
21
22 #include "kitemlistgroupheader.h"
23 #include "kfileitemmodelrolesupdater.h"
24 #include "kfileitemlistwidget.h"
25 #include "kfileitemmodel.h"
26 #include <KLocale>
27 #include <KStringHandler>
28
29 #include <KDebug>
30 #include <KIcon>
31
32 #include <QTextLine>
33 #include <QTimer>
34
35 #define KFILEITEMLISTVIEW_DEBUG
36
37 namespace {
38 const int ShortInterval = 50;
39 const int LongInterval = 300;
40 }
41
42 KFileItemListView::KFileItemListView(QGraphicsWidget* parent) :
43 KItemListView(parent),
44 m_itemLayout(IconsLayout),
45 m_modelRolesUpdater(0),
46 m_updateVisibleIndexRangeTimer(0),
47 m_updateIconSizeTimer(0),
48 m_minimumRolesWidths()
49 {
50 setAcceptDrops(true);
51
52 setScrollOrientation(Qt::Vertical);
53 setWidgetCreator(new KItemListWidgetCreator<KFileItemListWidget>());
54 setGroupHeaderCreator(new KItemListGroupHeaderCreator<KItemListGroupHeader>());
55
56 m_updateVisibleIndexRangeTimer = new QTimer(this);
57 m_updateVisibleIndexRangeTimer->setSingleShot(true);
58 m_updateVisibleIndexRangeTimer->setInterval(ShortInterval);
59 connect(m_updateVisibleIndexRangeTimer, SIGNAL(timeout()), this, SLOT(updateVisibleIndexRange()));
60
61 m_updateIconSizeTimer = new QTimer(this);
62 m_updateIconSizeTimer->setSingleShot(true);
63 m_updateIconSizeTimer->setInterval(ShortInterval);
64 connect(m_updateIconSizeTimer, SIGNAL(timeout()), this, SLOT(updateIconSize()));
65
66 updateMinimumRolesWidths();
67 }
68
69 KFileItemListView::~KFileItemListView()
70 {
71 // The group headers are children of the widgets created by
72 // widgetCreator(). So it is mandatory to delete the group headers
73 // first.
74 delete groupHeaderCreator();
75 delete widgetCreator();
76
77 delete m_modelRolesUpdater;
78 m_modelRolesUpdater = 0;
79 }
80
81 void KFileItemListView::setPreviewsShown(bool show)
82 {
83 if (m_modelRolesUpdater) {
84 m_modelRolesUpdater->setPreviewShown(show);
85 }
86 }
87
88 bool KFileItemListView::previewsShown() const
89 {
90 return m_modelRolesUpdater->isPreviewShown();
91 }
92
93 void KFileItemListView::setItemLayout(Layout layout)
94 {
95 if (m_itemLayout != layout) {
96 m_itemLayout = layout;
97 updateLayoutOfVisibleItems();
98 }
99 }
100
101 KFileItemListView::Layout KFileItemListView::itemLayout() const
102 {
103 return m_itemLayout;
104 }
105
106 QSizeF KFileItemListView::itemSizeHint(int index) const
107 {
108 const QHash<QByteArray, QVariant> values = model()->data(index);
109 const KItemListStyleOption& option = styleOption();
110 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
111
112 switch (m_itemLayout) {
113 case IconsLayout: {
114 const QString text = KStringHandler::preProcessWrap(values["name"].toString());
115
116 const qreal maxWidth = itemSize().width() - 2 * option.margin;
117 int textLinesCount = 0;
118 QTextLine line;
119
120 // Calculate the number of lines required for wrapping the name
121 QTextOption textOption(Qt::AlignHCenter);
122 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
123
124 QTextLayout layout(text, option.font);
125 layout.setTextOption(textOption);
126 layout.beginLayout();
127 while ((line = layout.createLine()).isValid()) {
128 line.setLineWidth(maxWidth);
129 line.naturalTextWidth();
130 ++textLinesCount;
131 }
132 layout.endLayout();
133
134 // Add one line for each additional information
135 textLinesCount += additionalRolesCount;
136
137 const qreal height = textLinesCount * option.fontMetrics.height() +
138 option.iconSize +
139 option.margin * 4;
140 return QSizeF(itemSize().width(), height);
141 }
142
143 case CompactLayout: {
144 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
145 // to show all roles without horizontal clipping.
146 qreal maximumRequiredWidth = 0.0;
147
148 foreach (const QByteArray& role, visibleRoles()) {
149 const QString text = KFileItemListWidget::roleText(role, values);
150 const qreal requiredWidth = option.fontMetrics.width(text);
151 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
152 }
153
154 const qreal width = option.margin * 4 + option.iconSize + maximumRequiredWidth;
155 const qreal height = option.margin * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * option.fontMetrics.height());
156 return QSizeF(width, height);
157 }
158
159 case DetailsLayout: {
160 // The width will be determined dynamically by KFileItemListView::visibleRoleSizes()
161 const qreal height = option.margin * 2 + qMax(option.iconSize, option.fontMetrics.height());
162 return QSizeF(-1, height);
163 }
164
165 default:
166 Q_ASSERT(false);
167 break;
168 }
169
170 return QSize();
171 }
172
173 QHash<QByteArray, QSizeF> KFileItemListView::visibleRolesSizes(const KItemRangeList& itemRanges) const
174 {
175 QElapsedTimer timer;
176 timer.start();
177
178 QHash<QByteArray, QSizeF> sizes;
179
180 int calculatedItemCount = 0;
181 bool maxTimeExceeded = false;
182 foreach (const KItemRange& itemRange, itemRanges) {
183 const int startIndex = itemRange.index;
184 const int endIndex = startIndex + itemRange.count - 1;
185
186 for (int i = startIndex; i <= endIndex; ++i) {
187 foreach (const QByteArray& visibleRole, visibleRoles()) {
188 QSizeF maxSize = sizes.value(visibleRole, QSizeF(0, 0));
189 const QSizeF itemSize = visibleRoleSizeHint(i, visibleRole);
190 maxSize = maxSize.expandedTo(itemSize);
191 sizes.insert(visibleRole, maxSize);
192 }
193
194 if (calculatedItemCount > 100 && timer.elapsed() > 200) {
195 // When having several thousands of items calculating the sizes can get
196 // very expensive. We accept a possibly too small role-size in favour
197 // of having no blocking user interface.
198 #ifdef KFILEITEMLISTVIEW_DEBUG
199 kDebug() << "Timer exceeded, stopped after" << calculatedItemCount << "items";
200 #endif
201 maxTimeExceeded = true;
202 break;
203 }
204 ++calculatedItemCount;
205 }
206 if (maxTimeExceeded) {
207 break;
208 }
209 }
210
211 #ifdef KFILEITEMLISTVIEW_DEBUG
212 int rangesItemCount = 0;
213 foreach (const KItemRange& itemRange, itemRanges) {
214 rangesItemCount += itemRange.count;
215 }
216 kDebug() << "[TIME] Calculated dynamic item size for " << rangesItemCount << "items:" << timer.elapsed();
217 #endif
218 return sizes;
219 }
220
221 QPixmap KFileItemListView::createDragPixmap(const QSet<int>& indexes) const
222 {
223 QPixmap pixmap;
224
225 if (model()) {
226 QSetIterator<int> it(indexes);
227 while (it.hasNext()) {
228 const int index = it.next();
229 // TODO: Only one item is considered currently
230 pixmap = model()->data(index).value("iconPixmap").value<QPixmap>();
231 if (pixmap.isNull()) {
232 KIcon icon(model()->data(index).value("iconName").toString());
233 pixmap = icon.pixmap(itemSize().toSize());
234 }
235 }
236 }
237
238 return pixmap;
239 }
240
241 void KFileItemListView::initializeItemListWidget(KItemListWidget* item)
242 {
243 KFileItemListWidget* fileItemListWidget = static_cast<KFileItemListWidget*>(item);
244
245 switch (m_itemLayout) {
246 case IconsLayout: fileItemListWidget->setLayout(KFileItemListWidget::IconsLayout); break;
247 case CompactLayout: fileItemListWidget->setLayout(KFileItemListWidget::CompactLayout); break;
248 case DetailsLayout: fileItemListWidget->setLayout(KFileItemListWidget::DetailsLayout); break;
249 default: Q_ASSERT(false); break;
250 }
251
252 fileItemListWidget->setAlternatingBackgroundColors(m_itemLayout == DetailsLayout);
253 }
254
255 bool KFileItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
256 {
257 // Even if the icons have a different size they are always aligned within
258 // the area defined by KItemStyleOption.iconSize and hence result in no
259 // change of the item-size.
260 const bool containsIconName = changedRoles.contains("iconName");
261 const bool containsIconPixmap = changedRoles.contains("iconPixmap");
262 const int count = changedRoles.count();
263
264 const bool iconChanged = (containsIconName && containsIconPixmap && count == 2) ||
265 (containsIconName && count == 1) ||
266 (containsIconPixmap && count == 1);
267 return !iconChanged;
268 }
269
270 void KFileItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
271 {
272 Q_UNUSED(previous);
273 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
274
275 if (m_modelRolesUpdater) {
276 delete m_modelRolesUpdater;
277 }
278
279 m_modelRolesUpdater = new KFileItemModelRolesUpdater(static_cast<KFileItemModel*>(current), this);
280 const int size = styleOption().iconSize;
281 m_modelRolesUpdater->setIconSize(QSize(size, size));
282 }
283
284 void KFileItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
285 {
286 Q_UNUSED(current);
287 Q_UNUSED(previous);
288 updateLayoutOfVisibleItems();
289 }
290
291 void KFileItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
292 {
293 Q_UNUSED(current);
294 Q_UNUSED(previous);
295 triggerVisibleIndexRangeUpdate();
296 }
297
298 void KFileItemListView::onScrollOffsetChanged(qreal current, qreal previous)
299 {
300 Q_UNUSED(current);
301 Q_UNUSED(previous);
302 triggerVisibleIndexRangeUpdate();
303 }
304
305 void KFileItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
306 {
307 Q_UNUSED(previous);
308
309 Q_ASSERT(qobject_cast<KFileItemModel*>(model()));
310 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(model());
311
312 // KFileItemModel does not distinct between "visible" and "invisible" roles.
313 // Add all roles that are mandatory for having a working KFileItemListView:
314 QSet<QByteArray> keys = current.toSet();
315 QSet<QByteArray> roles = keys;
316 roles.insert("iconPixmap");
317 roles.insert("iconName");
318 roles.insert("name"); // TODO: just don't allow to disable it
319 roles.insert("isDir");
320 if (m_itemLayout == DetailsLayout) {
321 roles.insert("isExpanded");
322 roles.insert("expansionLevel");
323 }
324
325 fileItemModel->setRoles(roles);
326
327 m_modelRolesUpdater->setRoles(keys);
328 }
329
330 void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
331 {
332 Q_UNUSED(current);
333 Q_UNUSED(previous);
334 triggerIconSizeUpdate();
335 }
336
337 void KFileItemListView::onTransactionBegin()
338 {
339 m_modelRolesUpdater->setPaused(true);
340 }
341
342 void KFileItemListView::onTransactionEnd()
343 {
344 // Only unpause the model-roles-updater if no timer is active. If one
345 // timer is still active the model-roles-updater will be unpaused later as
346 // soon as the timer has been exceeded.
347 const bool timerActive = m_updateVisibleIndexRangeTimer->isActive() ||
348 m_updateIconSizeTimer->isActive();
349 if (!timerActive) {
350 m_modelRolesUpdater->setPaused(false);
351 }
352 }
353
354 void KFileItemListView::resizeEvent(QGraphicsSceneResizeEvent* event)
355 {
356 KItemListView::resizeEvent(event);
357 triggerVisibleIndexRangeUpdate();
358 }
359
360 void KFileItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
361 {
362 KItemListView::slotItemsRemoved(itemRanges);
363 updateTimersInterval();
364 }
365
366 void KFileItemListView::triggerVisibleIndexRangeUpdate()
367 {
368 m_modelRolesUpdater->setPaused(true);
369 m_updateVisibleIndexRangeTimer->start();
370 }
371
372 void KFileItemListView::updateVisibleIndexRange()
373 {
374 if (!m_modelRolesUpdater) {
375 return;
376 }
377
378 const int index = firstVisibleIndex();
379 const int count = lastVisibleIndex() - index + 1;
380 m_modelRolesUpdater->setVisibleIndexRange(index, count);
381
382 if (m_updateIconSizeTimer->isActive()) {
383 // If the icon-size update is pending do an immediate update
384 // of the icon-size before unpausing m_modelRolesUpdater. This prevents
385 // an unnecessary expensive recreation of all previews afterwards.
386 m_updateIconSizeTimer->stop();
387 const KItemListStyleOption& option = styleOption();
388 m_modelRolesUpdater->setIconSize(QSize(option.iconSize, option.iconSize));
389 }
390
391 m_modelRolesUpdater->setPaused(isTransactionActive());
392 updateTimersInterval();
393 }
394
395 void KFileItemListView::triggerIconSizeUpdate()
396 {
397 m_modelRolesUpdater->setPaused(true);
398 m_updateIconSizeTimer->start();
399 }
400
401 void KFileItemListView::updateIconSize()
402 {
403 if (!m_modelRolesUpdater) {
404 return;
405 }
406
407 const KItemListStyleOption& option = styleOption();
408 m_modelRolesUpdater->setIconSize(QSize(option.iconSize, option.iconSize));
409
410 if (m_updateVisibleIndexRangeTimer->isActive()) {
411 // If the visibility-index-range update is pending do an immediate update
412 // of the range before unpausing m_modelRolesUpdater. This prevents
413 // an unnecessary expensive recreation of all previews afterwards.
414 m_updateVisibleIndexRangeTimer->stop();
415 const int index = firstVisibleIndex();
416 const int count = lastVisibleIndex() - index + 1;
417 m_modelRolesUpdater->setVisibleIndexRange(index, count);
418 }
419
420 m_modelRolesUpdater->setPaused(isTransactionActive());
421 updateTimersInterval();
422 }
423
424 QSizeF KFileItemListView::visibleRoleSizeHint(int index, const QByteArray& role) const
425 {
426 const KItemListStyleOption& option = styleOption();
427
428 qreal width = m_minimumRolesWidths.value(role, 0);
429 const qreal height = option.margin * 2 + option.fontMetrics.height();
430
431 const QHash<QByteArray, QVariant> values = model()->data(index);
432 const QString text = KFileItemListWidget::roleText(role, values);
433 if (!text.isEmpty()) {
434 const qreal columnMargin = option.margin * 3;
435 width = qMax(width, qreal(2 * columnMargin + option.fontMetrics.width(text)));
436 }
437
438 if (role == "name") {
439 // Increase the width by the expansion-toggle and the current expansion level
440 const int expansionLevel = values.value("expansionLevel", 0).toInt();
441 width += option.margin + expansionLevel * itemSize().height() + KIconLoader::SizeSmall;
442
443 // Increase the width by the required space for the icon
444 width += option.margin * 2 + option.iconSize;
445 }
446
447 return QSizeF(width, height);
448 }
449
450 void KFileItemListView::updateLayoutOfVisibleItems()
451 {
452 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
453 initializeItemListWidget(widget);
454 }
455 triggerVisibleIndexRangeUpdate();
456 }
457
458 void KFileItemListView::updateTimersInterval()
459 {
460 if (!model()) {
461 return;
462 }
463
464 // The ShortInterval is used for cases like switching the directory: If the
465 // model is empty and filled later the creation of the previews should be done
466 // as soon as possible. The LongInterval is used when the model already contains
467 // items and assures that operations like zooming don't result in too many temporary
468 // recreations of the previews.
469
470 const int interval = (model()->count() <= 0) ? ShortInterval : LongInterval;
471 m_updateVisibleIndexRangeTimer->setInterval(interval);
472 m_updateIconSizeTimer->setInterval(interval);
473 }
474
475 void KFileItemListView::updateMinimumRolesWidths()
476 {
477 m_minimumRolesWidths.clear();
478
479 const KItemListStyleOption& option = styleOption();
480 const QString sizeText = QLatin1String("888888") + i18nc("@item:intable", "items");
481 m_minimumRolesWidths.insert("size", option.fontMetrics.width(sizeText));
482 }
483
484 #include "kfileitemlistview.moc"