2 * SPDX-FileCopyrightText: 2014 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "mountpointobservercache.h"
9 #include "mountpointobserver.h"
11 #include <KMountPoint>
15 class MountPointObserverCacheSingleton
18 MountPointObserverCache instance
;
20 Q_GLOBAL_STATIC(MountPointObserverCacheSingleton
, s_MountPointObserverCache
)
23 MountPointObserverCache::MountPointObserverCache() :
24 m_observerForMountPoint(),
25 m_mountPointForObserver(),
26 m_updateTimer(nullptr)
28 m_updateTimer
= new QTimer(this);
31 MountPointObserverCache::~MountPointObserverCache()
35 MountPointObserverCache
* MountPointObserverCache::instance()
37 return &s_MountPointObserverCache
->instance
;
40 MountPointObserver
* MountPointObserverCache::observerForUrl(const QUrl
& url
)
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());
48 cachedObserverUrl
= QUrl::fromLocalFile(mountPoint
->mountPoint());
50 // Even if determining the mount point failed, the observer might still
51 // be able to retrieve information about the url.
52 cachedObserverUrl
= url
;
55 cachedObserverUrl
= url
;
58 MountPointObserver
* observer
= m_observerForMountPoint
.value(cachedObserverUrl
);
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());
65 connect(observer
, &MountPointObserver::destroyed
, this, &MountPointObserverCache::slotObserverDestroyed
);
67 if (!m_updateTimer
->isActive()) {
68 m_updateTimer
->start(60000); // 1 minute
71 connect(m_updateTimer
, &QTimer::timeout
, observer
, &MountPointObserver::update
);
77 void MountPointObserverCache::slotObserverDestroyed(QObject
* observer
)
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
);
85 Q_ASSERT(m_observerForMountPoint
.count() == m_mountPointForObserver
.count());
87 if (m_mountPointForObserver
.isEmpty()) {
88 m_updateTimer
->stop();