]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemlistview.cpp
KItemListKeyboardSearchManager improvements and unit tests
[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 QHashIterator<QByteArray, int> it(visibleRoles());
145 while (it.hasNext()) {
146 it.next();
147 const QByteArray& role = it.key();
148 const QString text = values[role].toString();
149 const qreal requiredWidth = option.fontMetrics.width(text);
150 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
151 }
152
153 const qreal width = option.margin * 4 + option.iconSize + maximumRequiredWidth;
154 const qreal height = option.margin * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * option.fontMetrics.height());
155 return QSizeF(width, height);
156 }
157
158 case DetailsLayout: {
159 // The width will be determined dynamically by KFileItemListView::visibleRoleSizes()
160 const qreal height = option.margin * 2 + qMax(option.iconSize, option.fontMetrics.height());
161 return QSizeF(-1, height);
162 }
163
164 default:
165 Q_ASSERT(false);
166 break;
167 }
168
169 return QSize();
170 }
171
172 QHash<QByteArray, QSizeF> KFileItemListView::visibleRoleSizes() const
173 {
174 QElapsedTimer timer;
175 timer.start();
176
177 QHash<QByteArray, QSizeF> sizes;
178
179 const int itemCount = model()->count();
180 for (int i = 0; i < itemCount; ++i) {
181 QHashIterator<QByteArray, int> it(visibleRoles());
182 while (it.hasNext()) {
183 it.next();
184 const QByteArray& visibleRole = it.key();
185
186 QSizeF maxSize = sizes.value(visibleRole, QSizeF(0, 0));
187
188 const QSizeF itemSize = visibleRoleSizeHint(i, visibleRole);
189 maxSize = maxSize.expandedTo(itemSize);
190 sizes.insert(visibleRole, maxSize);
191 }
192
193 if (i > 100 && timer.elapsed() > 200) {
194 // When having several thousands of items calculating the sizes can get
195 // very expensive. We accept a possibly too small role-size in favour
196 // of having no blocking user interface.
197 #ifdef KFILEITEMLISTVIEW_DEBUG
198 kDebug() << "Timer exceeded, stopped after" << i << "items";
199 #endif
200 break;
201 }
202 }
203
204 #ifdef KFILEITEMLISTVIEW_DEBUG
205 kDebug() << "[TIME] Calculated dynamic item size for " << itemCount << "items:" << timer.elapsed();
206 #endif
207 return sizes;
208 }
209
210 QPixmap KFileItemListView::createDragPixmap(const QSet<int>& indexes) const
211 {
212 QPixmap pixmap;
213
214 if (model()) {
215 QSetIterator<int> it(indexes);
216 while (it.hasNext()) {
217 const int index = it.next();
218 // TODO: Only one item is considered currently
219 pixmap = model()->data(index).value("iconPixmap").value<QPixmap>();
220 if (pixmap.isNull()) {
221 KIcon icon(model()->data(index).value("iconName").toString());
222 pixmap = icon.pixmap(itemSize().toSize());
223 }
224 }
225 }
226
227 return pixmap;
228 }
229
230 void KFileItemListView::initializeItemListWidget(KItemListWidget* item)
231 {
232 KFileItemListWidget* fileItemListWidget = static_cast<KFileItemListWidget*>(item);
233
234 switch (m_itemLayout) {
235 case IconsLayout: fileItemListWidget->setLayout(KFileItemListWidget::IconsLayout); break;
236 case CompactLayout: fileItemListWidget->setLayout(KFileItemListWidget::CompactLayout); break;
237 case DetailsLayout: fileItemListWidget->setLayout(KFileItemListWidget::DetailsLayout); break;
238 default: Q_ASSERT(false); break;
239 }
240 }
241
242 void KFileItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
243 {
244 Q_UNUSED(previous);
245 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
246
247 if (m_modelRolesUpdater) {
248 delete m_modelRolesUpdater;
249 }
250
251 m_modelRolesUpdater = new KFileItemModelRolesUpdater(static_cast<KFileItemModel*>(current), this);
252 const int size = styleOption().iconSize;
253 m_modelRolesUpdater->setIconSize(QSize(size, size));
254 }
255
256 void KFileItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
257 {
258 Q_UNUSED(current);
259 Q_UNUSED(previous);
260 updateLayoutOfVisibleItems();
261 }
262
263 void KFileItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
264 {
265 Q_UNUSED(current);
266 Q_UNUSED(previous);
267 triggerVisibleIndexRangeUpdate();
268 }
269
270 void KFileItemListView::onOffsetChanged(qreal current, qreal previous)
271 {
272 Q_UNUSED(current);
273 Q_UNUSED(previous);
274 triggerVisibleIndexRangeUpdate();
275 }
276
277 void KFileItemListView::onVisibleRolesChanged(const QHash<QByteArray, int>& current, const QHash<QByteArray, int>& previous)
278 {
279 Q_UNUSED(previous);
280
281 Q_ASSERT(qobject_cast<KFileItemModel*>(model()));
282 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(model());
283
284 // KFileItemModel does not distinct between "visible" and "invisible" roles.
285 // Add all roles that are mandatory for having a working KFileItemListView:
286 QSet<QByteArray> keys = current.keys().toSet();
287 QSet<QByteArray> roles = keys;
288 roles.insert("iconPixmap");
289 roles.insert("iconName");
290 roles.insert("name"); // TODO: just don't allow to disable it
291 roles.insert("isDir");
292 if (m_itemLayout == DetailsLayout) {
293 roles.insert("isExpanded");
294 roles.insert("expansionLevel");
295 }
296
297 fileItemModel->setRoles(roles);
298
299 m_modelRolesUpdater->setRoles(keys);
300 }
301
302 void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
303 {
304 Q_UNUSED(current);
305 Q_UNUSED(previous);
306 triggerIconSizeUpdate();
307 }
308
309 void KFileItemListView::onTransactionBegin()
310 {
311 m_modelRolesUpdater->setPaused(true);
312 }
313
314 void KFileItemListView::onTransactionEnd()
315 {
316 // Only unpause the model-roles-updater if no timer is active. If one
317 // timer is still active the model-roles-updater will be unpaused later as
318 // soon as the timer has been exceeded.
319 const bool timerActive = m_updateVisibleIndexRangeTimer->isActive() ||
320 m_updateIconSizeTimer->isActive();
321 if (!timerActive) {
322 m_modelRolesUpdater->setPaused(false);
323 }
324 }
325
326 void KFileItemListView::resizeEvent(QGraphicsSceneResizeEvent* event)
327 {
328 KItemListView::resizeEvent(event);
329 triggerVisibleIndexRangeUpdate();
330 }
331
332 void KFileItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
333 {
334 KItemListView::slotItemsRemoved(itemRanges);
335 updateTimersInterval();
336 }
337
338 void KFileItemListView::triggerVisibleIndexRangeUpdate()
339 {
340 m_modelRolesUpdater->setPaused(true);
341 m_updateVisibleIndexRangeTimer->start();
342 }
343
344 void KFileItemListView::updateVisibleIndexRange()
345 {
346 if (!m_modelRolesUpdater) {
347 return;
348 }
349
350 const int index = firstVisibleIndex();
351 const int count = lastVisibleIndex() - index + 1;
352 m_modelRolesUpdater->setVisibleIndexRange(index, count);
353
354 if (m_updateIconSizeTimer->isActive()) {
355 // If the icon-size update is pending do an immediate update
356 // of the icon-size before unpausing m_modelRolesUpdater. This prevents
357 // an unnecessary expensive recreation of all previews afterwards.
358 m_updateIconSizeTimer->stop();
359 const KItemListStyleOption& option = styleOption();
360 m_modelRolesUpdater->setIconSize(QSize(option.iconSize, option.iconSize));
361 }
362
363 m_modelRolesUpdater->setPaused(isTransactionActive());
364 updateTimersInterval();
365 }
366
367 void KFileItemListView::triggerIconSizeUpdate()
368 {
369 m_modelRolesUpdater->setPaused(true);
370 m_updateIconSizeTimer->start();
371 }
372
373 void KFileItemListView::updateIconSize()
374 {
375 if (!m_modelRolesUpdater) {
376 return;
377 }
378
379 const KItemListStyleOption& option = styleOption();
380 m_modelRolesUpdater->setIconSize(QSize(option.iconSize, option.iconSize));
381
382 if (m_updateVisibleIndexRangeTimer->isActive()) {
383 // If the visibility-index-range update is pending do an immediate update
384 // of the range before unpausing m_modelRolesUpdater. This prevents
385 // an unnecessary expensive recreation of all previews afterwards.
386 m_updateVisibleIndexRangeTimer->stop();
387 const int index = firstVisibleIndex();
388 const int count = lastVisibleIndex() - index + 1;
389 m_modelRolesUpdater->setVisibleIndexRange(index, count);
390 }
391
392 m_modelRolesUpdater->setPaused(isTransactionActive());
393 updateTimersInterval();
394 }
395
396 QSizeF KFileItemListView::visibleRoleSizeHint(int index, const QByteArray& role) const
397 {
398 const KItemListStyleOption& option = styleOption();
399
400 qreal width = m_minimumRolesWidths.value(role, 0);
401 const qreal height = option.margin * 2 + option.fontMetrics.height();
402
403 const QVariant value = model()->data(index).value(role);
404 const QString text = value.toString();
405 if (!text.isEmpty()) {
406 width = qMax(width, qreal(option.margin * 2 + option.fontMetrics.width(text)));
407 }
408
409 return QSizeF(width, height);
410 }
411
412 void KFileItemListView::updateLayoutOfVisibleItems()
413 {
414 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
415 initializeItemListWidget(widget);
416 }
417 triggerVisibleIndexRangeUpdate();
418 }
419
420 void KFileItemListView::updateTimersInterval()
421 {
422 if (!model()) {
423 return;
424 }
425
426 // The ShortInterval is used for cases like switching the directory: If the
427 // model is empty and filled later the creation of the previews should be done
428 // as soon as possible. The LongInterval is used when the model already contains
429 // items and assures that operations like zooming don't result in too many temporary
430 // recreations of the previews.
431
432 const int interval = (model()->count() <= 0) ? ShortInterval : LongInterval;
433 m_updateVisibleIndexRangeTimer->setInterval(interval);
434 m_updateIconSizeTimer->setInterval(interval);
435 }
436
437 void KFileItemListView::updateMinimumRolesWidths()
438 {
439 m_minimumRolesWidths.clear();
440
441 const KItemListStyleOption& option = styleOption();
442 const QString sizeText = QLatin1String("888888") + i18nc("@item:intable", "items");
443 m_minimumRolesWidths.insert("size", option.fontMetrics.width(sizeText));
444 }
445
446 #include "kfileitemlistview.moc"