QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
storetree.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "storetree.h"
9#include "util.h"
10#include <QDir>
11#include <QHeaderView>
12#include <QScrollBar>
13#include <QTreeView>
14#include <algorithm>
15
16StoreTree::StoreTree(QTreeView *view, QObject *parent)
17 : QObject(parent), m_view(view), m_fs(makeModel()) {
18 m_view->setModel(&m_proxy);
19 m_view->setHeaderHidden(true);
20 m_view->setIndentation(15);
21 m_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
22 m_view->setContextMenuPolicy(Qt::CustomContextMenu);
23 // An entry picked after a swap ends a restore still waiting: a later
24 // listing must not undo that pick, or a deselect after it.
25 connect(m_view->selectionModel(), &QItemSelectionModel::currentChanged, this,
26 [this](const QModelIndex &current) {
27 if (current.isValid()) {
28 m_restoreCurrent.clear();
29 }
30 });
31
32 // A burst of changes (a pull, a re-encryption) ends in one reload.
33 m_reloadTimer.setSingleShot(true);
34 m_reloadTimer.setInterval(300);
35 connect(&m_watcher, &QFileSystemWatcher::directoryChanged, &m_reloadTimer,
36 qOverload<>(&QTimer::start));
37 connect(&m_reloadTimer, &QTimer::timeout, this, &StoreTree::reload);
38 // Also when a folder is expanded: the model does not always report a
39 // listing (one it made while looking up a path, say).
40 connect(m_view, &QTreeView::expanded, this, [this](const QModelIndex &index) {
41 const QFileInfo info = m_fs->fileInfo(m_proxy.mapToSource(index));
42 if (info.isDir()) {
43 watchDir(info.absoluteFilePath());
44 }
45 });
46 m_freshDeadline.setSingleShot(true);
47 m_freshDeadline.setInterval(3000);
48 connect(&m_freshDeadline, &QTimer::timeout, this, &StoreTree::swapInFresh);
49}
50
51auto StoreTree::makeModel() -> std::unique_ptr<QFileSystemModel> {
52 auto model = std::make_unique<QFileSystemModel>();
53 model->setNameFilters(QStringList() << QStringLiteral("*.gpg"));
54 model->setNameFilterDisables(false);
55 model->setOption(QFileSystemModel::DontWatchForChanges, true);
56 QFileSystemModel *raw = model.get();
57 connect(raw, &QFileSystemModel::directoryLoaded, this,
58 [this, raw](const QString &path) {
59 if (raw == m_fs.get()) {
60 shownListed(path);
61 } else if (raw == m_fresh.get()) {
62 m_freshPending.remove(QDir::cleanPath(path));
63 if (m_freshPending.isEmpty()) {
64 // Out of the model's own signal: the swap deletes models.
65 QTimer::singleShot(0, this, &StoreTree::swapInFresh);
66 }
67 }
68 });
69 return model;
70}
71
73 // Columns exist only once a source model is attached: hiding the size,
74 // type and date ones is a no-op before that point, and addressing header
75 // section 0 without any sections crashes on Qt 6.8.
76 m_view->setColumnHidden(1, true);
77 m_view->setColumnHidden(2, true);
78 m_view->setColumnHidden(3, true);
79 m_view->header()->setSectionResizeMode(0, QHeaderView::Stretch);
80 m_view->sortByColumn(0, Qt::AscendingOrder);
81}
82
83void StoreTree::watchDir(const QString &dir) {
84 const QString clean = QDir::cleanPath(dir);
85 if (!m_watcher.directories().contains(clean)) {
86 m_watcher.addPath(clean);
87 }
88}
89
90void StoreTree::shownListed(const QString &path) {
91 const QString clean = QDir::cleanPath(path);
92 watchDir(clean);
93 // Listed during a build: the fresh model lists it too, or a search after
94 // the swap would judge it by its name alone.
95 if (m_fresh != nullptr) {
96 const QModelIndex fresh = m_fresh->index(clean);
97 if (fresh.isValid() && m_fresh->canFetchMore(fresh)) {
98 m_freshPending.insert(clean);
99 m_fresh->fetchMore(fresh);
100 }
101 }
102 // The last listing a swap did not wait for: filter again, as folders it
103 // judged before their rows came may match now.
104 const bool lastLate =
105 m_stillListing.remove(clean) && m_stillListing.isEmpty();
106 if (lastLate && !m_proxy.filterRegularExpression().pattern().isEmpty()) {
107 m_proxy.invalidate();
108 m_view->setRootIndex(m_proxy.rootIndexFor(m_store));
109 }
111 if (lastLate) {
112 // The wait ends with the late listings: a folder that does not show by
113 // then is not made current later, steps after the user left it.
114 m_restoreCurrent.clear();
115 }
116 emit directoryLoaded(path);
117}
118
120 if (m_restoreCurrent.isEmpty()) {
121 return;
122 }
123 if (!QFileInfo::exists(m_restoreCurrent)) {
124 m_restoreCurrent.clear();
125 return;
126 }
127 const QModelIndex shown = indexFor(m_restoreCurrent);
128 if (!shown.isValid()) {
129 return;
130 }
131 // Unless something else is current (a pick also ends the wait).
132 if (!m_view->currentIndex().isValid()) {
133 m_view->setCurrentIndex(shown);
134 }
135 m_restoreCurrent.clear();
136}
137
139 if (m_store.isEmpty()) {
140 return;
141 }
142 if (m_fresh != nullptr) {
143 // One build at a time. What changed meanwhile may be missing from it:
144 // list once more after the swap.
145 m_reloadAgain = true;
146 return;
147 }
148 m_reloadTimer.stop();
149 m_fresh = makeModel();
150 m_freshPending.clear();
151 const QString root = QDir::cleanPath(m_store);
152 m_fresh->setRootPath(root);
153 m_freshPending.insert(root);
154 m_fresh->fetchMore(m_fresh->index(root));
155 // Every folder the shown model listed and that still exists, expanded or
156 // not: a search judges a folder that was never listed by its name alone,
157 // and cannot expand one it hides, so a widened search would miss what is
158 // inside. The swap can also show the expanded ones expanded at once.
159 for (const QString &dir : m_watcher.directories()) {
160 if (dir == root || !QFileInfo(dir).isDir()) {
161 continue;
162 }
163 m_freshPending.insert(dir);
164 m_fresh->fetchMore(m_fresh->index(dir));
165 }
166 m_freshDeadline.start();
167}
168
169auto StoreTree::expandedDirs() const -> QStringList {
170 QStringList expanded;
171 for (const QString &dir : m_watcher.directories()) {
172 const QModelIndex shown = m_proxy.mapFromSource(m_fs->index(dir));
173 if (shown.isValid() && m_view->isExpanded(shown)) {
174 expanded << dir;
175 }
176 }
177 // Parents first, so each expand finds its row.
178 std::sort(expanded.begin(), expanded.end(),
179 [](const QString &a, const QString &b) {
180 return a.count(QLatin1Char('/')) < b.count(QLatin1Char('/'));
181 });
182 return expanded;
183}
184
186 const QStringList watched = m_watcher.directories();
187 QStringList gone;
188 for (const QString &dir : watched) {
189 if (!QFileInfo(dir).isDir()) {
190 gone << dir;
191 }
192 }
193 if (!gone.isEmpty()) {
194 m_watcher.removePaths(gone);
195 }
196}
197
199 m_freshDeadline.stop();
200 if (m_fresh == nullptr) {
201 return;
202 }
203 // What the view shows now, by path.
204 const QStringList expanded = expandedDirs();
205 const QString current =
206 m_fs->filePath(m_proxy.mapToSource(m_view->currentIndex()));
207 const int scroll = m_view->verticalScrollBar()->value();
208
209 m_retired = std::move(m_fs);
210 m_fs = std::move(m_fresh);
211 // Swapped at the deadline, the listings still under way finish in it.
213 m_freshPending.clear();
214 m_restoreCurrent.clear();
216 setUpColumns();
217 m_view->setRootIndex(m_proxy.rootIndexFor(m_store));
218 // The folders reload() had listed stay watched, as long as they exist; a
219 // folder the new model lists later is watched then.
222 for (const QString &dir : std::as_const(expanded)) {
223 const QModelIndex shown = m_proxy.mapFromSource(m_fs->index(dir));
224 if (shown.isValid()) {
225 m_view->expand(shown);
226 }
227 }
228 bool currentLost = false;
229 if (!current.isEmpty()) {
230 const QModelIndex shown = m_proxy.mapFromSource(m_fs->index(current));
231 if (shown.isValid()) {
232 m_view->setCurrentIndex(shown);
233 } else {
234 // Gone, or not listed yet when the swap came at the deadline: then
235 // it is made current again if the late listings show it.
236 currentLost = true;
237 m_restoreCurrent = current;
238 }
239 }
240 m_view->verticalScrollBar()->setValue(scroll);
241 if (currentLost) {
242 emit currentEntryLost(current);
243 }
245 if (m_stillListing.isEmpty()) {
246 // Every listing is in: what does not show now is not waited for.
247 m_restoreCurrent.clear();
248 }
250 if (m_reloadAgain) {
251 m_reloadAgain = false;
252 m_reloadTimer.start();
253 }
254}
255
256void StoreTree::setStore(const QString &path) {
257 m_store = path;
258 // A build for the previous store is dropped; the folders watched were
259 // that store's.
260 m_freshDeadline.stop();
261 m_fresh.reset();
262 m_freshPending.clear();
263 m_stillListing.clear();
264 m_restoreCurrent.clear();
265 m_reloadAgain = false;
266 if (const QStringList watched = m_watcher.directories(); !watched.isEmpty()) {
267 m_watcher.removePaths(watched);
268 }
269 // A fresh model for every store: one that listed this store before keeps
270 // its folders cached and would show them as they were, unwatched while
271 // another store was shown.
272 if (m_proxy.sourceModel() != nullptr) {
273 m_retired = std::move(m_fs);
274 m_fs = makeModel();
275 }
276 const QModelIndex rootDir = m_fs->setRootPath(path);
277 m_fs->fetchMore(rootDir);
278 m_proxy.setModelAndStore(m_fs.get(), path);
279 setUpColumns();
280 m_proxy.setFilterRegularExpression(QRegularExpression());
281 m_view->setRootIndex(m_proxy.rootIndexFor(path));
282 // Not left to directoryLoaded alone: the root may be listed before then.
283 if (QFileInfo(path).isDir()) {
284 watchDir(path);
285 }
286}
287
289
290void StoreTree::setFilter(const QRegularExpression &pattern) {
291 m_proxy.setFilterRegularExpression(pattern);
292 // Filtering re-derives the mapping; the root must be looked up again.
293 m_view->setRootIndex(m_proxy.rootIndexFor(m_store));
295}
296
297auto StoreTree::dirFor(const QModelIndex &index, bool forPass) const
298 -> QString {
299 const QString abspath = QDir(m_store).absolutePath() + QDir::separator();
300 if (!index.isValid()) {
301 return forPass ? QString() : abspath;
302 }
303 const QFileInfo info = m_fs->fileInfo(m_proxy.mapToSource(index));
304 QString filePath =
305 info.isFile() ? info.absolutePath() : info.absoluteFilePath();
306 if (forPass) {
307 filePath = QDir(abspath).relativeFilePath(filePath);
308 }
309 filePath += QDir::separator();
310 return filePath;
311}
312
313auto StoreTree::currentDir(bool forPass) const -> QString {
314 return dirFor(m_view->currentIndex(), forPass);
315}
316
317auto StoreTree::fileFor(const QModelIndex &index, bool forPass) const
318 -> QString {
319 if (!index.isValid() ||
320 !m_fs->fileInfo(m_proxy.mapToSource(index)).isFile()) {
321 return {};
322 }
323 QString filePath = m_fs->filePath(m_proxy.mapToSource(index));
324 if (forPass) {
325 filePath = QDir(m_store).relativeFilePath(filePath);
326 filePath.replace(Util::endsWithGpg(), "");
327 }
328 return filePath;
329}
330
331auto StoreTree::currentFile(bool forPass) const -> QString {
332 return fileFor(m_view->currentIndex(), forPass);
333}
334
335auto StoreTree::fileInfo(const QModelIndex &index) const -> QFileInfo {
336 return m_fs->fileInfo(m_proxy.mapToSource(index));
337}
338
339auto StoreTree::indexFor(const QString &path) const -> QModelIndex {
340 const QModelIndex src = m_fs->index(path);
341 return src.isValid() ? m_proxy.mapFromSource(src) : QModelIndex();
342}
343
344auto StoreTree::rootIndex() -> QModelIndex {
345 return m_proxy.rootIndexFor(m_store);
346}
347
348auto StoreTree::currentIndex() const -> QModelIndex {
349 return m_view->currentIndex();
350}
Abstract base class for password store operations.
Definition pass.h:77
void setModelAndStore(QFileSystemModel *sourceModel, const QString &passStore)
Initialize model with source model and store path.
void setPass(Pass *pass)
Inject the Pass backend for drag-and-drop Move/Copy operations.
auto rootIndexFor(const QString &path) -> QModelIndex
Set the source filesystem root and map it to a proxy index.
QString m_store
Absolute store directory last passed to setStore().
Definition storetree.h:263
auto dirFor(const QModelIndex &index, bool forPass) const -> QString
The folder an index stands for.
std::unique_ptr< QFileSystemModel > m_fs
Source model over the store directory, filtered to *.gpg; replaced by setStore() and reload().
Definition storetree.h:232
void shownListed(const QString &path)
The shown model listed path: watch it, list it in a model being built too, and filter again once the ...
Definition storetree.cpp:90
auto fileInfo(const QModelIndex &index) const -> QFileInfo
File system information for a view index.
auto rootIndex() -> QModelIndex
The proxy's root index for the current store.
void swapInFresh()
Swap in the model reload() built, restoring the view.
QString m_restoreCurrent
The current entry a swap could not show yet.
Definition storetree.h:245
auto currentIndex() const -> QModelIndex
The view's current index.
QTimer m_freshDeadline
Ends the wait for m_fresh: it is swapped in as it is.
Definition storetree.h:249
auto currentFile(bool forPass) const -> QString
fileFor() applied to the view's current index.
QTreeView * m_view
The tree view this object drives; owned by the main window.
Definition storetree.h:227
auto fileFor(const QModelIndex &index, bool forPass) const -> QString
The entry an index stands for.
void setFilter(const QRegularExpression &pattern)
Filter the visible entries.
std::unique_ptr< QFileSystemModel > m_retired
The model reload() replaced, kept until the next one: a caller still holding it reads stale rows inst...
Definition storetree.h:237
void directoryLoaded(const QString &path)
The file system model the view shows finished listing a folder; also once for the store root after re...
void restoreCurrent()
Make the entry a swap could not show current again, once it shows. The wait ends when the listings th...
void unwatchGoneDirs()
Stop watching the folders that no longer exist.
StoreTree(QTreeView *view, QObject *parent=nullptr)
Attach the proxy model to the view and set its look: hidden header, indentation, scroll bars,...
Definition storetree.cpp:16
auto view() const -> QTreeView *
Definition storetree.h:158
void setStore(const QString &path)
Point everything at path: file system root, proxy store and view root index. Also drops a search filt...
QSet< QString > m_freshPending
Folders m_fresh still has to list before the swap.
Definition storetree.h:241
StoreModel m_proxy
Proxy the view shows: hides .git, strips .gpg, applies the search filter and handles drag and drop.
Definition storetree.h:261
void watchDir(const QString &dir)
Watch dir from now on, as the shown model has listed it.
Definition storetree.cpp:83
auto makeModel() -> std::unique_ptr< QFileSystemModel >
A file system model as the tree uses it: *.gpg only, and not watching (see the class description).
Definition storetree.cpp:51
auto expandedDirs() const -> QStringList
The watched folders the view shows expanded, for swapInFresh().
QTimer m_reloadTimer
Waits for the watched folders to be quiet, then reload().
Definition storetree.h:256
void reload()
List the store again in a fresh file system model and swap it in once the store root and every folder...
bool m_reloadAgain
A reload() came while m_fresh was built: run one after it.
Definition storetree.h:247
void setUpColumns()
Hide the size, type and date columns and sort by name, once a source model is attached.
Definition storetree.cpp:72
auto indexFor(const QString &path) const -> QModelIndex
The view index for an absolute path, or invalid when the file system model does not (yet) know it.
void currentEntryLost(const QString &path)
After a reload() the current entry or folder could not be shown again: it was removed or renamed,...
std::unique_ptr< QFileSystemModel > m_fresh
The model reload() is building, until it is swapped in.
Definition storetree.h:239
QSet< QString > m_stillListing
Folders still being listed when m_fresh was swapped in.
Definition storetree.h:243
void setPass(Pass *pass)
Hand the proxy the backend it drops onto.
auto currentDir(bool forPass) const -> QString
dirFor() applied to the view's current index.
QFileSystemWatcher m_watcher
The folders the shown model has listed; reload() lists all of them again.
Definition storetree.h:254
static auto endsWithGpg() -> const QRegularExpression &
Returns a regex to match .gpg file extensions.
Definition util.cpp:759
StoreTree: owns the QFileSystemModel and StoreModel behind the password tree view and maps view index...
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...