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