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