Commit 7950d2fc authored by Kourser's avatar Kourser
Browse files

Vaults: open several vaults, each with its own sync

First step of docs/coffres-multiples.md: a device can now hold several
independent vaults, one open at a time, each with its own files, drafts,
sync state and Nextcloud account.

- EnvorennCore: VaultRegistry and VaultRegistryStore read and write
  vaults.json, a local list that is never synchronized. A malformed file is
  refused, never guessed or overwritten. On first launch the existing vault
  becomes "Mon coffre" and stays where it is: no file, sync state or
  keychain item moves.
- App: VaultLibrary keeps one VaultSession per vault (environment, recorder,
  identity, sync, calendars). Switching vaults swaps the whole session and
  rebuilds the screens, so no view can mix two vaults. Sessions stay alive so
  a sync or an autosave in the vault being left can finish.
- A switcher at the top of the sidebar lists the vaults, creates one and
  opens a sheet to rename, open or remove them. Removing deletes the vault
  from this device only; the server is not touched.
- Each vault gets its own keychain entry. Saving an app password used to
  delete every other one; the original vault keeps its historical entry.
  Erasing a vault now forgets only the CalDAV secrets of its own accounts.
- Background sync (iOS tasks, macOS activity) runs every vault, the open one
  first. The share queue key stays shared by all vaults.
- Linux: the same registry in vaults.py, with a "Coffres" submenu to open,
  add, rename and remove vaults. Removing never deletes the user's folder.
- conformance/vaults: ten registries that Swift (VaultRegistryTests) and
  Python (Linux/test_vaults.py) accept or refuse identically.
- Translations: 26 new strings in the 24 languages. The ten short labels were
  rewritten by hand with each language's existing term for "vault", and the
  machine translations that were wrong were corrected; the corrections are in
  tools/localization_overrides.json. "Ouvrir ce coffre" avoids the existing
  "Ouvrir" key, which means "Unlock".

Checks: 626 core tests, 4 Python registry tests and the localization checks
pass; macOS and iOS build. On the real vault, the registry was created at
launch and the original vault synchronized with its existing keychain item;
a second vault opened in its own folder. The switcher and the management
sheet have not been checked on screen.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 788f7099
Loading
Loading
Loading
Loading
+3 −2
Changes for App/Calendar/CalendarController.swift: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -263,8 +263,9 @@ final class CalendarController {
    /// Suppression totale : les comptes, les secrets et les caches s'en vont
    /// avec le reste.
    func resetAfterErase() {
        for account in accounts { cacheStore.forget(account.id) }
        try? credentials.forgetAll()
        // Les secrets de ce coffre seulement : les comptes des autres coffres
        // partagent le même service du trousseau.
        for account in accounts { cacheStore.forget(account.id); try? credentials.forget(account.id) }
        accounts = []
        caches = [:]
        outbox = CalendarOutbox()
+35 −38
Changes for App/EnvorennApp.swift: 35 added lines, 38 removed lines.
Original line number Diff line number Diff line
@@ -6,12 +6,9 @@ struct EnvorennApp: App {

    @Environment(\.scenePhase) private var scenePhase

    @State private var environment: AppEnvironment
    @State private var recorder: RecordingController
    @State private var playback: PlaybackController
    @State private var vault: VaultIdentity
    @State private var sync: SyncController
    @State private var calendar: CalendarController
    /// Les coffres de l'appareil ; tout ce qui appartient à un coffre passe
    /// par sa session (`VaultSession`).
    @State private var library: VaultLibrary
    @State private var appLock = AppLockController()
    @State private var location = LocationCapture()
    @State private var commands = AppCommands()
@@ -21,36 +18,23 @@ struct EnvorennApp: App {
    @AppStorage(AppPreference.textSize) private var textSize = AppTextSize.system.rawValue

    init() {
        let environment = AppEnvironment.live()
        let session = AudioSessionController()
        let sync = SyncController(environment: environment)

        _environment = State(initialValue: environment)
        _recorder = State(initialValue: RecordingController(
            layout: environment.layout,
            scanner: environment.scanner,
            session: session,
            clock: environment.clock
        ))
        _playback = State(initialValue: PlaybackController(session: session))
        _vault = State(initialValue: VaultIdentity(environment: environment))
        _sync = State(initialValue: sync)
        _calendar = State(initialValue: CalendarController(environment: environment))
        let library = VaultLibrary.live()
        _library = State(initialValue: library)

        // Avant la fin du lancement, comme l'exige le système : c'est aussi à ce
        // moment qu'il relance l'application pour une tâche de fond.
        BackgroundSyncScheduler.register(controller: sync)
        BackgroundSyncScheduler.register(library: library)
    }

    private var session: VaultSession { library.active }

    var body: some Scene {
        WindowGroup(id: Self.libraryWindowID) {
            LibraryView()
                .environment(environment)
                .environment(recorder)
                .environment(playback)
                .environment(vault)
                .environment(sync)
                .environment(calendar)
                // Un autre coffre, un autre écran : rien de l'état affiché ne
                // survit au changement.
                .id(session.id)
                .modifier(VaultSessionEnvironment(library: library))
                .environment(appLock)
                .environment(location)
                .environment(commands)
@@ -71,8 +55,8 @@ struct EnvorennApp: App {
                .onChange(of: language) { AppLanguage.select(language) }
                // Clé ou réglages du coffre arrivés du serveur — un coffre
                // retrouvé sur un nouvel appareil (CU7) : l'état est à relire.
                .onChange(of: sync.vaultFilesRevision) {
                    vault.refresh()
                .onChange(of: session.sync.vaultFilesRevision) {
                    session.vault.refresh()
                }
                // Verrouillée au lancement, l'application ne montre rien, pas
                // même le temps que la fenêtre de verrouillage apparaisse.
@@ -94,9 +78,9 @@ struct EnvorennApp: App {
            case .active:
                // Le retour dans l'application rattrape ce que les tâches de
                // fond n'ont pas pu faire.
                sync.synchronize(trigger: .appActive)
                session.sync.synchronize(trigger: .appActive)
            case .background:
                BackgroundSyncScheduler.schedule(for: sync)
                BackgroundSyncScheduler.schedule(for: library)
            default:
                break
            }
@@ -112,12 +96,8 @@ struct EnvorennApp: App {
            }
            .id(settingsRoute.page)
            .modifier(JournalWindowChromeStyle(appearance: appearance, textSize: textSize))
            .environment(environment)
            .environment(recorder)
            .environment(playback)
            .environment(vault)
            .environment(sync)
            .environment(calendar)
            .id(session.id)
            .modifier(VaultSessionEnvironment(library: library))
            .environment(appLock)
            .environment(location)
            .environment(commands)
@@ -140,6 +120,23 @@ struct EnvorennApp: App {
    #endif
}

/// Les objets du coffre ouvert, et la bibliothèque pour en changer.
struct VaultSessionEnvironment: ViewModifier {
    let library: VaultLibrary

    func body(content: Content) -> some View {
        let session = library.active
        content
            .environment(library)
            .environment(session.environment)
            .environment(session.recorder)
            .environment(library.playback)
            .environment(session.vault)
            .environment(session.sync)
            .environment(session.calendar)
    }
}

/// Les choix d'apparence de l'application valent pour toutes ses fenêtres, pas
/// seulement pour la bibliothèque.
struct JournalWindowChromeStyle: ViewModifier {
+7 −2
Changes for App/Features/LibraryView.swift: 7 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -116,6 +116,7 @@ private struct JournalTreeRowDrop: ViewModifier {
struct LibraryView: View {

    @Environment(AppEnvironment.self) private var environment
    @Environment(VaultLibrary.self) private var library
    @Environment(PlaybackController.self) private var playback
    @Environment(RecordingController.self) private var recorder
    @Environment(VaultIdentity.self) private var vault
@@ -169,11 +170,11 @@ struct LibraryView: View {
    @State private var sourceLink: JournalSourceLink?
    @State private var editingDraft: JournalEntryFile?
    @State private var draftReferences: [JournalDraftReference] = []
    private struct DraftPreview: Sendable { let title: String; let date: Date; let isPage: Bool; let folders: [UUID] }
    /// Brouillons qu'aucun éditeur ouvert ne tient : les seuls à reprendre.
    private var resumableDrafts: [JournalDraftReference] {
        draftReferences.filter { environment.openDraftIDs[$0.id] == nil }
    }
    private struct DraftPreview: Sendable { let title: String; let date: Date; let isPage: Bool; let folders: [UUID] }
    @State private var draftPreviews: [String: DraftPreview] = [:]
    @State private var draftPreviewTask: Task<Void, Never>?
    @State private var showDrafts = false
@@ -3265,6 +3266,8 @@ struct LibraryView: View {
    private var nativeSidebar: some View {
        VStack(alignment: .leading, spacing: 0) {
            VStack(alignment: .leading, spacing: 8) {
                VaultSwitcher()
                    .padding(.horizontal, 8).padding(.bottom, 2)
                Button {
                    if calendarDestination != nil { calendarWorkspace.creationRequest += 1 }
                    else {
@@ -3305,7 +3308,9 @@ struct LibraryView: View {
            .padding(.horizontal, 12).padding(.vertical, 8)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
        .navigationTitle(Text(verbatim: "Envorenn"))
        // Le nom du coffre dès qu'il y en a plusieurs : sur Mac, c'est aussi le
        // titre de la fenêtre.
        .navigationTitle(library.entries.count > 1 ? Text(verbatim: library.activeEntry.name) : Text(verbatim: "Envorenn"))
    }

    /// Le fond d'une ligne visée par un dépôt. `nil` laisse la liste peindre
+189
Changes for App/Features/VaultSwitcher.swift: 189 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI
import EnvorennCore

/// Le coffre ouvert, et le menu pour en changer, en créer ou les gérer.
///
/// En tête de la barre latérale : c'est le premier choix, avant ce qu'on écrit
/// et où. Un seul coffre est ouvert à la fois ; changer de coffre recharge tout
/// l'écran (`VaultLibrary.open`).
struct VaultSwitcher: View {
    @Environment(VaultLibrary.self) private var library
    @State private var managing = false
    @State private var naming = false
    @State private var newName = ""
    @State private var errorMessage: String?

    var body: some View {
        Menu {
            ForEach(library.entries) { entry in
                Button { open(entry.id) } label: {
                    if entry.id == library.activeEntry.id {
                        Label(entry.name, systemImage: "checkmark")
                    } else {
                        Text(entry.name)
                    }
                }
            }
            Divider()
            Button("Nouveau coffre…", systemImage: "plus") { newName = ""; naming = true }
            Button("Gérer les coffres…", systemImage: "slider.horizontal.3") { managing = true }
        } label: {
            HStack(spacing: 8) {
                Image(systemName: "archivebox").foregroundStyle(Color.accessibleAccent)
                Text(library.activeEntry.name).lineLimit(1).truncationMode(.tail)
                Spacer(minLength: 4)
                Image(systemName: "chevron.up.chevron.down").journalFont(.caption2).foregroundStyle(Color.secondaryText)
            }
            .journalFont(.subheadline, weight: .semibold)
            .contentShape(Rectangle())
        }
        .menuStyle(.button)
        .buttonStyle(.plain)
        .menuIndicator(.hidden)
        .accessibilityLabel(Text("Coffre ouvert : \(library.activeEntry.name)"))
        .accessibilityHint(Text("Changer de coffre, en créer un ou les gérer"))
        .accessibilityIdentifier("vault.switcher")
        .alert("Nouveau coffre", isPresented: $naming) {
            TextField("Nom du coffre", text: $newName)
            Button("Créer et ouvrir") { create() }
            Button("Annuler", role: .cancel) {}
        } message: {
            Text("Un coffre a ses propres notes, son journal et sa synchronisation. Vous pourrez le relier à un Nextcloud depuis les réglages.")
        }
        .alert("Coffres", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(errorMessage ?? "")
        }
        .sheet(isPresented: $managing) { VaultManagerView() }
    }

    private func open(_ id: UUID) {
        do { try library.open(id) } catch { errorMessage = error.localizedDescription }
    }

    private func create() {
        do {
            let entry = try library.create(name: newName)
            try library.open(entry.id)
        } catch VaultRegistryError.invalidName {
            errorMessage = String(localized: "Donnez au coffre un nom de 80 caractères au plus.", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}

/// Renommer, ouvrir et retirer les coffres de l'appareil.
struct VaultManagerView: View {
    @Environment(VaultLibrary.self) private var library
    @Environment(\.dismiss) private var dismiss
    @State private var renaming: VaultRegistry.Entry?
    @State private var newName = ""
    @State private var removing: VaultRegistry.Entry?
    @State private var errorMessage: String?

    var body: some View {
        NavigationStack {
            List {
                Section {
                    ForEach(library.entries) { entry in
                        row(entry)
                    }
                } footer: {
                    Text("Retirer un coffre le supprime de cet appareil seulement. Ce qui a déjà été envoyé à son serveur y reste.")
                }
            }
            .navigationTitle("Coffres")
            #if os(iOS)
            .navigationBarTitleDisplayMode(.inline)
            #endif
            .toolbar {
                ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } }
            }
        }
        #if os(macOS)
        .frame(minWidth: 460, minHeight: 320)
        #endif
        .alert("Renommer le coffre", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {
            TextField("Nom du coffre", text: $newName)
            Button("Renommer") { rename() }
            Button("Annuler", role: .cancel) {}
        }
        .confirmationDialog(removalTitle, isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
                            titleVisibility: .visible) {
            Button("Retirer de cet appareil", role: .destructive) { remove() }
            Button("Annuler", role: .cancel) {}
        } message: {
            removalMessage
        }
        .alert("Coffres", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(errorMessage ?? "")
        }
    }

    private func row(_ entry: VaultRegistry.Entry) -> some View {
        let isActive = entry.id == library.activeEntry.id
        let account = library.session(for: entry.id)?.sync.account
        return HStack(spacing: 12) {
            Image(systemName: isActive ? "archivebox.fill" : "archivebox")
                .foregroundStyle(isActive ? Color.accessibleAccent : Color.secondaryText)
                .accessibilityHidden(true)
            VStack(alignment: .leading, spacing: 2) {
                Text(entry.name).journalFont(.body, weight: isActive ? .semibold : .regular)
                Group {
                    if let account { Text("Nextcloud · \(account.serverLabel)") } else { Text("Sur cet appareil") }
                }
                .journalFont(.caption).foregroundStyle(Color.secondaryText)
            }
            Spacer(minLength: 8)
            if isActive {
                Text("Ouvert").journalFont(.caption).foregroundStyle(Color.secondaryText)
            } else {
                Button("Ouvrir ce coffre") { open(entry.id) }.buttonStyle(.borderless)
            }
            Menu {
                Button("Renommer…", systemImage: "pencil") { newName = entry.name; renaming = entry }
                Button("Retirer de cet appareil…", systemImage: "trash", role: .destructive) { removing = entry }
                    .disabled(isActive)
            } label: {
                Image(systemName: "ellipsis.circle").accessibilityLabel(Text("Actions pour \(entry.name)"))
            }
            .menuStyle(.button).buttonStyle(.borderless).menuIndicator(.hidden)
        }
        .padding(.vertical, 4)
    }

    private var removalTitle: Text {
        Text("Retirer « \(removing?.name ?? "") » ?")
    }

    private var removalMessage: Text {
        guard let removing else { return Text("") }
        if library.session(for: removing.id)?.sync.account != nil {
            return Text("Ses notes, ses brouillons et son appairage seront supprimés de cet appareil. Ce qui est déjà sur le serveur n'est pas touché : vous pourrez le retrouver en reliant un nouveau coffre au même dossier.")
        }
        return Text("Ce coffre n'est relié à aucun serveur : ses notes seront définitivement supprimées. Exportez-les d'abord si vous voulez les garder.")
    }

    private func open(_ id: UUID) {
        do { try library.open(id); dismiss() } catch { errorMessage = error.localizedDescription }
    }

    private func rename() {
        guard let entry = renaming else { return }
        do { try library.rename(entry.id, to: newName) }
        catch VaultRegistryError.invalidName {
            errorMessage = String(localized: "Donnez au coffre un nom de 80 caractères au plus.", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        } catch { errorMessage = error.localizedDescription }
        renaming = nil
    }

    private func remove() {
        guard let entry = removing else { return }
        do { try library.remove(entry.id) } catch { errorMessage = error.localizedDescription }
        removing = nil
    }
}
+3692

File changed.

Preview size limit exceeded, changes collapsed.

Loading