diff --git a/.gitignore b/.gitignore index 3416bd1f..bf31cca4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /build/ *.pkg.tar.* __pycache__/ +/pkgbuild/ diff --git a/README.md b/README.md index aa126641..3194f43a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Files (`folio`) is Omarchy's file manager. It's one quiet window that follows yo - **Three views**: Finder-style columns, a list that opens folders in place as a tree, and a grid with real previews. Ctrl+1/2/3 switches. - **Space previews** pictures, video, audio, PDFs, text and Markdown at full size, in their own window. -- **The sidebar** holds everything in your home folder, pinned folders (shared with GTK file dialogs), Recents, Trash with restore, your drives, and the machines on your tailnet, which open over SFTP. +- **The sidebar** holds everything in your home folder, pinned folders (shared with GTK file dialogs), Recents, Trash with restore, your drives (mounted or not, as Nautilus lists them: a click mounts one, and a drive plugged in mounts by itself), and the machines on your tailnet, which open over SFTP. - **Right-click** (or Alt+Enter) to open with another app, rename, duplicate, compress, share by Dropbox link, Taildrop or LocalSend, and delete. Copy and paste work with other apps, and nothing is ever overwritten. - **Split** the window in two with Ctrl+Alt+N to move things between folders. - **Plugins** add sidebar sections, Share entries and views; Tailscale, Dropbox and LocalSend are plugins too. [docs/plugins.md](docs/plugins.md) shows how to write one. diff --git a/src/DriveMenu.qml b/src/DriveMenu.qml index ba24d3e5..b3ea25c9 100644 --- a/src/DriveMenu.qml +++ b/src/DriveMenu.qml @@ -6,18 +6,19 @@ import QtQuick FolioMenu { id: menu - // The sidebar's row for the drive: {name, path, release}. + // The sidebar's row for the drive: {name, path, release}, with no path + // but its `volume` while it isn't mounted. property var drive: ({}) // What udisks knows of it (fileOps.driveAt), or empty. property var disk: ({}) - signal openRequested(string path) + signal openRequested(var drive) signal formatRequested(var disk) // Opens at the pointer, or (from the keyboard) beside the row. function show(row, near) { drive = row - disk = fileOps.driveAt(row.path) + disk = row.path ? fileOps.driveAt(row.path) : ({}) if (near) popup(near, Math.min(near.width / 2, 120), near.height / 2) else @@ -28,7 +29,7 @@ FolioMenu { FolioMenuItem { text: qsTr("Mount") - onTriggered: menu.openRequested(menu.drive.path) + onTriggered: menu.openRequested(menu.drive) } FolioMenuItem { shown: !!menu.drive.release diff --git a/src/MountPrompt.qml b/src/MountPrompt.qml index ec0a180c..b922d407 100644 --- a/src/MountPrompt.qml +++ b/src/MountPrompt.qml @@ -4,14 +4,17 @@ import QtQuick.Layouts // GVfs's password request while connecting to another machine whose keys // aren't set up, or its question about a server it can't vouch for (a key // seen for the first time, a certificate that can't be verified), put to -// the user in the window. The wording comes from GVfs, already translated. +// the user in the window, as is an encrypted drive's passphrase. The +// wording comes from GVfs, already translated. FolioDialog { id: prompt readonly property var mounter: backend.mounter readonly property bool question: mounter.choices.length > 0 - title: question ? qsTr("Check the server") : qsTr("Sign in") + readonly property bool drive: mounter.drive + title: question ? (drive ? qsTr("Check the drive") : qsTr("Check the server")) + : drive ? qsTr("Unlock") : qsTr("Sign in") cardWidth: 600 spacing: 18 visible: mounter.asking @@ -26,7 +29,7 @@ FolioDialog { if (visible && question) { forceActiveFocus() } else if (visible) { - user.text = mounter.user + user.text = drive ? "" : mounter.user password.forceActiveFocus() } } @@ -52,7 +55,8 @@ FolioDialog { PlainField { id: user - visible: !prompt.question + // A drive's passphrase has no user to go with it. + visible: !prompt.question && !prompt.drive Layout.fillWidth: true placeholderText: qsTr("User") } @@ -60,7 +64,7 @@ FolioDialog { id: password visible: !prompt.question Layout.fillWidth: true - placeholderText: qsTr("Password") + placeholderText: prompt.drive ? qsTr("Passphrase") : qsTr("Password") echoMode: TextInput.Password onAccepted: prompt.submit() } @@ -87,7 +91,7 @@ FolioDialog { } PlainButton { visible: !prompt.question - text: qsTr("Connect") + text: prompt.drive ? qsTr("Unlock") : qsTr("Connect") primary: true onClicked: prompt.submit() } diff --git a/src/Sidebar.qml b/src/Sidebar.qml index 64dfa2c9..4665347e 100644 --- a/src/Sidebar.qml +++ b/src/Sidebar.qml @@ -77,9 +77,16 @@ Rectangle { if (row.root !== undefined) sidebar.target.open(row.path) else - sidebar.go(row.path) + openDevice(row) finished() } + // A drive that isn't mounted yet has no path: opening it mounts it. + function openDevice(row) { + if (row.path) + sidebar.go(row.path) + else if (row.volume !== undefined) + sidebar.target.openVolume(row.volume, row.name) + } function reveal(item) { const y = item.mapToItem(column, 0, 0).y if (y < flick.contentY) @@ -142,7 +149,7 @@ Rectangle { DriveMenu { id: driveMenu - onOpenRequested: (path) => { sidebar.go(path); sidebar.finished() } + onOpenRequested: (drive) => { sidebar.openDevice(drive); sidebar.finished() } onFormatRequested: (disk) => sidebar.formatRequested(disk) } @@ -430,11 +437,11 @@ Rectangle { onKeyedChanged: if (keyed) sidebar.reveal(this) text: modelData.name glyph: eject.visible ? "" : modelData.icon - active: sidebar.activePath === modelData.path - onClicked: sidebar.go(modelData.path) + active: !!modelData.path && sidebar.activePath === modelData.path + onClicked: sidebar.openDevice(modelData) detail: { translator.language // Re-read when the language (and so its digits) changes. - return modelData.free < 0 ? "" : Format.free(modelData.free) + return modelData.free === undefined || modelData.free < 0 ? "" : Format.free(modelData.free) } TapHandler { acceptedButtons: Qt.RightButton @@ -448,7 +455,7 @@ Rectangle { anchors.verticalCenter: parent.verticalCenter implicitWidth: 28 implicitHeight: 28 - visible: driveRow.modelData.release !== "" && (driveRow.hovered || hovered || driveRow.keyed) + visible: !!driveRow.modelData.release && (driveRow.hovered || hovered || driveRow.keyed) glyph: "eject" text: driveRow.modelData.release === "eject" ? qsTr("Eject") : qsTr("Unmount") onClicked: places.eject(driveRow.modelData.path) diff --git a/src/backend.cpp b/src/backend.cpp index 8ae4fc67..68b8c883 100644 --- a/src/backend.cpp +++ b/src/backend.cpp @@ -28,6 +28,14 @@ Backend::Backend(const QString &home, QObject *parent) }); connect(&m_mounter, &Mounter::mounted, this, [this](const QString &folder) { setBusy({}); + // A drive opens at its top, or (plugged in) only says it's there. + if (std::exchange(m_mountDrive, false)) { + if (m_mountOpens) + navigate(folder); + else + showNotice(tr("%1 is mounted").arg(m_mountName)); + return; + } // The mount's folder is known now, so the plugin's row can light up. if (m_plugins) m_plugins->mountsChanged(); @@ -37,7 +45,9 @@ Backend::Backend(const QString &home, QObject *parent) setBusy({}); // An empty error is the user cancelling the sign-in: nothing to report. if (!error.isEmpty()) - setMessage(tr("Couldn't connect to %1: %2").arg(m_mountName, error)); + setMessage(m_mountDrive ? tr("Couldn't open %1: %2").arg(m_mountName, error) + : tr("Couldn't connect to %1: %2").arg(m_mountName, error)); + m_mountDrive = false; }); // The preview reports each file it steps to, and the grid follows. connect(&m_preview, &QProcess::readyReadStandardOutput, this, [this] { @@ -365,6 +375,9 @@ void Backend::openItem(const QString &path) { } void Backend::mount(const QString &url, const QString &name, bool verified) { + if (m_mounter.busy()) + return; + m_mountDrive = false; m_mountBare = QUrl(url).path().isEmpty() || QUrl(url).path() == "/"; m_mountName = name; // Mounted already (by Folio or another app): straight there. @@ -430,6 +443,33 @@ void Backend::finish(int run, const Plugins::Result &result) { navigate(Plugins::expand(result.path)); } +void Backend::openVolume(const QString &volume, const QString &name) { + if (m_mounter.busy()) { + // Clicked while it's mounting as it was plugged in: that mount + // goes on, and opens the drive once it's done. + if (m_mountDrive && !m_mountOpens && m_mounter.volume() == volume) { + m_mountOpens = true; + setBusy(tr("Opening %1…").arg(m_mountName)); + } + return; + } + m_mountName = name.isEmpty() ? tr("the drive") : name; + m_mountDrive = true; + m_mountOpens = true; + setBusy(tr("Opening %1…").arg(m_mountName)); + m_mounter.mountVolume(volume); +} + +bool Backend::mountVolume(const QString &volume, const QString &name) { + if (m_mounter.busy()) + return false; + m_mountName = name.isEmpty() ? tr("the drive") : name; + m_mountDrive = true; + m_mountOpens = false; + m_mounter.mountVolume(volume); + return true; +} + void Backend::showNotice(const QString ¬ice) { m_notice = notice; emit noticeChanged(); diff --git a/src/backend.h b/src/backend.h index 4e5ea958..b5eb5203 100644 --- a/src/backend.h +++ b/src/backend.h @@ -81,6 +81,13 @@ class Backend : public QObject { // it's done. Q_INVOKABLE void perform(const QString &plugin, const QString &action, const QStringList &paths, const QString &target = {}); + // Opens a drive from the sidebar's Devices, mounting it first when it + // isn't, which may ask for its passphrase or (through polkit) for + // permission. + Q_INVOKABLE void openVolume(const QString &volume, const QString &name); + // Mounts a drive just plugged in, staying where it is. False when this + // window is mounting something else already. + bool mountVolume(const QString &volume, const QString &name); Q_INVOKABLE void dismissMessage(); Q_INVOKABLE void showMessage(const QString &message) { setMessage(message); } // Good news that needs no answer ("Link copied"): shown for a few @@ -202,6 +209,9 @@ class Backend : public QObject { // The plugin actions running, each with its busy text, oldest first. QList> m_runs; int m_lastRun = 0; + // What's being mounted is a drive, and whether to go there once it is. + bool m_mountDrive = false; + bool m_mountOpens = false; QProcess m_preview; // Set while Folio closes the preview itself, which isn't a crash. bool m_closingPreview = false; diff --git a/src/drives.cpp b/src/drives.cpp new file mode 100644 index 00000000..ac4c7c3f --- /dev/null +++ b/src/drives.cpp @@ -0,0 +1,188 @@ +#include "drives.h" + +#include +#include + +// GIO's headers use `signals` as a struct member, which Qt defines as a +// keyword. +#undef signals +#include +#define signals Q_SIGNALS + +namespace { + +QString take(char *text) { + const QString s = QString::fromUtf8(text ? text : ""); + g_free(text); + return s; +} + +QString rootOf(GMount *mount) { + GFile *root = g_mount_get_root(mount); + const QString path = take(g_file_get_path(root)); + g_object_unref(root); + return path; +} + +// What the callbacks carry: the Drives (gone if Folio quit first) and the +// drive's name for what they say. +struct Pending { + QPointer drives; + QString name; +}; + +// The user dismissing the polkit prompt, or a question nobody answered. +bool cancelled(const GError *error) { + return g_error_matches(error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED) + || g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED); +} + +} // namespace + +struct DrivesCallbacks { + static void changed(GVolumeMonitor *, gpointer, gpointer data) { + emit static_cast(data)->changed(); + } + + static void added(GVolumeMonitor *, GVolume *volume, gpointer data) { + auto *self = static_cast(data); + emit self->changed(); + // Only what udisks marks to mount by itself (removable media, not + // another internal partition). + if (!g_volume_should_automount(volume) || !g_volume_can_mount(volume) || !Drives::automountWanted()) + return; + // An automounter of the desktop's own (udiskie, a shell) gets the + // first go, so a drive isn't mounted twice, nor an encrypted one's + // passphrase asked for twice. + const QString id = Drives::idOf(volume); + const QString name = take(g_volume_get_name(volume)); + QTimer::singleShot(Drives::automountDelayMs, self, [self, id, name] { + GVolume *now = Drives::find(id); + if (!now) + return; + GMount *mount = g_volume_get_mount(now); + const bool unmounted = !mount && g_volume_can_mount(now); + if (mount) + g_object_unref(mount); + g_object_unref(now); + if (unmounted) + emit self->plugged(id, name); + }); + } + + // Unmounted from anywhere (here, another app, the drive pulled out): + // nothing should keep showing a folder that's gone. + static void mountRemoved(GVolumeMonitor *, GMount *mount, gpointer data) { + auto *self = static_cast(data); + const QString root = rootOf(mount); + if (!root.isEmpty()) + emit self->leaving(root); + emit self->changed(); + } + + static void mounted(GObject *source, GAsyncResult *result, gpointer data) { + auto *pending = static_cast(data); + GError *error = nullptr; + const bool ok = g_volume_mount_finish(G_VOLUME(source), result, &error); + if (Drives *self = pending->drives.data()) { + if (ok) + emit self->notice(QObject::tr("%1 is mounted").arg(pending->name)); + else if (!cancelled(error) && !g_error_matches(error, G_IO_ERROR, G_IO_ERROR_ALREADY_MOUNTED)) + emit self->failed(QObject::tr("Couldn't mount %1: %2").arg(pending->name, QString::fromUtf8(error->message))); + } + if (error) + g_error_free(error); + delete pending; + } +}; + +Drives::Drives(QObject *parent) : QObject(parent), m_monitor(g_volume_monitor_get()) { + // Qt runs on GLib's main loop on Linux, so these arrive on the UI + // thread, as soon as udisks sees the change. + for (const char *signal : {"volume-removed", "volume-changed", "mount-added", "mount-changed", + "drive-connected", "drive-disconnected", "drive-changed"}) + g_signal_connect(m_monitor, signal, G_CALLBACK(DrivesCallbacks::changed), this); + g_signal_connect(m_monitor, "volume-added", G_CALLBACK(DrivesCallbacks::added), this); + g_signal_connect(m_monitor, "mount-removed", G_CALLBACK(DrivesCallbacks::mountRemoved), this); +} + +Drives::~Drives() { + g_signal_handlers_disconnect_by_data(m_monitor, this); + g_object_unref(m_monitor); +} + +QString Drives::idOf(GVolume *volume) { + // The device first: two disks copied from one image share a filesystem + // UUID, but never a device while both are connected. + for (const char *kind : {G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE, G_VOLUME_IDENTIFIER_KIND_UUID}) { + const QString id = take(g_volume_get_identifier(volume, kind)); + if (!id.isEmpty()) + return id; + } + return take(g_volume_get_name(volume)); +} + +GVolume *Drives::find(const QString &id) { + GVolumeMonitor *monitor = g_volume_monitor_get(); + GList *volumes = g_volume_monitor_get_volumes(monitor); + GVolume *found = nullptr; + for (GList *l = volumes; l && !found; l = l->next) { + if (idOf(G_VOLUME(l->data)) == id) + found = G_VOLUME(g_object_ref(l->data)); + } + g_list_free_full(volumes, g_object_unref); + g_object_unref(monitor); + return found; +} + +QList Drives::volumes() const { + QList list; + GList *volumes = g_volume_monitor_get_volumes(m_monitor); + for (GList *l = volumes; l; l = l->next) { + GVolume *volume = G_VOLUME(l->data); + Volume v{take(g_volume_get_name(volume)), idOf(volume), {}}; + if (GMount *mount = g_volume_get_mount(volume)) { + v.root = rootOf(mount); + // What the mount calls itself: its label, else "1.0 TB Volume", + // never the UUID folder udisks mounts an unlabeled one in. + const QString name = take(g_mount_get_name(mount)); + if (!name.isEmpty()) + v.name = name; + v.canEject = g_mount_can_eject(mount); + v.canUnmount = g_mount_can_unmount(mount); + g_object_unref(mount); + } else if (!g_volume_can_mount(volume)) { + continue; + } + list << v; + } + g_list_free_full(volumes, g_object_unref); + return list; +} + +void Drives::mountQuietly(const QString &id) { + GVolume *volume = find(id); + if (!volume) + return; + GMountOperation *operation = g_mount_operation_new(); + g_volume_mount(volume, G_MOUNT_MOUNT_NONE, operation, nullptr, DrivesCallbacks::mounted, + new Pending{this, take(g_volume_get_name(volume))}); + g_object_unref(operation); + g_object_unref(volume); +} + +bool Drives::automountWanted() { + GSettingsSchemaSource *source = g_settings_schema_source_get_default(); + GSettingsSchema *schema = source ? g_settings_schema_source_lookup(source, "org.gnome.desktop.media-handling", TRUE) + : nullptr; + if (!schema) + return true; + bool wanted = true; + if (g_settings_schema_has_key(schema, "automount")) { + GSettings *settings = g_settings_new_full(schema, nullptr, nullptr); + wanted = g_settings_get_boolean(settings, "automount"); + g_object_unref(settings); + } + g_settings_schema_unref(schema); + return wanted; +} diff --git a/src/drives.h b/src/drives.h new file mode 100644 index 00000000..816119fc --- /dev/null +++ b/src/drives.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include +#include + +typedef struct _GVolume GVolume; +typedef struct _GVolumeMonitor GVolumeMonitor; + +// The drives GIO knows, through GVfs's udisks monitor: the list Nautilus +// shows, partitions not mounted yet included (another system's, a USB stick +// just plugged in), and the system's own and hidden ones (EFI, recovery) +// already left out by udisks. Mounting a drive as it's plugged in goes +// through here too; mounting one to open it is the window's Mounter, which +// can put a passphrase request to the user, and letting go of one is +// Places::eject. +class Drives : public QObject { + Q_OBJECT + +public: + struct Volume { + QString name; + // What finds the volume again: its device, else its UUID, else its name. + QString id; + // Where it's mounted; empty while it isn't. + QString root; + // While mounted: how it's let go of. + bool canEject = false; + bool canUnmount = false; + }; + + explicit Drives(QObject *parent = nullptr); + ~Drives() override; + + QList volumes() const; + + // Mounts it with nobody to ask for a passphrase, for a drive plugged in + // when no window can. + void mountQuietly(const QString &id); + + // The volume `id` names, with a reference the caller drops; null when + // it's gone. + static GVolume *find(const QString &id); + static QString idOf(GVolume *volume); + // GNOME's "mount drives as they're plugged in" setting, on where it + // isn't installed. + static bool automountWanted(); + // How long a plugged drive is left for another automounter first. + static constexpr int automountDelayMs = 2000; + +signals: + void changed(); + // A drive was plugged in that udisks says should mount by itself. + void plugged(const QString &id, const QString &name); + // `root` just went away: whatever shows a folder on it moves out. + void leaving(const QString &root); + void notice(const QString ¬ice); + void failed(const QString &message); + +private: + friend struct DrivesCallbacks; + GVolumeMonitor *m_monitor = nullptr; +}; diff --git a/src/i18n/en.json b/src/i18n/en.json index b742a47c..926e7299 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -22,6 +22,7 @@ "%1 is already under Home.": "%1 is already under Home.", "%1 is in use and can't be ejected.": "%1 is in use and can't be ejected.", "%1 is in use and can't be unmounted.": "%1 is in use and can't be unmounted.", + "%1 is mounted": "%1 is mounted", "%1 is no longer there.": "%1 is no longer there.", "%1 isn't a folder.": "%1 isn't a folder.", "%1 keeps at most %2 characters of a drive's name.": "%1 keeps at most %2 characters of a drive's name.", @@ -63,6 +64,7 @@ "Can't undo that: %1 already exists in %2.": "Can't undo that: %1 already exists in %2.", "Can't undo that: %1 isn't where it was left.": "Can't undo that: %1 isn't where it was left.", "Cancel": "Cancel", + "Check the drive": "Check the drive", "Check the server": "Check the server", "Choose": "Choose", "Close": "Close", @@ -114,10 +116,12 @@ "Couldn't extract %1: it's protected by a password.": "Couldn't extract %1: it's protected by a password.", "Couldn't format %1. %2": "Couldn't format %1. %2", "Couldn't make %1 the default app for %2: %3": "Couldn't make %1 the default app for %2: %3", + "Couldn't mount %1: %2": "Couldn't mount %1: %2", "Couldn't move %1 to the trash to replace it: %2": "Couldn't move %1 to the trash to replace it: %2", "Couldn't move %1 to the trash: %2": "Couldn't move %1 to the trash: %2", "Couldn't move to the trash: %1": "Couldn't move to the trash: %1", "Couldn't open %1 with %2: %3": "Couldn't open %1 with %2: %3", + "Couldn't open %1: %2": "Couldn't open %1: %2", "Couldn't open this PDF: %1": "Couldn't open this PDF: %1", "Couldn't play this file: %1": "Couldn't play this file: %1", "Couldn't read %1.": "Couldn't read %1.", @@ -214,6 +218,7 @@ "Hide Hidden Files": "Hide Hidden Files", "Home": "Home", "Into a folder / back out": "Into a folder / back out", + "It's no longer connected": "It's no longer connected", "Keep Both": "Keep Both", "Keyboard shortcuts": "Keyboard shortcuts", "Kind": "Kind", @@ -273,6 +278,7 @@ "Opens with": "Opens with", "Original location": "Original location", "Page %1 of %2": "Page %1 of %2", + "Passphrase": "Passphrase", "Password": "Password", "Paste": "Paste", "Paste Into Folder": "Paste Into Folder", @@ -440,6 +446,7 @@ "other": "Undoing %L1 of %Ln items…" }, "Undoing…": "Undoing…", + "Unlock": "Unlock", "Unmount": "Unmount", "Unpin": "Unpin", "Unpin from the sidebar": "Unpin from the sidebar", @@ -459,7 +466,10 @@ "file not found": "file not found", "incorrect password": "incorrect password", "invalid file format": "invalid file format", + "it didn't finish mounting within a minute": "it didn't finish mounting within a minute", + "it unlocked, but there's nothing on it that can be mounted": "it unlocked, but there's nothing on it that can be mounted", "right-click": "right-click", + "the drive": "the drive", "unknown error": "unknown error", "unsupported security scheme": "unsupported security scheme", "“%1” already exists in %2.": "“%1” already exists in %2." diff --git a/src/main.cpp b/src/main.cpp index 48852d89..0fa62ff1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,6 +12,7 @@ #include #include +#include "backend.h" #include "chooser.h" #include "filemanager1.h" #include "foldermodel.h" @@ -169,5 +170,24 @@ int main(int argc, char *argv[]) { FileManager1::registerOn(&windows); } + if (Drives *drives = places.drives()) { + // A drive plugged in mounts through the last window used, which can + // ask for an encrypted drive's passphrase; with none free, it mounts + // without asking. + QObject::connect(drives, &Drives::plugged, &windows, [&windows, drives](const QString &id, const QString &name) { + Backend *backend = windows.latest(); + if (!backend || !backend->mountVolume(id, name)) + drives->mountQuietly(id); + }); + QObject::connect(drives, &Drives::notice, &windows, [&windows](const QString ¬ice) { + if (Backend *backend = windows.latest()) + backend->showNotice(notice); + }); + QObject::connect(drives, &Drives::failed, &windows, [&windows](const QString &message) { + if (Backend *backend = windows.latest()) + backend->showMessage(message); + }); + } + return app.exec(); } diff --git a/src/mounter.cpp b/src/mounter.cpp index 5a520ff4..db7c53c1 100644 --- a/src/mounter.cpp +++ b/src/mounter.cpp @@ -1,7 +1,11 @@ #include "mounter.h" +#include "drives.h" #include +#include +#include #include +#include #include #include @@ -11,6 +15,42 @@ #include #define signals Q_SIGNALS +namespace { + +// A block device holds a filesystem, by what udev found on it. +bool holdsFilesystem(const QString &name) { + QFile dev(QStringLiteral("/sys/class/block/%1/dev").arg(name)); + if (!dev.open(QIODevice::ReadOnly)) + return false; + QFile data(QStringLiteral("/run/udev/data/b%1").arg(QString::fromLatin1(dev.readAll()).trimmed())); + return data.open(QIODevice::ReadOnly) && data.readAll().contains("\nE:ID_FS_USAGE=filesystem\n"); +} + +// The encrypted volume `id` names unlocked (the kernel shows a cleartext, +// dm-crypt, device holding it) and nothing inside is a filesystem: no +// filesystem at all, or LVM. A filesystem inside means it's only slow. +bool unlockedEmpty(const QString &id) { + GVolume *volume = Drives::find(id); + if (!volume) + return false; + char *device = g_volume_get_identifier(volume, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE); + const QString name = QFileInfo(QFileInfo(QString::fromUtf8(device ? device : "")).canonicalFilePath()).fileName(); + g_free(device); + g_object_unref(volume); + if (name.isEmpty()) + return false; + const QStringList holders = QDir(QStringLiteral("/sys/class/block/%1/holders").arg(name)) + .entryList(QDir::NoDotAndDotDot | QDir::AllEntries); + if (holders.isEmpty()) + return false; + for (const QString &holder : holders) + if (holdsFilesystem(holder)) + return false; + return true; +} + +} // namespace + struct MounterCallbacks { // GMountOperation's own handlers run after these and answer // "unhandled" at once, which GVfs reports as a cancelled login; stopping @@ -41,6 +81,8 @@ struct MounterCallbacks { GAskPasswordFlags, gpointer data) { g_signal_stop_emission_by_name(op, "ask-password"); auto *self = static_cast(data); + // Asked again (a wrong passphrase): the last reply's clock stops. + ++self->m_attempt; self->m_prompt = QString::fromUtf8(message).trimmed(); self->m_user = QString::fromUtf8(user ? user : ""); self->setAsking(true); @@ -58,33 +100,82 @@ struct MounterCallbacks { GError *error = nullptr; const bool ok = g_file_mount_enclosing_volume_finish(G_FILE(source), result, &error); if (self) { - // Mounted earlier (by Folio or another app) is as good as now. - const bool already = error && g_error_matches(error, G_IO_ERROR, G_IO_ERROR_ALREADY_MOUNTED); - if (ok || already) { - char *path = g_file_get_path(G_FILE(source)); - const QString local = QString::fromUtf8(path ? path : ""); + char *path = g_file_get_path(G_FILE(source)); + const QString local = QString::fromUtf8(path ? path : ""); + g_free(path); + // Where GVfs put it, for the address it was asked for: only + // SFTP's folder can be worked out ahead of time. + if ((ok || alreadyMounted(error)) && local.startsWith(Mounter::root() + "/")) + Mounter::known()[self->m_url] = local; + self->report(ok, alreadyMounted(error), local, error); + } + if (error) + g_error_free(error); + } + + static void volumeMounted(GObject *source, GAsyncResult *result, gpointer data) { + auto *guard = static_cast *>(data); + Mounter *self = guard->data(); + delete guard; + GError *error = nullptr; + const bool ok = g_volume_mount_finish(G_VOLUME(source), result, &error); + if (self) { + QString local; + if (GMount *mount = g_volume_get_mount(G_VOLUME(source))) { + GFile *root = g_mount_get_root(mount); + char *path = g_file_get_path(root); + local = QString::fromUtf8(path ? path : ""); g_free(path); - // Where GVfs put it, for the address it was asked for: only - // SFTP's folder can be worked out ahead of time. - if (local.startsWith(Mounter::root() + "/")) - Mounter::known()[self->m_url] = local; - self->finish(); - if (local.isEmpty()) - emit self->failed(QObject::tr("GVfs gave no local folder for the mount")); - else - emit self->mounted(local); - } else { - const bool cancelled = error && g_error_matches(error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED); - const QString message = cancelled ? QString() : QString::fromUtf8(error ? error->message : ""); - self->finish(); - emit self->failed(message); + g_object_unref(root); + g_object_unref(mount); } + self->report(ok, alreadyMounted(error), local, error); } if (error) g_error_free(error); } + + // Mounted earlier (by Folio or another app) is as good as now. + static bool alreadyMounted(const GError *error) { + return error && g_error_matches(error, G_IO_ERROR, G_IO_ERROR_ALREADY_MOUNTED); + } }; +void Mounter::report(bool ok, bool already, const QString &local, const GError *error) { + // Given up on after the passphrase went in, or GVfs calling it + // cancelled when nobody did: either the drive unlocked with nothing to + // mount inside, or it's still working (unlocking, or mounting a slow + // filesystem). Which, the kernel and udev say. + const bool stopped = m_drive && m_answered && !ok && !already + && (!error || g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)); + const bool empty = stopped && unlockedEmpty(m_volume); + const bool timedOut = stopped && m_lost; + finish(); + if (ok || already) { + if (local.isEmpty()) + emit failed(tr("GVfs gave no local folder for the mount")); + else + emit mounted(local); + return; + } + // The user turning down the password, or polkit's prompt for a drive, + // is nothing to report. + if (error && g_error_matches(error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED)) { + emit failed(QString()); + return; + } + // An encrypted drive that unlocked with nothing udisks can mount inside. + if (empty) { + emit failed(tr("it unlocked, but there's nothing on it that can be mounted")); + return; + } + if (timedOut) { + emit failed(tr("it didn't finish mounting within a minute")); + return; + } + emit failed(QString::fromUtf8(error ? error->message : "")); +} + Mounter::Mounter(QObject *parent) : QObject(parent) {} Mounter::~Mounter() { @@ -135,16 +226,21 @@ QString Mounter::destinationFor(const QString &url) { return parts.isEmpty() ? mount : mount + '/' + parts.join('/'); } -void Mounter::mount(const QString &uri, bool verified) { - if (m_operation) - return; +void Mounter::begin(bool drive, bool verified) { + m_drive = drive; m_verified = verified; - m_url = uri; - GFile *file = g_file_new_for_uri(uri.toUtf8().constData()); m_operation = g_mount_operation_new(); g_signal_connect(m_operation, "ask-question", G_CALLBACK(MounterCallbacks::question), this); g_signal_connect(m_operation, "ask-password", G_CALLBACK(MounterCallbacks::password), this); g_signal_connect(m_operation, "aborted", G_CALLBACK(MounterCallbacks::aborted), this); +} + +void Mounter::mount(const QString &uri, bool verified) { + if (m_operation) + return; + begin(false, verified); + m_url = uri; + GFile *file = g_file_new_for_uri(uri.toUtf8().constData()); // Qt runs on GLib's main loop on Linux, so the reply arrives on the UI // thread like any other event. The window can close before GVfs answers, // and GIO calls back regardless, so the callback gets a guard, not `this`. @@ -154,6 +250,25 @@ void Mounter::mount(const QString &uri, bool verified) { g_object_unref(file); } +void Mounter::mountVolume(const QString &id) { + if (m_operation) + return; + GVolume *volume = Drives::find(id); + if (!volume) { + emit failed(tr("It's no longer connected")); + return; + } + // A drive's questions (another app has files open on it) are the + // user's, as an unverified server's are. + begin(true, false); + m_volume = id; + m_lost = false; + m_cancellable = g_cancellable_new(); + g_volume_mount(volume, G_MOUNT_MOUNT_NONE, m_operation, m_cancellable, MounterCallbacks::volumeMounted, + new QPointer(this)); + g_object_unref(volume); +} + void Mounter::providePassword(const QString &user, const QString &password) { if (!m_operation || !m_asking) return; @@ -161,8 +276,24 @@ void Mounter::providePassword(const QString &user, const QString &password) { if (!user.isEmpty()) g_mount_operation_set_username(m_operation, user.toUtf8().constData()); g_mount_operation_set_password(m_operation, password.toUtf8().constData()); - g_mount_operation_set_password_save(m_operation, G_PASSWORD_SAVE_FOR_SESSION); + // A drive's passphrase isn't kept at all: once unlocked it stays so. + g_mount_operation_set_password_save(m_operation, m_drive ? G_PASSWORD_SAVE_NEVER : G_PASSWORD_SAVE_FOR_SESSION); g_mount_operation_reply(m_operation, G_MOUNT_OPERATION_HANDLED); + // An encrypted drive that unlocks but holds nothing udisks can mount + // (no filesystem, or LVM inside) leaves GVfs's mount pending for good; + // past this, it's given up on. Asked only once the passphrase is in, so + // a polkit prompt before it isn't cut short. + if (m_drive && m_cancellable) { + m_answered = true; + // Each reply gets its own minute, from when it went in. + const int attempt = ++m_attempt; + QTimer::singleShot(stalledAfterMs, this, [this, attempt] { + if (attempt != m_attempt || !m_cancellable || m_asking) + return; + m_lost = true; + g_cancellable_cancel(m_cancellable); + }); + } } void Mounter::choose(int choice) { @@ -192,6 +323,13 @@ void Mounter::setAsking(bool asking) { void Mounter::finish() { if (m_asking) setAsking(false); + if (m_cancellable) { + g_object_unref(m_cancellable); + m_cancellable = nullptr; + } + m_lost = false; + m_answered = false; + ++m_attempt; if (m_operation) { g_object_unref(m_operation); m_operation = nullptr; diff --git a/src/mounter.h b/src/mounter.h index 5bc22a50..75bf462e 100644 --- a/src/mounter.h +++ b/src/mounter.h @@ -5,6 +5,8 @@ #include typedef struct _GMountOperation GMountOperation; +typedef struct _GError GError; +typedef struct _GCancellable GCancellable; // Mounts other machines (sftp://, smb://, anything GVfs mounts) through GIO, // the way Nautilus does, so they land under GVfs where every app can see @@ -13,7 +15,9 @@ typedef struct _GMountOperation GMountOperation; // already made sure who's on the other end). Everything else (a password, // when keys aren't set up; a server's unknown key or certificate) goes to // the window to put to the user, instead of dying silently as it does under -// `gio mount` with no terminal to ask in. +// `gio mount` with no terminal to ask in. Drives from the sidebar mount +// here too, their passphrase (an encrypted drive) put to the user the same +// way; anything udisks needs authorized goes to the session's polkit agent. class Mounter : public QObject { Q_OBJECT Q_PROPERTY(bool asking READ asking NOTIFY askingChanged) @@ -21,6 +25,8 @@ class Mounter : public QObject { Q_PROPERTY(QString user READ user NOTIFY askingChanged) // A question's answers, in GVfs's words; empty for a password request. Q_PROPERTY(QStringList choices READ choices NOTIFY askingChanged) + // The request is for a drive's passphrase, not a sign-in. + Q_PROPERTY(bool drive READ drive NOTIFY askingChanged) public: explicit Mounter(QObject *parent = nullptr); @@ -31,11 +37,18 @@ class Mounter : public QObject { QString prompt() const { return m_prompt; } QString user() const { return m_user; } QStringList choices() const { return m_choices; } + bool drive() const { return m_drive; } + // The volume a drive's mount is for, while busy with one. + QString volume() const { return busy() && m_drive ? m_volume : QString(); } // Mounts the location; `mounted` carries its local GVfs path. A // verified location's questions are answered here, with their first // choice. void mount(const QString &uri, bool verified); + // Mounts the volume Drives knows by `id`; `mounted` carries its folder. + void mountVolume(const QString &id); + // How long a drive's mount may run once its passphrase is in. + static constexpr int stalledAfterMs = 60000; // Where GVfs keeps its mounts, and the mount `url` is in (its root, // where its row is lit): worked out for SFTP, whose mount is named by @@ -65,9 +78,21 @@ class Mounter : public QObject { friend struct MounterCallbacks; void setAsking(bool asking); void finish(); + void begin(bool drive, bool verified); + void report(bool ok, bool already, const QString &local, const GError *error); GMountOperation *m_operation = nullptr; bool m_verified = false; + bool m_drive = false; + // A drive's mount, cancelled when it stalls after unlocking (see + // providePassword); each mount, passphrase request and reply counts as + // a new attempt, so only the latest reply's timer can cancel it. + QString m_volume; + GCancellable *m_cancellable = nullptr; + bool m_lost = false; + // Its passphrase was given. + bool m_answered = false; + int m_attempt = 0; QString m_url; bool m_asking = false; QString m_prompt; diff --git a/src/places.cpp b/src/places.cpp index 272de4c6..80d67c51 100644 --- a/src/places.cpp +++ b/src/places.cpp @@ -137,6 +137,14 @@ Places::Places(const QString &home, QObject *parent) m_systemDevice = QString::fromUtf8(QStorageInfo::root().device()); connect(&m_mounts, &QFutureWatcherBase::finished, this, &Places::mountsRead); m_poll.setInterval(15000); + // GIO's drives say at once when they come, go or mount; one unmounted + // from anywhere (here, another app, pulled out) is left by whatever + // shows a folder on it. + if (m_realHome) { + m_drives = new Drives(this); + connect(m_drives, &Drives::changed, this, &Places::refreshDevices); + connect(m_drives, &Drives::leaving, this, &Places::leave); + } connect(&m_poll, &QTimer::timeout, this, &Places::refresh); if (m_realHome) m_poll.start(); @@ -386,6 +394,55 @@ QVariantList Places::physicalDrives(const QList &mounts, const QString &s return drives; } +QVariantList Places::devicesFrom(const QList &volumes, const QVariantList &drives, + const QList &mounts) { + QVariantList devices; + QStringList listed; + for (const Drives::Volume &v : volumes) { + if (v.root.isEmpty()) { + devices << QVariantMap{{"name", v.name}, {"path", QString()}, {"icon", "drive"}, {"volume", v.id}, + {"release", QString()}, {"free", -1}}; + continue; + } + bool found = false; + for (const QVariant &d : drives) { + QVariantMap drive = d.toMap(); + if (drive.value("path").toString() != v.root) + continue; + drive.insert("volume", v.id); + // GIO's name, as the row had before it mounted; the mount folder + // an unlabeled drive would be named after is its UUID. + if (!v.name.isEmpty()) + drive.insert("name", v.name); + devices << drive; + listed << v.root; + found = true; + break; + } + // One physicalDrives passes over that isn't the system's (a disk + // image set up with udisksctl loop-setup) is still the drive it was + // before it mounted, so it stays, with its way to let go of it. + if (!found && !Disks::isSystemMount(v.root)) { + const QString release = v.canEject ? "eject" : v.canUnmount ? "unmount" : ""; + // What's free comes from the mounts read off the UI thread; a + // drive slow to answer never holds up the window here. + qint64 free = -1; + for (const Mount &m : mounts) + if (m.root == v.root) { + free = m.free; + break; + } + devices << QVariantMap{{"name", v.name.isEmpty() ? v.root : v.name}, {"path", v.root}, {"icon", "drive"}, + {"volume", v.id}, {"release", release}, {"free", free}}; + listed << v.root; + } + } + for (const QVariant &drive : drives) + if (!listed.contains(drive.toMap().value("path").toString())) + devices << drive; + return devices; +} + QList Places::readMounts() { QList mounts; auto volumes = QStorageInfo::mountedVolumes(); @@ -428,7 +485,8 @@ void Places::mountsRead() { mount.canUnmount = g_mount_can_unmount(gmount); g_object_unref(gmount); } - const QVariantList devices = physicalDrives(mounts, m_systemDevice); + const QVariantList physical = physicalDrives(mounts, m_systemDevice); + const QVariantList devices = m_drives ? devicesFrom(m_drives->volumes(), physical, mounts) : physical; if (devices != m_devices) { m_devices = devices; emit changed(); diff --git a/src/places.h b/src/places.h index 9026fabc..4b60ce14 100644 --- a/src/places.h +++ b/src/places.h @@ -5,6 +5,8 @@ #include #include +#include "drives.h" + // The sidebar's own rows: the user's places, pinned folders, views and // drives (plugins add the rest). Each list is small, so it is handed to QML // as plain maps rather than a model. @@ -70,6 +72,18 @@ class Places : public QObject { // says how it's let go of ("release": "eject", "unmount", or empty when // it can't be) and how much is free. static QVariantList physicalDrives(const QList &mounts, const QString &systemDevice); + // The Devices list: GIO's volumes in its order, each mounted one as its + // drive among `drives` under GIO's name, and each unmounted one by + // `volume` (no path, and nothing to let go of, until it's mounted), + // then the drives GIO + // doesn't list (an fstab mount). A mounted volume `drives` leaves out + // stays out when it's the system's own, and is listed from GIO's mount + // otherwise (a loop device), with what's free from `mounts`. + static QVariantList devicesFrom(const QList &volumes, const QVariantList &drives, + const QList &mounts = {}); + + // GIO's drives; null for a test's home, which has none. + Drives *drives() const { return m_drives; } signals: void changed(); @@ -107,4 +121,5 @@ class Places : public QObject { bool m_rereadMounts = false; // The device the system runs from, read once: it doesn't change. QString m_systemDevice; + Drives *m_drives = nullptr; }; diff --git a/tests/folio_tests.cpp b/tests/folio_tests.cpp index 3f606369..d05eeb52 100644 --- a/tests/folio_tests.cpp +++ b/tests/folio_tests.cpp @@ -6058,6 +6058,60 @@ private slots: QCOMPARE(notice.count(), 0); } + void placesListDrivesNotMountedYet() + { + // GIO's volumes come first, in its order: one not mounted, one + // mounted, and one mounted where the system lives. + const QList volumes{ + {"Windows", "/dev/nvme0n1p3", ""}, + {"Photos", "/dev/sdb1", "/run/media/me/Photos"}, + {"Home", "/dev/nvme0n1p2", "/home"}, + {"1.0 TB Volume", "/dev/sdc1", "/run/media/me/8CAE187EAE18634E"}, + // A disk image set up with udisksctl loop-setup, which + // physicalDrives passes over. + {"Image", "/dev/loop3", "/run/media/me/Image", false, true}, + }; + // The physical drives: a mounted volume is its drive, with what's + // free and how it's let go of; one GIO doesn't list (an fstab + // mount) follows. + const QVariantList drives{ + QVariantMap{{"name", "archive"}, {"path", "/mnt/archive"}, {"icon", "drive"}, {"release", ""}, {"free", 5}}, + QVariantMap{{"name", "Photos"}, {"path", "/run/media/me/Photos"}, {"icon", "drive"}, {"release", "eject"}, {"free", 7}}, + // Unlabeled, so named after its mount folder, the UUID. + QVariantMap{{"name", "8CAE187EAE18634E"}, {"path", "/run/media/me/8CAE187EAE18634E"}, {"icon", "drive"}, + {"release", "eject"}, {"free", 9}}, + }; + // What's free on the image comes from the mounts already read. + Places::Mount imageMount{"/run/media/me/Image", "/dev/loop3", "ext4", "Image"}; + imageMount.free = 11; + const auto devices = Places::devicesFrom(volumes, drives, {imageMount}); + QCOMPARE(devices.size(), 5); + const QVariantMap windows = devices.at(0).toMap(); + QCOMPARE(windows.value("name").toString(), QString("Windows")); + QVERIFY(windows.value("path").toString().isEmpty()); + QCOMPARE(windows.value("volume").toString(), QString("/dev/nvme0n1p3")); + QVERIFY(windows.value("release").toString().isEmpty()); + const QVariantMap photos = devices.at(1).toMap(); + QCOMPARE(photos.value("path").toString(), QString("/run/media/me/Photos")); + QCOMPARE(photos.value("volume").toString(), QString("/dev/sdb1")); + QCOMPARE(photos.value("release").toString(), QString("eject")); + QCOMPARE(photos.value("free").toLongLong(), 7); + // The system's own stays out, as physicalDrives left it. An + // unlabeled drive takes GIO's name, not its UUID folder's. + const QVariantMap unlabeled = devices.at(2).toMap(); + QCOMPARE(unlabeled.value("name").toString(), QString("1.0 TB Volume")); + QCOMPARE(unlabeled.value("path").toString(), QString("/run/media/me/8CAE187EAE18634E")); + // The image stays once mounted, from GIO's mount, and unmounts. + const QVariantMap image = devices.at(3).toMap(); + QCOMPARE(image.value("name").toString(), QString("Image")); + QCOMPARE(image.value("path").toString(), QString("/run/media/me/Image")); + QCOMPARE(image.value("volume").toString(), QString("/dev/loop3")); + QCOMPARE(image.value("release").toString(), QString("unmount")); + QCOMPARE(image.value("free").toLongLong(), 11); + QCOMPARE(devices.at(4).toMap().value("path").toString(), QString("/mnt/archive")); + QVERIFY(!devices.at(4).toMap().contains("volume")); + } + void drivesSayWhatsFreeInTheLanguagesDigits() { QQmlEngine engine;