]> cloud.milkyroute.net Git - dolphin.git/blob - src/statusbar/mountpointobservercache.cpp
Drop KNS3 prefix for KMoreTools includes
[dolphin.git] / src / statusbar / mountpointobservercache.cpp
1 /*
2 * SPDX-FileCopyrightText: 2014 Frank Reininghaus <frank78ac@googlemail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "mountpointobservercache.h"
8
9 #include "mountpointobserver.h"
10
11 #include <KMountPoint>
12
13 #include <QTimer>
14
15 class MountPointObserverCacheSingleton
16 {
17 public:
18 MountPointObserverCache instance;
19 };
20 Q_GLOBAL_STATIC(MountPointObserverCacheSingleton, s_MountPointObserverCache)
21
22
23 MountPointObserverCache::MountPointObserverCache() :
24 m_observerForMountPoint(),
25 m_mountPointForObserver(),
26 m_updateTimer(nullptr)
27 {
28 m_updateTimer = new QTimer(this);
29 }
30
31 MountPointObserverCache::~MountPointObserverCache()
32 {
33 }
34
35 MountPointObserverCache* MountPointObserverCache::instance()
36 {
37 return &s_MountPointObserverCache->instance;
38 }
39
40 MountPointObserver* MountPointObserverCache::observerForUrl(const QUrl& url)
41 {
42 QUrl cachedObserverUrl;
43 // If the url is a local path we can extract the root dir by checking the mount points.
44 if (url.isLocalFile()) {
45 // Try to share the observer with other paths that have the same mount point.
46 KMountPoint::Ptr mountPoint = KMountPoint::currentMountPoints().findByPath(url.toLocalFile());
47 if (mountPoint) {
48 cachedObserverUrl = QUrl::fromLocalFile(mountPoint->mountPoint());
49 } else {
50 // Even if determining the mount point failed, the observer might still
51 // be able to retrieve information about the url.
52 cachedObserverUrl = url;
53 }
54 } else {
55 cachedObserverUrl = url;
56 }
57
58 MountPointObserver* observer = m_observerForMountPoint.value(cachedObserverUrl);
59 if (!observer) {
60 observer = new MountPointObserver(cachedObserverUrl, this);
61 m_observerForMountPoint.insert(cachedObserverUrl, observer);
62 m_mountPointForObserver.insert(observer, cachedObserverUrl);
63 Q_ASSERT(m_observerForMountPoint.count() == m_mountPointForObserver.count());
64
65 connect(observer, &MountPointObserver::destroyed, this, &MountPointObserverCache::slotObserverDestroyed);
66
67 if (!m_updateTimer->isActive()) {
68 m_updateTimer->start(60000); // 1 minute
69 }
70
71 connect(m_updateTimer, &QTimer::timeout, observer, &MountPointObserver::update);
72 }
73
74 return observer;
75 }
76
77 void MountPointObserverCache::slotObserverDestroyed(QObject* observer)
78 {
79 Q_ASSERT(m_mountPointForObserver.contains(observer));
80 const QUrl& url = m_mountPointForObserver.value(observer);
81 Q_ASSERT(m_observerForMountPoint.contains(url));
82 m_observerForMountPoint.remove(url);
83 m_mountPointForObserver.remove(observer);
84
85 Q_ASSERT(m_observerForMountPoint.count() == m_mountPointForObserver.count());
86
87 if (m_mountPointForObserver.isEmpty()) {
88 m_updateTimer->stop();
89 }
90 }