]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodelrolesupdater.cpp
Make sure that widgets are initialized when changing the view mode
[dolphin.git] / src / kitemviews / kfileitemmodelrolesupdater.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 "kfileitemmodelrolesupdater.h"
21
22 #include "kfileitemmodel.h"
23
24 #include <KConfig>
25 #include <KConfigGroup>
26 #include <KDebug>
27 #include <KDirWatch>
28 #include <KFileItem>
29 #include <KGlobal>
30 #include <KIO/JobUiDelegate>
31 #include <KIO/PreviewJob>
32
33 #include "private/kpixmapmodifier.h"
34
35 #include <QApplication>
36 #include <QPainter>
37 #include <QPixmap>
38 #include <QElapsedTimer>
39 #include <QTimer>
40
41 #include <algorithm>
42
43 #ifdef HAVE_NEPOMUK
44 #include "private/knepomukrolesprovider.h"
45 #include <Nepomuk2/ResourceWatcher>
46 #include <Nepomuk2/ResourceManager>
47 #endif
48
49 // Required includes for subItemsCount():
50 #ifdef Q_WS_WIN
51 #include <QDir>
52 #else
53 #include <dirent.h>
54 #include <QFile>
55 #endif
56
57 // #define KFILEITEMMODELROLESUPDATER_DEBUG
58
59 namespace {
60 // Maximum time in ms that the KFileItemModelRolesUpdater
61 // may perform a blocking operation
62 const int MaxBlockTimeout = 200;
63
64 // If the number of items is smaller than ResolveAllItemsLimit,
65 // the roles of all items will be resolved.
66 const int ResolveAllItemsLimit = 500;
67
68 // Not only the visible area, but up to ReadAheadPages before and after
69 // this area will be resolved.
70 const int ReadAheadPages = 5;
71 }
72
73 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QObject* parent) :
74 QObject(parent),
75 m_state(Idle),
76 m_previewChangedDuringPausing(false),
77 m_iconSizeChangedDuringPausing(false),
78 m_rolesChangedDuringPausing(false),
79 m_previewShown(false),
80 m_enlargeSmallPreviews(true),
81 m_clearPreviews(false),
82 m_finishedItems(),
83 m_model(model),
84 m_iconSize(),
85 m_firstVisibleIndex(0),
86 m_lastVisibleIndex(-1),
87 m_maximumVisibleItems(50),
88 m_roles(),
89 m_resolvableRoles(),
90 m_enabledPlugins(),
91 m_pendingSortRoleItems(),
92 m_pendingIndexes(),
93 m_pendingPreviewItems(),
94 m_previewJob(),
95 m_recentlyChangedItemsTimer(0),
96 m_recentlyChangedItems(),
97 m_changedItems(),
98 m_dirWatcher(0),
99 m_watchedDirs()
100 #ifdef HAVE_NEPOMUK
101 , m_nepomukResourceWatcher(0),
102 m_nepomukUriItems()
103 #endif
104 {
105 Q_ASSERT(model);
106
107 const KConfigGroup globalConfig(KGlobal::config(), "PreviewSettings");
108 m_enabledPlugins = globalConfig.readEntry("Plugins", QStringList()
109 << "directorythumbnail"
110 << "imagethumbnail"
111 << "jpegthumbnail");
112
113 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
114 this, SLOT(slotItemsInserted(KItemRangeList)));
115 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
116 this, SLOT(slotItemsRemoved(KItemRangeList)));
117 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
118 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
119 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
120 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
121 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
122 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
123
124 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
125 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
126 m_recentlyChangedItemsTimer = new QTimer(this);
127 m_recentlyChangedItemsTimer->setInterval(1000);
128 m_recentlyChangedItemsTimer->setSingleShot(true);
129 connect(m_recentlyChangedItemsTimer, SIGNAL(timeout()), this, SLOT(resolveRecentlyChangedItems()));
130
131 m_resolvableRoles.insert("size");
132 m_resolvableRoles.insert("type");
133 m_resolvableRoles.insert("isExpandable");
134 #ifdef HAVE_NEPOMUK
135 m_resolvableRoles += KNepomukRolesProvider::instance().roles();
136 #endif
137
138 // When folders are expandable or the item-count is shown for folders, it is necessary
139 // to watch the number of items of the sub-folder to be able to react on changes.
140 m_dirWatcher = new KDirWatch(this);
141 connect(m_dirWatcher, SIGNAL(dirty(QString)), this, SLOT(slotDirWatchDirty(QString)));
142 }
143
144 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
145 {
146 killPreviewJob();
147 }
148
149 void KFileItemModelRolesUpdater::setIconSize(const QSize& size)
150 {
151 if (size != m_iconSize) {
152 m_iconSize = size;
153 if (m_state == Paused) {
154 m_iconSizeChangedDuringPausing = true;
155 } else if (m_previewShown) {
156 // An icon size change requires the regenerating of
157 // all previews
158 m_finishedItems.clear();
159 startUpdating();
160 }
161 }
162 }
163
164 QSize KFileItemModelRolesUpdater::iconSize() const
165 {
166 return m_iconSize;
167 }
168
169 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index, int count)
170 {
171 if (index < 0) {
172 index = 0;
173 }
174 if (count < 0) {
175 count = 0;
176 }
177
178 if (index == m_firstVisibleIndex && count == m_lastVisibleIndex - m_firstVisibleIndex + 1) {
179 // The range has not been changed
180 return;
181 }
182
183 m_firstVisibleIndex = index;
184 m_lastVisibleIndex = qMin(index + count - 1, m_model->count() - 1);
185
186 startUpdating();
187 }
188
189 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count)
190 {
191 m_maximumVisibleItems = count;
192 }
193
194 void KFileItemModelRolesUpdater::setPreviewsShown(bool show)
195 {
196 if (show == m_previewShown) {
197 return;
198 }
199
200 m_previewShown = show;
201 if (!show) {
202 m_clearPreviews = true;
203 }
204
205 updateAllPreviews();
206 }
207
208 bool KFileItemModelRolesUpdater::previewsShown() const
209 {
210 return m_previewShown;
211 }
212
213 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge)
214 {
215 if (enlarge != m_enlargeSmallPreviews) {
216 m_enlargeSmallPreviews = enlarge;
217 if (m_previewShown) {
218 updateAllPreviews();
219 }
220 }
221 }
222
223 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
224 {
225 return m_enlargeSmallPreviews;
226 }
227
228 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList& list)
229 {
230 if (m_enabledPlugins != list) {
231 m_enabledPlugins = list;
232 if (m_previewShown) {
233 updateAllPreviews();
234 }
235 }
236 }
237
238 void KFileItemModelRolesUpdater::setPaused(bool paused)
239 {
240 if (paused == (m_state == Paused)) {
241 return;
242 }
243
244 if (paused) {
245 m_state = Paused;
246 killPreviewJob();
247 } else {
248 const bool updatePreviews = (m_iconSizeChangedDuringPausing && m_previewShown) ||
249 m_previewChangedDuringPausing;
250 const bool resolveAll = updatePreviews || m_rolesChangedDuringPausing;
251 if (resolveAll) {
252 m_finishedItems.clear();
253 }
254
255 m_iconSizeChangedDuringPausing = false;
256 m_previewChangedDuringPausing = false;
257 m_rolesChangedDuringPausing = false;
258
259 if (!m_pendingSortRoleItems.isEmpty()) {
260 m_state = ResolvingSortRole;
261 resolveNextSortRole();
262 } else {
263 m_state = Idle;
264 }
265
266 startUpdating();
267 }
268 }
269
270 void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
271 {
272 if (m_roles != roles) {
273 m_roles = roles;
274
275 #ifdef HAVE_NEPOMUK
276 if (Nepomuk2::ResourceManager::instance()->initialized()) {
277 // Check whether there is at least one role that must be resolved
278 // with the help of Nepomuk. If this is the case, a (quite expensive)
279 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
280 // the role gets watched for changes.
281 const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
282 bool hasNepomukRole = false;
283 QSetIterator<QByteArray> it(roles);
284 while (it.hasNext()) {
285 const QByteArray& role = it.next();
286 if (rolesProvider.roles().contains(role)) {
287 hasNepomukRole = true;
288 break;
289 }
290 }
291
292 if (hasNepomukRole && !m_nepomukResourceWatcher) {
293 Q_ASSERT(m_nepomukUriItems.isEmpty());
294
295 m_nepomukResourceWatcher = new Nepomuk2::ResourceWatcher(this);
296 connect(m_nepomukResourceWatcher, SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)),
297 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource,Nepomuk2::Types::Property)));
298 } else if (!hasNepomukRole && m_nepomukResourceWatcher) {
299 delete m_nepomukResourceWatcher;
300 m_nepomukResourceWatcher = 0;
301 m_nepomukUriItems.clear();
302 }
303 }
304 #endif
305
306 if (m_state == Paused) {
307 m_rolesChangedDuringPausing = true;
308 } else {
309 startUpdating();
310 }
311 }
312 }
313
314 QSet<QByteArray> KFileItemModelRolesUpdater::roles() const
315 {
316 return m_roles;
317 }
318
319 bool KFileItemModelRolesUpdater::isPaused() const
320 {
321 return m_state == Paused;
322 }
323
324 QStringList KFileItemModelRolesUpdater::enabledPlugins() const
325 {
326 return m_enabledPlugins;
327 }
328
329 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRanges)
330 {
331 QElapsedTimer timer;
332 timer.start();
333
334 // Determine the sort role synchronously for as many items as possible.
335 if (m_resolvableRoles.contains(m_model->sortRole())) {
336 int insertedCount = 0;
337 foreach (const KItemRange& range, itemRanges) {
338 const int lastIndex = insertedCount + range.index + range.count - 1;
339 for (int i = insertedCount + range.index; i <= lastIndex; ++i) {
340 if (timer.elapsed() < MaxBlockTimeout) {
341 applySortRole(i);
342 } else {
343 m_pendingSortRoleItems.insert(m_model->fileItem(i));
344 }
345 }
346 insertedCount += range.count;
347 }
348
349 applySortProgressToModel();
350
351 // If there are still items whose sort role is unknown, check if the
352 // asynchronous determination of the sort role is already in progress,
353 // and start it if that is not the case.
354 if (!m_pendingSortRoleItems.isEmpty() && m_state != ResolvingSortRole) {
355 killPreviewJob();
356 m_state = ResolvingSortRole;
357 resolveNextSortRole();
358 }
359 }
360
361 startUpdating();
362 }
363
364 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRanges)
365 {
366 Q_UNUSED(itemRanges);
367
368 const bool allItemsRemoved = (m_model->count() == 0);
369
370 if (!m_watchedDirs.isEmpty()) {
371 // Don't let KDirWatch watch for removed items
372 if (allItemsRemoved) {
373 foreach (const QString& path, m_watchedDirs) {
374 m_dirWatcher->removeDir(path);
375 }
376 m_watchedDirs.clear();
377 } else {
378 QMutableSetIterator<QString> it(m_watchedDirs);
379 while (it.hasNext()) {
380 const QString& path = it.next();
381 if (m_model->index(KUrl(path)) < 0) {
382 m_dirWatcher->removeDir(path);
383 it.remove();
384 }
385 }
386 }
387 }
388
389 #ifdef HAVE_NEPOMUK
390 if (m_nepomukResourceWatcher) {
391 // Don't let the ResourceWatcher watch for removed items
392 if (allItemsRemoved) {
393 m_nepomukResourceWatcher->setResources(QList<Nepomuk2::Resource>());
394 m_nepomukResourceWatcher->stop();
395 m_nepomukUriItems.clear();
396 } else {
397 QList<Nepomuk2::Resource> newResources;
398 const QList<Nepomuk2::Resource> oldResources = m_nepomukResourceWatcher->resources();
399 foreach (const Nepomuk2::Resource& resource, oldResources) {
400 const QUrl uri = resource.uri();
401 const KUrl itemUrl = m_nepomukUriItems.value(uri);
402 if (m_model->index(itemUrl) >= 0) {
403 newResources.append(resource);
404 } else {
405 m_nepomukUriItems.remove(uri);
406 }
407 }
408 m_nepomukResourceWatcher->setResources(newResources);
409 if (newResources.isEmpty()) {
410 Q_ASSERT(m_nepomukUriItems.isEmpty());
411 m_nepomukResourceWatcher->stop();
412 }
413 }
414 }
415 #endif
416
417 if (allItemsRemoved) {
418 m_state = Idle;
419
420 m_finishedItems.clear();
421 m_pendingSortRoleItems.clear();
422 m_pendingIndexes.clear();
423 m_pendingPreviewItems.clear();
424 m_recentlyChangedItems.clear();
425 m_recentlyChangedItemsTimer->stop();
426 m_changedItems.clear();
427
428 killPreviewJob();
429 } else {
430 // Only remove the items from m_finishedItems. They will be removed
431 // from the other sets later on.
432 QSet<KFileItem>::iterator it = m_finishedItems.begin();
433 while (it != m_finishedItems.end()) {
434 if (m_model->index(*it) < 0) {
435 it = m_finishedItems.erase(it);
436 } else {
437 ++it;
438 }
439 }
440
441 // The visible items might have changed.
442 startUpdating();
443 }
444 }
445
446 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange& itemRange, QList<int> movedToIndexes)
447 {
448 Q_UNUSED(itemRange);
449 Q_UNUSED(movedToIndexes);
450
451 // The visible items might have changed.
452 startUpdating();
453 }
454
455 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRanges,
456 const QSet<QByteArray>& roles)
457 {
458 Q_UNUSED(roles);
459
460 // Find out if slotItemsChanged() has been done recently. If that is the
461 // case, resolving the roles is postponed until a timer has exceeded
462 // to prevent expensive repeated updates if files are updated frequently.
463 const bool itemsChangedRecently = m_recentlyChangedItemsTimer->isActive();
464
465 QSet<KFileItem>& targetSet = itemsChangedRecently ? m_recentlyChangedItems : m_changedItems;
466
467 foreach (const KItemRange& itemRange, itemRanges) {
468 int index = itemRange.index;
469 for (int count = itemRange.count; count > 0; --count) {
470 const KFileItem item = m_model->fileItem(index);
471 targetSet.insert(item);
472 ++index;
473 }
474 }
475
476 m_recentlyChangedItemsTimer->start();
477
478 if (!itemsChangedRecently) {
479 updateChangedItems();
480 }
481 }
482
483 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current,
484 const QByteArray& previous)
485 {
486 Q_UNUSED(current);
487 Q_UNUSED(previous);
488
489 if (m_resolvableRoles.contains(current)) {
490 m_pendingSortRoleItems.clear();
491 m_finishedItems.clear();
492
493 const int count = m_model->count();
494 QElapsedTimer timer;
495 timer.start();
496
497 // Determine the sort role synchronously for as many items as possible.
498 for (int index = 0; index < count; ++index) {
499 if (timer.elapsed() < MaxBlockTimeout) {
500 applySortRole(index);
501 } else {
502 m_pendingSortRoleItems.insert(m_model->fileItem(index));
503 }
504 }
505
506 applySortProgressToModel();
507
508 if (!m_pendingSortRoleItems.isEmpty()) {
509 // Trigger the asynchronous determination of the sort role.
510 killPreviewJob();
511 m_state = ResolvingSortRole;
512 resolveNextSortRole();
513 }
514 } else {
515 m_state = Idle;
516 m_pendingSortRoleItems.clear();
517 applySortProgressToModel();
518 }
519 }
520
521 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPixmap& pixmap)
522 {
523 if (m_state != PreviewJobRunning) {
524 return;
525 }
526
527 m_changedItems.remove(item);
528
529 const int index = m_model->index(item);
530 if (index < 0) {
531 return;
532 }
533
534 QPixmap scaledPixmap = pixmap;
535
536 const QString mimeType = item.mimetype();
537 const int slashIndex = mimeType.indexOf(QLatin1Char('/'));
538 const QString mimeTypeGroup = mimeType.left(slashIndex);
539 if (mimeTypeGroup == QLatin1String("image")) {
540 if (m_enlargeSmallPreviews) {
541 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
542 } else {
543 // Assure that small previews don't get enlarged. Instead they
544 // should be shown centered within the frame.
545 const QSize contentSize = KPixmapModifier::sizeInsideFrame(m_iconSize);
546 const bool enlargingRequired = scaledPixmap.width() < contentSize.width() &&
547 scaledPixmap.height() < contentSize.height();
548 if (enlargingRequired) {
549 QSize frameSize = scaledPixmap.size();
550 frameSize.scale(m_iconSize, Qt::KeepAspectRatio);
551
552 QPixmap largeFrame(frameSize);
553 largeFrame.fill(Qt::transparent);
554
555 KPixmapModifier::applyFrame(largeFrame, frameSize);
556
557 QPainter painter(&largeFrame);
558 painter.drawPixmap((largeFrame.width() - scaledPixmap.width()) / 2,
559 (largeFrame.height() - scaledPixmap.height()) / 2,
560 scaledPixmap);
561 scaledPixmap = largeFrame;
562 } else {
563 // The image must be shrinked as it is too large to fit into
564 // the available icon size
565 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
566 }
567 }
568 } else {
569 KPixmapModifier::scale(scaledPixmap, m_iconSize);
570 }
571
572 QHash<QByteArray, QVariant> data = rolesData(item);
573 data.insert("iconPixmap", scaledPixmap);
574
575 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
576 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
577 m_model->setData(index, data);
578 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
579 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
580
581 m_finishedItems.insert(item);
582 }
583
584 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item)
585 {
586 if (m_state != PreviewJobRunning) {
587 return;
588 }
589
590 m_changedItems.remove(item);
591
592 const int index = m_model->index(item);
593 if (index >= 0) {
594 QHash<QByteArray, QVariant> data;
595 data.insert("iconPixmap", QPixmap());
596
597 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
598 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
599 m_model->setData(index, data);
600 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
601 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
602
603 applyResolvedRoles(item, ResolveAll);
604 m_finishedItems.insert(item);
605 }
606 }
607
608 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
609 {
610 m_previewJob = 0;
611
612 if (m_state != PreviewJobRunning) {
613 return;
614 }
615
616 m_state = Idle;
617
618 if (!m_pendingPreviewItems.isEmpty()) {
619 startPreviewJob();
620 } else {
621 if (!m_changedItems.isEmpty()) {
622 updateChangedItems();
623 }
624 }
625 }
626
627 void KFileItemModelRolesUpdater::resolveNextSortRole()
628 {
629 if (m_state != ResolvingSortRole) {
630 return;
631 }
632
633 QSet<KFileItem>::iterator it = m_pendingSortRoleItems.begin();
634 while (it != m_pendingSortRoleItems.end()) {
635 const KFileItem item = *it;
636 const int index = m_model->index(item);
637
638 // Continue if the sort role has already been determined for the
639 // item, and the item has not been changed recently.
640 if (!m_changedItems.contains(item) && m_model->data(index).contains(m_model->sortRole())) {
641 it = m_pendingSortRoleItems.erase(it);
642 continue;
643 }
644
645 applySortRole(index);
646 m_pendingSortRoleItems.erase(it);
647 break;
648 }
649
650 if (!m_pendingSortRoleItems.isEmpty()) {
651 applySortProgressToModel();
652 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
653 } else {
654 m_state = Idle;
655
656 // Prevent that we try to update the items twice.
657 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
658 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
659 applySortProgressToModel();
660 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
661 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
662 startUpdating();
663 }
664 }
665
666 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
667 {
668 if (m_state != ResolvingAllRoles) {
669 return;
670 }
671
672 while (!m_pendingIndexes.isEmpty()) {
673 const int index = m_pendingIndexes.takeFirst();
674 const KFileItem item = m_model->fileItem(index);
675
676 if (m_finishedItems.contains(item)) {
677 continue;
678 }
679
680 applyResolvedRoles(item, ResolveAll);
681 m_finishedItems.insert(item);
682 m_changedItems.remove(item);
683 break;
684 }
685
686 if (!m_pendingIndexes.isEmpty()) {
687 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
688 } else {
689 m_state = Idle;
690
691 if (m_clearPreviews) {
692 // Only go through the list if there are items which might still have previews.
693 if (m_finishedItems.count() != m_model->count()) {
694 QHash<QByteArray, QVariant> data;
695 data.insert("iconPixmap", QPixmap());
696
697 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
698 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
699 for (int index = 0; index <= m_model->count(); ++index) {
700 if (m_model->data(index).contains("iconPixmap")) {
701 m_model->setData(index, data);
702 }
703 }
704 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
705 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
706
707 }
708 m_clearPreviews = false;
709 }
710
711 if (!m_changedItems.isEmpty()) {
712 updateChangedItems();
713 }
714 }
715 }
716
717 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
718 {
719 m_changedItems += m_recentlyChangedItems;
720 m_recentlyChangedItems.clear();
721 updateChangedItems();
722 }
723
724 void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource& resource, const Nepomuk2::Types::Property& property)
725 {
726 #ifdef HAVE_NEPOMUK
727 if (!Nepomuk2::ResourceManager::instance()->initialized()) {
728 return;
729 }
730
731 const KUrl itemUrl = m_nepomukUriItems.value(resource.uri());
732 const KFileItem item = m_model->fileItem(itemUrl);
733
734 if (item.isNull()) {
735 // itemUrl is not in the model anymore, probably because
736 // the corresponding file has been deleted in the meantime.
737 return;
738 }
739
740 QHash<QByteArray, QVariant> data = rolesData(item);
741
742 const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
743 const QByteArray role = rolesProvider.roleForPropertyUri(property.uri());
744 if (!role.isEmpty() && m_roles.contains(role)) {
745 // Overwrite the changed role value with an empty QVariant, because the roles
746 // provider doesn't overwrite it when the property value list is empty.
747 // See bug 322348
748 data.insert(role, QVariant());
749 }
750
751 QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(resource, m_roles));
752 while (it.hasNext()) {
753 it.next();
754 data.insert(it.key(), it.value());
755 }
756
757 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
758 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
759 const int index = m_model->index(item);
760 m_model->setData(index, data);
761 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
762 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
763 #else
764 #ifndef Q_CC_MSVC
765 Q_UNUSED(resource);
766 #endif
767 #endif
768 }
769
770 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString& path)
771 {
772 const bool getSizeRole = m_roles.contains("size");
773 const bool getIsExpandableRole = m_roles.contains("isExpandable");
774
775 if (getSizeRole || getIsExpandableRole) {
776 const int index = m_model->index(KUrl(path));
777 if (index >= 0) {
778 if (!m_model->fileItem(index).isDir()) {
779 // If INotify is used, KDirWatch issues the dirty() signal
780 // also for changed files inside the directory, even if we
781 // don't enable this behavior explicitly (see bug 309740).
782 return;
783 }
784
785 QHash<QByteArray, QVariant> data;
786
787 const int count = subItemsCount(path);
788 if (getSizeRole) {
789 data.insert("size", count);
790 }
791 if (getIsExpandableRole) {
792 data.insert("isExpandable", count > 0);
793 }
794
795 // Note that we do not block the itemsChanged signal here.
796 // This ensures that a new preview will be generated.
797 m_model->setData(index, data);
798 }
799 }
800 }
801
802 void KFileItemModelRolesUpdater::startUpdating()
803 {
804 if (m_state == Paused) {
805 return;
806 }
807
808 if (m_finishedItems.count() == m_model->count()) {
809 // All roles have been resolved already.
810 m_state = Idle;
811 return;
812 }
813
814 // Terminate all updates that are currently active.
815 killPreviewJob();
816 m_pendingIndexes.clear();
817
818 QElapsedTimer timer;
819 timer.start();
820
821 // Determine the icons for the visible items synchronously.
822 updateVisibleIcons();
823
824 // A detailed update of the items in and near the visible area
825 // only makes sense if sorting is finished.
826 if (m_state == ResolvingSortRole) {
827 return;
828 }
829
830 // Start the preview job or the asynchronous resolving of all roles.
831 QList<int> indexes = indexesToResolve();
832
833 if (m_previewShown) {
834 m_pendingPreviewItems.clear();
835 m_pendingPreviewItems.reserve(indexes.count());
836
837 foreach (int index, indexes) {
838 const KFileItem item = m_model->fileItem(index);
839 if (!m_finishedItems.contains(item)) {
840 m_pendingPreviewItems.append(item);
841 }
842 }
843
844 startPreviewJob();
845 } else {
846 m_pendingIndexes = indexes;
847 // Trigger the asynchronous resolving of all roles.
848 m_state = ResolvingAllRoles;
849 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
850 }
851 }
852
853 void KFileItemModelRolesUpdater::updateVisibleIcons()
854 {
855 int lastVisibleIndex = m_lastVisibleIndex;
856 if (lastVisibleIndex <= 0) {
857 // Guess a reasonable value for the last visible index if the view
858 // has not told us about the real value yet.
859 lastVisibleIndex = qMin(m_firstVisibleIndex + m_maximumVisibleItems, m_model->count() - 1);
860 if (lastVisibleIndex <= 0) {
861 lastVisibleIndex = qMin(200, m_model->count() - 1);
862 }
863 }
864
865 QElapsedTimer timer;
866 timer.start();
867
868 // Try to determine the final icons for all visible items.
869 int index;
870 for (index = m_firstVisibleIndex; index <= lastVisibleIndex && timer.elapsed() < MaxBlockTimeout; ++index) {
871 const KFileItem item = m_model->fileItem(index);
872 applyResolvedRoles(item, ResolveFast);
873 }
874
875 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
876 // preliminary icons (i.e., without mime type determination) for the
877 // remaining items.
878 }
879
880 void KFileItemModelRolesUpdater::startPreviewJob()
881 {
882 m_state = PreviewJobRunning;
883
884 if (m_pendingPreviewItems.isEmpty()) {
885 QTimer::singleShot(0, this, SLOT(slotPreviewJobFinished()));
886 return;
887 }
888
889 // PreviewJob internally caches items always with the size of
890 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
891 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
892 // do a downscaling anyhow because of the frame, so in this case only the provided
893 // cache sizes are requested.
894 const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128)
895 ? QSize(256, 256) : QSize(128, 128);
896
897 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
898 // worst case) might block the application for several seconds. To prevent such
899 // a blocking, we only pass items with known mime type to the preview job.
900 const int count = m_pendingPreviewItems.count();
901 KFileItemList itemSubSet;
902 itemSubSet.reserve(count);
903
904 if (m_pendingPreviewItems.first().isMimeTypeKnown()) {
905 // Some mime types are known already, probably because they were
906 // determined when loading the icons for the visible items. Start
907 // a preview job for all items at the beginning of the list which
908 // have a known mime type.
909 do {
910 itemSubSet.append(m_pendingPreviewItems.takeFirst());
911 } while (!m_pendingPreviewItems.isEmpty() && m_pendingPreviewItems.first().isMimeTypeKnown());
912 } else {
913 // Determine mime types for MaxBlockTimeout ms, and start a preview
914 // job for the corresponding items.
915 QElapsedTimer timer;
916 timer.start();
917
918 do {
919 const KFileItem item = m_pendingPreviewItems.takeFirst();
920 item.determineMimeType();
921 itemSubSet.append(item);
922 } while (!m_pendingPreviewItems.isEmpty() && timer.elapsed() < MaxBlockTimeout);
923 }
924
925 KIO::PreviewJob* job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins);
926
927 job->setIgnoreMaximumSize(itemSubSet.first().isLocalFile());
928 if (job->ui()) {
929 job->ui()->setWindow(qApp->activeWindow());
930 }
931
932 connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)),
933 this, SLOT(slotGotPreview(KFileItem,QPixmap)));
934 connect(job, SIGNAL(failed(KFileItem)),
935 this, SLOT(slotPreviewFailed(KFileItem)));
936 connect(job, SIGNAL(finished(KJob*)),
937 this, SLOT(slotPreviewJobFinished()));
938
939 m_previewJob = job;
940 }
941
942 void KFileItemModelRolesUpdater::updateChangedItems()
943 {
944 if (m_state == Paused) {
945 return;
946 }
947
948 if (m_changedItems.isEmpty()) {
949 return;
950 }
951
952 m_finishedItems -= m_changedItems;
953
954 if (m_resolvableRoles.contains(m_model->sortRole())) {
955 m_pendingSortRoleItems += m_changedItems;
956
957 if (m_state != ResolvingSortRole) {
958 // Stop the preview job if necessary, and trigger the
959 // asynchronous determination of the sort role.
960 killPreviewJob();
961 m_state = ResolvingSortRole;
962 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
963 }
964
965 return;
966 }
967
968 QList<int> visibleChangedIndexes;
969 QList<int> invisibleChangedIndexes;
970
971 foreach (const KFileItem& item, m_changedItems) {
972 const int index = m_model->index(item);
973
974 if (index < 0) {
975 m_changedItems.remove(item);
976 continue;
977 }
978
979 if (index >= m_firstVisibleIndex && index <= m_lastVisibleIndex) {
980 visibleChangedIndexes.append(index);
981 } else {
982 invisibleChangedIndexes.append(index);
983 }
984 }
985
986 std::sort(visibleChangedIndexes.begin(), visibleChangedIndexes.end());
987
988 if (m_previewShown) {
989 foreach (int index, visibleChangedIndexes) {
990 m_pendingPreviewItems.append(m_model->fileItem(index));
991 }
992
993 foreach (int index, invisibleChangedIndexes) {
994 m_pendingPreviewItems.append(m_model->fileItem(index));
995 }
996
997 if (!m_previewJob) {
998 startPreviewJob();
999 }
1000 } else {
1001 const bool resolvingInProgress = !m_pendingIndexes.isEmpty();
1002 m_pendingIndexes = visibleChangedIndexes + m_pendingIndexes + invisibleChangedIndexes;
1003 if (!resolvingInProgress) {
1004 // Trigger the asynchronous resolving of the changed roles.
1005 m_state = ResolvingAllRoles;
1006 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
1007 }
1008 }
1009 }
1010
1011 void KFileItemModelRolesUpdater::applySortRole(int index)
1012 {
1013 QHash<QByteArray, QVariant> data;
1014 const KFileItem item = m_model->fileItem(index);
1015
1016 if (m_model->sortRole() == "type") {
1017 if (!item.isMimeTypeKnown()) {
1018 item.determineMimeType();
1019 }
1020
1021 data.insert("type", item.mimeComment());
1022 } else if (m_model->sortRole() == "size" && item.isLocalFile() && item.isDir()) {
1023 const QString path = item.localPath();
1024 data.insert("size", subItemsCount(path));
1025 } else {
1026 // Probably the sort role is a Nepomuk role - just determine all roles.
1027 data = rolesData(item);
1028 }
1029
1030 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1031 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1032 m_model->setData(index, data);
1033 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1034 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1035 }
1036
1037 void KFileItemModelRolesUpdater::applySortProgressToModel()
1038 {
1039 // Inform the model about the progress of the resolved items,
1040 // so that it can give an indication when the sorting has been finished.
1041 const int resolvedCount = m_model->count() - m_pendingSortRoleItems.count();
1042 m_model->emitSortProgress(resolvedCount);
1043 }
1044
1045 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem& item, ResolveHint hint)
1046 {
1047 if (item.isNull()) {
1048 return false;
1049 }
1050
1051 const bool resolveAll = (hint == ResolveAll);
1052
1053 bool iconChanged = false;
1054 if (!item.isMimeTypeKnown() || !item.isFinalIconKnown()) {
1055 item.determineMimeType();
1056 iconChanged = true;
1057 } else {
1058 const int index = m_model->index(item);
1059 if (!m_model->data(index).contains("iconName")) {
1060 iconChanged = true;
1061 }
1062 }
1063
1064 if (iconChanged || resolveAll || m_clearPreviews) {
1065 const int index = m_model->index(item);
1066 if (index < 0) {
1067 return false;
1068 }
1069
1070 QHash<QByteArray, QVariant> data;
1071 if (resolveAll) {
1072 data = rolesData(item);
1073 }
1074
1075 data.insert("iconName", item.iconName());
1076
1077 if (m_clearPreviews) {
1078 data.insert("iconPixmap", QPixmap());
1079 }
1080
1081 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1082 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1083 m_model->setData(index, data);
1084 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1085 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1086 return true;
1087 }
1088
1089 return false;
1090 }
1091
1092 QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem& item) const
1093 {
1094 QHash<QByteArray, QVariant> data;
1095
1096 const bool getSizeRole = m_roles.contains("size");
1097 const bool getIsExpandableRole = m_roles.contains("isExpandable");
1098
1099 if ((getSizeRole || getIsExpandableRole) && item.isDir()) {
1100 if (item.isLocalFile()) {
1101 const QString path = item.localPath();
1102 const int count = subItemsCount(path);
1103 if (getSizeRole) {
1104 data.insert("size", count);
1105 }
1106 if (getIsExpandableRole) {
1107 data.insert("isExpandable", count > 0);
1108 }
1109
1110 if (!m_dirWatcher->contains(path)) {
1111 m_dirWatcher->addDir(path);
1112 m_watchedDirs.insert(path);
1113 }
1114 } else if (getSizeRole) {
1115 data.insert("size", -1); // -1 indicates an unknown number of items
1116 }
1117 }
1118
1119 if (m_roles.contains("type")) {
1120 data.insert("type", item.mimeComment());
1121 }
1122
1123 data.insert("iconOverlays", item.overlays());
1124
1125 #ifdef HAVE_NEPOMUK
1126 if (m_nepomukResourceWatcher) {
1127 const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
1128 Nepomuk2::Resource resource(item.nepomukUri());
1129 QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(resource, m_roles));
1130 while (it.hasNext()) {
1131 it.next();
1132 data.insert(it.key(), it.value());
1133 }
1134
1135 QUrl uri = resource.uri();
1136 if (uri.isEmpty()) {
1137 // TODO: Is there another way to explicitly create a resource?
1138 // We need a resource to be able to track it for changes.
1139 resource.setRating(0);
1140 uri = resource.uri();
1141 }
1142 if (!uri.isEmpty() && !m_nepomukUriItems.contains(uri)) {
1143 m_nepomukResourceWatcher->addResource(resource);
1144
1145 if (m_nepomukUriItems.isEmpty()) {
1146 m_nepomukResourceWatcher->start();
1147 }
1148
1149 m_nepomukUriItems.insert(uri, item.url());
1150 }
1151 }
1152 #endif
1153
1154 return data;
1155 }
1156
1157 int KFileItemModelRolesUpdater::subItemsCount(const QString& path) const
1158 {
1159 const bool countHiddenFiles = m_model->showHiddenFiles();
1160 const bool showFoldersOnly = m_model->showDirectoriesOnly();
1161
1162 #ifdef Q_WS_WIN
1163 QDir dir(path);
1164 QDir::Filters filters = QDir::NoDotAndDotDot | QDir::System;
1165 if (countHiddenFiles) {
1166 filters |= QDir::Hidden;
1167 }
1168 if (showFoldersOnly) {
1169 filters |= QDir::Dirs;
1170 } else {
1171 filters |= QDir::AllEntries;
1172 }
1173 return dir.entryList(filters).count();
1174 #else
1175 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1176 // Copyright (C) 2006 David Faure <faure@kde.org>
1177
1178 int count = -1;
1179 DIR* dir = ::opendir(QFile::encodeName(path));
1180 if (dir) { // krazy:exclude=syscalls
1181 count = 0;
1182 struct dirent *dirEntry = 0;
1183 while ((dirEntry = ::readdir(dir))) {
1184 if (dirEntry->d_name[0] == '.') {
1185 if (dirEntry->d_name[1] == '\0' || !countHiddenFiles) {
1186 // Skip "." or hidden files
1187 continue;
1188 }
1189 if (dirEntry->d_name[1] == '.' && dirEntry->d_name[2] == '\0') {
1190 // Skip ".."
1191 continue;
1192 }
1193 }
1194
1195 // If only directories are counted, consider an unknown file type and links also
1196 // as directory instead of trying to do an expensive stat()
1197 // (see bugs 292642 and 299997).
1198 const bool countEntry = !showFoldersOnly ||
1199 dirEntry->d_type == DT_DIR ||
1200 dirEntry->d_type == DT_LNK ||
1201 dirEntry->d_type == DT_UNKNOWN;
1202 if (countEntry) {
1203 ++count;
1204 }
1205 }
1206 ::closedir(dir);
1207 }
1208 return count;
1209 #endif
1210 }
1211
1212 void KFileItemModelRolesUpdater::updateAllPreviews()
1213 {
1214 if (m_state == Paused) {
1215 m_previewChangedDuringPausing = true;
1216 } else {
1217 m_finishedItems.clear();
1218 startUpdating();
1219 }
1220 }
1221
1222 void KFileItemModelRolesUpdater::killPreviewJob()
1223 {
1224 if (m_previewJob) {
1225 disconnect(m_previewJob, SIGNAL(gotPreview(KFileItem,QPixmap)),
1226 this, SLOT(slotGotPreview(KFileItem,QPixmap)));
1227 disconnect(m_previewJob, SIGNAL(failed(KFileItem)),
1228 this, SLOT(slotPreviewFailed(KFileItem)));
1229 disconnect(m_previewJob, SIGNAL(finished(KJob*)),
1230 this, SLOT(slotPreviewJobFinished()));
1231 m_previewJob->kill();
1232 m_previewJob = 0;
1233 m_pendingPreviewItems.clear();
1234 }
1235 }
1236
1237 QList<int> KFileItemModelRolesUpdater::indexesToResolve() const
1238 {
1239 const int count = m_model->count();
1240
1241 QList<int> result;
1242 result.reserve(ResolveAllItemsLimit);
1243
1244 // Add visible items.
1245 for (int i = m_firstVisibleIndex; i <= m_lastVisibleIndex; ++i) {
1246 result.append(i);
1247 }
1248
1249 // We need a reasonable upper limit for number of items to resolve after
1250 // and before the visible range. m_maximumVisibleItems can be quite large
1251 // when using Compace View.
1252 const int readAheadItems = qMin(ReadAheadPages * m_maximumVisibleItems, ResolveAllItemsLimit / 2);
1253
1254 // Add items after the visible range.
1255 const int endExtendedVisibleRange = qMin(m_lastVisibleIndex + readAheadItems, count - 1);
1256 for (int i = m_lastVisibleIndex + 1; i <= endExtendedVisibleRange; ++i) {
1257 result.append(i);
1258 }
1259
1260 // Add items before the visible range in reverse order.
1261 const int beginExtendedVisibleRange = qMax(0, m_firstVisibleIndex - readAheadItems);
1262 for (int i = m_firstVisibleIndex - 1; i >= beginExtendedVisibleRange; --i) {
1263 result.append(i);
1264 }
1265
1266 // Add items on the last page.
1267 const int beginLastPage = qMax(qMin(endExtendedVisibleRange + 1, count - 1), count - m_maximumVisibleItems);
1268 for (int i = beginLastPage; i < count; ++i) {
1269 result.append(i);
1270 }
1271
1272 // Add items on the first page.
1273 const int endFirstPage = qMin(qMax(beginExtendedVisibleRange - 1, 0), m_maximumVisibleItems);
1274 for (int i = 0; i <= endFirstPage; ++i) {
1275 result.append(i);
1276 }
1277
1278 // Continue adding items until ResolveAllItemsLimit is reached.
1279 int remainingItems = ResolveAllItemsLimit - result.count();
1280
1281 for (int i = endExtendedVisibleRange + 1; i < beginLastPage && remainingItems > 0; ++i) {
1282 result.append(i);
1283 --remainingItems;
1284 }
1285
1286 for (int i = beginExtendedVisibleRange - 1; i > endFirstPage && remainingItems > 0; --i) {
1287 result.append(i);
1288 --remainingItems;
1289 }
1290
1291 return result;
1292 }
1293
1294 #include "kfileitemmodelrolesupdater.moc"