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
)
22 MountPointObserverCache::MountPointObserverCache()
23 : m_observerForMountPoint()
24 , m_mountPointForObserver()
25 , m_updateTimer(nullptr)
27 m_updateTimer
= new QTimer(this);
30 MountPointObserverCache::~MountPointObserverCache()
34 MountPointObserverCache
*MountPointObserverCache::instance()
36 return &s_MountPointObserverCache
->instance
;
39 MountPointObserver
*MountPointObserverCache::observerForUrl(const QUrl
&url
)
41 QUrl cachedObserverUrl
;
42 // If the url is a local path we can extract the root dir by checking the mount points.
43 if (url
.isLocalFile()) {
44 // Try to share the observer with other paths that have the same mount point.
45 KMountPoint::Ptr mountPoint
= KMountPoint::currentMountPoints().findByPath(url
.toLocalFile());
47 cachedObserverUrl
= QUrl::fromLocalFile(mountPoint
->mountPoint());
49 // Even if determining the mount point failed, the observer might still
50 // be able to retrieve information about the url.
51 cachedObserverUrl
= url
;
54 cachedObserverUrl
= url
;
57 MountPointObserver
*observer
= m_observerForMountPoint
.value(cachedObserverUrl
);
59 observer
= new MountPointObserver(cachedObserverUrl
, this);
60 m_observerForMountPoint
.insert(cachedObserverUrl
, observer
);
61 m_mountPointForObserver
.insert(observer
, cachedObserverUrl
);
62 Q_ASSERT(m_observerForMountPoint
.count() == m_mountPointForObserver
.count());
64 connect(observer
, &MountPointObserver::destroyed
, this, &MountPointObserverCache::slotObserverDestroyed
);
66 if (!m_updateTimer
->isActive()) {
67 m_updateTimer
->start(60000); // 1 minute
70 connect(m_updateTimer
, &QTimer::timeout
, observer
, &MountPointObserver::update
);
76 void MountPointObserverCache::slotObserverDestroyed(QObject
*observer
)
78 Q_ASSERT(m_mountPointForObserver
.contains(observer
));
79 const QUrl
&url
= m_mountPointForObserver
.value(observer
);
80 Q_ASSERT(m_observerForMountPoint
.contains(url
));
81 m_observerForMountPoint
.remove(url
);
82 m_mountPointForObserver
.remove(observer
);
84 Q_ASSERT(m_observerForMountPoint
.count() == m_mountPointForObserver
.count());
86 if (m_mountPointForObserver
.isEmpty()) {
87 m_updateTimer
->stop();
91 #include "moc_mountpointobservercache.cpp"