diff --git a/src/FileMenu.qml b/src/FileMenu.qml index 6af294eb..5e1ecb7c 100644 --- a/src/FileMenu.qml +++ b/src/FileMenu.qml @@ -39,7 +39,7 @@ FolioMenu { // A selected item in the folder being shown stands for the whole // selection, so Copy, Compress or Delete act on all of it. readonly property bool forSelection: forItem && target.selected === true && backend.folder.selectedCount > 1 - && backend.folder.indexOf(target.name) >= 0 + && backend.folder.indexOfPath(target.path) >= 0 readonly property var paths: !forItem ? [] : forSelection ? backend.folder.selectedPaths() : [target.path] // One disk image, and the drives it could be burned to, asked of udisks // as the menu opens rather than on every binding. diff --git a/src/FileRow.qml b/src/FileRow.qml index 2a6babec..1a990b36 100644 --- a/src/FileRow.qml +++ b/src/FileRow.qml @@ -20,15 +20,21 @@ Item { required property int itemCount required property string icon required property bool selected + required property int depth + required property bool expanded property bool current: false // In a column to the left: the folder the next column is showing. property bool trail: false property bool detailed: false property bool chevron: false + // In the list, a tree: each level indented, and a folder's arrow opens + // it in place (or closes it). + property bool tree: false signal clicked(int modifiers) signal activated() + signal toggled() implicitHeight: 32 @@ -71,10 +77,34 @@ Item { RowLayout { anchors.fill: parent - anchors.leftMargin: 14 + anchors.leftMargin: row.tree ? 4 + row.depth * 20 : 14 anchors.rightMargin: 14 spacing: 12 + // The folder's arrow: pointing on (with the reading direction) + // while it's closed, down while it's open. + Item { + visible: row.tree + Layout.rightMargin: -8 + implicitWidth: 18 + implicitHeight: 32 + Glyph { + visible: row.isDir + anchors.centerIn: parent + name: row.LayoutMirroring.enabled ? "back" : "forward" + size: 12 + rotation: row.expanded ? (row.LayoutMirroring.enabled ? -90 : 90) : 0 + color: arrowHover.hovered ? theme.foreground : theme.secondaryForeground + } + HoverHandler { id: arrowHover; enabled: row.isDir } + TapHandler { + enabled: row.isDir + // Before the row's own tap, which would select it instead. + grabPermissions: PointerHandler.CanTakeOverFromAnything + onTapped: row.toggled() + } + } + Item { implicitWidth: 20 implicitHeight: 20 diff --git a/src/FolderList.qml b/src/FolderList.qml index 330fdd70..ecdcfbd8 100644 --- a/src/FolderList.qml +++ b/src/FolderList.qml @@ -1,8 +1,10 @@ import QtQuick import QtQuick.Controls -// The folder as a list: name, size and date (the date, then the size, step -// aside in a narrow window). No headings: the sort menu and S sort it. +// The folder as a list, and a tree, as in the Finder: name, size and date +// (the date, then the size, step aside in a narrow window), and an arrow on +// each folder that opens it in place, its items listed under it a level +// in. No headings: the sort menu and S sort it. FileListView { id: list @@ -24,15 +26,42 @@ FileListView { rectOf: (i) => Qt.rect(0, i * 32, list.width, 32) } - // → goes into the selected folder and ← back up, as in the columns; - // mirrored, the other way round, with the reading direction. - function enter() { + // → opens the selected folder in place, and on one open already steps + // to its first item; ← closes it, or steps out to the folder the item + // is in, and from the top goes up a folder. Where nothing opens in + // place (a search, Recents, the trash), → goes into the folder. Mirrored, + // the other way round, with the reading direction. ⏎ or a double click + // goes into a folder anywhere. + function deeper() { const item = backend.folder.get(currentIndex) - if (item.isDir) + if (!item.isDir) + return + if (!backend.folder.expandable) backend.navigate(item.path) + else if (!item.expanded) + backend.folder.setExpanded(currentIndex, true) + else if (currentIndex + 1 < count && backend.folder.get(currentIndex + 1).depth > item.depth) + currentIndex = currentIndex + 1 } - Keys.onRightPressed: LayoutMirroring.enabled ? backend.goUp() : enter() - Keys.onLeftPressed: LayoutMirroring.enabled ? enter() : backend.goUp() + function shallower() { + const item = backend.folder.get(currentIndex) + if (item.expanded) + backend.folder.setExpanded(currentIndex, false) + else if (item.depth > 0) + currentIndex = backend.folder.parentRow(currentIndex) + else + backend.goUp() + } + Keys.onRightPressed: LayoutMirroring.enabled ? shallower() : deeper() + Keys.onLeftPressed: LayoutMirroring.enabled ? deeper() : shallower() + // A folder that couldn't be opened in place says why. + Connections { + target: backend.folder + function onExpandFailed(message) { backend.showMessage(message) } + } + // Open folders close on going to another view; coming back, the list + // starts closed. + Component.onDestruction: backend.folder.collapseAll() // Right-click on an item (selecting it) or on empty space. signal contextMenu(var item, string folder, point at) @@ -52,7 +81,9 @@ FileListView { delegate: FileRow { width: list.width detailed: true + tree: backend.folder.expandable current: selected + onToggled: backend.folder.setExpanded(index, !expanded) onClicked: (modifiers) => { selecting.click(index, modifiers); list.forceActiveFocus() } onActivated: backend.open(path) } diff --git a/src/FolderPane.qml b/src/FolderPane.qml index cc872c73..0fe23488 100644 --- a/src/FolderPane.qml +++ b/src/FolderPane.qml @@ -270,8 +270,22 @@ FocusScope { // through a rename, and through undoing and redoing one. function onRenamed(from, to) { places.renamed(from, to) } function onDone(folder, name) { - if (folder !== backend.path) + // Done inside a folder opened in place (the list's tree): its + // item is found by its whole path, now or once the folder's + // been read again. + if (folder !== backend.path) { + if (!backend.folder.expandable || !folder.startsWith(backend.path + "/")) + return + const path = folder + "/" + name + const inside = backend.folder.indexOfPath(path) + if (inside >= 0 && view.item) { + view.item.select(inside, false) + } else { + pane.lastPath = path + pane.cursorLetGo = false + } return + } const row = backend.folder.indexOf(name) if (row >= 0 && view.item) view.item.select(row, false) diff --git a/src/Selecting.qml b/src/Selecting.qml index 089a42cb..d6453cf9 100644 --- a/src/Selecting.qml +++ b/src/Selecting.qml @@ -8,6 +8,14 @@ QtObject { // The ListView or GridView whose currentIndex is the cursor. required property var view property int anchor: -1 + // The anchor's item, so its row is found again when rows come or go + // above it (a folder opening in the list's tree): it can be on the + // other side of them from the cursor. + property string anchorPath: "" + function setAnchor(row) { + anchor = row + anchorPath = row >= 0 ? (backend.folder.get(row).path || "") : "" + } // Set while the cursor is moved on purpose, so moving it doesn't also // reset the selection. property bool quiet: false @@ -16,15 +24,35 @@ QtObject { quiet = true view.currentIndex = index quiet = false + placed() + } + + // The item the cursor is on, and its row. Rows coming or going above it + // (a folder opening in the list's tree) move the cursor's row without + // moving the cursor: that isn't a move, and leaves the selection alone. + property string cursorPath: "" + property int cursorRow: -1 + function placed() { + cursorPath = view.currentIndex >= 0 ? (backend.folder.get(view.currentIndex).path || "") : "" + cursorRow = view.currentIndex } // The cursor moved by the keyboard (or the view itself). function cursorMoved() { if (quiet) return + const path = view.currentIndex >= 0 ? (backend.folder.get(view.currentIndex).path || "") : "" + if (path.length > 0 && path === cursorPath) { + // Still on its item: the anchor stays on its own item too. + if (anchorPath.length > 0) + anchor = backend.folder.indexOfPath(anchorPath) + cursorRow = view.currentIndex + return + } backend.folder.selectOnly(view.currentIndex) - anchor = view.currentIndex + setAnchor(view.currentIndex) view.positionViewAtIndex(view.currentIndex, ListView.Contain) + placed() } function click(index, modifiers) { @@ -34,10 +62,10 @@ QtObject { backend.folder.selectRange(anchor < 0 ? index : anchor, index, (modifiers & Qt.AltModifier) !== 0) } else if (modifiers & Qt.AltModifier) { backend.folder.toggleSelected(index) - anchor = index + setAnchor(index) } else { backend.folder.selectOnly(index) - anchor = index + setAnchor(index) } moveTo(index) } @@ -80,7 +108,7 @@ QtObject { // With no cursor (let go of by a click on empty space), the range // starts at the first item, where a step from no cursor starts. if (anchor < 0) - anchor = Math.max(0, view.currentIndex) + setAnchor(Math.max(0, view.currentIndex)) moveTo(index) backend.folder.selectRange(anchor, index, false) view.positionViewAtIndex(index, ListView.Contain) @@ -90,7 +118,7 @@ QtObject { // Ctrl+A or the rubber band since) stays selected. function letGo() { moveTo(-1) - anchor = -1 + setAnchor(-1) } // Puts the cursor on `row` (or, for -1, the first item). `keep` leaves a @@ -100,7 +128,7 @@ QtObject { moveTo(index) if (!(keep && backend.folder.selectedCount > 0)) { backend.folder.selectOnly(index) - anchor = index + setAnchor(index) } if (index >= 0) view.positionViewAtIndex(index, ListView.Contain) diff --git a/src/foldermodel.cpp b/src/foldermodel.cpp index 97392e4e..b4de493d 100644 --- a/src/foldermodel.cpp +++ b/src/foldermodel.cpp @@ -35,6 +35,8 @@ FolderModel::FolderModel(QObject *parent) : QAbstractListModel(parent) { m_staleClear.setSingleShot(true); m_staleClear.setInterval(150); connect(&m_staleClear, &QTimer::timeout, this, &FolderModel::clearEntries); + connect(this, &FolderModel::pathChanged, this, &FolderModel::expandableChanged); + connect(this, &FolderModel::queryChanged, this, &FolderModel::expandableChanged); } // Generations start at 1, so 0 stops any search or folder count still @@ -75,7 +77,13 @@ void FolderModel::remember() { // Search results are a moment's question, not a folder to come back to. if (!m_query.isEmpty()) return; - recentListings().insert(cacheKey(), new QVector(m_entries)); + // The folder's own items: what's opened in place is closed on coming + // back. + auto *own = new QVector; + for (const Entry &e : m_entries) + if (e.depth == 0) + own->push_back(e); + recentListings().insert(cacheKey(), own); } bool FolderModel::sameListing(const QVector &a, const QVector &b) { @@ -88,7 +96,7 @@ bool FolderModel::sameListing(const QVector &a, const QVector &b) // path (its id) when they change. if (a[i].path != b[i].path || a[i].size != b[i].size || a[i].modified != b[i].modified || a[i].isDir != b[i].isDir || a[i].name != b[i].name || a[i].extension != b[i].extension - || a[i].icon != b[i].icon || a[i].details != b[i].details) + || a[i].icon != b[i].icon || a[i].details != b[i].details || a[i].depth != b[i].depth) return false; return true; } @@ -126,6 +134,8 @@ QVariant FolderModel::data(const QModelIndex &index, int role) const { case ItemCountRole: return e.itemCount; case SelectedRole: return m_selected.contains(e.path); case IconRole: return e.icon; + case DepthRole: return e.depth; + case ExpandedRole: return m_expanded.contains(e.path); } return {}; } @@ -135,7 +145,7 @@ QHash FolderModel::roleNames() const { {NameRole, "name"}, {PathRole, "path"}, {IsDirRole, "isDir"}, {SizeRole, "size"}, {ModifiedRole, "modified"}, {KindRole, "kind"}, {MimeRole, "mime"}, {ExtensionRole, "extension"}, {ItemCountRole, "itemCount"}, {SelectedRole, "selected"}, - {IconRole, "icon"}, + {IconRole, "icon"}, {DepthRole, "depth"}, {ExpandedRole, "expanded"}, }; } @@ -172,6 +182,9 @@ void FolderModel::setQuery(const QString &query) { if (query == m_query) return; m_query = query; + // Search results are a flat list. + if (!m_query.isEmpty()) + forgetExpanded(); emit queryChanged(); setSelected({}); // Back to the folder: its remembered listing shows at once. @@ -209,6 +222,8 @@ void FolderModel::setPath(const QString &path) { if (!m_watcher.files().isEmpty()) m_watcher.removePaths(m_watcher.files()); m_path = clean; + m_expanded.clear(); + m_open.clear(); emit pathChanged(); // A search is of one folder; going elsewhere ends it. if (!m_query.isEmpty()) { @@ -543,15 +558,25 @@ void FolderModel::reload() { const QLocale locale; const QVariantList items = m_items; const QStringList filter = m_filter; + const QStringList expanded = expandable() ? QStringList(m_expanded.begin(), m_expanded.end()) : QStringList(); *m_latest = generation; const auto latest = m_latest; - auto *watcher = new QFutureWatcher, QString, QStringList>>(this); + auto *watcher = new QFutureWatcher, QString, QStringList, QHash>, QHash>>(this); connect(watcher, &QFutureWatcherBase::finished, this, [this, watcher, generation] { watcher->deleteLater(); if (generation != m_generation) return; // A newer listing replaced this one while it ran. m_staleClear.stop(); - const auto [entries, error, trashDirs] = watcher->result(); + const auto [listed, error, trashDirs, open, unread] = watcher->result(); + // The folders opened in place, each with its items under it, and + // those that can no longer be read closed. + for (auto it = open.begin(); it != open.end(); ++it) + if (m_expanded.contains(it.key())) + m_open.insert(it.key(), it.value()); + for (auto it = unread.begin(); it != unread.end(); ++it) + if (m_expanded.contains(it.key())) + failExpanded(it.key(), it.value()); + const QVector entries = m_open.isEmpty() ? listed : flatten(listed, m_open); // Unchanged (the usual case after showing a remembered listing): // leave the items alone, and only fill in folder counts still missing. const bool same = error == m_error && !m_entries.isEmpty() && sameListing(m_entries, entries); @@ -578,7 +603,7 @@ void FolderModel::reload() { remember(); countFolders(generation); }); - watcher->setFuture(QtConcurrent::run(&FolderModel::listingPool(), [path, showHidden, sort, query, items, filter, latest, generation, locale] { + watcher->setFuture(QtConcurrent::run(&FolderModel::listingPool(), [path, showHidden, sort, query, items, filter, expanded, latest, generation, locale] { QString error; const auto overtaken = [&] { return *latest != generation; }; // Finding the drives' trash looks over every mount, so it's done here, @@ -590,7 +615,23 @@ void FolderModel::reload() { : search(path, query, showHidden, sort, overtaken, 1000, locale, filter); if (!isPluginView(path)) entries.removeIf([&](const Entry &entry) { return !fits(filter, entry); }); - return std::make_tuple(entries, error, trashDirs); + // Every folder opened in place, read again with it; one that can't + // be is told by its error. + QHash> open; + QHash unread; + for (const QString &folder : expanded) { + if (overtaken()) + break; + QString why; + auto items = list(folder, showHidden, sort, &why, overtaken, locale); + if (!why.isEmpty()) { + unread.insert(folder, why); + continue; + } + items.removeIf([&](const Entry &entry) { return !fits(filter, entry); }); + open.insert(folder, items); + } + return std::make_tuple(entries, error, trashDirs, open, unread); })); } @@ -646,6 +687,7 @@ QVariantMap FolderModel::get(int row) const { const Entry &e = m_entries.at(row); QVariantMap map = toMap(e); map.insert("selected", m_selected.contains(e.path)); + map.insert("expanded", m_expanded.contains(e.path)); return map; } @@ -654,7 +696,7 @@ QVariantMap FolderModel::toMap(const Entry &entry) { {"name", entry.name}, {"path", entry.path}, {"isDir", entry.isDir}, {"size", entry.size}, {"modified", entry.modified}, {"kind", entry.kind}, {"mime", entry.mime}, {"extension", entry.extension}, {"itemCount", entry.itemCount}, {"icon", entry.icon}, - {"details", entry.details}, + {"details", entry.details}, {"depth", entry.depth}, }; } @@ -724,13 +766,176 @@ QStringList FolderModel::selectedPaths() const { return paths; } +// Among the folder's own items, not those of a folder opened in place. int FolderModel::indexOf(const QString &name) const { for (int row = 0; row < m_entries.size(); ++row) - if (m_entries[row].name == name) + if (m_entries[row].depth == 0 && m_entries[row].name == name) return row; return -1; } +bool FolderModel::expandable() const { + return !m_path.isEmpty() && !isView(m_path) && !isTrash(m_path) && m_query.isEmpty(); +} + +QVector FolderModel::flatten(const QVector &entries, const QHash> &open, int depth) { + QVector rows; + for (Entry e : entries) { + e.depth = depth; + rows.push_back(e); + if (e.isDir) + if (const auto inside = open.constFind(e.path); inside != open.constEnd()) + rows += flatten(*inside, open, depth + 1); + } + return rows; +} + +bool FolderModel::isExpanded(int row) const { + return row >= 0 && row < m_entries.size() && m_expanded.contains(m_entries[row].path); +} + +int FolderModel::parentRow(int row) const { + if (row < 0 || row >= m_entries.size()) + return -1; + for (int above = row - 1; above >= 0; --above) + if (m_entries[above].depth < m_entries[row].depth) + return above; + return -1; +} + +void FolderModel::setExpanded(int row, bool expanded) { + if (row < 0 || row >= m_entries.size() || !m_entries[row].isDir || !expandable() + || expanded == m_expanded.contains(m_entries[row].path)) + return; + const QString folder = m_entries[row].path; + const QModelIndex at = index(row); + if (!expanded) { + // It, and every folder opened inside it, close. + const QString inside = folder + '/'; + for (auto it = m_expanded.begin(); it != m_expanded.end();) { + if (*it == folder || it->startsWith(inside)) { + m_watcher.removePath(*it); + m_open.remove(*it); + m_opening.remove(*it); + it = m_expanded.erase(it); + } else { + ++it; + } + } + int end = row + 1; + while (end < m_entries.size() && m_entries[end].depth > m_entries[row].depth) + ++end; + if (end > row + 1) { + QSet selected = m_selected; + for (int r = row + 1; r < end; ++r) + selected.remove(m_entries[r].path); + beginRemoveRows({}, row + 1, end - 1); + m_entries.remove(row + 1, end - row - 1); + endRemoveRows(); + emit countChanged(); + // What was selected inside goes with it. + setSelected(selected); + } + emit dataChanged(at, at, {ExpandedRole}); + return; + } + + m_expanded.insert(folder); + m_watcher.addPath(folder); + emit dataChanged(at, at, {ExpandedRole}); + const quint64 opening = ++m_openings; + m_opening.insert(folder, opening); + const quint64 generation = m_generation; + const bool showHidden = m_showHidden; + const QString sort = m_sort; + const QStringList filter = m_filter; + const QLocale locale; + const auto latest = m_latest; + auto *watcher = new QFutureWatcher, QString>>(this); + connect(watcher, &QFutureWatcherBase::finished, this, [this, watcher, generation, folder, opening] { + watcher->deleteLater(); + // A re-read since (which reads it too), or closed meanwhile, and + // perhaps opened again: only this opening's reading counts. + if (generation != m_generation || m_opening.value(folder) != opening) + return; + m_opening.remove(folder); + const auto &[items, error] = watcher->result(); + if (!error.isEmpty()) { + failExpanded(folder, error); + return; + } + const int row = indexOfPath(folder); + if (row < 0) + return; + m_open.insert(folder, items); + // A re-read that finished first may have listed it already: its rows + // are replaced, never listed twice. + int end = row + 1; + while (end < m_entries.size() && m_entries[end].depth > m_entries[row].depth) + ++end; + if (end > row + 1) { + beginRemoveRows({}, row + 1, end - 1); + m_entries.remove(row + 1, end - row - 1); + endRemoveRows(); + } + const QVector rows = flatten(items, m_open, m_entries[row].depth + 1); + if (rows.isEmpty()) + return; + beginInsertRows({}, row + 1, row + int(rows.size())); + for (int i = 0; i < rows.size(); ++i) + m_entries.insert(row + 1 + i, rows[i]); + endInsertRows(); + emit countChanged(); + countFolders(generation); + }); + watcher->setFuture(QtConcurrent::run(&FolderModel::listingPool(), [folder, showHidden, sort, filter, latest, generation, locale] { + QString error; + auto items = list(folder, showHidden, sort, &error, [&] { return *latest != generation; }, locale); + items.removeIf([&](const Entry &entry) { return !fits(filter, entry); }); + return std::make_pair(items, error); + })); +} + +void FolderModel::failExpanded(const QString &folder, const QString &error) { + // Closed as a click on its arrow would, its items (if any were shown) + // going with it. + if (const int row = indexOfPath(folder); row >= 0 && m_expanded.contains(folder)) { + setExpanded(row, false); + } else { + m_expanded.remove(folder); + m_open.remove(folder); + m_opening.remove(folder); + m_watcher.removePath(folder); + } + //: %1 is a folder's name, %2 why it couldn't be opened. + emit expandFailed(tr("%1: %2").arg(QFileInfo(folder).fileName(), error)); +} + +void FolderModel::forgetExpanded() { + for (const QString &folder : std::as_const(m_expanded)) + if (folder != m_path) + m_watcher.removePath(folder); + m_expanded.clear(); + m_open.clear(); + m_opening.clear(); +} + +void FolderModel::collapseAll() { + if (m_expanded.isEmpty()) + return; + forgetExpanded(); + QVector own; + for (const Entry &e : std::as_const(m_entries)) + if (e.depth == 0) + own.push_back(e); + QSet selected; + for (const Entry &e : std::as_const(own)) + if (m_selected.contains(e.path)) + selected.insert(e.path); + setEntries(own); + setSelected(selected); +} + int FolderModel::indexOfPath(const QString &path) const { for (int row = 0; row < m_entries.size(); ++row) if (m_entries[row].path == path) diff --git a/src/foldermodel.h b/src/foldermodel.h index 24e9496e..80cf9aeb 100644 --- a/src/foldermodel.h +++ b/src/foldermodel.h @@ -35,6 +35,10 @@ class FolderModel : public QAbstractListModel { Q_PROPERTY(QVariantList items READ items WRITE setItems NOTIFY itemsChanged) // A file chooser's filter: only files that fit it are listed (see fits()). Q_PROPERTY(QStringList filter READ filter WRITE setFilter NOTIFY filterChanged) + // Whether folders here can be opened in place, as a tree (the list + // view's): in a folder, not a search, Recents, the trash or a plugin's + // view. + Q_PROPERTY(bool expandable READ expandable NOTIFY expandableChanged) public: enum Role { @@ -49,6 +53,8 @@ class FolderModel : public QAbstractListModel { ItemCountRole, SelectedRole, IconRole, + DepthRole, + ExpandedRole, }; struct Entry { @@ -67,6 +73,9 @@ class FolderModel : public QAbstractListModel { int itemCount = -1; // The first pictures in a folder, for the preview window. QStringList peek; + // How deep in the tree: 0 for the folder's own items, 1 for those of + // a folder opened in place under them, and so on. + int depth = 0; }; explicit FolderModel(QObject *parent = nullptr); @@ -113,6 +122,20 @@ class FolderModel : public QAbstractListModel { Q_INVOKABLE bool isSelected(int row) const; Q_INVOKABLE QStringList selectedPaths() const; + // The tree: a folder opened in place lists its items right under it, a + // level deeper, read in the background; closed, they go, and so does + // any folder opened inside it. Rows keep being rows, so selecting, + // file work and the cursor treat them as any other. Going to another + // folder closes them all. + bool expandable() const; + Q_INVOKABLE void setExpanded(int row, bool expanded); + Q_INVOKABLE bool isExpanded(int row) const; + Q_INVOKABLE void collapseAll(); + // The row of the folder `row` is listed under, or -1 at the top. + Q_INVOKABLE int parentRow(int row) const; + // A folder's items with the open folders' own under them, `depth` deep. + static QVector flatten(const QVector &entries, const QHash> &open, int depth = 0); + // Listings run here, not on the global pool, so folder counts and file // transfers can't hold up the folder just opened. static QThreadPool &listingPool(); @@ -177,6 +200,10 @@ class FolderModel : public QAbstractListModel { void filterChanged(); void selectionChanged(); void loaded(); + void expandableChanged(); + // A folder opened in place couldn't be read (or read again), and was + // closed: `message` says which, and why. + void expandFailed(const QString &message); private: void setLoading(bool loading); @@ -191,6 +218,17 @@ class FolderModel : public QAbstractListModel { QString m_path; QVector m_entries; QSet m_selected; + // The folders opened in place, by path, and what each was last read to + // hold. One just opened is in m_expanded until its listing arrives. + QSet m_expanded; + QHash> m_open; + // Each opening's own number, while it's read, so a reading from before + // the folder was closed and opened again is dropped. + QHash m_opening; + quint64 m_openings = 0; + // Closes a folder that couldn't be read, saying why. + void failExpanded(const QString &folder, const QString &error); + void forgetExpanded(); void setSelected(const QSet &paths); bool m_loading = false; QString m_error; diff --git a/tests/folio_tests.cpp b/tests/folio_tests.cpp index f0c391c7..3f606369 100644 --- a/tests/folio_tests.cpp +++ b/tests/folio_tests.cpp @@ -783,6 +783,96 @@ private slots: QTRY_COMPARE(root->property("selected").toString(), QString("2025")); } + // The list's tree: a folder opened in place lists its items under it a + // level in, read again with the folder when anything changes; closed, + // they go, with anything opened or selected inside. + void folderOpensFoldersInPlace() + { + QTemporaryDir dir; + QDir(dir.path()).mkpath("alpha/inner"); + QDir(dir.path()).mkpath("beta"); + write(dir.filePath("alpha/x.txt"), "x"); + write(dir.filePath("alpha/inner/deep.txt"), "x"); + write(dir.filePath("top.txt"), "x"); + FolderModel model; + QSignalSpy loaded(&model, &FolderModel::loaded); + model.setPath(dir.path()); + QVERIFY(loaded.wait(3000)); + const auto names = [&] { + QStringList list; + for (int row = 0; row < model.count(); ++row) + list << QString(model.get(row).value("depth").toInt() * 2, ' ') + model.get(row).value("name").toString(); + return list; + }; + QCOMPARE(names(), QStringList({"alpha", "beta", "top.txt"})); + QVERIFY(model.expandable()); + + model.setExpanded(0, true); + QVERIFY(model.isExpanded(0)); + QTRY_COMPARE(names(), QStringList({"alpha", " inner", " x.txt", "beta", "top.txt"})); + QCOMPARE(model.parentRow(2), 0); + QCOMPARE(model.parentRow(3), -1); + // Only the folder's own items go by their names. + QCOMPARE(model.indexOf("x.txt"), -1); + QCOMPARE(model.indexOfPath(dir.filePath("alpha/x.txt")), 2); + + // A level deeper still. + model.setExpanded(1, true); + QTRY_COMPARE(names(), QStringList({"alpha", " inner", " deep.txt", " x.txt", "beta", "top.txt"})); + + // A file added inside shows, the folder read again with it. + write(dir.filePath("alpha/y.txt"), "y"); + QTRY_COMPARE_WITH_TIMEOUT(names(), QStringList({"alpha", " inner", " deep.txt", " x.txt", " y.txt", "beta", "top.txt"}), 3000); + + // Closed, what's inside goes, the folder opened within it and what + // was selected there too. + model.selectRows({2, 4}); + QCOMPARE(model.selectedCount(), 2); + model.setExpanded(0, false); + QCOMPARE(names(), QStringList({"alpha", "beta", "top.txt"})); + QCOMPARE(model.selectedCount(), 0); + model.setExpanded(0, true); + QTRY_COMPARE(names(), QStringList({"alpha", " inner", " x.txt", " y.txt", "beta", "top.txt"})); + + // Closed and opened again before its first reading is in, it lists + // its items once, not once for each opening. + model.setExpanded(0, false); + model.setExpanded(0, true); + model.setExpanded(0, false); + model.setExpanded(0, true); + QTRY_COMPARE(names(), QStringList({"alpha", " inner", " x.txt", " y.txt", "beta", "top.txt"})); + QTest::qWait(200); + QCOMPARE(names(), QStringList({"alpha", " inner", " x.txt", " y.txt", "beta", "top.txt"})); + + // One that can't be read closes again, saying why, rather than + // looking empty. + QSignalSpy failed(&model, &FolderModel::expandFailed); + QVERIFY(QFile::setPermissions(dir.filePath("beta"), QFileDevice::Permissions())); + model.setExpanded(4, true); + QTRY_COMPARE(failed.count(), 1); + QVERIFY(failed.last().first().toString().startsWith("beta: ")); + QVERIFY(!model.isExpanded(4)); + QCOMPARE(names(), QStringList({"alpha", " inner", " x.txt", " y.txt", "beta", "top.txt"})); + QVERIFY(QFile::setPermissions(dir.filePath("beta"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)); + + // Files and the folder's other views don't open. + model.setExpanded(5, true); + QVERIFY(!model.isExpanded(5)); + model.collapseAll(); + QCOMPARE(names(), QStringList({"alpha", "beta", "top.txt"})); + + // A search is a flat list, and nothing opens in it. + model.setExpanded(0, true); + QTRY_COMPARE(model.count(), 6); + model.setQuery("x"); + QVERIFY(!model.expandable()); + QVERIFY(loaded.wait(3000)); + QVERIFY(!names().join(",").contains(" ")); + model.setQuery({}); + QVERIFY(loaded.wait(3000)); + QCOMPARE(names(), QStringList({"alpha", "beta", "top.txt"})); + } + void folderListsDirectoriesFirstWithoutHidden() { QTemporaryDir dir; @@ -6509,6 +6599,178 @@ private slots: QCOMPARE(backend.folder()->selectedCount(), 2 * paged + 1); } + // The list's keys for its tree, as the Finder's: → opens a folder in + // place, then steps into it; ← steps back out to the folder, closes it, + // and from the top goes up a folder. A click on a folder's arrow opens + // or closes it. + void listWalksItsTree() + { + QTemporaryDir home; + QDir(home.path()).mkpath("files/alpha"); + write(home.filePath("files/alpha/inside.txt"), "x"); + write(home.filePath("files/beside.txt"), "x"); + Backend backend(home.path()); + backend.navigate(home.filePath("files")); + QTRY_COMPARE(backend.folder()->rowCount(), 2); + Theme theme(home.filePath("theme")); + FileOps fileOps; + Translator translator(home.filePath("language"), home.path()); + Thumbnails thumbnails(home.filePath("cache"), {home.filePath("none")}); + qmlRegisterType("Folio", 1, 0, "FolderModel"); + QQmlEngine engine; + engine.rootContext()->setContextProperty("backend", &backend); + engine.rootContext()->setContextProperty("theme", &theme); + engine.rootContext()->setContextProperty("fileOps", &fileOps); + engine.rootContext()->setContextProperty("translator", &translator); + engine.rootContext()->setContextProperty("plugins", QVariantMap{{"views", QVariantMap{}}}); + engine.addImageProvider("thumb", new ThumbnailProvider(&thumbnails)); + QQmlComponent component(&engine); + component.setData(R"( + import QtQuick + Window { + width: 700; height: 300; visible: true + property alias cursor: folderView.currentIndex + FolderList { id: folderView; anchors.fill: parent; Component.onCompleted: focusView() } + function clickRow(row, modifiers) { folderView.itemAtIndex(row).clicked(modifiers) } + } + )", QUrl::fromLocalFile(sourceFolder() + "/ListTreeTest.qml")); + std::unique_ptr root(component.create()); + QVERIFY2(root, qPrintable(component.errorString())); + auto *window = qobject_cast(root.get()); + window->requestActivate(); + QVERIFY(QTest::qWaitForWindowActive(window)); + FolderModel *folder = backend.folder(); + root->setProperty("cursor", 0); + + QTest::keyClick(window, Qt::Key_Right); + QTRY_COMPARE(folder->rowCount(), 3); + QVERIFY(folder->isExpanded(0)); + QCOMPARE(root->property("cursor").toInt(), 0); + QTest::keyClick(window, Qt::Key_Right); + QCOMPARE(root->property("cursor").toInt(), 1); + QCOMPARE(folder->get(1).value("name").toString(), QString("inside.txt")); + QTest::keyClick(window, Qt::Key_Left); + QCOMPARE(root->property("cursor").toInt(), 0); + QTest::keyClick(window, Qt::Key_Left); + QCOMPARE(folder->rowCount(), 2); + QVERIFY(!folder->isExpanded(0)); + QCOMPARE(backend.path(), home.filePath("files")); + + // The arrow, at the row's start, opens it too, without moving into it. + QTest::mouseClick(window, Qt::LeftButton, {}, QPoint(13, 16)); + QTRY_COMPARE(folder->rowCount(), 3); + QCOMPARE(backend.path(), home.filePath("files")); + QTest::qWait(200); + window->grabWindow().save(sourceFolder() + "/../build/tree.png"); + QTest::mouseClick(window, Qt::LeftButton, {}, QPoint(13, 16)); + QCOMPARE(folder->rowCount(), 2); + + // From the top, ← goes up a folder, as before. + QTest::keyClick(window, Qt::Key_Left); + QTRY_COMPARE(backend.path(), home.path()); + + // Rows a folder opening lists above the cursor move its row, not + // the cursor: what's selected stays selected. + backend.navigate(home.filePath("files")); + QTRY_COMPARE(folder->rowCount(), 2); + root->setProperty("cursor", 1); + folder->selectRange(0, 1, false); + QCOMPARE(folder->selectedCount(), 2); + folder->setExpanded(0, true); + QTRY_COMPARE(folder->rowCount(), 3); + QCOMPARE(root->property("cursor").toInt(), 2); + QCOMPARE(folder->get(2).value("name").toString(), QString("beside.txt")); + QCOMPARE(folder->selectedCount(), 2); + + // The range's start keeps to its own item too, though the folder + // opened between it and the cursor: a Shift-click then selects from + // it, not from where its row was. + folder->setExpanded(0, false); + QCOMPARE(folder->rowCount(), 2); + QDir(home.path()).mkpath("files/beta"); + write(home.filePath("files/beta/in-beta.txt"), "x"); + QTRY_COMPARE(folder->rowCount(), 3); + // alpha, beta, beside.txt: start on alpha, Shift-click beside.txt. + QMetaObject::invokeMethod(root.get(), "clickRow", Q_ARG(QVariant, 0), Q_ARG(QVariant, 0)); + QMetaObject::invokeMethod(root.get(), "clickRow", Q_ARG(QVariant, 2), Q_ARG(QVariant, int(Qt::ShiftModifier))); + QCOMPARE(folder->selectedCount(), 3); + folder->setExpanded(1, true); + QTRY_COMPARE(folder->rowCount(), 4); + // alpha, beta, in-beta.txt, beside.txt: Shift-click in-beta.txt + // selects alpha through it. + QMetaObject::invokeMethod(root.get(), "clickRow", Q_ARG(QVariant, 2), Q_ARG(QVariant, int(Qt::ShiftModifier))); + QCOMPARE(folder->selectedCount(), 3); + QVERIFY(folder->isSelected(0)); + QVERIFY(!folder->isSelected(3)); + } + + // Renamed inside a folder opened in the list's tree, an item stays + // selected under its new name, wherever that sorts it. + void listKeepsARenamedNestedItemSelected() + { + QTemporaryDir home, plugins; + QDir(home.path()).mkpath("files/alpha"); + for (const char *name : {"a.txt", "b.txt", "c.txt"}) + write(home.filePath(QString("files/alpha/") + name), "x"); + Backend backend(home.path()); + Theme theme(home.filePath("theme")); + Places places(home.path()); + FileOps fileOps; + Plugins bundled("en", {plugins.path()}, home.filePath("folio.conf")); + Translator translator(home.filePath("language"), home.path()); + Thumbnails thumbnails(home.filePath("cache"), {home.filePath("none")}); + qmlRegisterType("Folio", 1, 0, "FolderModel"); + QQmlEngine engine; + engine.addImageProvider("thumb", new ThumbnailProvider(&thumbnails)); + engine.rootContext()->setContextProperty("backend", &backend); + engine.rootContext()->setContextProperty("chooser", static_cast(nullptr)); + engine.rootContext()->setContextProperty("theme", &theme); + engine.rootContext()->setContextProperty("fileOps", &fileOps); + engine.rootContext()->setContextProperty("plugins", &bundled); + engine.rootContext()->setContextProperty("translator", &translator); + engine.rootContext()->setContextProperty("places", &places); + QQmlComponent component(&engine); + component.setData(R"( + import QtQuick + import QtQuick.Controls + ApplicationWindow { + width: 900; height: 620; visible: true + property string viewMode: "list" + property real zoom: 1 + property bool split: false + property bool helpVisible: false + property var activePane: null + function raise() {} + function requestActivate() {} + FolderPane { id: pane; anchors.fill: parent; focus: true } + Component.onCompleted: activePane = pane + readonly property var paneItem: pane + } + )", QUrl::fromLocalFile(sourceFolder() + "/RenameNestedTest.qml")); + std::unique_ptr root(component.create()); + QVERIFY2(root, qPrintable(component.errorString())); + auto *window = qobject_cast(root.get()); + QVERIFY(QTest::qWaitForWindowExposed(window)); + auto *pane = root->property("paneItem").value(); + QVERIFY(pane); + QVERIFY(QMetaObject::invokeMethod(pane, "focusView")); + FolderModel *folder = backend.folder(); + backend.navigate(home.filePath("files")); + QTRY_COMPARE(folder->count(), 1); + folder->setExpanded(0, true); + QTRY_COMPARE(folder->count(), 4); + const auto cursor = [&] { return pane->property("current").toMap().value("path").toString(); }; + QVERIFY(QMetaObject::invokeMethod(pane, "focusView")); + QTest::keyClick(window, Qt::Key_Down); + QTRY_COMPARE(cursor(), home.filePath("files/alpha/a.txt")); + + // a.txt renamed to z.txt sorts last: the cursor goes with it. + QCOMPARE(fileOps.rename(home.filePath("files/alpha/a.txt"), "z.txt"), QString()); + QTRY_COMPARE_WITH_TIMEOUT(cursor(), home.filePath("files/alpha/z.txt"), 3000); + QCOMPARE(folder->get(folder->indexOfPath(home.filePath("files/alpha/z.txt"))).value("selected").toBool(), true); + QCOMPARE(folder->selectedCount(), 1); + } + void gridBandHitsTheTilesBothWays() { // The rubber band's hit areas sit where the grid put the tiles, also