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