diff --git a/.gitattributes b/.gitattributes index de1f0e4d..e787035e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,7 +6,7 @@ /docs export-ignore /hosts/standalone export-ignore /hosts/caelestia export-ignore -/hosts/dankmaterialshell export-ignore +/hosts/dux-shell export-ignore /hosts/illogical-impulse export-ignore /hosts/waybar export-ignore /tests export-ignore diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9fe3b3cd..2d317692 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,6 +25,15 @@ jobs: - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 with: node-version: '24' + # Merges from older branches can bring back files that are now local + # only; fail instead of publishing them again. + - name: No tracked files match .gitignore + run: | + tracked=$(git ls-files -ci --exclude-standard) + [[ -z $tracked ]] || { + printf 'tracked but ignored, run git rm --cached:\n%s\n' "$tracked" + exit 1 + } - name: Core and launcher contracts run: >- go -C core test -race -covermode=atomic @@ -43,8 +52,24 @@ jobs: use_oidc: true - name: Installation script contracts run: bash tests/scripts.test.sh --installation-only + - name: Install Qt controller test tools + run: | + sudo apt-get update + sudo apt-get install -y qt6-declarative-dev-tools qml6-module-qttest \ + qml6-module-qtquick qml6-module-qtquick-window \ + qml6-module-qtqml-workerscript + - name: DMS adapter contracts and reproducible package + run: | + bash integrations/dux-shell/assemble.sh "$GITHUB_WORKSPACE/dist/dux-shell" + bash tests/dux-shell-adapter.test.sh - name: Device sharing form contracts run: node --test tests/device-sharing.test.mjs + - name: Portable adapter contracts and Caelestia package + run: | + node --test tests/adapter-contract.test.mjs tests/caelestia-*.test.mjs + bash integrations/caelestia/assemble.sh "$RUNNER_TEMP/caelestia-one" + bash integrations/caelestia/assemble.sh "$RUNNER_TEMP/caelestia-two" + diff -qr "$RUNNER_TEMP/caelestia-one" "$RUNNER_TEMP/caelestia-two" - name: Integration fixture contracts run: go -C tests/integration test -race ./... - name: Reproduce bundled core @@ -98,3 +123,22 @@ jobs: name: syncshell-runtime path: ${{ runner.temp }}/syncshell-runtime.tar.gz if-no-files-found: error + + # Apple Silicon Macs, Snapdragon and NVIDIA ARM machines run Omarchy on + # aarch64, so test the core and the bundled binary on a native ARM host. + arm64: + runs-on: ubuntu-24.04-arm + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e + with: + go-version-file: core/go.mod + cache-dependency-path: core/go.sum + - name: Core contracts on aarch64 + run: go -C core test -race ./... + - name: Bundled aarch64 core + run: | + sudo apt-get update + sudo apt-get install -y ripgrep + bash packaging/bundled/verify.sh diff --git a/.gitignore b/.gitignore index 0ede03e8..ee014e52 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,20 @@ # Local capture harness, archives, and project-only Codex workflow. -/docs/interactive/ +/docs/* +!/docs/status-colors.md /tests/live/* !/tests/live/*.sh /.agents/skills/ /assets/backups/ /TODO/ /test-results/ +/dist/dux-shell/ /.omarchy-plugin-dev/ /assets/old-published/ /assets/README.md + +# Assembled local native plugin. +/dist/caelestia/ + +# Local maintainer notes and checklists. +/hosts/*/NOTES.md +/integrations/dux-shell/submission.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 6da5ed29..710c7269 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,36 @@ # Changelog -Notable changes to Syncshell for Omarchy are documented here. +Notable changes to Syncshell and its shell adapters are documented here. + +## Unreleased + +- remember the folder sort and filters across restarts: Omarchy writes them to + the new `[view]` section of `settings.toml` when the view options or the + panel close; files without it keep the defaults +- edit Omarchy's `settings.toml` in place from one parser: saves keep your + comments, quoting, CRLF line endings and symlinks, and a hand edit made + while the panel is open is no longer overwritten +- support Omarchy 4.5 on Apple Silicon Macs (M1, M2, M3 and MacBook Neo) with + the bundled aarch64 core; verify that it maps on 16K- and 64K-page kernels, + pin the x86_64 and aarch64 instruction-set baselines, and test it on a + native ARM CI runner +- ask Syncthing to rescan a directory only once while that rescan is still + running, so repeated index updates during a pull cannot pile up requests +- keep the syncing file name visible during bulk syncs: the core no longer + stalls for up to minutes on lookups and rescans for files Syncthing already + reported, and the Omarchy folder card no longer rebuilds on each update +- fit the monochrome icons' view box to the mark so the Omarchy 4.5 bar no + longer shrinks them below its built-in icons +- replace the experimental DMS adapter with native folder, device, sharing + and invitation workflows, pending desktop acceptance on DMS 2.0.0 +- target DMS 2.0 (Dux Shell) only: `qs.DCommon.Widgets` controls and the 2.0 + surface roles; DMS 1.6 is no longer supported +- rename the DMS adapter to `hosts/dux-shell` and `integrations/dux-shell` + after the shell's rename; the plugin id and `dms` command are unchanged +- add adapter-owned Modern and DMS-themed Web UI profiles with explicit + cleanup, and require explicit authority for Syncthing service control +- assemble a reproducible DMS package with bundled Linux workers and a Nix + recipe, without installing tools or changing bar placement ## 0.2.4 - 2026-10-19 diff --git a/README.md b/README.md index d0a2449b..d868b864 100644 --- a/README.md +++ b/README.md @@ -148,10 +148,11 @@ If UFW is enabled, run `sudo ufw allow syncthing` to allow [device discovery and synchronization][firewall]. The plugin supports Omarchy on Linux x86_64 and aarch64, including Apple Silicon -M1/M2 Macs running Omarchy (stable). Alpha adapters for DankMaterialShell, -Illogical Impulse, Caelestia, and Waybar are under development; they are not -officially released and WIP, but can be tested via manual installation on those -systems: see the `hosts/...` in the source. Daemon mode remains future work. +M1/M2/M3 and MacBook Neo Macs running Omarchy 4.5 or later. Alpha adapters for +Dux Shell (DMS), Illogical Impulse, Caelestia, and Waybar are under development; +they are not officially released and WIP, but can be tested via manual +installation on those systems: see the `hosts/...` in the source. Daemon mode +remains future work. ## File activity @@ -306,7 +307,7 @@ shared folders. | Shell | Status | Release plan | | ----------------- | ------- | ---------------------- | | Omarchy | Stable | stable since 0.1.0 | -| DankMaterialShell | Alpha | beta planned for 0.2.3 | +| Dux Shell (DMS) | Alpha | beta planned for 0.2.3 | | Illogical Impulse | Alpha | beta planned for 0.2.4 | | Caelestia | Alpha | beta planned for 0.2.5 | | Waybar | Alpha | beta planned for 0.2.6 | diff --git a/assets/LICENSE.md b/assets/LICENSE.md index 187e551e..c2bce527 100644 --- a/assets/LICENSE.md +++ b/assets/LICENSE.md @@ -14,10 +14,14 @@ They were retrieved from the Syncthing repository at commit `mono/` holds monochrome redraws of the same four icons, tinted to the theme at -runtime by `MonoIcon.qml`. They must stay pure white on transparent: the tint +runtime by `SharedWidgetMonoIcon.qml`. They must stay pure white on transparent: the tint multiplies the source's value channel, so anything darker comes out darker still. +Their shared square view box hugs the mark because Omarchy normalizes the whole +image rect, so transparent margin shrinks the icon; sharing it keeps the mark in +place across states. Badges must stay inside it, hence the sync badge's scale. + Copyright belongs to the Syncthing contributors. These adapted files remain licensed under the Mozilla Public License 2.0: diff --git a/assets/mono/status-default.svg b/assets/mono/status-default.svg index be0395e4..6b1d152d 100644 --- a/assets/mono/status-default.svg +++ b/assets/mono/status-default.svg @@ -1,5 +1,5 @@ - + diff --git a/assets/mono/status-notify.svg b/assets/mono/status-notify.svg index 8e85ed8c..b880c31b 100644 --- a/assets/mono/status-notify.svg +++ b/assets/mono/status-notify.svg @@ -1,5 +1,5 @@ - + diff --git a/assets/mono/status-pause.svg b/assets/mono/status-pause.svg index 274040fb..351d8811 100644 --- a/assets/mono/status-pause.svg +++ b/assets/mono/status-pause.svg @@ -1,5 +1,5 @@ - + diff --git a/assets/mono/status-sync.svg b/assets/mono/status-sync.svg index ae09791f..9dfb54cf 100644 --- a/assets/mono/status-sync.svg +++ b/assets/mono/status-sync.svg @@ -1,5 +1,5 @@ - + @@ -20,7 +20,7 @@ - + = maxFinishedItems { + for key, expires := range s.finishedItems { + if !expires.After(now) { + delete(s.finishedItems, key) + } + } + if s.finishedItems == nil || len(s.finishedItems) >= maxFinishedItems { + s.finishedItems = make(map[string]time.Time) + } + } + s.finishedItems[folderID+"\x00"+path] = now.Add(finishedItemMemory) +} + +// rescanSubdirectory runs in the background: Syncthing answers only once the +// scan ends, which waits for any pull. A directory already being rescanned is +// not asked again, so repeated index events cannot pile up requests. +func (s *Session) rescanSubdirectory(ctx context.Context, folderID, subdirectory string) { + key := folderID + "\x00" + subdirectory + s.rescansMu.Lock() + if s.rescansInFlight[key] { + s.rescansMu.Unlock() + return + } + if s.rescansInFlight == nil { + s.rescansInFlight = make(map[string]bool) + } + s.rescansInFlight[key] = true + s.rescansMu.Unlock() + go func() { + defer func() { + s.rescansMu.Lock() + delete(s.rescansInFlight, key) + s.rescansMu.Unlock() + }() + _ = s.client.RescanSubdirectory(ctx, folderID, subdirectory) + }() +} + +func (s *Session) rescanInFlight(folderID, subdirectory string) bool { + s.rescansMu.Lock() + defer s.rescansMu.Unlock() + return s.rescansInFlight[folderID+"\x00"+subdirectory] +} + func (s *Session) localIndex(ctx context.Context, event syncthing.Event, now time.Time) bool { var data struct { Folder string `json:"folder"` @@ -111,7 +162,16 @@ func (s *Session) localIndex(ctx context.Context, event syncthing.Event, now tim return false } changed := false - for _, name := range data.Filenames[:min(len(data.Filenames), 16)] { + names := make([]string, 0, 16) + for _, name := range data.Filenames { + if expires, ok := s.finishedItems[data.Folder+"\x00"+name]; ok && expires.After(now) { + continue + } + if names = append(names, name); len(names) == 16 { + break + } + } + for _, name := range names { info, err := s.currentFileInfo(ctx, data.Folder, name) entry := info.Local if entry == nil { @@ -122,7 +182,7 @@ func (s *Session) localIndex(ctx context.Context, event syncthing.Event, now tim continue } if fileType(entry.Type) == "directory" && !entry.Deleted { - _ = s.client.RescanSubdirectory(ctx, data.Folder, name) + s.rescanSubdirectory(ctx, data.Folder, name) continue } action := "syncing" @@ -178,7 +238,7 @@ func (s *Session) itemStarted(event syncthing.Event, now time.Time) bool { return s.storeActivity(data.Folder, data.Item, action, "", now) } -func (s *Session) itemFinished(event syncthing.Event) bool { +func (s *Session) itemFinished(event syncthing.Event, now time.Time) bool { var data struct { Folder string `json:"folder"` Item string `json:"item"` @@ -186,9 +246,12 @@ func (s *Session) itemFinished(event syncthing.Event) bool { if json.Unmarshal(event.Data, &data) != nil { return false } + s.rememberFinished(data.Folder, data.Item, now) changed := false for key, record := range s.activityRecords { if record.activity.FolderID == data.Folder && record.activity.Path == data.Item { + last := record.activity + s.lastFile, s.lastFileUntil = &last, now.Add(lastFileHold) delete(s.activityRecords, key) changed = true } @@ -274,6 +337,9 @@ func (s *Session) publishActivity(advance bool, now time.Time) PublishedSnapshot if len(activity.Files) > 0 { current := activity.Files[s.activityIndex] activity.Current = ¤t + } else if s.lastFile != nil && s.lastFileUntil.After(now) { + current := *s.lastFile + activity.Current = ¤t } s.activityMu.Unlock() diff --git a/core/internal/session/events.go b/core/internal/session/events.go index 576e112b..05521708 100644 --- a/core/internal/session/events.go +++ b/core/internal/session/events.go @@ -90,6 +90,10 @@ func (s *Session) eventLoop(ctx context.Context, updates chan PublishedSnapshot) if len(events) > 0 { gap := eventDiscontinuity(cursor, events) cursor = events[len(events)-1].ID + // Report files first: a refresh can take a second under load. + if s.processActivityEvents(ctx, events, time.Now()) { + emitLatest(updates, s.publishActivity(false, time.Now())) + } if gap || requiresHydration(events) { published, _ := s.Refresh(ctx) emitLatest(updates, published) @@ -97,9 +101,6 @@ func (s *Session) eventLoop(ctx context.Context, updates chan PublishedSnapshot) nextLifecycle = time.Now().Add(s.ProbeInterval()) nextTelemetry = time.Now().Add(deviceTelemetryInterval) } - if s.processActivityEvents(ctx, events, time.Now()) { - emitLatest(updates, s.publishActivity(false, time.Now())) - } } s.reconcileScheduled(ctx, updates, time.Now(), &nextRefresh, &nextLifecycle, &nextTelemetry, &nextActivity) diff --git a/core/internal/session/events_test.go b/core/internal/session/events_test.go index db648c5d..0c1e9814 100644 --- a/core/internal/session/events_test.go +++ b/core/internal/session/events_test.go @@ -172,6 +172,59 @@ func TestActivityNormalizationRotationAndCleanup(t *testing.T) { } } +func TestLastFileStaysVisibleBriefly(t *testing.T) { + now := time.Unix(100, 0) + coreSession := &Session{ + activityRecords: make(map[string]activityRecord), + current: PublishedSnapshot{Revision: 1}, + } + batch := []syncthing.Event{ + {Type: "ItemStarted", Data: []byte(`{"folder":"folder","item":"dir/small.txt","action":"update"}`)}, + {Type: "ItemFinished", Data: []byte(`{"folder":"folder","item":"dir/small.txt"}`)}, + } + coreSession.processActivityEvents(context.Background(), batch, now) + shown := coreSession.publishActivity(false, now) + if shown.State.Activity.Current == nil || shown.State.Activity.Current.Detail != "small.txt" { + t.Fatalf("batched file never reached the panel: %#v", shown.State.Activity) + } + if len(shown.State.Activity.Files) != 0 { + t.Fatalf("finished file still counted as active: %#v", shown.State.Activity.Files) + } + cleared := coreSession.publishActivity(false, now.Add(lastFileHold+time.Millisecond)) + if cleared.State.Activity.Current != nil { + t.Fatalf("finished file outlived its hold: %#v", cleared.State.Activity.Current) + } +} + +func TestLocalIndexSkipsFilesAlreadyReportedFinished(t *testing.T) { + api := &actionAPI{folders: map[string]syncthing.Folder{}, + devices: []syncthing.Device{{DeviceID: "LOCAL"}}, + pending: syncthing.PendingFolders{}, theme: "default"} + coreSession := newActionSession(t, api) + if _, err := coreSession.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + now := time.Unix(100, 0) + events := []syncthing.Event{ + {Type: "ItemFinished", Data: []byte(`{"folder":"folder","item":"directory"}`)}, + {Type: "LocalIndexUpdated", Data: []byte(`{"folder":"folder","filenames":["directory"]}`)}, + } + coreSession.processActivityEvents(context.Background(), events, now) + time.Sleep(50 * time.Millisecond) + if got := api.rescanCount(); got != 0 { + t.Fatalf("pulled directory was rescanned %d times", got) + } + later := []syncthing.Event{{Type: "LocalIndexUpdated", + Data: []byte(`{"folder":"folder","filenames":["directory"]}`)}} + coreSession.processActivityEvents(context.Background(), later, now.Add(finishedItemMemory+time.Second)) + for deadline := time.Now().Add(2 * time.Second); api.rescanCount() != 1; { + if time.Now().After(deadline) { + t.Fatalf("local directory change was not rescanned: rescans=%d", api.rescanCount()) + } + time.Sleep(5 * time.Millisecond) + } +} + func TestLocalIndexUsesCurrentFileInformation(t *testing.T) { api := &actionAPI{folders: map[string]syncthing.Folder{}, devices: []syncthing.Device{{DeviceID: "LOCAL"}}, @@ -187,9 +240,14 @@ func TestLocalIndexUsesCurrentFileInformation(t *testing.T) { t.Fatal("local index did not change activity") } published := coreSession.publishActivity(false, now) - if len(published.State.Activity.Files) != 2 || api.rescanCount() != 1 { - t.Fatalf("unexpected indexed activity: %#v rescans=%d", - published.State.Activity, api.rescanCount()) + if len(published.State.Activity.Files) != 2 { + t.Fatalf("unexpected indexed activity: %#v", published.State.Activity) + } + for deadline := time.Now().Add(2 * time.Second); api.rescanCount() != 1; { + if time.Now().After(deadline) { + t.Fatalf("directory was not rescanned: rescans=%d", api.rescanCount()) + } + time.Sleep(5 * time.Millisecond) } actions := make(map[string]string) for _, activity := range published.State.Activity.Files { @@ -559,3 +617,38 @@ func cancelEventUpdates( t.Fatal("event loop did not cancel") } } + +func TestSubdirectoryRescanIsNotRepeatedWhileInFlight(t *testing.T) { + api := &actionAPI{folders: map[string]syncthing.Folder{}, + devices: []syncthing.Device{{DeviceID: "LOCAL"}}, + pending: syncthing.PendingFolders{}, theme: "default", + rescanStarted: make(chan struct{}, 1), rescanRelease: make(chan struct{})} + coreSession := newActionSession(t, api) + ctx := context.Background() + coreSession.rescanSubdirectory(ctx, "folder", "directory") + select { + case <-api.rescanStarted: + case <-time.After(2 * time.Second): + t.Fatal("first rescan never reached Syncthing") + } + // Still blocked in Syncthing: the same directory is not asked again. + coreSession.rescanSubdirectory(ctx, "folder", "directory") + close(api.rescanRelease) + for deadline := time.Now().Add(2 * time.Second); coreSession.rescanInFlight("folder", "directory"); { + if time.Now().After(deadline) { + t.Fatal("finished rescan stayed in flight") + } + time.Sleep(5 * time.Millisecond) + } + if count := api.rescanCount(); count != 1 { + t.Fatalf("rescans while one was in flight: %d", count) + } + // Once it has finished, the directory can be rescanned again. + coreSession.rescanSubdirectory(ctx, "folder", "directory") + for deadline := time.Now().Add(2 * time.Second); api.rescanCount() != 2; { + if time.Now().After(deadline) { + t.Fatalf("a later rescan was dropped: %d", api.rescanCount()) + } + time.Sleep(5 * time.Millisecond) + } +} diff --git a/core/internal/session/input_validation_test.go b/core/internal/session/input_validation_test.go new file mode 100644 index 00000000..92f6572b --- /dev/null +++ b/core/internal/session/input_validation_test.go @@ -0,0 +1,39 @@ +package session + +import ( + "context" + "strings" + "testing" + + "github.com/omarchy-QOL/syncshell/core/internal/syncthing" +) + +func TestAddDeviceRejectsInvalidSelfAndDuplicateWithoutWriting(t *testing.T) { + localID := strings.TrimSuffix(strings.Repeat("AAAAAAA-", 8), "-") + remoteID := strings.TrimSuffix(strings.Repeat("BBBBBBB-", 8), "-") + for _, tc := range []struct{ name, id, code string }{ + {"invalid", "not-a-device-id", "device_id_invalid"}, + {"self", localID, "device_self"}, + {"duplicate", remoteID, "device_exists"}, + } { + t.Run(tc.name, func(t *testing.T) { + api := &actionAPI{devices: []syncthing.Device{{DeviceID: remoteID}}} + session := newActionSession(t, api) + if _, err := session.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + snapshot := session.Current().State + snapshot.Identity.DeviceID = localID + session.publish(snapshot) + result := session.Act(context.Background(), "device.add", ActionArguments{DeviceID: tc.id, DeviceName: "kept name"}) + if result.OK || result.Error == nil || result.Error.Code != tc.code || result.Error.Message == "" { + t.Fatalf("unexpected rejection: %#v", result) + } + api.mu.Lock() + defer api.mu.Unlock() + if api.lastDeviceAdd != nil { + t.Fatalf("rejected device was written: %#v", api.lastDeviceAdd) + } + }) + } +} diff --git a/core/internal/session/lifecycle.go b/core/internal/session/lifecycle.go index 632e9d70..fad6254a 100644 --- a/core/internal/session/lifecycle.go +++ b/core/internal/session/lifecycle.go @@ -22,7 +22,11 @@ func (s *Session) lifecycleAction(ctx context.Context, name string) ActionResult if lifecycleReached(name, published) { return ActionResult{OK: true} } - if err := s.lifecycle.Apply(ctx, s.binding.Unit, systemduser.Action(name)); err != nil { + // Hydration must not observe a partially applied unit transition. + s.refreshMu.Lock() + err := s.lifecycle.Apply(ctx, s.binding.Unit, systemduser.Action(name)) + s.refreshMu.Unlock() + if err != nil { return rejected("lifecycle_failed", err.Error()) } return s.waitForLifecycle(ctx, name) diff --git a/core/internal/session/lifecycle_test.go b/core/internal/session/lifecycle_test.go index 6c2b4c06..91056ba4 100644 --- a/core/internal/session/lifecycle_test.go +++ b/core/internal/session/lifecycle_test.go @@ -165,6 +165,102 @@ func TestLifecycleActionsRequireAndRetainTargetAuthority(t *testing.T) { } } +func TestRefreshCannotReclassifyAnAuthorizedStop(t *testing.T) { + directory := t.TempDir() + active := filepath.Join(directory, "active") + apiActive := filepath.Join(directory, "api-active") + enabled := filepath.Join(directory, "enabled") + calls := filepath.Join(directory, "calls") + entered := filepath.Join(directory, "stop-entered") + release := filepath.Join(directory, "stop-release") + for path, value := range map[string]string{ + active: "active", apiActive: "active", enabled: "enabled", calls: "0", + } { + writeState(t, path, value) + } + healthDuringStop := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/rest/noauth/health" { + if _, err := os.Stat(entered); err == nil { + if _, err := os.Stat(release); os.IsNotExist(err) { + select { + case healthDuringStop <- struct{}{}: + default: + } + } + } + } + (lifecycleAPI{activeFile: apiActive}).ServeHTTP(w, r) + })) + defer server.Close() + configPath := filepath.Join(directory, "config.xml") + config := fmt.Sprintf(`
%s
%s
`, + strings.TrimPrefix(server.URL, "http://"), sessionTestKey) + if err := os.WriteFile(configPath, []byte(config), 0o600); err != nil { + t.Fatal(err) + } + command := lifecycleSystemctl(t, directory, configPath, active, enabled, calls) + script, err := os.ReadFile(command) + if err != nil { + t.Fatal(err) + } + // The API can still answer while systemd is stopping its process. + stop := fmt.Sprintf("stop) printf 'inactive\\n' >%q; touch %q; "+ + "while [[ ! -e %q ]]; do sleep 0.005; done; "+ + "printf 'inactive\\n' >%q ;;", active, entered, release, apiActive) + script = []byte(strings.Replace(string(script), + fmt.Sprintf("stop) printf 'inactive\\n' >%q ;;", active), stop, 1)) + if err := os.WriteFile(command, script, 0o700); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + coreSession, err := New(ctx, Config{ + Discovery: syncthing.DiscoveryOptions{ConfigPath: configPath}, + Lifecycle: systemduser.Binding{Authorized: true, Unit: "syncthing.service", ConfigPath: configPath}, + SystemdCommand: command, + }) + if err != nil { + t.Fatal(err) + } + actionDone := make(chan ActionResult, 1) + go func() { actionDone <- coreSession.Act(ctx, "lifecycle.stop", ActionArguments{}) }() + for { + if _, err := os.Stat(entered); err == nil { + break + } + if ctx.Err() != nil { + t.Fatal("stop did not begin") + } + time.Sleep(time.Millisecond) + } + refreshDone := make(chan struct{}) + go func() { coreSession.Refresh(ctx); close(refreshDone) }() + select { + case <-healthDuringStop: + select { + case <-refreshDone: + case <-ctx.Done(): + t.Fatal("overlapping refresh did not finish") + } + case <-time.After(300 * time.Millisecond): + } + writeState(t, release, "release") + select { + case result := <-actionDone: + if !result.OK { + t.Fatalf("authorized stop failed: %#v", result) + } + case <-ctx.Done(): + t.Fatal("stop did not finish") + } + <-refreshDone + state := coreSession.Current().State.Lifecycle + if state.Classification != "stopped-candidate" || !state.CanControl || !state.CanStart { + t.Fatalf("controlled stop lost lifecycle authority: %#v", state) + } +} + type lifecycleAPI struct{ activeFile string } func (a lifecycleAPI) ServeHTTP(writer http.ResponseWriter, request *http.Request) { diff --git a/core/internal/session/profile.go b/core/internal/session/profile.go new file mode 100644 index 00000000..bd826438 --- /dev/null +++ b/core/internal/session/profile.go @@ -0,0 +1,55 @@ +package session + +import "context" + +func (s *Session) profileAssets(ctx context.Context) (string, *ActionResult) { + if result := s.requireOnline(); result != nil { + return "", result + } + if err := s.webProfile.Validate(); err != nil || !s.target.Local || s.target.ConfigPath == "" { + result := rejected("profile_forbidden", "Web UI profiles require an authorized local Syncthing configuration") + return "", &result + } + paths, err := s.client.SystemPaths(ctx) + if err != nil || paths.GUIAssets == "" || paths.GUIAssets != s.Current().State.WebUI.GUIAssets { + result := rejected("profile_target_changed", "Syncthing's GUI asset directory changed or is unavailable; refresh first") + return "", &result + } + return paths.GUIAssets, nil +} + +func (s *Session) applyWebProfile(ctx context.Context, args ActionArguments) ActionResult { + assets, failure := s.profileAssets(ctx) + if failure != nil { + return *failure + } + name, err := s.webProfile.Prepare(assets, args.Profile, args.Palette) + if err != nil { + return rejected("profile_prepare", err.Error()) + } + return s.setWebUITheme(ctx, name) +} + +func (s *Session) removeWebProfile(ctx context.Context) ActionResult { + assets, failure := s.profileAssets(ctx) + if failure != nil { + return *failure + } + current, err := s.client.GUIConfig(ctx) + if err != nil { + return ActionResult{Error: publicError(err)} + } + modern, _ := s.webProfile.Name("modern") + themed, _ := s.webProfile.Name("themed") + // Only a theme this adapter owns would be left pointing at deleted files; + // any other selection is the user's or another adapter's and stays. + if current.Theme == modern || current.Theme == themed { + if result := s.setWebUITheme(ctx, "default"); !result.OK { + return result + } + } + if err := s.webProfile.Remove(assets); err != nil { + return rejected("profile_cleanup", err.Error()) + } + return s.refreshAfterMutation(ctx) +} diff --git a/core/internal/session/profile_test.go b/core/internal/session/profile_test.go new file mode 100644 index 00000000..6aeda334 --- /dev/null +++ b/core/internal/session/profile_test.go @@ -0,0 +1,152 @@ +package session + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/omarchy-QOL/syncshell/core/internal/syncthing" + "github.com/omarchy-QOL/syncshell/core/internal/webprofile" +) + +func profileSession(t *testing.T) (*Session, *actionAPI) { + t.Helper() + api := &actionAPI{folders: map[string]syncthing.Folder{}, + devices: []syncthing.Device{{DeviceID: "LOCAL"}}, + pending: syncthing.PendingFolders{}, theme: "default", guiAssets: t.TempDir()} + s := newActionSession(t, api) + bundle, err := filepath.Abs("../../../webui") + if err != nil { + t.Fatal(err) + } + s.webProfile = webprofile.Policy{Authorized: true, Owner: "test", Bundle: bundle} + if _, err := s.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + return s, api +} + +func TestProfileActionVerifiesThemeAndOwnedFileOutcomes(t *testing.T) { + s, api := profileSession(t) + api.setDropThemeResponse(true) + result := s.Act(context.Background(), "webui.apply-profile", ActionArguments{Profile: "modern"}) + if !result.OK || api.currentTheme() != "syncshell-test-modern" || + s.Current().State.WebUI.Theme != "syncshell-test-modern" { + t.Fatalf("profile theme was not verified: %#v", result) + } + profile := filepath.Join(api.guiAssets, "syncshell-test-modern") + if _, err := os.Stat(filepath.Join(profile, "index.html")); err != nil { + t.Fatal(err) + } + other := filepath.Join(api.guiAssets, "another-adapter") + if err := os.Mkdir(other, 0700); err != nil { + t.Fatal(err) + } + result = s.Act(context.Background(), "webui.remove-profile", ActionArguments{}) + if !result.OK || api.currentTheme() != "default" || s.Current().State.WebUI.Theme != "default" { + t.Fatalf("profile cleanup did not verify default theme: %#v", result) + } + if _, err := os.Stat(profile); !os.IsNotExist(err) { + t.Fatalf("owned profile remains: %v", err) + } + if _, err := os.Stat(other); err != nil { + t.Fatal("another adapter's directory was changed", err) + } +} + +func TestProfileCleanupLeavesAThemeItDoesNotOwn(t *testing.T) { + s, api := profileSession(t) + result := s.Act(context.Background(), "webui.apply-profile", ActionArguments{Profile: "modern"}) + if !result.OK { + t.Fatalf("profile was not applied: %#v", result) + } + profile := filepath.Join(api.guiAssets, "syncshell-test-modern") + other := filepath.Join(api.guiAssets, "another-adapter") + if err := os.Mkdir(other, 0700); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"dark", "another-adapter"} { + api.mu.Lock() + api.theme = theme + api.mu.Unlock() + if result := s.Act(context.Background(), "webui.remove-profile", ActionArguments{}); !result.OK { + t.Fatalf("cleanup refused %s: %#v", theme, result) + } + if api.currentTheme() != theme { + t.Fatalf("cleanup changed %s to %s", theme, api.currentTheme()) + } + if _, err := os.Stat(profile); !os.IsNotExist(err) { + t.Fatalf("owned profile remains under %s: %v", theme, err) + } + if _, err := os.Stat(other); err != nil { + t.Fatal("another adapter's directory was changed", err) + } + } +} + +func TestProfileActionRejectsChangedAssetDirectory(t *testing.T) { + s, api := profileSession(t) + changed := t.TempDir() + api.mu.Lock() + api.guiAssets = changed + api.mu.Unlock() + result := s.Act(context.Background(), "webui.apply-profile", ActionArguments{Profile: "modern"}) + if result.OK || result.Error == nil || result.Error.Code != "profile_target_changed" { + t.Fatalf("changed profile destination was accepted: %#v", result) + } + entries, err := os.ReadDir(changed) + if err != nil || len(entries) != 0 { + t.Fatalf("changed destination was written: %v %v", entries, err) + } +} + +func TestProfileAuthorityRequiresLocalSelectedConfiguration(t *testing.T) { + s := &Session{} + s.current.State.Connection.Online = true + for _, setup := range []func(){ + func() {}, + func() { s.webProfile = webprofile.Policy{Authorized: true, Owner: "test", Bundle: "/bundle"} }, + func() { s.target.Local = true }, + } { + setup() + _, failure := s.profileAssets(context.Background()) + if failure == nil || failure.Error.Code != "profile_forbidden" { + t.Fatalf("unverified local profile authority: %#v", failure) + } + } +} + +func TestProfileArgumentIsolation(t *testing.T) { + if result := validateActionArguments("webui.apply-profile", ActionArguments{ + Profile: "modern", Path: t.TempDir(), + }); result == nil { + t.Fatal("caller-selected output path was accepted") + } + if result := validateActionArguments("webui.remove-profile", ActionArguments{ + Profile: "modern", + }); result == nil { + t.Fatal("cleanup accepted caller-selected profile names") + } + if result := validateActionArguments("webui.apply-profile", ActionArguments{ + Profile: "themed", Palette: map[string]string{"mode": "dark"}, + }); result == nil { + t.Fatal("incomplete semantic palette was accepted") + } +} + +func TestCleanupNeverDeletesUnmarkedDirectory(t *testing.T) { + assets := t.TempDir() + p := webprofile.Policy{Authorized: true, Owner: "test", Bundle: "/bundle"} + name, _ := p.Name("modern") + path := filepath.Join(assets, name) + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + if err := p.Remove(assets); err == nil { + t.Fatal("unmarked profile was accepted") + } + if _, err := os.Stat(path); err != nil { + t.Fatal("unmarked directory was removed") + } +} diff --git a/core/internal/session/session.go b/core/internal/session/session.go index 78fde2af..d6813bf9 100644 --- a/core/internal/session/session.go +++ b/core/internal/session/session.go @@ -10,6 +10,7 @@ import ( "github.com/omarchy-QOL/syncshell/core/internal/desktop" "github.com/omarchy-QOL/syncshell/core/internal/syncthing" "github.com/omarchy-QOL/syncshell/core/internal/systemduser" + "github.com/omarchy-QOL/syncshell/core/internal/webprofile" ) // Config constructs one authoritative session. @@ -19,6 +20,7 @@ type Config struct { SystemdCommand string ProbeInterval time.Duration DesiredServiceState string + WebProfile webprofile.Policy } type deviceTransferSample struct { @@ -48,6 +50,7 @@ type Session struct { target syncthing.Target binding systemduser.Binding lifecycle systemduser.Controller + webProfile webprofile.Policy refreshMu sync.Mutex actionMu sync.Mutex @@ -63,6 +66,11 @@ type Session struct { eventsOnce sync.Once activityMu sync.Mutex activityRecords map[string]activityRecord + finishedItems map[string]time.Time + rescansMu sync.Mutex + rescansInFlight map[string]bool + lastFile *Activity + lastFileUntil time.Time activityIndex int externalLatched bool deviceSamples map[string]deviceTransferSample @@ -93,6 +101,7 @@ func New(ctx context.Context, config Config) (*Session, error) { target: target, binding: config.Lifecycle, lifecycle: systemduser.Controller{Command: config.SystemdCommand}, + webProfile: config.WebProfile, probeInterval: interval, refreshInterval: 60 * time.Second, desiredServiceState: desired, diff --git a/core/internal/session/types.go b/core/internal/session/types.go index efcdd200..2cc6f000 100644 --- a/core/internal/session/types.go +++ b/core/internal/session/types.go @@ -209,14 +209,16 @@ type RescanResult struct { // ActionArguments is the single protocol-to-session action input shape. type ActionArguments struct { - FolderID string `json:"folderId,omitempty"` - Path string `json:"path,omitempty"` - CreateDirectory bool `json:"createDirectory,omitempty"` - Label string `json:"label,omitempty"` - DeviceIDs []string `json:"deviceIds,omitempty"` - FolderIDs []string `json:"folderIds,omitempty"` - PendingDeviceID string `json:"pendingDeviceId,omitempty"` - DeviceID string `json:"deviceId,omitempty"` - DeviceName string `json:"deviceName,omitempty"` - Theme string `json:"theme,omitempty"` + FolderID string `json:"folderId,omitempty"` + Path string `json:"path,omitempty"` + CreateDirectory bool `json:"createDirectory,omitempty"` + Label string `json:"label,omitempty"` + DeviceIDs []string `json:"deviceIds,omitempty"` + FolderIDs []string `json:"folderIds,omitempty"` + PendingDeviceID string `json:"pendingDeviceId,omitempty"` + DeviceID string `json:"deviceId,omitempty"` + DeviceName string `json:"deviceName,omitempty"` + Theme string `json:"theme,omitempty"` + Profile string `json:"profile,omitempty"` + Palette map[string]string `json:"palette,omitempty"` } diff --git a/core/internal/systemduser/systemduser.go b/core/internal/systemduser/systemduser.go index 692c26c5..8463ca2f 100644 --- a/core/internal/systemduser/systemduser.go +++ b/core/internal/systemduser/systemduser.go @@ -13,6 +13,9 @@ import ( const maxShowOutput = 64 << 10 +// Syncthing may need ten seconds to close its database during a clean stop. +const actionTimeout = 30 * time.Second + var validUnit = regexp.MustCompile(`^[A-Za-z0-9_.@:-]+[.]service$`) // Binding is host authority for one exact systemd user unit. @@ -76,7 +79,7 @@ func (c Controller) Apply(ctx context.Context, unit string, action Action) error if command == "" { command = "systemctl" } - actionContext, cancel := context.WithTimeout(ctx, 10*time.Second) + actionContext, cancel := context.WithTimeout(ctx, actionTimeout) defer cancel() output, err := exec.CommandContext(actionContext, command, "--user", string(action), unit).CombinedOutput() diff --git a/core/internal/systemduser/systemduser_test.go b/core/internal/systemduser/systemduser_test.go index 9fec56a5..e795096d 100644 --- a/core/internal/systemduser/systemduser_test.go +++ b/core/internal/systemduser/systemduser_test.go @@ -7,8 +7,42 @@ import ( "path/filepath" "strings" "testing" + "time" ) +func TestApplyHonorsCancellationDuringAServiceJob(t *testing.T) { + directory := t.TempDir() + started := filepath.Join(directory, "started") + command := filepath.Join(directory, "systemctl") + script := "#!/bin/sh\ntouch '" + started + "'\nexec sleep 60\n" + if err := os.WriteFile(command, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- (Controller{Command: command}).Apply(ctx, "syncthing.service", ActionStop) }() + deadline := time.Now().Add(2 * time.Second) + for { + if _, err := os.Stat(started); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("service command did not begin") + } + time.Sleep(time.Millisecond) + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("canceled service job reported success") + } + case <-time.After(time.Second): + t.Fatal("service job did not honor cancellation") + } +} + func TestApplyUsesExactAuthorizedUnit(t *testing.T) { directory := t.TempDir() record := filepath.Join(directory, "record") diff --git a/core/internal/webprofile/profile.go b/core/internal/webprofile/profile.go new file mode 100644 index 00000000..b62995cf --- /dev/null +++ b/core/internal/webprofile/profile.go @@ -0,0 +1,298 @@ +// Package webprofile installs owned profiles from a verified Web UI bundle. +package webprofile + +import ( + "bufio" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" +) + +const markerName = ".syncshell-profile.json" + +var ownerPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`) +var colorPattern = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) + +type Policy struct { + Authorized bool + Owner string + Bundle string +} + +type marker struct { + Owner string `json:"owner"` +} + +func (p Policy) Validate() error { + if !p.Authorized { + return errors.New("Web UI profile installation is not authorized") + } + if !ownerPattern.MatchString(p.Owner) || !filepath.IsAbs(p.Bundle) { + return errors.New("Web UI profile authority is incomplete") + } + return nil +} + +func (p Policy) Name(style string) (string, error) { + if err := p.Validate(); err != nil { + return "", err + } + if style != "modern" && style != "themed" { + return "", errors.New("unsupported Web UI profile") + } + return "syncshell-" + p.Owner + "-" + style, nil +} + +// plainPath rejects redirected ancestors before replacing or removing a profile. +func plainPath(path string, missing bool) error { + if !filepath.IsAbs(path) || filepath.Clean(path) == string(filepath.Separator) { + return errors.New("profile path must be an absolute non-root directory") + } + for current := filepath.Clean(path); current != string(filepath.Separator); current = filepath.Dir(current) { + info, err := os.Lstat(current) + if missing && errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return errors.New("profile path is unavailable") + } + if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + return errors.New("profile path contains a link or non-directory") + } + } + return nil +} + +func (p Policy) checkOwned(path string) error { + if err := plainPath(path, false); err != nil { + return err + } + info, err := os.Lstat(filepath.Join(path, markerName)) + if err != nil || !info.Mode().IsRegular() || info.Size() > 4096 { + return errors.New("refusing to change an unowned Web UI profile") + } + data, err := os.ReadFile(filepath.Join(path, markerName)) + var value marker + if err != nil || json.Unmarshal(data, &value) != nil || value.Owner != p.Owner { + return errors.New("Web UI profile belongs to another adapter") + } + return nil +} + +func readRegular(root, relative string) ([]byte, error) { + if !filepath.IsLocal(relative) || filepath.Clean(relative) != relative { + return nil, errors.New("invalid bundle path") + } + path := filepath.Join(root, relative) + if err := plainPath(filepath.Dir(path), false); err != nil { + return nil, err + } + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() > 8<<20 { + return nil, errors.New("bundle file is unavailable or invalid") + } + return os.ReadFile(path) +} + +func (p Policy) verifiedBundle() (map[string][]byte, error) { + // Plugin managers may link the package root into their installation tree. + bundle, err := filepath.EvalSymlinks(p.Bundle) + if err != nil { + return nil, errors.New("Web UI bundle is unavailable") + } + manifest, err := readRegular(bundle, "SHA256SUMS") + if err != nil { + return nil, err + } + files := make(map[string][]byte) + scanner := bufio.NewScanner(strings.NewReader(string(manifest))) + total := 0 + for scanner.Scan() { + line := scanner.Text() + if len(line) < 67 || line[64:66] != " " { + return nil, errors.New("invalid Web UI checksum manifest") + } + name := line[66:] + if _, exists := files[name]; exists { + return nil, errors.New("duplicate Web UI checksum entry") + } + content, err := readRegular(bundle, name) + if err != nil { + return nil, err + } + sum := sha256.Sum256(content) + if hex.EncodeToString(sum[:]) != line[:64] { + return nil, errors.New("Web UI bundle checksum mismatch") + } + total += len(content) + if total > 16<<20 || len(files) >= 2048 { + return nil, errors.New("Web UI bundle exceeds profile limits") + } + files[name] = content + } + if err := scanner.Err(); err != nil { + return nil, err + } + if len(files["gui/syncshell-modern/index.html"]) == 0 { + return nil, errors.New("Web UI bundle has no entrypoint") + } + return files, nil +} + +// Prepare returns a theme name only after the complete profile is in place. +func (p Policy) Prepare(assets, style string, palette map[string]string) (string, error) { + name, err := p.Name(style) + if err != nil { + return "", err + } + if err := plainPath(assets, true); err != nil { + return "", err + } + files, err := p.verifiedBundle() + if err != nil { + return "", err + } + var css string + if style == "themed" { + css, err = renderPalette(string(files["integration/omarchy-theme.css.in"]), palette) + if err != nil { + return "", err + } + } + if err := os.MkdirAll(assets, 0700); err != nil { + return "", err + } + target := filepath.Join(assets, name) + if _, err := os.Lstat(target); err == nil { + if err := p.checkOwned(target); err != nil { + return "", err + } + } else if !errors.Is(err, fs.ErrNotExist) { + return "", err + } + stage, err := os.MkdirTemp(assets, ".syncshell-profile-") + if err != nil { + return "", err + } + defer os.RemoveAll(stage) + for path, content := range files { + const prefix = "gui/syncshell-modern/" + if !strings.HasPrefix(path, prefix) { + continue + } + output := filepath.Join(stage, strings.TrimPrefix(path, prefix)) + if err := os.MkdirAll(filepath.Dir(output), 0700); err != nil { + return "", err + } + if err := os.WriteFile(output, content, 0600); err != nil { + return "", err + } + } + if style == "themed" { + generation := fmt.Sprintf("%x", sha256.Sum256([]byte(css))) + wrapper := "/* omarchy-generation: " + generation + " */\n@import \"syncshell-" + palette["mode"] + ".css\";\n" + wrapper += "@import \"omarchy_syncthing_theme.css?v=" + generation + "\";\n" + index := strings.ReplaceAll(string(files["gui/syncshell-modern/index.html"]), + `href="assets/css/theme.css"`, `href="assets/css/theme.css?v=`+generation+`"`) + index = strings.Replace(index, "", ``, 1) + outputs := map[string][]byte{ + "assets/css/theme.css": []byte(wrapper), "assets/css/omarchy_syncthing_theme.css": []byte(css), + "assets/js/omarchy_theme_refresh.js": files["integration/omarchy-theme-refresh.js"], + "index.html": []byte(index), "theme-version.txt": []byte(generation + "\n"), + } + for path, content := range outputs { + if len(content) == 0 { + return "", errors.New("profile template is missing") + } + if err := os.MkdirAll(filepath.Dir(filepath.Join(stage, path)), 0700); err != nil { + return "", err + } + if err := os.WriteFile(filepath.Join(stage, path), content, 0600); err != nil { + return "", err + } + } + } + ownership, _ := json.Marshal(marker{Owner: p.Owner}) + if err := os.WriteFile(filepath.Join(stage, markerName), ownership, 0600); err != nil { + return "", err + } + previous := stage + "-previous" + if _, err := os.Lstat(target); err == nil { + if err := os.Rename(target, previous); err != nil { + return "", err + } + } + if err := os.Rename(stage, target); err != nil { + _ = os.Rename(previous, target) + return "", err + } + if err := os.RemoveAll(previous); err != nil { + return "", err + } + return name, nil +} + +// Remove touches only fixed profile names carrying this adapter's owner marker. +func (p Policy) Remove(assets string) error { + if err := p.Validate(); err != nil { + return err + } + if err := plainPath(assets, true); err != nil { + return err + } + var owned []string + for _, style := range []string{"modern", "themed"} { + name, _ := p.Name(style) + target := filepath.Join(assets, name) + if _, err := os.Lstat(target); errors.Is(err, fs.ErrNotExist) { + continue + } + if err := p.checkOwned(target); err != nil { + return err + } + owned = append(owned, target) + } + for _, target := range owned { + if err := os.RemoveAll(target); err != nil { + return err + } + } + return nil +} + +func renderPalette(template string, palette map[string]string) (string, error) { + if template == "" || (palette["mode"] != "dark" && palette["mode"] != "light") { + return "", errors.New("profile palette or template is missing") + } + for _, key := range []string{"background", "surface", "surfaceVariant", "foreground", + "muted", "accent", "success", "warning", "danger", "border", "info"} { + if !colorPattern.MatchString(palette[key]) { + return "", errors.New("profile palette contains an invalid semantic color") + } + } + // Template names are imported Web UI internals, not host theme settings. + tokens := map[string]string{ + "palette": "portable", "mode": palette["mode"], "background": palette["background"], + "surface": palette["surface"], "surface_dark": palette["surfaceVariant"], + "foreground": palette["foreground"], "foreground_light": palette["foreground"], + "foreground_dark": palette["muted"], "accent": palette["accent"], + "muted": palette["border"], "selection": palette["surfaceVariant"], + "red": palette["danger"], "yellow": palette["warning"], "bright_yellow": palette["warning"], + "green": palette["success"], "cyan": palette["info"], "blue": palette["accent"], + "magenta": palette["accent"], "orange": palette["warning"], + } + for key, value := range tokens { + template = strings.ReplaceAll(template, "{{"+key+"}}", value) + } + if strings.Contains(template, "{{") { + return "", errors.New("profile template has unresolved tokens") + } + return template, nil +} diff --git a/core/internal/webprofile/profile_test.go b/core/internal/webprofile/profile_test.go new file mode 100644 index 00000000..6c4859b8 --- /dev/null +++ b/core/internal/webprofile/profile_test.go @@ -0,0 +1,143 @@ +package webprofile + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func policy(t *testing.T) Policy { + t.Helper() + bundle, err := filepath.Abs("../../../webui") + if err != nil { + t.Fatal(err) + } + return Policy{Authorized: true, Owner: "test-host", Bundle: bundle} +} + +func palette() map[string]string { + return map[string]string{ + "mode": "dark", "background": "#101010", "surface": "#202020", + "surfaceVariant": "#303030", "foreground": "#eeeeee", "muted": "#aaaaaa", + "accent": "#8888ff", "success": "#88ff88", "warning": "#ffff88", + "danger": "#ff8888", "border": "#444444", "info": "#88ffff", + } +} + +func TestProfilesInstallUpdateAndOwnedCleanup(t *testing.T) { + p := policy(t) + assets := filepath.Join(t.TempDir(), "gui") + for _, style := range []string{"modern", "themed"} { + name, err := p.Prepare(assets, style, palette()) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(assets, name, "index.html")); err != nil { + t.Fatal(err) + } + if style == "themed" { + css, err := os.ReadFile(filepath.Join(assets, name, "assets/css/omarchy_syncthing_theme.css")) + if err != nil || strings.Contains(string(css), "{{") || !strings.Contains(string(css), "#101010") { + t.Fatalf("palette was not rendered: %v", err) + } + updated := palette() + updated["background"] = "#121212" + if _, err := p.Prepare(assets, style, updated); err != nil { + t.Fatal(err) + } + css, _ = os.ReadFile(filepath.Join(assets, name, "assets/css/omarchy_syncthing_theme.css")) + if !strings.Contains(string(css), "#121212") { + t.Fatal("existing owned palette was not replaced") + } + } + } + other := filepath.Join(assets, "another-adapter") + if err := os.Mkdir(other, 0700); err != nil { + t.Fatal(err) + } + if err := p.Remove(assets); err != nil { + t.Fatal(err) + } + entries, _ := os.ReadDir(assets) + if len(entries) != 1 || entries[0].Name() != "another-adapter" { + t.Fatalf("cleanup changed other resources: %v", entries) + } +} + +func TestProfilesRejectForeignTargetsAndLinks(t *testing.T) { + p := policy(t) + assets := t.TempDir() + name, _ := p.Name("modern") + target := filepath.Join(assets, name) + if err := os.Mkdir(target, 0700); err != nil { + t.Fatal(err) + } + if _, err := p.Prepare(assets, "modern", nil); err == nil { + t.Fatal("unowned directory was overwritten") + } + if err := p.Remove(assets); err == nil { + t.Fatal("unowned directory was removed") + } + linkedAssets := filepath.Join(t.TempDir(), "linked") + if err := os.Symlink(assets, linkedAssets); err != nil { + t.Fatal(err) + } + if _, err := p.Prepare(linkedAssets, "modern", nil); err == nil { + t.Fatal("linked assets were accepted") + } + p.Authorized = false + if _, err := p.Prepare(assets, "modern", nil); err == nil { + t.Fatal("missing authority was accepted") + } +} + +func TestProfilesReadThroughLinkedPluginDirectory(t *testing.T) { + p := policy(t) + installed := filepath.Join(t.TempDir(), "syncshell") + if err := os.Symlink(filepath.Dir(p.Bundle), installed); err != nil { + t.Fatal(err) + } + p.Bundle = filepath.Join(installed, "webui") + assets := t.TempDir() + name, err := p.Prepare(assets, "themed", palette()) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(assets, name, "index.html")); err != nil { + t.Fatal(err) + } + if err := p.Remove(assets); err != nil { + t.Fatal(err) + } +} + +func TestProfileBundleEntriesCannotRedirectOutsidePackage(t *testing.T) { + p := policy(t) + original := p.Bundle + p.Bundle = t.TempDir() + if err := os.Symlink(filepath.Join(original, "SHA256SUMS"), + filepath.Join(p.Bundle, "SHA256SUMS")); err != nil { + t.Fatal(err) + } + if _, err := p.Prepare(t.TempDir(), "modern", nil); err == nil { + t.Fatal("linked checksum file inside the bundle was accepted") + } +} + +func TestProfilePaletteAndBundleValidation(t *testing.T) { + p := policy(t) + bad := palette() + bad["accent"] = "red; background: url(https://invalid)" + if _, err := p.Prepare(t.TempDir(), "themed", bad); err == nil { + t.Fatal("invalid semantic color was accepted") + } + p.Bundle = t.TempDir() + if err := os.WriteFile(filepath.Join(p.Bundle, "SHA256SUMS"), + []byte(strings.Repeat("0", 64)+" ../escape\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err := p.Prepare(t.TempDir(), "modern", nil); err == nil { + t.Fatal("escaping bundle path was accepted") + } +} diff --git a/docs/adr/0001-parent-bound-native-core.md b/docs/adr/0001-parent-bound-native-core.md deleted file mode 100644 index 411ec877..00000000 --- a/docs/adr/0001-parent-bound-native-core.md +++ /dev/null @@ -1,10 +0,0 @@ -# Use a parent-bound Go core over JSONL - -Each live Syncshell adapter owns one Go child process and communicates through -bounded JSONL over standard input and output. A stateless command cannot own -the Event API cursor and recovery state. A daemon and control socket would add -client brokerage that no supported adapter needs. - -The core may become a daemon only when a supported target needs simultaneous -independent rich clients, shared state or notifications across host processes, -a core that survives its host, or a host that cannot supervise a child. diff --git a/docs/adr/0002-host-adapter-ownership.md b/docs/adr/0002-host-adapter-ownership.md deleted file mode 100644 index 4eeec833..00000000 --- a/docs/adr/0002-host-adapter-ownership.md +++ /dev/null @@ -1,19 +0,0 @@ -# Keep presentation and platform behavior in host adapters - -The native core owns host-neutral Syncthing state and actions. Each host adapter -owns its native presentation, settings, package behavior, notifications, -pickers, URLs, paths, and removal flow. Root `Panel.qml` and `Service.qml` -remain the stable Omarchy entry boundary so the plugin retains its native -manifest and bar placement. Plugin updates take effect after the user's -ordinary shell restart. The current panel and service evolve together without -supporting mixed versions during the interval before restart. - -`shared/CoreProcess.qml` owns the child-process contract. -`shared/AdapterService.qml` and `shared/DeviceWorkflow.qml` provide common -state and actions for DMS, Illogical Impulse, Caelestia, and Waybar. Their -views remain host-native. Omarchy keeps its richer facade and settings because -those behaviors are specific to its plugin contract. - -Shared code stops at process, state, action, and compact workflow behavior. -Layout and shell controls remain in each adapter instead of being forced -through a generic visual abstraction. diff --git a/docs/adr/0003-omarchy-settings-boundary.md b/docs/adr/0003-omarchy-settings-boundary.md deleted file mode 100644 index 052f3538..00000000 --- a/docs/adr/0003-omarchy-settings-boundary.md +++ /dev/null @@ -1,11 +0,0 @@ -# Keep Omarchy settings outside the native core - -Omarchy remains the sole owner of its existing four-field settings file, -including parsing, watching, safe writes, editor integration, defaults, and -errors. The native core receives only validated, nonsecret operational values -that affect its session, and never receives, parses, watches, or writes the -settings path or style preferences. - -This avoids turning one host's physical file into a false cross-shell contract. -Future hosts will own their own presentation settings while sharing the native -core protocol. diff --git a/docs/omarchy-service-contract.md b/docs/omarchy-service-contract.md deleted file mode 100644 index 31260077..00000000 --- a/docs/omarchy-service-contract.md +++ /dev/null @@ -1,216 +0,0 @@ -# Omarchy service contract - -This contract describes the current Omarchy panel-to-service boundary. The -panel, native-backed facade, and member fixture evolve together within a -release; they are not a cross-version interface for retained older services. - -## Update boundary - -`manifest.json` declares one kept-loaded `service` and one `bar-widget` under -the stable plugin ID `io.github.ilyazar.syncthing`. The panel resolves the -service with `bar.shell.serviceFor(moduleName)`. - -The supported update sequence is a normal Omarchy plugin update followed by -a shell restart. Omarchy may retain an older service before that restart; -plugin usability during that interval is unsupported. After restart, the -current panel, service, helpers, and bundled core must work together while -preserving user settings, bar placement, and Syncthing data. - -The plugin does not restart the shell automatically. Old helper paths, -aliases, fallback runtimes, and mixed-version bridges are not retained. - -## Connection, identity, and models - -| Property | Type | Meaning | -| ------------------------ | ------ | -------------------------------------- | -| `phase` | string | current connection or install phase | -| `online` | bool | authenticated API state is ready | -| `refreshing` | bool | a visible refresh is open | -| `canRefresh` | bool | core can accept a status refresh | -| `statusFresh` | bool | current core state is fresh | -| `lastError` | string | sanitized connection error | -| `recoveryWarning` | string | startup or truncation warning | -| `baseUrl` | string | URL used by the Web UI action | -| `localDeviceId` | string | live local device ID | -| `displayDeviceId` | string | live or remembered device ID | -| `displayDeviceName` | string | live or remembered device name | -| `devices` | array | configured device objects | -| `folders` | array | configured folder objects | -| `pendingFolders` | object | offers by folder and device | -| `pendingDevices` | array | unknown incoming device requests | -| `nearbyDevices` | array | unknown discovered device IDs | -| `folderStatuses` | object | status keyed by folder ID | -| `syncingFiles` | array | bounded active file tokens | -| `folderCount` | int | configured folder count | -| `deviceCount` | int | configured device count | -| `connectedDeviceCount` | int | core-reported connected count | -| `folderProblemCount` | int | folders with state or pull errors | -| `syncingFolderCount` | int | folders with remaining items | -| `summaryText` | string | panel summary for the current state | - -The facade publishes connection, installation, and native-core phases. API -health is authoritative for `online`, including for a healthy external -instance with an inactive unrelated user unit. Native-core availability is -reported separately from Syncthing connection state. - -Folder objects expose at least `id`, `label`, `path`, `paused`, `markerName`, -and `devices[].deviceID`. Folder status objects expose at least `state`, -`error`, `errors`, `pullErrors`, `needTotalItems`, `needBytes`, `globalFiles`, -and `globalBytes`. Device objects expose `deviceID`, `name`, `untrusted`, and -`connected`. - -The `openWebUi()` method opens the selected GUI. Bundled profiles request the -core's `webui.open` action to grant local desktop access; the default profile -opens `baseUrl` directly. An unavailable desktop connection leaves the ordinary -Web UI accessible without local file actions. - -## Installation and lifecycle - -| Property | Type | Meaning | -| ---------------------------- | ------ | ------------------------------ | -| `installationState` | string | current installation phase | -| `installationLabel` | string | visible installation summary | -| `executablePath` | string | discovered executable | -| `canUseRuntime` | bool | core executable or API exists | -| `canInstall` | bool | install action is safe | -| `packageStatus` | string | installation progress | -| `packageError` | string | installation or status error | -| `serviceAvailable` | bool | trusted user unit is available | -| `serviceActive` | bool | observed run state | -| `serviceActionRunning` | bool | start or stop is in progress | -| `canControlService` | bool | lifecycle switch may be shown | -| `controlError` | string | lifecycle action error | -| `configuredServiceState` | string | enabled or disabled preference | -| `probeIntervalSeconds` | int | lifecycle probe interval | -| `serviceUnitFileState` | string | observed unit-file state | -| `serviceStateDrift` | bool | preference and unit differ | -| `serviceStateActionRunning` | bool | drift action is in progress | -| `serviceStateMessage` | string | drift dialog body | -| `serviceStatePrimaryLabel` | string | preferred drift action | -| `serviceStateSecondaryLabel` | string | alternate drift action | -| `serviceStateWarning` | string | unsupported observed state | - -Installation phases are `checking`, `existing`, `incomplete`, and `missing`. - -`serviceAvailable` does not itself grant authority. `canControlService` is -true only for an explicit, target-aware lifecycle binding. An API-online -external instance stays online and hides unrelated lifecycle controls. - -## Folder preparation and mutations - -| Property | Type | Meaning | -| ------------------------ | ------ | ------------------------------------ | -| `folderMutationBusy` | bool | one panel mutation is active | -| `folderMutationId` | string | affected folder or device ID | -| `folderMutationAction` | string | current panel mutation | -| `folderMutationError` | string | current mutation failure | -| `folderMutationNotice` | string | successful mutation notice | -| `recentlyLinkedFolderId` | string | recently resumed folder highlight | -| `folderPreparationBusy` | bool | ID suggestion is in progress | -| `folderPreparationError` | string | ID suggestion failure | -| `folderIdSuggestion` | string | generated ten-character folder ID | - -Mutation actions are `add`, `link`, `unlink`, `rescan`, `rescan-all`, `forget`, -`share`, `device-add`, `device-dismiss`, and `device-remove-shares`. - -Only one mutation is accepted at a time. A false method result means the -request was rejected before asynchronous work began. Forgetting removes only -the Syncthing folder record and never local data. Add requires an existing, -canonical, non-overlapping path and a unique ID. - -An accepted rescan records the stable mutation action and target ID locally -before the API request starts. Its result distinguishes a completed request -from explicitly reported folder IDs that are still scanning. The shared rescan -tracker follows only those IDs. The host keeps matching buttons inert, rotates -their refresh glyphs, and presents `RESCANNING` until success, failure, -cancellation, API loss, or core loss clears the mutation. - -## Activity and host settings - -| Property | Type | Meaning | -| ---------------------- | ------ | --------------------------------------- | -| `syncActivity` | string | complete visible activity label | -| `syncActivityDots` | string | aligned animation frame | -| `syncActivityFolderId` | string | folder owning the current file | -| `syncActivityAction` | string | `syncing`, `upload`, or `removing` | -| `syncActivityDetail` | string | bounded file detail | -| `iconStyle` | string | host preference: `branded` or `themed` | -| `settingsReady` | bool | host settings loaded and valid | -| `settingsBusy` | bool | settings, theme, or removal work active | -| `settingsError` | string | host settings or theme error | -| `settingsNotice` | string | host settings or theme success notice | - -Migration properties are `settingsMigrationOpen` (bool), `settingsCanAutoPort` -(bool), and `settingsMigrationMessage` (string). The message identifies the -actual file, explains compatibility, and previews the mapped preferences. - -`RemoteDownloadProgress` is presented as a local upload. Indexed additions and -deletions are classified from current file information. Rename and move are -not inferred. - -## Methods - -- `refresh(recheckErrors)` refreshes installation and API state. The explicit - error-recheck form rescans only active folders with reported problems before - publishing the latest Syncthing state. -- `setRefreshInterval(seconds)` clamps native reconciliation to 60-3600 - seconds. -- `toggleService()` starts or stops an authorized unit. -- `chooseServiceStateAction(index)` applies the selected drift resolution. -- `installSyncthing()` opens the host-owned Omarchy installer. -- `requestFolderIdSuggestion()` requests one new folder ID. -- `setFolderLinked(id, linked)` resumes or pauses a verified folder. -- `rescanFolder(id)` rescans one active folder. -- `rescanAllFolders()` rescans every linked folder. The core uses the global - endpoint only when no configured folder is paused. It rejects the action - when bounded state cannot expose every configured folder and directs the - user to the Web UI. -- `forgetFolder(id)` forgets one verified paused folder. -- `addFolder(path, label, id, devices, offer, createDirectory)` adds a local - directory. A missing directory emits `folderDirectoryRequired(args)` so - the panel can request confirmation. Only an explicitly confirmed retry - passes `createDirectory: true`. -- `setFolderSharing(id, devices)` replaces one folder's remote-device - membership. -- `addDevice(id, name)` configures one remote device from Syncthing's current - default device template. -- `removeDevice(id, name)` removes one device from the local configuration. -- `dismissPendingDevice(id, name)` dismisses one incoming device request. -- `removeDeviceFolderShares(id, folders, name)` removes the specified existing - folder shares from a device. -- `clearFolderMutationMessage()` clears the folder error and notice. -- `clearFolderMutationNotice()` clears the folder notice only. -- `openWebUi()` opens the selected Syncthing interface. -- `openSettings()` opens the host file or its migration dialog. -- `recheckSettings()` reloads and validates the actual file. -- `autoPortSettings()` writes a validated older-format conversion with backup. -- `manualPortSettings()` opens the user file and temporary reference template. -- `cancelSettingsMigration()` dismisses without writing; a warning remains. -- `clearSettingsNotice()` clears the host settings notice. -- `requestSelfRemoval(deleteSettings)` starts native removal, restoring the - default Web UI first when Syncthing is reachable. - -Mutation methods and drift selection return whether work was accepted. Other -methods are asynchronous fire-and-observe calls through the properties above. - -## Signals, timing, errors, and cancellation - -QML supplies change signals for every property. The panel explicitly observes -`folderIdSuggestionChanged`, `folderMutationNoticeChanged`, and -`folderMutationErrorChanged`. Their timing and meanings are part of this -contract. - -Successful folder notices remain available for about ten seconds and are also -sent through the host notification helper. The panel displays notices for ten -seconds, then fades them for 350 milliseconds. A recently linked folder is -highlighted for ten seconds. File activity cycles every 2.5 seconds. - -The panel's visible error priority is folder picker, folder mutation, package, -settings, lifecycle control, then connection. Recovery and lifecycle drift -warnings are separate from errors. - -There is no user-facing cancel action for an accepted mutation. Service -destruction, target loss, or runtime loss aborts outstanding API requests, -event polling, preparation, and mutation work. A stopped mutation clears busy -state and reports a bounded error when appropriate. Closing the add view is -blocked while its add mutation is active. diff --git a/docs/ownership.md b/docs/ownership.md deleted file mode 100644 index 1182b304..00000000 --- a/docs/ownership.md +++ /dev/null @@ -1,90 +0,0 @@ -# Syncshell ownership - -This is the ownership map for the current runtime. Omarchy presentation and -settings live in the host adapter around the native core. - -| Path | Responsibility | -| ----------------------------- | ------------------------------------------ | -| `core/` | Go native core | -| `core/internal/syncthing/` | discovery, secrets, transport, wire data | -| `core/internal/session/` | normalized state, events, retries, actions | -| `core/internal/systemduser/` | one trusted user lifecycle binding | -| `core/internal/desktop/` | browser grants and bounded file actions | -| `core/internal/protocol/` | bounded JSONL for session public types | -| `shared/CoreProcess.qml` | child process and serialization boundary | -| `shared/AdapterService.qml` | normalized adapter state and actions | -| `shared/DeviceWorkflow.qml` | shared compact device-form state | -| `shared/RescanTracker.qml` | shared confirmed-running rescan tracking | -| `hosts/omarchy/` | Omarchy facade, settings, UI, and platform | -| `hosts/standalone/` | maintained contract harness | -| `integrations/` | shell UI, registration, and installation | -| `packaging/bundled/` | reproducible x86_64 artifact tooling | -| `webui/gui/syncshell-modern/` | imported compiled browser frontend | - -The root `Panel.qml`, `Service.qml`, and `manifest.json` remain regular-file -Omarchy entry points. They are boundaries, not additional owners. - -## State and policy - -- API health is authoritative for the selected instance. -- One session owns discovery, connection, hydration, events, retry, public - state, and serialized mutations. -- Lifecycle controls require a host-authorized exact unit and a verified match - to the selected target. Unit presence or activity is not authority. -- `hosts/omarchy/` alone owns - `$XDG_CONFIG_HOME/omarchy/ilyazar.syncthing/settings.toml` and its four - fields. -- The core receives only host-neutral operational values. It never receives - the Omarchy settings path, icon style, or Web UI theme preference. -- `shared/CoreProcess.qml` knows framing and process state, not Syncthing or - systemd semantics. -- Protocol code serializes session public types directly. No repository, - service, mapper, DTO, or view-model chain may merely rename values. - -## Runtime and updates - -Omarchy presentation and settings files live in `hosts/omarchy/`. Syncthing -REST, credential, event, normalized state, mutation, and lifecycle behavior -has one implementation in the Go core rather than parallel QML implementations. -There is no mixed runtime, fallback, alias, or feature flag. - -Users restart the shell after updating to load the current panel, service, -and bundled core together. The interval before restart is unsupported. Old -helpers or runtime compatibility paths are not retained for that interval; -released implementations remain available in Git history. - -The bundled browser frontend is served by Syncthing. Its source and complete -frontend tests live in the standalone -[syncshell-webui](https://github.com/syncshell/syncshell-webui) repository; -this repository imports a pinned compiled release. Omarchy owns preparing its -runtime profiles and supplying colors to the release's template. See -[webui.md](webui.md). -An Omarchy-hosted core also provides an ephemeral loopback endpoint for -explicit local file actions. It uses the selected client, validates local -process/configuration identity and requires the exact GUI origin and private -tab grant. The endpoint exposes no general command execution, file inventory -or credential API. It closes with the core and does not add a daemon or system -service. - -The DMS, Illogical Impulse, and Caelestia adapters embed the shared service in -their native shell lifecycle. The standalone Waybar bridge owns one shared -service and publishes one status stream for every Waybar output. Popups never -start another core. - -## SyncThingy discovery - -When native configuration discovery finds nothing, the core checks -SyncThingy's two documented config locations under -`~/.var/app/com.github.zocker_160.SyncThingy/`: `config/syncthing/` and -`.local/state/syncthing/`. It reuses the config parser, configured API address -and TLS certificate validation. Multiple Flatpak configs require explicit -selection through the core's `--config` option. - -The host checks `flatpak info` only when no native binary is available, so an -installed but stopped SyncThingy is not offered a duplicate package install. -Start SyncThingy through its own launcher. Discovering it does not authorize -the default native user service, and desktop file actions keep their existing -container restrictions. No Flatpak permissions are changed. - -Configuration locations and launcher behavior are documented in -[SyncThingy's source](https://github.com/zocker-160/SyncThingy/tree/e74c695d011f9e6174d7dab5fd6c9d5ab653e7dc). diff --git a/docs/plugin-ui-cleanup.md b/docs/plugin-ui-cleanup.md deleted file mode 100644 index 9766f1b1..00000000 --- a/docs/plugin-ui-cleanup.md +++ /dev/null @@ -1,125 +0,0 @@ -# Plugin UI cleanup audit - -Scope: plugin QML/JavaScript and its test harnesses, based on `180e438`. -Web UI assets and source, Go implementation, and Go tests are excluded. - -## Decisions - -- Remove `cycleCurrentFolder`: the panel now navigates controls, and only its - old test still called this function. Test actual dropdown key events instead. -- Remove unused panel forwarding methods for device names, parent directory - names, and status help. Keep the model functions used by real consumers. -- Remove the old icon-setting forwarding chain: its two branches already yield - the same default. The settings controller is the single preference owner. -- Reuse `PanelModel.resolveFolderPath` rather than maintain a second copy. -- Share file-URL decoding in the eight-line `shared/Paths.js`. Keep packaging - explicit so assembled adapters include the helper. -- Share the encrypted-offer predicate: actionable offers and the hidden-offer - count must agree, including offers from several devices. -- Keep host-specific layouts and form state separate. Similar-looking Omarchy, - DMS, and Waybar components have different focus, lifecycle, and layout APIs. - A generic UI factory would add more complexity than it removes. -- Keep cohesive declarative panels intact despite their size. This pass removes - dead imperative code, not QML object trees solely to meet a line limit. -- Keep explicit settings migration. It is an exercised user-facing operation, - not a second runtime parser path: incompatible settings are refused until - converted. No old runtime behavior or new compatibility shim is introduced. - -## Test disposition - -The least useful static assertions counted a uniquely named root manifest and -checked individual package files. `architecture.test.sh` now validates a -staged installable tree using Omarchy's actual validator. CI already verifies -bundled checksums. No source-text assertion is counted as execution coverage. - -Keep these behavioral tests: - -- `run.qml`: model transformations, invalid settings, grouped errors, lifecycle - presentation, and rescan transitions; now included in the plugin UI runner -- dropdown and folder overview: focus, search, stable selection, keyboard - activation, filters, sorting, and reconciliation -- busy button: disabled and pending actions must not issue duplicate requests -- recovery fixtures: installation recovery, refresh serialization, protocol - failure, and loss of a core process during a rescan are different failures - (refresh recovery also exercises rescan API and process loss) -- settings, removal, and palette fixtures: user-file preservation, explicit - migration, destructive-operation boundaries, and theme refresh -- adapter scripts: execute assembly or patching, rather than merely matching - source text; they protect deployable imports and reversible configuration -- folder creation: executes extracted methods and verifies missing-directory - confirmation and immutable submission arguments; brittle extraction is a - reason to improve this later, not to discard its unique safety checks - -`plugin-acceptance.qml` remains owned by the integration harness, not a dead -standalone test. `native-core-architecture.test.sh`, live core/VM acceptance, -Web UI tests, and Go tests are outside this cleanup and remain unchanged. - -Run the local plugin suite with: - -```sh -bash tests/plugin-ui.test.sh -``` - -It requires Qt 6 tools, Quickshell, Omarchy, Node, and a desktop session. Tests -run serially because popup focus is shared. The GitHub-hosted contracts job -cannot substitute for this host-specific runtime suite. - -## Coverage evidence - -Qt 6.11.2's QML profiler and Quickshell 0.3.1 recorded the existing model and -runtime suites before and after the changes. This measures **named function -entry coverage**, not line or branch coverage. Source assertions and the Node -method-extraction fixture are not counted. The denominator includes plugin -sources in `hosts`, `shared`, and `integrations`, including adapter templates. - -| Source | Before | After | -|---------------|------------------|------------------| -| QML | 185/361 (51.25%) | 181/350 (51.71%) | -| JavaScript | 45/48 (93.75%) | 48/50 (96.00%) | -| QML templates | 0/10 (0.00%) | 0/8 (0.00%) | -| Total | 230/419 (54.89%) | 229/408 (56.13%) | - -Coverage did not fall under this metric. Four formerly hit methods were -removed or consolidated. Every retained function hit in the baseline was also -hit in the final trace. Unconfigured shell adapters are not claimed as -interactively covered. - -Profiling instruments only temporary staged fixtures to stop and flush before -process exit; normal acceptance runs use the unmodified fixtures. An initial -unflushed trace was rejected, not used to justify deletion. Raw profiler files -are development artifacts outside Git. - -## Installed-panel verification - -Deployed through Neovim's normal check/deploy/restart action, then exercised -with `computer-use-linux` on the live Omarchy panel: - -- search narrows results without changing the selected folder or total count -- keyboard activation changes both the selector and the visible folder card -- `l` opens view options; `q` closes only that innermost layer -- side-card text entry accepts `j` and `k`; Tab retains native field navigation -- the real folder chooser returns a decoded local path and derived label -- cancelling the form leaves configuration unchanged; the original selection - and collapsed panel state were restored - -No folder was added, removed, paused, or shared. Runtime logs contain no new -Syncshell error. The temporary input daemon and socket were removed afterward. - -## Remaining tooling warnings - -`Process.onExited` exposes `QProcess::ExitStatus`, which Quickshell 0.3.1's -QML tooling metadata does not resolve. Qt 6.11.2 reports the same warning for a -standalone process with no Syncshell imports, even with explicitly typed -handler parameters. Extra Qt imports do not fix it. - -This is the previously reported Quickshell issue #1218. Do not suppress all -signal-handler diagnostics or replace declarative handlers with manual signal -connections to hide it. A clean raw LSP result requires corrected upstream -metadata. The Neovim check validates staged installation files and lints 61 -Omarchy-owned QML/JS files: it exits successfully with only this warning class. -Adapters must be assembled before linting; linting their source templates in -place produces misleading missing-import diagnostics. The changed Caelestia -and Illogical Impulse service templates lint without diagnostics after -assembly. Waybar has the same three `PanelWindow`/`margins` metadata warnings -before and after this pass. DMS packaging passes, but complete static lint -requires its host modules and generated tooling VFS, unavailable here. diff --git a/docs/release-0.1.8.md b/docs/release-0.1.8.md deleted file mode 100644 index 35938281..00000000 --- a/docs/release-0.1.8.md +++ /dev/null @@ -1,26 +0,0 @@ -# 0.1.8 release notes - -- A native Go core for Syncthing monitoring and service controls. -- A Preact Web UI with grouped details, notifications and Omarchy theme support. -- Conflict review (beta), with local folder opening and guarded renaming. -- Settings migration with validation, a preview and an exact backup. -- SyncThingy Flatpak detection alongside native Syncthing installations. -- Stable folder status through zero-work Syncthing preparation transitions. -- A refined 400-pixel panel with fixed interface actions, consistent tooltips - and visible status-refresh feedback. - -## Thanks - -Thanks to [@baranskyi](https://github.com/baranskyi) for the themed bar icon -contrast and rendering improvements in -[#47](https://github.com/omarchy-QOL/syncshell/pull/47). - -Thanks also to [@whelanh](https://github.com/whelanh) for contributing -SyncThingy Flatpak detection in -[#48](https://github.com/omarchy-QOL/syncshell/pull/48). His full commit is -retained, with a separate adaptation to the Go core. SyncThingy manages its -own startup; desktop file actions remain unsupported inside Flatpak. - -Thanks to [@dawez](https://github.com/dawez) for removing transient -`sync-preparing` status flicker in -[#101](https://github.com/omarchy-QOL/syncshell/pull/101). diff --git a/docs/status-colors.md b/docs/status-colors.md new file mode 100644 index 00000000..b8951384 --- /dev/null +++ b/docs/status-colors.md @@ -0,0 +1,104 @@ +# Status colors + +Read this before choosing a color for a Syncshell state in any adapter: +Omarchy, Dux Shell (DMS), Caelestia, Illogical Impulse, Noctalia, Waybar, +the TUI or the Web UI. + +The Omarchy plugin defines what each state means. Every other adapter keeps +those meanings and only takes the color values from its own shell theme. +Do not reinterpret a state through a shell's own conventions; for example, +syncing stays a warning color even where the shell uses its accent for +progress. + +## Semantic roles + +Omarchy resolves yellow, green and cyan from the active theme with +`omarchy-theme-color --all` (`hosts/omarchy/models/ThemePaletteModel.js` +holds the fallbacks). Red is the bar's `urgent` color and muted is Omarchy's +`Color.muted`. + +| Role | Omarchy color | Meaning | +| ------- | ------------------ | ----------------------------------------- | +| success | theme green | healthy, up to date, connected, completed | +| warning | theme yellow | in motion or stopped: syncing, paused | +| error | `Color.urgent` red | failed, destructive, removing | +| info | theme cyan | synchronization activity | +| muted | `Color.muted` | unknown, disconnected, secondary text | + +## States + +The Omarchy source of each rule is named in the last column, relative to +`hosts/omarchy/`. + +| Surface | State or element | Role | Omarchy source | +| ------------------- | -------------------------------------- | ------------------------- | ------------------------------------------ | +| Folder card, list | SYNCED, LINKED | success | `OmarchyPanel.qml` `folderStateColor` | +| Folder card, list | SYNCING, SCANNING, SCAN+SYNC, UNLINKED | warning | `OmarchyPanel.qml` `folderStateColor` | +| Folder card, list | ERROR | error | `OmarchyPanel.qml` `folderStateColor` | +| Folder card, list | UNKNOWN | muted | `OmarchyPanel.qml` `folderStateColor` | +| Device card, list | CONNECTED | success | `ui/BodyTabDevices.qml` `deviceStateColor` | +| Device card, list | PAUSED | warning | `ui/BodyTabDevices.qml` `deviceStateColor` | +| Device card, list | DISCONNECTED | muted | `ui/BodyTabDevices.qml` `deviceStateColor` | +| Activity line | syncing | info | `ui/BodyTabFoldersCardActivity.qml` | +| Activity line | removing | error | `ui/BodyTabFoldersCardActivity.qml` | +| Activity line | upload | success | `ui/BodyTabFoldersCardActivity.qml` | +| More, status word | clean / errors / unavailable | success / error / muted | `ui/BodyMore.qml` | +| More, installation | existing / incomplete / missing | success / error / warning | `ui/BodyMore.qml` | +| Header notice | completed action | success | `ui/Header.qml` | +| Hints | unconfirmed shares, no nearby device | warning | sharing and device forms | +| Destructive actions | remove, forget, confirm Yes | error | `ui/SharedDialogConfirm.qml` | + +## Adapter tokens + +Each adapter maps the roles to its shell's theme tokens. Record a token here +when an adapter adopts it; mark a role "open" until the adapter decides. + +### Dux Shell (DMS) + +`hosts/dux-shell/models/PanelModel.js` (`folderStateRole`, +`deviceStateRole`, `activityRole`) returns the `Theme` property names below. +DMS defines `success`, `warning` and `info` as fixed Material colors under +the wallpaper theme; custom and stock themes can override them. + +| Role | Token | +| ------- | ------------------------ | +| success | `Theme.success` | +| warning | `Theme.warning` | +| error | `Theme.error` | +| info | `Theme.info` | +| muted | `Theme.onSurfaceVariant` | + +### Caelestia + +Caelestia's palette has `m3success` and `m3error` but no warning or info +role, and its terminal colors follow the wallpaper rather than ANSI hues. + +| Role | Token | +| ------- | ------------------------------------ | +| success | `Colours.palette.m3success` | +| warning | open | +| error | `Colours.palette.m3error` | +| info | open | +| muted | `Colours.palette.m3onSurfaceVariant` | + +### Illogical Impulse + +`Appearance.m3colors` offers `m3success` and the `colError` family; its +`term*` colors follow the wallpaper. + +| Role | Token | +| ------- | ------------------------------- | +| success | `Appearance.m3colors.m3success` | +| warning | open | +| error | `Appearance.colors.colError` | +| info | open | +| muted | `Appearance.colors.colSubtext` | + +### Noctalia, Waybar, TUI and Web UI + +- Noctalia: all roles open. +- Waybar: states are CSS classes; the user's stylesheet colors them. +- TUI: ANSI success, warning and danger roles and cyan/teal for information + (`syncshell-tui`). +- Web UI: the adapter's themed profile receives `success`, `warning`, + `danger` and `info` from the host palette. diff --git a/docs/webui.md b/docs/webui.md deleted file mode 100644 index 1bedea1a..00000000 --- a/docs/webui.md +++ /dev/null @@ -1,71 +0,0 @@ -# Bundled Web UI - -The frontend source and complete browser suite live in the standalone -[syncshell-webui](https://github.com/syncshell/syncshell-webui) repository. -This repository carries its compiled release in `webui/`, so ordinary plugin -installation needs neither Node nor a download. - -Import a release during plugin development: - -```sh -go -C core run ./cmd/import-webui --version 0.1.3 --sha256 EXPECTED_SHA256 -``` - -For a local release, additionally pass `--archive /absolute/release.tar.gz`. -The importer validates the exact archive checksum, paths, asset inventory and -integration format before atomically replacing `webui/` on Linux. It uses the -existing Go module. `webui/import.json` records the -version, source commit and archive checksum. Never edit imported assets here; -change the Web repository and import a new release. - -`hosts/omarchy/scripts/syncthing-theme.sh` installs Modern or Omarchy profiles. -The Web release owns the CSS template and browser refresh helper. The plugin -owns palette discovery, settings, launcher behavior and the Go desktop bridge. -The generator supplies `{{palette}}` alongside the resolved colors and mode. -Explicit palette files and current-theme symlinks use the resolved directory -name; copied current themes use Omarchy's `current/theme.name`. Both are -normalized to a lowercase CSS-safe token. This identity travels with the -stylesheet during palette refresh. - -Resolved colors include `{{bright_yellow}}` for palettes with a distinct native -warning alternative. Palette selection, shading, and foreground decisions stay -in the Web-owned helper; the plugin only supplies native values. - -Run the focused consumer checks with: - -```sh -npm ci --prefix tests/webui -cd tests/webui && npx playwright install chromium && cd ../.. -bash scripts/test-webui-integration.sh -``` - -These check checksum refusal, asset installation, real API access, Omarchy -palette refresh and the production desktop bridge. The full frontend suite -and historical fixtures run only in the Web repository. Tests are development -tools and are absent from the imported Web release. - -## Automated updates - -`update-webui.yml` accepts `webui-release` dispatches or manual version and -checksum inputs. It imports and tests the release, then opens an update PR -against `dev`. It does not merge or publish the plugin. - -Create the private App under `omarchy-QOL`, disable its webhook, grant it -Contents and Pull requests write permissions, and install it only on -`omarchy-QOL/syncshell`. Set `SYNCSHELL_APP_ID` as a repository variable and -`SYNCSHELL_APP_PRIVATE_KEY` as a secret in both repositories. The workflows -request one-hour installation tokens and limit them to the permissions each -job needs; the stored private key does not expire automatically. - -The receiving workflow must be on this repository's default branch before -GitHub can deliver dispatches. Before releasing, manually run `update webui` -with `verify_only` enabled. This validates the receiver's App configuration -without importing files, creating a branch or opening a pull request. The Web -repository has a matching non-release credential check. See its `RELEASES.md` -for the complete release and activation procedure. - -For an actual update, the workflow verifies the release, runs the focused -consumer checks, and creates `build-webui-X.Y.Z`. Its pull request records the -release, source commit, archive checksum and completed checks. The ordinary -pull-request workflow then runs the complete repository validation. Neither -workflow merges the pull request or publishes a plugin release. diff --git a/hosts/caelestia/CaelestiaBarEntry.qml b/hosts/caelestia/CaelestiaBarEntry.qml new file mode 100644 index 00000000..cfee0cda --- /dev/null +++ b/hosts/caelestia/CaelestiaBarEntry.qml @@ -0,0 +1,123 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import Quickshell +import Caelestia.Plugins +import Caelestia.Config +import qs.components +import qs.services +import "." +import "ui" +import "models/PanelModel.js" as Model + +// Omarchy keeps its bar button inside OmarchyPanel; Caelestia's manifest +// needs a separate bar-entry entry point next to the popout. +Item { + id: root + required property pluginEntryPoint entryPoint + required property var settings + readonly property var window: QsWindow.window + readonly property string screenName: window?.screen?.name || "" + readonly property var host: window ? ShellState.componentsFor(window.screen) : null + readonly property var popouts: host?.bar?.popouts ?? null + readonly property bool overviewOpen: !!popouts && popouts.hasCurrent && popouts.currentName === Model.overviewPopout + readonly property bool pinned: !!CaelestiaService.pinnedOverviews[screenName] + implicitWidth: Tokens.font.icon.medium.pointSize + Tokens.padding.large + implicitHeight: implicitWidth + activeFocusOnTab: true + + // The SDK opens popouts whose entry matches the bar id on hover, so the + // overview uses another name and opens only from here. + function toggle() { + var bar = host && host.bar; + if (!bar) + return; + if (overviewOpen) { + CaelestiaService.pinOverview(screenName, false); + popouts.hasCurrent = false; + return; + } + CaelestiaService.controller(screenName).update({ + anchorCenter: root.mapToItem(bar, 0, height / 2).y + }); + show(); + CaelestiaService.pinOverview(screenName, true); + } + function show() { + // While the overview is current its panel binds the center; writing it + // here would override that binding and shift the panel. + if (popouts.currentName !== Model.overviewPopout) + popouts.currentCenter = CaelestiaService.controller(screenName).view.anchorCenter; + popouts.currentName = Model.overviewPopout; + popouts.hasCurrent = true; + } + // The host closes popouts when the pointer leaves them, and hovering + // another bar icon swaps in its popout. Keep an explicitly opened overview + // until it is dismissed, returning to it when a hover popout closes. + Connections { + target: root.popouts + function onHasCurrentChanged() { + if (root.popouts.hasCurrent || !root.pinned) + return; + // The host wrapper binds focus to hasCurrent, so re-showing takes + // keyboard focus from the overview; hand it back to the same item. + const focused = root.popouts.currentName === Model.overviewPopout ? root.Window.window?.activeFocusItem : null; + root.show(); + if (focused) + focused.forceActiveFocus(); + } + } + readonly property bool svgIcon: root.settings.icon === "themed" || root.settings.icon === "branded" + readonly property string iconVariant: Model.statusVariant(CaelestiaService.adapter) + readonly property string iconRoot: CaelestiaService.adapter?.bundleRoot ?? "" + readonly property color iconColour: CaelestiaService.adapter?.online ? Colours.palette.m3primary : Colours.palette.m3onSurfaceVariant + // Legacy glyph settings keep working. + MaterialIcon { + anchors.centerIn: parent + visible: !root.svgIcon + text: root.settings.icon + color: root.iconColour + fontStyle: Tokens.font.icon.medium + } + SharedWidgetMonoIcon { + anchors.centerIn: parent + width: Tokens.font.icon.medium.pointSize * 1.4 + height: width + visible: root.settings.icon === "themed" + source: visible ? Model.statusIconUrl(root.iconRoot, root.iconVariant, true) : "" + tint: root.iconColour + } + Image { + anchors.centerIn: parent + width: Tokens.font.icon.medium.pointSize * 1.4 + height: width + visible: root.settings.icon === "branded" + source: visible ? Model.statusIconUrl(root.iconRoot, root.iconVariant, false) : "" + sourceSize.width: width + sourceSize.height: height + fillMode: Image.PreserveAspectFit + smooth: true + } + HoverHandler { + id: hover + } + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton + onClicked: root.toggle() + } + SharedWidgetToolTip { + x: root.width + root.Tokens.spacing.medium + y: (root.height - height) / 2 + visible: hover.hovered && !root.overviewOpen + text: Model.barTooltip(CaelestiaService.adapter) + } + Keys.onPressed: event => { + if ((event.key === Qt.Key_Return || event.key === Qt.Key_Space) && !event.isAutoRepeat) { + toggle(); + event.accepted = true; + } + } + Component.onCompleted: CaelestiaService.acquire(entryPoint, settings, root) + Component.onDestruction: CaelestiaService.release(root) +} diff --git a/hosts/caelestia/CaelestiaPanel.qml b/hosts/caelestia/CaelestiaPanel.qml new file mode 100644 index 00000000..527780d4 --- /dev/null +++ b/hosts/caelestia/CaelestiaPanel.qml @@ -0,0 +1,70 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import Quickshell +import Quickshell.Wayland +import Quickshell.Hyprland +import Caelestia.Config +import Caelestia.Plugins +import qs.services +import "." +import "ui" + +FocusScope { + id: root + required property pluginEntryPoint entryPoint + required property var settings + readonly property var window: QsWindow.window + readonly property var host: window ? ShellState.componentsFor(window.screen) : null + readonly property var popouts: host?.bar?.popouts + // Read-only: the bar entry creates the controller before opening, and + // creating it here mutated `views` inside this binding (binding loop). + readonly property var controller: window && CaelestiaService.adapter && CaelestiaService.hasScreen(window.screen.name) ? CaelestiaService.views[window.screen.name] ?? null : null + readonly property real hostPadding: Tokens.padding.extraLargeIncreased + readonly property bool active: !!popouts && popouts.hasCurrent && popouts.currentName === entryPoint.properties.entry + readonly property SyncshellPanelPopup content: panel.item as SyncshellPanelPopup + implicitWidth: content?.implicitWidth || 0 + implicitHeight: content?.implicitHeight || 0 + focus: true + + Binding { + target: root.window + property: "WlrLayershell.keyboardFocus" + when: root.active + value: WlrKeyboardFocus.OnDemand + restoreMode: Binding.RestoreBindingOrValue + } + Binding { + target: root.popouts + property: "currentCenter" + when: root.active && !!panel.item + value: (root.content?.geometry.center || 0) + root.host.panels.anchors.topMargin + root.hostPadding / 2 + restoreMode: Binding.RestoreBindingOrValue + } + HyprlandFocusGrab { + active: root.active + windows: root.window ? [root.window] : [] + onCleared: root.close() + } + Loader { + id: panel + anchors.fill: parent + active: !!root.controller && !!root.host + sourceComponent: SyncshellPanelPopup { + controller: root.controller + owner: CaelestiaService + availableWidth: root.host.panels.width - root.hostPadding + availableHeight: root.host.panels.height - root.hostPadding + // The bar entry owns the opening anchor; the loader completes this + // item before it has a window, so the host state is not readable yet. + anchorCenter: (root.controller.view.anchorCenter || 0) - root.host.panels.anchors.topMargin - root.hostPadding / 2 + onDismissed: root.close() + } + } + function close() { + CaelestiaService.pinOverview(window?.screen?.name || "", false); + if (popouts) + popouts.close(); + } + Component.onCompleted: CaelestiaService.attach(entryPoint, settings) +} diff --git a/hosts/caelestia/CaelestiaService.qml b/hosts/caelestia/CaelestiaService.qml new file mode 100644 index 00000000..4850fbcf --- /dev/null +++ b/hosts/caelestia/CaelestiaService.qml @@ -0,0 +1,210 @@ +pragma ComponentBehavior: Bound +pragma Singleton + +import QtQuick +import "../../shared" as Shared +import "controllers" +import "models/Ownership.js" as Ownership + +QtObject { + id: root + property var plugin: null + property var settings: null + property int ownerGeneration: -1 + property var owners: [] + property var predecessor: null + property bool retired: false + property bool awaitingExit: false + property string pendingStyle: "" + property string lastPaletteAttempt: "" + property var views: ({}) + property var pinnedOverviews: ({}) + readonly property Shared.AdapterService adapter: worker.item as Shared.AdapterService + readonly property bool eligible: plugin && plugin.enabled && !retired && plugin.generation === ownerGeneration && owners.length > 0 && preferences.valid + + function attach(entry, injectedSettings) { + if (!plugin) { + plugin = entry.plugin; + ownerGeneration = plugin.generation; + predecessor = Ownership.claim(root); + } + settings = injectedSettings; + } + function acquire(entry, injectedSettings, token) { + attach(entry, injectedSettings); + if (!owners.includes(token)) + owners = owners.concat([token]); + Qt.callLater(maybeStart); + } + function pinOverview(screenName, pinned) { + if (!!pinnedOverviews[screenName] === pinned) + return; + let next = Object.assign({}, pinnedOverviews); + if (pinned) + next[screenName] = true; + else + delete next[screenName]; + pinnedOverviews = next; + } + function hasScreen(name) { + return owners.some(owner => owner.screenName === name); + } + function release(token) { + owners = owners.filter(value => value !== token); + if (token.screenName && !hasScreen(token.screenName) && views[token.screenName]) { + let next = Object.assign({}, views); + next[token.screenName].retire(); + next[token.screenName].destroy(); + delete next[token.screenName]; + views = next; + } + if (!owners.length && adapter) + adapter.core.terminate(); + } + function retire() { + retired = true; + Object.values(views).forEach(controller => { + controller.retire(); + controller.destroy(); + }); + views = {}; + settings = null; + paletteUpdate.stop(); + if (adapter) + adapter.core.terminate(); + } + function maybeStart() { + if (!adapter || !eligible || predecessor && predecessor.adapter && predecessor.adapter.core.running) + return; + predecessor = null; + if (adapter.core.running) { + awaitingExit = !adapter.core.desiredRunning; + return; + } + awaitingExit = false; + adapter.core.start(); + } + function controller(screenName) { + if (!views[screenName]) { + let next = Object.assign({}, views); + next[screenName] = controllerComponent.createObject(root, { + service: adapter, + screenName: screenName + }); + views = next; + } + return views[screenName]; + } + function applyWebUi(style) { + if (!eligible || !adapter || adapter.busy || adapter.refreshing) + return false; + var accepted = style === "default" ? adapter.setWebUiTheme("default") : adapter.applyWebProfile(style, style === "themed" ? theme.palette : {}); + if (accepted) { + pendingStyle = style; + if (style === "themed") + lastPaletteAttempt = JSON.stringify(theme.palette); + } + return accepted; + } + property Timer paletteUpdate: Timer { + interval: 300 + onTriggered: { + if (root.eligible && root.adapter.online && !root.adapter.busy && !root.adapter.refreshing && root.adapter.webUi.theme === "syncshell-caelestia-themed" && root.lastPaletteAttempt !== JSON.stringify(root.theme.palette)) + root.applyWebUi("themed"); + } + } + property Connections paletteChanges: Connections { + target: root.theme + function onPaletteChanged() { + root.paletteUpdate.restart(); + } + } + property Connections profileResults: Connections { + target: root.adapter + function onBusyChanged() { + if (!root.adapter.busy) + root.paletteUpdate.restart(); + } + function onWebUiChanged() { + root.paletteUpdate.restart(); + } + function onActionFinished(action, ok, data, error) { + if (action !== "webui.apply-profile" && action !== "webui.set-theme" && action !== "webui.remove-profile") + return; + if (ok && root.settings) { + root.settings.webUiStyle = action === "webui.remove-profile" ? "default" : root.pendingStyle || root.settings.webUiStyle; + } + root.pendingStyle = ""; + } + } + onEligibleChanged: { + if (!eligible && adapter) + adapter.core.terminate(); + else + Qt.callLater(maybeStart); + } + property Connections previousWorker: Connections { + target: root.predecessor ? root.predecessor.adapter.core : null + function onRunningChanged() { + root.maybeStart(); + } + } + property Connections manifest: Connections { + target: root.plugin + function onGenerationChanged() { + if (root.plugin.generation !== root.ownerGeneration) + root.retire(); + } + function onSettingsChanged() { + if (!root.retired) + root.settings = root.plugin.settings; + } + } + property Connections executable: Connections { + target: root.adapter ? root.adapter.core : null + function onExecutableReadyChanged() { + root.maybeStart(); + } + function onRunningChanged() { + if (root.awaitingExit && !root.adapter.core.running) + root.maybeStart(); + } + } + property Component controllerComponent: Component { + PanelController {} + } + property SettingsController preferences: SettingsController { + settings: root.settings + } + property ThemePaletteController theme: ThemePaletteController { + } + property Loader worker: Loader { + active: !!root.plugin + onLoaded: Qt.callLater(root.maybeStart) + sourceComponent: Shared.AdapterService { + startCore: false + bundleRoot: root.plugin ? root.plugin.dir : "" + probeIntervalSeconds: root.preferences.valid ? root.settings.probeSeconds : 15 + refreshIntervalSeconds: root.preferences.valid ? root.settings.refreshSeconds : 60 + desktopAuthorized: true + profilePolicy: ({ + authorized: true, + owner: "caelestia", + bundle: bundleRoot + "/webui" + }) + lifecyclePolicy: root.preferences.valid && root.settings.lifecycleAuthorized ? { + authorized: true, + kind: "systemd-user", + unit: root.settings.lifecycleUnit, + configPath: root.settings.lifecycleConfig + } : ({}) + configPath: root.preferences.valid ? root.settings.configPath : "" + endpoint: root.preferences.valid ? root.settings.endpoint : "" + credentialFile: root.preferences.valid ? root.settings.credentialFile : "" + tlsCertificate: root.preferences.valid ? root.settings.tlsCertificate : "" + expectedDeviceId: root.preferences.valid ? root.settings.expectedDeviceId : "" + } + } + Component.onDestruction: if (adapter) + adapter.core.terminate() +} diff --git a/hosts/caelestia/README.md b/hosts/caelestia/README.md index cbe371df..f6ba45dd 100644 --- a/hosts/caelestia/README.md +++ b/hosts/caelestia/README.md @@ -1,5 +1,185 @@ -# Caelestia host +# Caelestia native plugin -An alpha native Caelestia adapter is under development in this repository. It -is not part of the supported Syncshell release and has no published -installation contract yet. +Experimental native adapter for Caelestia PR 1703 at +`4e288c54a3b039154d19fe8a2064a174eb634405`. This is a PR-only loading contract, +not a released or marketplace installation API. The matching C++ plugin and +QML shell must come from that revision. Native acceptance is pending. + +The package contains the complete panel, forms, directory picker, settings, +core, Web UI profiles and cleanup action. It does not install Syncthing or +manage a service until an exact binding is explicitly authorized in settings. + +## Build and install + +Run from the Syncshell source checkout. Go must match `core/go.mod`; Node, +Python, Bash and standard GNU file utilities are required for preparation. + +```bash +GOTOOLCHAIN=go1.23.12 bash packaging/bundled/build.sh +bash integrations/caelestia/assemble.sh "$PWD/dist/caelestia" +(cd dist/caelestia && sha256sum --check SHA256SUMS) +``` + +Assembly requires an empty output directory. Move a previous build aside +before regenerating it. Install one copy on the target Caelestia host: + +```bash +package="$PWD/dist/caelestia" +plugins="${XDG_DATA_HOME:-$HOME/.local/share}/caelestia/plugins" +mkdir -p "$plugins" +test ! -e "$plugins/syncshell" && test ! -L "$plugins/syncshell" && \ + cp -a "$package" "$plugins/syncshell" +``` + +For development, replace the final `cp` with +`ln -s "$package" "$plugins/syncshell"`. Do not install both copies: the +loader rejects duplicate `syncshell/syncshell` identities. Alternatively, +`bash install.sh --shell caelestia` assembles directly into this plugin root. +It does not rebuild, restart or patch the shell. + +## Build the pinned shell on the target host + +Install the dependencies listed in that revision's manual-installation +section, including Caelestia CLI, its required Quickshell build, Qt 6, +libqalculate, PipeWire, aubio, libcava, lm-sensors, fonts, CMake and Ninja. +Build outside the Syncshell repository; do not mix in another shell revision. + +```bash +sdk="$HOME/src/caelestia-shell-syncshell" +prefix="$HOME/.local/opt/caelestia-syncshell" +git clone https://github.com/caelestia-dots/shell.git "$sdk" +git -C "$sdk" fetch origin 4e288c54a3b039154d19fe8a2064a174eb634405 +git -C "$sdk" checkout --detach 4e288c54a3b039154d19fe8a2064a174eb634405 +cmake -S "$sdk" -B "$sdk/build" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$prefix" \ + -DVERSION=2.2.0 \ + -DGIT_REVISION=4e288c54a3b039154d19fe8a2064a174eb634405 \ + -DINSTALL_QSCONFDIR="$prefix/share/caelestia-shell" +cmake --build "$sdk/build" -j 4 +cmake --install "$sdk/build" +``` + +With Caelestia stopped, add `"syncshell/syncshell"` to the `enabled` array in +`$XDG_CONFIG_HOME/caelestia/plugins.json`, preserving its other keys and +entries. Add `{"id":"syncshell","enabled":true}` to `bar.entries` in +`$XDG_CONFIG_HOME/caelestia/shell.json`, preserving the existing bar entries. +When unset, `XDG_CONFIG_HOME` means `$HOME/.config`. For a clean test config, +the relevant files are: + +```json +{"enabled":["syncshell/syncshell"],"settings":{}} +``` + +```json +{"bar":{"entries":[{"id":"syncshell","enabled":true}]}} +``` + +Start the pinned installation in the target Hyprland session: + +```bash +QML_IMPORT_PATH="$prefix/lib/qt6/qml${QML_IMPORT_PATH:+:$QML_IMPORT_PATH}" \ +CAELESTIA_LIB_DIR="$prefix/lib/caelestia" \ + qs -p "$prefix/share/caelestia-shell" +``` + +Use disposable Syncthing peers for acceptance, selecting their configuration +in Syncshell settings. Do not repoint the owner's regular Syncthing instance. +The adapter also supports explicit endpoint, credential-file, pinned TLS +certificate and expected-device-ID settings. API keys never enter QML. + +## Use, ownership and removal + +Hovering the bar icon shows a compact status tooltip with Omarchy's wording. +Either click toggles the overview. Its popout entry deliberately differs from +the bar entry name, because the SDK's `Bar.checkPopout` opens every popout +whose entry matches a hovered bar entry. An opened overview stays until +Escape, `q`, the icon or an outside click closes it: moving the pointer away +does not close it, and a hovered host popout hands it back when it closes. +Search supports the Omarchy fuzzy matcher; +folder filters can combine states. Tab and arrow keys navigate controls. +Outside editors: `r` rescans, `w` opens Web UI, `p` links/unlinks the folder, +`s` opens settings and `q` closes. Escape dismisses the innermost menu, +confirmation, picker, form, then panel. Closing the panel retains drafts; +Cancel discards the current form. Confirmations reopen with Cancel focused. + +Each bar acquires the singleton service; popouts borrow it. The last bar +release stops the core. A stable JS ownership record retains per-screen view +state and retires the previous QML generation before its replacement starts. +Controllers are released when their last screen owner disappears. Changing JS +requires a shell restart because this loader does not reload JS. + +The host's `ShellState.componentsFor(screen)` supplies the actual bar/popout +and window references. A scoped layer-shell focus binding is restored when +the panel closes. The bar entry records the opening anchor: the loader +completes the panel before parenting it, so the panel cannot read the host +state in `Component.onCompleted`. Geometry compensates for the host's center +anchor and +padding so a taller side form does not move the main pane. This pin has a +left-side bar: the form opens rightward and stacks on narrow screens. + +Service start/stop and autostart changes require the exact authorized user +unit/configuration binding to match the selected instance. External instances +show their state and a reason control is unavailable. Missing installations +show package-manager guidance and support recovery through Refresh. + +Web UI selection is explicit. Palette changes update only the currently +selected `syncshell-caelestia-themed` profile; another adapter's selection is +left alone. Profiles use the `caelestia` ownership marker. Use Settings, +**Restore default UI and clean owned profiles**, before disabling/removing +Syncshell. Any other selected theme stays selected. + +For direct removal without a manager hook, run the same core action before +deleting the installed package (set `config` to the selected configuration): + +```bash +package="${XDG_DATA_HOME:-$HOME/.local/share}/caelestia/plugins/syncshell" +config="/absolute/path/to/syncthing/config.xml" +set -o pipefail +printf '%s\n' \ + '{"v":2,"type":"action","id":"cleanup","action":"webui.remove-profile","args":{}}' \ + | "$package/bin/syncshell-core" stream --config "$config" \ + --web-profile-authorized --web-profile-owner caelestia \ + --web-profile-bundle "$package/webui" \ + | jq -e 'select(.type == "result" and .id == "cleanup") | .ok' +``` + +Proceed only if that prints `true`. Disable `syncshell/syncshell`, remove its +bar entry, then remove the single plugin directory or link. Keep Syncthing's +configuration, files and other adapters' profiles. Plugin settings live in +Caelestia's `plugins.json`; removing the package does not remove that file. + +## Noninteractive checks + +```bash +export CAELESTIA_SDK=/absolute/path/to/the/pinned/shell +export CAELESTIA_SDK_BUILD=/tmp/syncshell-caelestia-sdk-tests +bash tests/caelestia-adapter.test.sh +go -C core test ./... +node --test tests/adapter-contract.test.mjs tests/caelestia-*.test.mjs +bash tests/native-core-architecture.test.sh +bash tests/scripts.test.sh --installation-only +bash tests/architecture.test.sh +bash tests/plugin-acceptance-lint.test.sh +``` + +The SDK test builds real pinned C++ modules for static checking and runs the +pinned manifest/module scanner against copied and linked payloads. An isolated +offscreen probe uses the actual entry-point loader to verify settings injection, +generation rebinding and stable JS state. It runs controller tests with the +payload's generated named imports, verifies all checksums, executes the native +launcher argument-rejection path and compares two builds. It does not launch a +shell or Syncthing. A full shell build still requires its audio dependencies; +the static SDK build is not a replacement shell distribution. + +The loader warns about static JS and the imported Web UI directory name +`syncshell-modern`; that asset directory contains no QML types. Qt 6.11.2's +installed Quickshell metadata also warns about `QProcess::ExitStatus` in the +existing process handlers. Neither warning establishes runtime acceptance. + +Preparation checks passed on 2026-10-07: 11 Qt behavior tests, 17 targeted Node +contracts, all Go packages, architecture/install/lint checks, both binary +rebuild checksums and the assembled-package SDK/reproducibility suite. +The full Node suite reports 27 passes and one pre-existing failure in +`tests/device-sharing.test.mjs:138`: its expected Omarchy hint text differs +from current `dev`. The same assertion fails on the untouched main checkout. +It is not a known Caelestia runtime defect. diff --git a/hosts/caelestia/controllers/PanelController.qml b/hosts/caelestia/controllers/PanelController.qml new file mode 100644 index 00000000..e0373117 --- /dev/null +++ b/hosts/caelestia/controllers/PanelController.qml @@ -0,0 +1,338 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import "../../../shared/Paths.js" as Paths +import "../models/PanelModel.js" as Model +import "../models/Ownership.js" as Ownership + +QtObject { + id: root + required property var service + required property string screenName + property var view: Model.clone(Ownership.view(screenName, Model.initialView())) + property string submittedAction: "" + property var submitted: null + property string error: view.interrupted ? "An operation was interrupted by reload. Refresh and review before retrying." : "" + property bool acceptingResults: true + property bool idSuggestionPending: false + readonly property var folder: service.folder(view.folderId) + readonly property var device: service.device(view.deviceId) + readonly property bool fresh: service.online && service.connection.fresh === true + readonly property bool busy: !acceptingResults || service.busy || service.refreshing + readonly property var folderOptions: Model.options(service.folders, "", view.filters, view.sort, fresh, folder => root.folderStatus(folder)) + readonly property var deviceOptions: Model.options(service.remoteDevices(), "", null, "name", fresh) + property string recentlyLinkedFolderId: "" + property Timer linkedFeedback: Timer { + interval: 10000 + onTriggered: root.recentlyLinkedFolderId = "" + } + function folderActivity(folder) { + return Model.folderActivity(folder, fresh, service ? service.currentActivity : null); + } + function rescanning(folder) { + if (!service || !folder || folder.paused || !service.busy) + return false; + if (service._actionName === "folder.rescan") + return service._actionTargetId === folder.id; + return service._actionName === "folder.rescan-all" && (service.scanning(folder.id) || service.scanningFolderIds().length === 0); + } + function folderStatus(folder) { + return Model.folderStatus(folder, fresh, recentlyLinkedFolderId, !!folderActivity(folder), rescanning(folder)); + } + + signal restoreFocus(string name) + + function retire() { + if (submittedAction) + update({ + interrupted: true + }); + acceptingResults = false; + } + function connectionChanged() { + if (submittedAction || view.form || view.confirmation) { + submittedAction = ""; + submitted = null; + update({ + confirmation: null, + interrupted: true + }); + error = "The connection changed or an operation was interrupted. Refresh and review your draft before retrying."; + } + idSuggestionPending = false; + recentlyLinkedFolderId = ""; + } + property Connections coreGeneration: Connections { + target: root.service ? root.service.core || null : null + function onGenerationChanged() { + if (root.acceptingResults) + root.connectionChanged(); + } + } + function update(values) { + if (!acceptingResults) + return; + view = Object.assign({}, view, values); + Ownership.save(screenName, Model.clone(view)); + } + function draft(values) { + if (Object.prototype.hasOwnProperty.call(values, "folderId")) + idSuggestionPending = false; + update({ + draft: Object.assign({}, view.draft, values) + }); + } + function reconcile() { + if (view.form === "device-folders" && !submittedAction && !view.confirmation) { + let current = service.folderIdsForDevice(view.draft.deviceId); + let original = view.draft.originalFolderIds || []; + draft({ + folderIds: current.filter(id => !original.includes(id) || view.draft.folderIds.includes(id)), + originalFolderIds: current.slice() + }); + } + update({ + folderId: Model.selectedId(service.folders, view.folderId), + deviceId: Model.selectedId(service.remoteDevices(), view.deviceId) + }); + } + function openForm(kind, target, anchor) { + if (busy || view.confirmation) + return; + if (view.form === kind) + return; + if (view.form) { + error = "Finish or cancel the current form first"; + return; + } + error = ""; + var d = { + folderId: "", + path: "", + label: "", + deviceId: "", + deviceName: "", + deviceIds: [], + folderIds: [], + pendingDeviceId: "" + }; + if (kind === "add-folder" && target) { + if (target.encrypted) { + service.openWebUi(); + return; + } + d.folderId = target.folderId; + d.label = target.label; + d.pendingDeviceId = target.deviceId; + d.deviceIds = [target.deviceId]; + } else if (kind === "share-folder" && target) { + d.folderId = target.id; + d.deviceIds = service.remoteDeviceIdsForFolder(target.id); + } else if (kind === "device-folders" && target) { + d.deviceId = target.id; + d.folderIds = service.folderIdsForDevice(target.id); + d.originalFolderIds = d.folderIds.slice(); + } else if (target) { + d.deviceId = target.id; + d.deviceName = target.name || ""; + d.address = target.address || ""; + } + update({ + form: kind, + draft: d, + formAnchor: anchor || 0 + }); + if (kind === "add-folder" && !d.folderId) + suggestFolderId(); + restoreFocus("form"); + } + function suggestFolderId() { + if (busy || submittedAction || view.confirmation || view.form !== "add-folder" || view.draft.pendingDeviceId) + return false; + error = ""; + idSuggestionPending = service.requestFolderIdSuggestion(); + if (!idSuggestionPending) + error = service.actionError || "Could not generate a folder ID"; + return idSuggestionPending; + } + function requestServiceToggle() { + if (busy || submittedAction || view.form || view.confirmation || !service.canControlService) + return; + var start = !service.lifecycle.active; + confirm(start ? "lifecycle.start" : "lifecycle.stop", {}, start ? "Start Syncthing?" : "Stop Syncthing?", "Change the running state of the verified systemd user service. Autostart is unchanged."); + } + function cancelForm() { + if (!acceptingResults || submittedAction) + return; + idSuggestionPending = false; + update({ + form: "", + draft: {}, + settingsDraft: null, + confirmation: null, + picking: false + }); + error = ""; + restoreFocus("formTrigger"); + } + function confirm(action, args, title, detail) { + if (busy || view.confirmation) + return; + update({ + confirmation: { + action: action, + args: Model.clone(args), + title: title, + detail: detail + } + }); + restoreFocus("cancel"); + } + function cancelConfirmation() { + if (!acceptingResults || submittedAction) + return; + update({ + confirmation: null + }); + reconcile(); + restoreFocus(view.form ? "form" : "main"); + } + function validTarget(action, args) { + if (["folder.pause", "folder.resume", "folder.rescan", "folder.forget", "folder.set-sharing"].includes(action) && !service.folder(args.folderId)) + return false; + if (["device.pause", "device.resume", "device.remove", "device.remove-folder-shares"].includes(action) && !service.device(args.deviceId)) + return false; + if (action === "folder.add-existing" && args.pendingDeviceId) { + return service.pendingFolderOffers().some(o => o.folderId === args.folderId && o.deviceId === args.pendingDeviceId && !o.encrypted); + } + if (action === "device.dismiss-pending" || action === "device.add" && view.form === "accept-device") + return service.pendingDevices.some(device => device.id === args.deviceId); + if (action === "folder.dismiss-pending") + return service.pendingFolderOffers().some(offer => offer.folderId === args.folderId && offer.deviceId === args.pendingDeviceId); + return true; + } + function send(action, args) { + if (busy || submittedAction) + return false; + if (!fresh && !action.startsWith("lifecycle.")) { + error = "Status is stale; refresh before changing Syncthing"; + return false; + } + if (!validTarget(action, args)) { + error = "The target or invitation changed or disappeared; refresh and review it"; + return false; + } + update({ + interrupted: false + }); + submitted = Model.clone(args); + submittedAction = action; + error = ""; + if (service.runAction(action, submitted, "Operation completed", args.folderId || args.deviceId || "")) + return true; + submittedAction = ""; + submitted = null; + return false; + } + function acceptConfirmation() { + var c = view.confirmation; + if (c) + send(c.action, c.args); + } + function submitForm() { + if (busy || submittedAction || view.confirmation || !view.form) + return; + var d = Model.clone(view.draft); + if (view.form === "add-folder") { + if (!d.path.trim() || !d.folderId.trim()) { + error = "Directory and Folder ID are required"; + return; + } + send("folder.add-existing", { + folderId: d.folderId.trim(), + path: Paths.resolveFolderPath(d.path.trim(), service.homePath), + label: d.label.trim(), + deviceIds: d.deviceIds, + pendingDeviceId: d.pendingDeviceId + }); + } else if (view.form === "share-folder") { + confirm("folder.set-sharing", { + folderId: d.folderId, + deviceIds: d.deviceIds + }, "Update folder sharing?", "Review the selected devices. Directory contents are kept."); + } else if (view.form === "device-folders") { + let removed = d.originalFolderIds.filter(id => !d.folderIds.includes(id)); + if (!removed.length) { + error = "Uncheck a folder to remove its share"; + return; + } + confirm("device.remove-folder-shares", { + deviceId: d.deviceId, + folderIds: removed + }, "Remove selected shares?", removed.map(id => service.folderLabel(id)).join("\n") + "\nFiles are kept on both devices."); + } else { + if (!d.deviceId.trim()) { + error = "Device ID is required"; + return; + } + send("device.add", { + deviceId: d.deviceId.trim(), + deviceName: d.deviceName.trim() + }); + } + } + property Connections results: Connections { + target: root.service + function onFoldersChanged() { + root.reconcile(); + } + function onDevicesChanged() { + root.reconcile(); + } + function onActionFinished(action, ok, data, failure) { + if (!root.acceptingResults) + return; + if (action === "folder.suggest-id") { + let applySuggestion = root.idSuggestionPending && root.view.form === "add-folder" && !root.view.draft.pendingDeviceId; + root.idSuggestionPending = false; + if (applySuggestion) { + if (ok && data && data.folderId) + root.draft({ + folderId: data.folderId + }); + else + root.error = failure && failure.message || "Could not generate a folder ID"; + } + return; + } + if (action !== root.submittedAction) + return; + var frozen = root.submitted; + if (ok && action === "folder.resume") { + root.recentlyLinkedFolderId = frozen.folderId; + root.linkedFeedback.restart(); + } + root.submittedAction = ""; + root.submitted = null; + if (ok) { + root.update({ + confirmation: null + }); + if (["folder.add-existing", "folder.set-sharing", "device.add", "device.remove-folder-shares"].includes(action)) + root.cancelForm(); + else + root.restoreFocus("main"); + } else if (action === "folder.add-existing" && failure && failure.code === "path_missing") { + frozen.createDirectory = true; + root.update({ + confirmation: null + }); + root.confirm(action, frozen, "Create this directory?", frozen.path); + } else { + root.error = failure && failure.message || "Operation failed"; + root.restoreFocus(root.view.confirmation ? "cancel" : "form"); + } + } + } + Component.onCompleted: reconcile() +} diff --git a/hosts/caelestia/controllers/SettingsController.qml b/hosts/caelestia/controllers/SettingsController.qml new file mode 100644 index 00000000..1026ffab --- /dev/null +++ b/hosts/caelestia/controllers/SettingsController.qml @@ -0,0 +1,41 @@ +pragma ComponentBehavior: Bound + +import QtQuick + +QtObject { + id: root + property var settings: null + readonly property string error: validate(settings) + readonly property bool valid: settings !== null && error === "" + + function validate(s) { + if (!s) + return "Plugin settings are unavailable"; + if (s.schemaVersion !== 1) + return "Incompatible Syncshell settings schema"; + if (!["themed", "branded", "sync", "cloud_sync", "folder"].includes(s.icon)) + return "Unsupported bar icon"; + if (!Number.isInteger(s.probeSeconds) || s.probeSeconds < 1 || s.probeSeconds > 3600) + return "Probe interval must be 1 to 3600 seconds"; + if (!Number.isInteger(s.refreshSeconds) || s.refreshSeconds < 60 || s.refreshSeconds > 3600) + return "Refresh interval must be 60 to 3600 seconds"; + if (!["default", "modern", "themed"].includes(s.webUiStyle)) + return "Unsupported Web UI selection"; + if (s.lifecycleAuthorized && (!/^[A-Za-z0-9_.@:-]+\.service$/.test(s.lifecycleUnit) || !s.lifecycleConfig.startsWith("/"))) + return "Service control requires an exact unit and absolute configuration path"; + return ""; + } + function values() { + var result = {}; + if (settings) + settings.keys().forEach(key => result[key] = settings[key]); + return result; + } + function save(draft) { + var failure = validate(draft); + if (failure) + return failure; + Object.keys(draft).forEach(key => settings[key] = draft[key]); + return ""; + } +} diff --git a/hosts/caelestia/controllers/ThemePaletteController.qml b/hosts/caelestia/controllers/ThemePaletteController.qml new file mode 100644 index 00000000..317f9073 --- /dev/null +++ b/hosts/caelestia/controllers/ThemePaletteController.qml @@ -0,0 +1,21 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import qs.services + +QtObject { + readonly property var palette: ({ + mode: Colours.light ? "light" : "dark", + background: String(Colours.palette.m3surface), + surface: String(Colours.palette.m3surfaceContainer), + surfaceVariant: String(Colours.palette.m3surfaceContainerHigh), + foreground: String(Colours.palette.m3onSurface), + muted: String(Colours.palette.m3onSurfaceVariant), + accent: String(Colours.palette.m3primary), + success: String(Colours.palette.m3tertiary), + warning: String(Colours.palette.m3secondary), + danger: String(Colours.palette.m3error), + border: String(Colours.palette.m3outline), + info: String(Colours.palette.m3primary) + }) +} diff --git a/hosts/caelestia/models/Ownership.js b/hosts/caelestia/models/Ownership.js new file mode 100644 index 00000000..0d40c153 --- /dev/null +++ b/hosts/caelestia/models/Ownership.js @@ -0,0 +1,18 @@ +.pragma library + +// JS URLs are stable across this loader's QML generations. +var owner = null; +var views = {}; + +function claim(service) { + var previous = owner; + if (previous === service) return null; + owner = service; + if (previous) previous.retire(); + return previous; +} +function view(key, initial) { + if (!views[key]) views[key] = initial; + return views[key]; +} +function save(key, value) { views[key] = value; } diff --git a/hosts/caelestia/models/PanelModel.js b/hosts/caelestia/models/PanelModel.js new file mode 100644 index 00000000..01002732 --- /dev/null +++ b/hosts/caelestia/models/PanelModel.js @@ -0,0 +1,186 @@ +.pragma library + +var overviewPopout = "syncshell-overview"; + +function clone(value) { return JSON.parse(JSON.stringify(value)); } +function byId(rows, id) { return (rows || []).find(row => row.id === id) || null; } +function label(row) { return String(row.label || row.name || row.path || row.id || ""); } +function bytes(value) { + var n = Math.max(0, Number(value || 0)), units = ["B", "KiB", "MiB", "GiB", "TiB"], i = 0; + while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; } + return (i ? n.toFixed(1) : String(Math.round(n))) + " " + units[i]; +} +function folderState(folder, fresh) { + if (!fresh) return "unknown"; + if (folder.paused) return "paused"; + var s = folder.status || {}; + if (s.error || s.pullErrors || (s.errors || []).length || s.state === "error") return "errors"; + if (s.needTotalItems || s.state === "syncing" || String(s.state).indexOf("scan") === 0) return "active"; + return s.state === "idle" ? "ready" : "unknown"; +} +function options(rows, search, filters, sort, fresh, presentation) { + var query = String(search || "").toLowerCase(); + return (rows || []).filter(row => { + return matchesSearch([label(row), row.path, row.id, row.address].join(" "), query) + && (filters === null || filters.includes(folderState(row, fresh))); + }).slice().sort((a, b) => { + var rank = row => sort === "name" || folderState(row, fresh) === sort ? 0 : 1; + return rank(a) - rank(b) || label(a).toLowerCase().localeCompare(label(b).toLowerCase()) + || a.id.localeCompare(b.id); + }).map(row => { + var state = filters === null ? deviceStatus(row, fresh) : presentation ? presentation(row) : folderStatus(row, fresh); + return { value: row.id, label: label(row), detail: (row.path || row.address || "") + " · " + row.id, + status: state, help: filters === null ? state : stateHelp(state), group: filters === null ? "" : folderState(row, fresh) }; + }); +} +function selectedId(rows, id) { + return byId(rows, id) ? id : rows.length ? rows[0].id : ""; +} +function initialView() { + return { tab: "folders", anchorCenter: 0, folderId: "", deviceId: "", search: "", filters: ["active", "errors", "paused", "ready", "unknown"], + sort: "name", more: false, form: "", draft: {}, confirmation: null, + formAnchor: 0, settingsDraft: null }; +} +function syncInProgress(a) { + return !!a && a.online && (a.syncingFolderCount > 0 || !!(a.currentActivity && a.currentActivity.detail) + || (a.busy && String(a._actionName).indexOf("folder.rescan") === 0)); +} +// Same precedence as Omarchy's iconVariant. +function statusVariant(a) { + if (!a || String(a.phase).indexOf("core-") === 0) return "notify"; + if (a.canControlService && a.lifecycle && a.lifecycle.active === false) return "pause"; + if (!a.online) return a.phase === "discovering" || a.phase === "loading" ? "sync" : "notify"; + if (a.folderProblemCount > 0) return "notify"; + if (a.refreshing || syncInProgress(a)) return "sync"; + return "default"; +} +function statusIconUrl(bundleRoot, variant, themed) { + return bundleRoot ? fileUrl(bundleRoot + "/assets/" + (themed ? "mono/" : "") + "status-" + variant + ".svg") : ""; +} +function barTooltip(a) { + if (!a) return "Syncthing unavailable"; + if (a.installation && a.installation.available === false) return "Syncthing: Syncthing is not installed"; + if (a.canControlService && a.lifecycle && a.lifecycle.active === false) return "Syncthing: Syncing stopped"; + if (syncInProgress(a)) return "Syncthing: Sync in progress..."; + return "Syncthing: " + a.summaryText; +} +function formatCount(value) { + var count = Math.max(0, Number(value || 0)); + if (count >= 1000000) return (count / 1000000).toFixed(1) + "m"; + if (count >= 1000) return (count / 1000).toFixed(count >= 10000 ? 0 : 1) + "k"; + return String(Math.round(count)); +} +function plural(count, noun) { return count + " " + noun + (count === 1 ? "" : "s"); } +function toggle(ids, id) { return ids.includes(id) ? ids.filter(x => x !== id) : ids.concat([id]); } + + +function remoteShare(folder, device, fresh) { + var member = (folder.devices || []).find(d => d.id === device.id); + return fresh && device.connected && !device.paused && member ? member.remoteState || "unknown" : "unknown"; +} +function remoteShareDescription(state) { + return ({ valid: "Remote share confirmed", paused: "Remote folder paused", + notSharing: "Remote is not sharing back" })[state] || "Remote acceptance unconfirmed"; +} + +// The host anchors the union's center; offset the main pane inside that union. +function geometry(mainWidth, mainHeight, formWidth, formHeight, anchor, availableWidth, availableHeight, center, padding) { + var maxHeight = Math.max(1, availableHeight - padding * 2); + var mh = Math.min(mainHeight, maxHeight), fh = Math.min(formHeight, maxHeight); + var mainTop = Math.max(0, Math.min(center - mh / 2, maxHeight - mh)); + var stacked = formWidth > 0 && mainWidth + formWidth + padding > availableWidth - padding * 2; + var formTop = Math.max(0, Math.min(mainTop + anchor, maxHeight - fh)); + var top = formWidth > 0 && !stacked ? Math.min(mainTop, formTop) : mainTop; + var height = formWidth > 0 && !stacked ? Math.max(mainTop + mh, formTop + fh) - top : mh; + if (stacked) height = Math.min(maxHeight, mh + padding + fh); + return { width: Math.min(availableWidth - padding * 2, mainWidth + (formWidth && !stacked ? formWidth + padding : 0)), + height: height, mainY: mainTop - top, formY: stacked ? mh + padding : formTop - top, + mainHeight: mh, formHeight: fh, stacked: stacked, center: top + height / 2 }; +} +function fileUrl(path) { return "file://" + String(path).split("/").map(encodeURIComponent).join("/"); } + +function matchesSearch(label, query) { + var text = String(label || "").toLowerCase(); + var needle = String(query || "").trim().toLowerCase(); + var position = 0; + for (var i = 0; i < needle.length; i++) { + position = text.indexOf(needle[i], position); + if (position < 0) return false; + position++; + } + return true; +} +function matchesOption(option, query) { + return matchesSearch([option.label, option.value, option.detail].join(" "), query); +} +function deviceStatus(device, fresh) { + if (!device) return ""; + return !fresh ? "Status unknown" : device.paused ? "Paused" : device.connected ? "Connected" : "Disconnected"; +} + +function folderStatus(folder, fresh, recentlyLinkedId, activity, rescanning) { + if (!folder || !fresh) return "UNKNOWN"; + if (folder.paused) return "UNLINKED"; + var s = folder.status || {}; + if (s.error || s.pullErrors > 0 || (s.errors || []).length || s.state === "error") return "ERROR"; + var syncing = s.needTotalItems > 0 || s.state === "syncing" || !!activity; + if (rescanning || String(s.state).indexOf("scan") === 0) + return syncing ? "SCAN+SYNC" : "SCANNING"; + if (folder.id === recentlyLinkedId) return "LINKED"; + if (syncing) return "SYNCING"; + return s.state === "idle" ? "SYNCED" : "UNKNOWN"; +} +function stateHelp(state) { + return state + " · " + ({ UNKNOWN: "Status unavailable", UNLINKED: "Syncing paused", + ERROR: "Needs attention", SCANNING: "Rescanning local files", + SYNCING: "Applying changes", "SCAN+SYNC": "Rescanning and syncing", + LINKED: "Newly linked", SYNCED: "Up to date" }[state] || "Status unavailable"); +} +function folderMeta(folder, fresh, localDeviceId, rescanning) { + if (!folder) return ""; + var s = folder.status || {}; + var pathName = String(folder.path || "").replace(/\/+$/, "").split("/").pop(); + var suffix = folder.label && folder.label !== pathName ? " · " + folder.label : ""; + if (!fresh) return "Last reported: " + (s.globalFiles || 0) + " files · " + bytes(s.globalBytes) + suffix; + if (s.error || s.pullErrors > 0 || (s.errors || []).length || s.state === "error") + return (s.error || (s.errors || [])[0]?.error || "Folder needs attention") + suffix; + if (folder.paused) return "Syncing paused" + suffix; + if (rescanning || String(s.state).indexOf("scan") === 0) return "Scanning local changes" + suffix; + if (s.needTotalItems > 0 || s.state === "syncing") + return (s.needTotalItems || 0) + " item" + (s.needTotalItems === 1 ? "" : "s") + " remaining" + + (s.needBytes > 0 ? " · " + bytes(s.needBytes) : "") + suffix; + var localOnly = !(folder.devices || []).some(d => d.id && d.id !== localDeviceId); + return (s.globalFiles || 0) + " files · " + (localOnly ? "local only" : bytes(s.globalBytes)) + suffix; +} +function folderActivity(folder, fresh, activity) { + return folder && fresh && activity && activity.folderId === folder.id && activity.detail + ? String(activity.action || "Syncing") + " " + activity.detail : ""; +} + +function totals(folders) { + return (folders || []).reduce((sum, f) => ({ + files: sum.files + Number((f.status || {}).globalFiles || 0), + bytes: sum.bytes + Number((f.status || {}).globalBytes || 0) + }), { files: 0, bytes: 0 }); +} + +function hasErrors(folder) { + var s = folder && folder.status || {}; + return !!(s.error || s.pullErrors > 0 || (s.errors || []).length || s.state === "error"); +} +function errorDetails(folder) { + if (!hasErrors(folder)) return ""; + var s = folder.status || {}, groups = Object.create(null); + var errors = s.errors || []; + errors.forEach(e => { + var reason = e.error || "Unknown error"; + if (!groups[reason]) groups[reason] = []; + if (e.path) groups[reason].push(e.path); + }); + var details = Object.keys(groups).map(reason => reason + (groups[reason].length ? "\n" + groups[reason].join("\n") : "")); + if (s.error) details.unshift(s.error); + var count = Math.max(Number(s.pullErrors || 0), errors.length); + var summary = count ? "Showing " + errors.length + " of " + count + " current error" + (count === 1 ? "" : "s") + "." : ""; + if (errors.length < count) summary += " Open Web UI for the full list."; + return (details.join("\n\n") || "Syncthing reported no error details.") + (summary ? "\n\n" + summary : ""); +} diff --git a/hosts/caelestia/ui/BodyFormHeader.qml b/hosts/caelestia/ui/BodyFormHeader.qml new file mode 100644 index 00000000..fed97b45 --- /dev/null +++ b/hosts/caelestia/ui/BodyFormHeader.qml @@ -0,0 +1,26 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import Caelestia.Config +import qs.components +import "." + +RowLayout { + id: root + property string title: "" + property bool busy: false + signal cancelled + StyledText { + Layout.fillWidth: true + text: root.title + textFormat: Text.PlainText + font: Tokens.font.title.medium + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Cancel" + disabled: root.busy + onClicked: root.cancelled() + } +} diff --git a/hosts/caelestia/ui/BodyFormSideCard.qml b/hosts/caelestia/ui/BodyFormSideCard.qml new file mode 100644 index 00000000..c26a0cb4 --- /dev/null +++ b/hosts/caelestia/ui/BodyFormSideCard.qml @@ -0,0 +1,79 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import "." + +ColumnLayout { + id: root + required property var controller + required property var owner + Loader { + active: !!root.controller.view.form + Layout.fillWidth: true + sourceComponent: root.controller.view.picking ? picker : root.controller.view.form === "settings" ? settings : root.controller.view.form === "add-folder" ? folder : root.controller.view.form === "share-folder" ? sharing : root.controller.view.form === "device-folders" ? deviceFolders : device + } + StyledText { + Layout.fillWidth: true + text: root.controller.error + textFormat: Text.PlainText + visible: !!text + wrapMode: Text.Wrap + } + Component { + id: folder + BodyTabFoldersAddForm { + controller: root.controller + onBrowseRequested: root.controller.update({ + picking: true + }) + } + } + Component { + id: sharing + BodyTabFoldersShareForm { + controller: root.controller + } + } + Component { + id: deviceFolders + BodyTabDevicesFoldersForm { + controller: root.controller + } + } + Component { + id: device + BodyTabDevicesAddForm { + controller: root.controller + } + } + Component { + id: settings + SettingsPage { + controller: root.controller + owner: root.owner + } + } + Component { + id: picker + BodyTabFoldersAddFormPicker { + initialPath: root.controller.view.draft.path || "" + onSelected: path => { + root.controller.draft({ + path: path + }); + root.controller.update({ + picking: false + }); + root.controller.restoreFocus("form"); + } + onCancelled: { + root.controller.update({ + picking: false + }); + root.controller.restoreFocus("form"); + } + } + } +} diff --git a/hosts/caelestia/ui/BodyInvitations.qml b/hosts/caelestia/ui/BodyInvitations.qml new file mode 100644 index 00000000..88cb7274 --- /dev/null +++ b/hosts/caelestia/ui/BodyInvitations.qml @@ -0,0 +1,81 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import "." + +// Caelestia lists device and folder invitations below both tabs, which share +// one toolbar, so there is no BodyTabDevices; hence this file name. +ColumnLayout { + id: root + required property var controller + signal formRequested(string kind, var target, Item trigger) + // An empty column would still add the body's spacing above More. + visible: controller.service.pendingDevices.length + controller.service.pendingFolderOffers().length > 0 + Repeater { + model: root.controller.service.pendingDevices + ColumnLayout { + id: deviceOffer + required property var modelData + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: (deviceOffer.modelData.name || deviceOffer.modelData.id) + " wants to connect" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + RowLayout { + SharedWidgetBusyButton { + id: acceptDevice + caption: "Accept" + disabled: root.controller.busy + onClicked: root.formRequested("accept-device", deviceOffer.modelData, acceptDevice) + } + SharedWidgetBusyButton { + caption: "Dismiss" + disabled: root.controller.busy + onClicked: root.controller.confirm("device.dismiss-pending", { + deviceId: deviceOffer.modelData.id + }, "Dismiss pending request from " + (deviceOffer.modelData.name || deviceOffer.modelData.id) + "?", "It can reappear if the device connects again.") + } + } + } + } + Repeater { + model: root.controller.service.pendingFolderOffers() + ColumnLayout { + id: folderOffer + required property var modelData + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: folderOffer.modelData.label + " offered by " + root.controller.service.deviceName(folderOffer.modelData.deviceId) + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + visible: folderOffer.modelData.encrypted + text: "Encrypted or untrusted shares require setup in Web UI." + wrapMode: Text.Wrap + } + RowLayout { + SharedWidgetBusyButton { + id: acceptFolder + caption: folderOffer.modelData.encrypted ? "Open Web UI" : "Accept" + disabled: root.controller.busy + onClicked: root.formRequested("add-folder", folderOffer.modelData, acceptFolder) + } + SharedWidgetBusyButton { + caption: "Dismiss" + disabled: root.controller.busy + onClicked: root.controller.confirm("folder.dismiss-pending", { + folderId: folderOffer.modelData.folderId, + pendingDeviceId: folderOffer.modelData.deviceId + }, "Dismiss folder invitation?", folderOffer.modelData.label) + } + } + } + } +} diff --git a/hosts/caelestia/ui/BodyMore.qml b/hosts/caelestia/ui/BodyMore.qml new file mode 100644 index 00000000..8623a1e9 --- /dev/null +++ b/hosts/caelestia/ui/BodyMore.qml @@ -0,0 +1,64 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Syncthing status" + value: root.controller.service.summaryText + } + StyledText { + Layout.fillWidth: true + visible: !root.controller.fresh + text: "Last reported errors; current status is unavailable" + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: "Syncthing " + (root.controller.service.identity.version || "unknown") + " · " + (root.controller.service.installation.available ? "installed" : "not found") + textFormat: Text.PlainText + elide: Text.ElideRight + } + StyledText { + Layout.fillWidth: true + visible: !root.controller.service.canControlService + text: root.controller.service.lifecycle.error || "Externally managed. Start Syncthing using its service manager, or authorize its exact unit in settings." + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + visible: !root.controller.service.installation.available + text: "Install Syncthing using your distribution's package manager, start it, then Refresh." + wrapMode: Text.Wrap + } + Repeater { + model: root.controller.service.folders.filter(f => Model.hasErrors(f)) + StyledText { + required property var modelData + Layout.fillWidth: true + text: Model.label(modelData) + "\nAffected: " + (modelData.path || modelData.id) + "\n" + Model.errorDetails(modelData) + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + } + StyledText { + Layout.fillWidth: true + text: Object.values(root.controller.service.truncation).some(n => n > 0) ? "Some entries are omitted by the core's display limits. Inspect the full list in Web UI." : "" + visible: !!text + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Recheck errors" + busy: root.controller.busy + disabled: busy || !root.controller.fresh + onClicked: root.controller.service.recheckErrors() + } +} diff --git a/hosts/caelestia/ui/BodyTabDevicesAddForm.qml b/hosts/caelestia/ui/BodyTabDevicesAddForm.qml new file mode 100644 index 00000000..caf6f098 --- /dev/null +++ b/hosts/caelestia/ui/BodyTabDevicesAddForm.qml @@ -0,0 +1,79 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.components.controls +import "." + +ColumnLayout { + id: root + required property var controller + BodyFormHeader { + Layout.fillWidth: true + title: root.controller.view.form === "accept-device" ? "Accept device" : "Add device" + busy: root.controller.busy + onCancelled: root.controller.cancelForm() + } + SharedWidgetDropdown { + Layout.fillWidth: true + visible: root.controller.view.form !== "accept-device" + placeholder: "Nearby devices" + options: root.controller.service.nearbyDevices.map(d => ({ + value: d.id, + label: d.name || d.id, + detail: [d.id, (d.addresses || []).join(", ")].filter(Boolean).join(" · ") + })) + onChosen: id => root.controller.draft({ + deviceId: id + }) + } + StyledTextField { + Layout.fillWidth: true + objectName: root.controller.view.form === "accept-device" ? "syncshellInitialFocus" : "" + placeholderText: "Device name" + text: root.controller.view.draft.deviceName || "" + readOnly: root.controller.busy + onTextEdited: root.controller.draft({ + deviceName: text + }) + } + StyledText { + Layout.fillWidth: true + visible: root.controller.view.form === "accept-device" + text: "Observed address: " + (root.controller.view.draft.address || "unknown") + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledTextField { + Layout.fillWidth: true + objectName: root.controller.view.form === "accept-device" ? "" : "syncshellInitialFocus" + placeholderText: "Device ID" + text: root.controller.view.draft.deviceId || "" + readOnly: root.controller.busy || root.controller.view.form === "accept-device" + onTextEdited: root.controller.draft({ + deviceId: text + }) + } + SharedWidgetBusyButton { + caption: "Copy ID" + copyValue: root.controller.view.draft.deviceId || "" + disabled: !copyValue + } + StyledText { + Layout.fillWidth: true + visible: root.controller.view.form !== "accept-device" && !root.controller.service.nearbyDevices.length + text: "No nearby devices found. Paste a Device ID to add one manually." + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: "Add this device on the other device too, then select folders to share." + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Add device" + busy: root.controller.busy + onClicked: root.controller.submitForm() + } +} diff --git a/hosts/caelestia/ui/BodyTabDevicesCard.qml b/hosts/caelestia/ui/BodyTabDevicesCard.qml new file mode 100644 index 00000000..efaf6f1a --- /dev/null +++ b/hosts/caelestia/ui/BodyTabDevicesCard.qml @@ -0,0 +1,66 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + readonly property var device: controller.device + RowLayout { + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: root.device ? Model.label(root.device) : "No remote devices" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + SharedWidgetIdCopyButton { + visible: !!root.device + value: root.device ? root.device.id : "" + caption: "device ID" + help: "Copy device ID" + } + } + StyledText { + Layout.fillWidth: true + text: Model.deviceStatus(root.device, root.controller.fresh) + } + StyledText { + Layout.fillWidth: true + text: root.device?.address || "" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: root.controller.fresh ? "Download " + Model.bytes(root.device?.downloadBps) + "/s · Upload " + Model.bytes(root.device?.uploadBps) + "/s" : "Transfer rates unknown" + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: root.device ? Model.plural(root.controller.service.folderIdsForDevice(root.device.id).length, "shared folder") : "No folders shared" + wrapMode: Text.Wrap + } + Flow { + Layout.fillWidth: true + spacing: 6 + SharedWidgetBusyButton { + caption: root.device?.paused ? "Resume" : "Pause" + disabled: !root.device || !root.controller.fresh || root.controller.busy + onClicked: root.controller.send(root.device.paused ? "device.resume" : "device.pause", { + deviceId: root.device.id + }) + } + SharedWidgetBusyButton { + caption: "Remove" + disabled: !root.device || !root.controller.fresh || root.controller.busy + onClicked: root.controller.confirm("device.remove", { + deviceId: root.device.id + }, "Remove " + Model.label(root.device) + " from this device?", "Folder sharing with it will be removed locally. Local folders and files remain. The other device is unchanged.") + } + } +} diff --git a/hosts/caelestia/ui/BodyTabDevicesFoldersForm.qml b/hosts/caelestia/ui/BodyTabDevicesFoldersForm.qml new file mode 100644 index 00000000..312e7028 --- /dev/null +++ b/hosts/caelestia/ui/BodyTabDevicesFoldersForm.qml @@ -0,0 +1,79 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.services +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + readonly property var device: controller.service.device(controller.view.draft.deviceId) + readonly property var shares: controller.service.folders.filter(f => (f.devices || []).some(d => d.id === controller.view.draft.deviceId)) + function options(confirmed) { + return shares.filter(f => ["valid", "paused"].includes(Model.remoteShare(f, device || {}, controller.fresh)) === confirmed).map(f => ({ + value: f.id, + label: Model.label(f), + detail: [f.path, f.id, Model.remoteShareDescription(Model.remoteShare(f, device || {}, controller.fresh))].filter(Boolean).join(" · ") + })); + } + BodyFormHeader { + Layout.fillWidth: true + title: "Device folders" + busy: root.controller.busy + onCancelled: root.controller.cancelForm() + } + StyledText { + Layout.fillWidth: true + text: root.device ? root.device.name || root.device.id : "Device is no longer configured" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledText { + text: "Existing shares" + } + SharedWidgetDropdown { + Layout.fillWidth: true + multiple: true + options: root.options(true) + selectedIds: (root.controller.view.draft.folderIds || []).filter(id => options.some(o => o.value === id)) + disabled: root.controller.busy || !!root.controller.view.confirmation + onToggled: id => root.controller.draft({ + folderIds: Model.toggle(root.controller.view.draft.folderIds, id) + }) + } + RowLayout { + StyledText { + text: "Unconfirmed shares" + } + StyledText { + Layout.fillWidth: true + text: "(acceptance pending/device offline)" + color: Colours.palette.m3secondary + elide: Text.ElideRight + visible: root.options(false).length > 0 + } + } + SharedWidgetDropdown { + Layout.fillWidth: true + multiple: true + options: root.options(false) + selectedIds: (root.controller.view.draft.folderIds || []).filter(id => options.some(o => o.value === id)) + disabled: root.controller.busy || !!root.controller.view.confirmation + onToggled: id => root.controller.draft({ + folderIds: Model.toggle(root.controller.view.draft.folderIds, id) + }) + } + StyledText { + Layout.fillWidth: true + text: "Uncheck shares to remove. Files remain on both devices. Use Share folder to restore a share." + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Review removals" + busy: root.controller.busy + onClicked: root.controller.submitForm() + } +} diff --git a/hosts/caelestia/ui/BodyTabFoldersAddForm.qml b/hosts/caelestia/ui/BodyTabFoldersAddForm.qml new file mode 100644 index 00000000..383973ea --- /dev/null +++ b/hosts/caelestia/ui/BodyTabFoldersAddForm.qml @@ -0,0 +1,90 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.components.controls +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + signal browseRequested + BodyFormHeader { + Layout.fillWidth: true + title: root.controller.view.draft.pendingDeviceId ? "Accept folder" : "Add folder" + busy: root.controller.busy + onCancelled: root.controller.cancelForm() + } + StyledTextField { + objectName: "syncshellInitialFocus" + Layout.fillWidth: true + placeholderText: "Directory" + text: root.controller.view.draft.path || "" + readOnly: root.controller.busy || !!root.controller.view.confirmation + onTextEdited: root.controller.draft({ + path: text + }) + } + SharedWidgetBusyButton { + caption: "Browse directories" + disabled: root.controller.busy + onClicked: root.browseRequested() + } + StyledTextField { + Layout.fillWidth: true + placeholderText: "Label" + text: root.controller.view.draft.label || "" + readOnly: root.controller.busy || !!root.controller.view.confirmation + onTextEdited: root.controller.draft({ + label: text + }) + } + StyledTextField { + Layout.fillWidth: true + placeholderText: "Folder ID" + text: root.controller.view.draft.folderId || "" + readOnly: root.controller.busy || !!root.controller.view.draft.pendingDeviceId || !!root.controller.view.confirmation + onTextEdited: root.controller.draft({ + folderId: text + }) + } + SharedWidgetBusyButton { + caption: "Generate ID" + disabled: root.controller.busy || !!root.controller.view.confirmation || !!root.controller.view.draft.pendingDeviceId + onClicked: root.controller.suggestFolderId() + } + StyledText { + Layout.fillWidth: true + text: "Reuse the exact ID to join an existing folder. A new ID creates a different folder identity." + wrapMode: Text.Wrap + } + StyledText { + text: "Share with selected devices" + } + SharedWidgetDropdown { + Layout.fillWidth: true + multiple: true + disabled: root.controller.busy || !!root.controller.view.confirmation + options: root.controller.service.shareableDevices().map(d => ({ + value: d.id, + label: d.name || d.id, + detail: d.id + })) + selectedIds: root.controller.view.draft.deviceIds || [] + onToggled: id => root.controller.draft({ + deviceIds: Model.toggle(selectedIds, id) + }) + } + StyledText { + Layout.fillWidth: true + text: (!(root.controller.view.draft.deviceIds || []).length ? "Local only: not shared with other devices. " : "Only the selected devices will share this folder. ") + "Existing files are kept. Missing directories require confirmation." + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Add folder" + busy: root.controller.busy + onClicked: root.controller.submitForm() + } +} diff --git a/hosts/caelestia/ui/BodyTabFoldersAddFormPicker.qml b/hosts/caelestia/ui/BodyTabFoldersAddFormPicker.qml new file mode 100644 index 00000000..441bb665 --- /dev/null +++ b/hosts/caelestia/ui/BodyTabFoldersAddFormPicker.qml @@ -0,0 +1,89 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC +import Qt.labs.folderlistmodel +import Quickshell +import Caelestia.Config +import qs.components +import qs.components.controls +import qs.components.containers +import "." +import "../models/PanelModel.js" as Model +import "../../../shared/Paths.js" as Paths + +ColumnLayout { + id: root + property string initialPath: "" + property string directory: Paths.resolveFolderPath(initialPath || "~", Quickshell.env("HOME")) || "/" + signal selected(string path) + signal cancelled + spacing: Tokens.spacing.medium + StyledText { + Layout.fillWidth: true + text: "Choose a directory" + wrapMode: Text.Wrap + } + StyledTextField { + id: path + Layout.fillWidth: true + text: root.directory + placeholderText: "Absolute directory path" + onAccepted: root.directory = Paths.resolveFolderPath(text, Quickshell.env("HOME")) + } + RowLayout { + SharedWidgetBusyButton { + caption: "Up" + onClicked: root.directory = root.directory.replace(/\/+$/, "").replace(/\/[^/]*$/, "") || "/" + } + SharedWidgetBusyButton { + caption: "Go" + onClicked: root.directory = Paths.resolveFolderPath(path.text, Quickshell.env("HOME")) + } + } + FolderListModel { + id: directories + folder: Model.fileUrl(root.directory) + showFiles: false + showDirs: true + showDotAndDotDot: false + showHidden: true + } + StyledListView { + id: list + Layout.fillWidth: true + implicitHeight: 230 + clip: true + model: directories + spacing: Tokens.spacing.small + QQC.ScrollBar.vertical: StyledScrollBar { + flickable: list + } + delegate: SharedWidgetBusyButton { + required property string fileName + required property string filePath + width: ListView.view.width + caption: fileName + onClicked: root.directory = filePath + } + } + StyledText { + Layout.fillWidth: true + text: "Only directories are listed. Use Go to load a typed path." + wrapMode: Text.Wrap + } + RowLayout { + SharedWidgetBusyButton { + caption: "Cancel" + onClicked: root.cancelled() + } + SharedWidgetBusyButton { + caption: "Choose" + disabled: directories.status !== FolderListModel.Ready + onClicked: root.selected(root.directory) + } + } + Keys.onEscapePressed: root.cancelled() + Component.onCompleted: path.forceActiveFocus() +} diff --git a/hosts/caelestia/ui/BodyTabFoldersCard.qml b/hosts/caelestia/ui/BodyTabFoldersCard.qml new file mode 100644 index 00000000..72afd484 --- /dev/null +++ b/hosts/caelestia/ui/BodyTabFoldersCard.qml @@ -0,0 +1,102 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.services +import "." +import "../models/PanelModel.js" as Model +import "../../../shared/Paths.js" as Paths + +ColumnLayout { + id: root + required property var controller + readonly property var folder: controller.folder + RowLayout { + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: root.folder ? Model.label(root.folder) : "No folder selected" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + SharedWidgetIdCopyButton { + visible: !!root.folder + value: root.folder ? root.folder.id : "" + caption: "folder ID" + help: "Copy folder ID" + } + } + StyledText { + Layout.fillWidth: true + text: root.folder?.path || "" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: root.folder ? root.controller.folderStatus(root.folder) : "" + color: text === "ERROR" ? Colours.palette.m3error : text === "UNKNOWN" || text === "UNLINKED" ? Colours.palette.m3onSurfaceVariant : Colours.palette.m3primary + } + StyledText { + Layout.fillWidth: true + visible: !!root.folder + text: Model.folderMeta(root.folder, root.controller.fresh, root.controller.service.localDeviceId, root.controller.rescanning(root.folder)) + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + Flow { + Layout.fillWidth: true + spacing: 6 + SharedWidgetBusyButton { + caption: "Open" + disabled: !root.folder + onClicked: Qt.openUrlExternally(Model.fileUrl(Paths.resolveFolderPath(root.folder.path, root.controller.service.homePath))) + } + SharedWidgetBusyButton { + caption: "Rescan" + busyCaption: "Rescanning..." + busy: root.controller.rescanning(root.folder) + help: !root.controller.fresh ? "Refresh current status before rescanning" : root.folder?.paused ? "Link this folder before rescanning" : "Rescan local changes" + disabled: !root.folder || !!root.folder.paused || !root.controller.fresh || root.controller.busy + onClicked: root.controller.service.rescanFolder(root.folder.id) + } + SharedWidgetBusyButton { + caption: "Forget" + disabled: !root.folder || !root.controller.fresh || root.controller.busy + onClicked: root.controller.confirm("folder.forget", { + folderId: root.folder.id + }, "Forget " + Model.label(root.folder) + " (" + root.folder.id + ")?", "This removes only its Syncthing configuration. The directory and data files will not be deleted. " + (root.folder.markerName === ".stfolder" ? "Syncthing will also attempt to remove its internal .stfolder marker. " : "") + "Rejoining the same remote folder requires this exact Folder ID.") + } + } + StyledText { + Layout.fillWidth: true + text: Model.errorDetails(root.folder) + textFormat: Text.PlainText + visible: !!text + wrapMode: Text.Wrap + } + StyledText { + id: activityLabel + animate: true + SharedWidgetToolTip { + text: activityLabel.text + visible: activityHover.hovered && !!text + } + HoverHandler { + id: activityHover + } + Layout.fillWidth: true + Layout.minimumHeight: activityMetrics.height + FontMetrics { + id: activityMetrics + font: activityLabel.font + } + text: root.controller.folderActivity(root.folder) + textFormat: Text.PlainText + visible: !!root.folder + elide: Text.ElideMiddle + maximumLineCount: 1 + color: Colours.palette.m3primary + } +} diff --git a/hosts/caelestia/ui/BodyTabFoldersShareForm.qml b/hosts/caelestia/ui/BodyTabFoldersShareForm.qml new file mode 100644 index 00000000..602f45ee --- /dev/null +++ b/hosts/caelestia/ui/BodyTabFoldersShareForm.qml @@ -0,0 +1,48 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + BodyFormHeader { + Layout.fillWidth: true + title: "Folder sharing" + busy: root.controller.busy + onCancelled: root.controller.cancelForm() + } + StyledText { + Layout.fillWidth: true + text: root.controller.service.folderLabel(root.controller.view.draft.folderId) + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + SharedWidgetDropdown { + Layout.fillWidth: true + multiple: true + disabled: root.controller.busy || !!root.controller.view.confirmation + options: root.controller.service.shareableDevices().map(d => ({ + value: d.id, + label: d.name || d.id, + detail: d.id + })) + selectedIds: root.controller.view.draft.deviceIds || [] + onToggled: id => root.controller.draft({ + deviceIds: Model.toggle(selectedIds, id) + }) + } + StyledText { + Layout.fillWidth: true + text: "New devices receive a share offer. Unchecked devices lose this share; their files are kept. Encrypted sharing is managed in Web UI." + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Review sharing" + busy: root.controller.busy + onClicked: root.controller.submitForm() + } +} diff --git a/hosts/caelestia/ui/BodyTabFoldersViewOptions.qml b/hosts/caelestia/ui/BodyTabFoldersViewOptions.qml new file mode 100644 index 00000000..c5d50754 --- /dev/null +++ b/hosts/caelestia/ui/BodyTabFoldersViewOptions.qml @@ -0,0 +1,96 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.components.controls +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + readonly property var groups: ["ready", "active", "errors", "paused", "unknown"] + readonly property var selected: controller ? controller.view.filters : [] + readonly property int count: groups.filter(g => selected.includes(g)).length + GridLayout { + Layout.fillWidth: true + columns: 2 + Repeater { + model: [ + { + value: "all", + label: root.count > 0 && root.count < root.groups.length ? "All (mixed)" : "All" + }, + { + value: "ready", + label: "Ready" + }, + { + value: "active", + label: "Active" + }, + { + value: "errors", + label: "Errors" + }, + { + value: "paused", + label: "Paused" + }, + { + value: "unknown", + label: "Unknown" + } + ] + SharedWidgetBusyButton { + required property var modelData + Layout.fillWidth: true + caption: modelData.label + isToggle: true + type: TextButton.Tonal + checked: modelData.value === "all" ? root.count === root.groups.length : root.selected.includes(modelData.value) + onClicked: root.controller.update({ + filters: modelData.value === "all" ? (root.count === root.groups.length ? [] : root.groups.slice()) : Model.toggle(root.selected, modelData.value) + }) + } + } + } + StyledText { + text: "Sort folders" + } + Repeater { + model: [ + { + value: "name", + label: "Name" + }, + { + value: "active", + label: "Active first" + }, + { + value: "errors", + label: "Errors first" + } + ] + SharedWidgetBusyButton { + required property var modelData + Layout.fillWidth: true + caption: modelData.label + isToggle: true + type: TextButton.Tonal + checked: !!root.controller && root.controller.view.sort === modelData.value + onClicked: root.controller.update({ + sort: modelData.value + }) + } + } + SharedWidgetBusyButton { + caption: "Reset" + onClicked: root.controller.update({ + filters: root.groups.slice(), + sort: "name" + }) + } +} diff --git a/hosts/caelestia/ui/FooterActions.qml b/hosts/caelestia/ui/FooterActions.qml new file mode 100644 index 00000000..a64a055b --- /dev/null +++ b/hosts/caelestia/ui/FooterActions.qml @@ -0,0 +1,45 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import "." + +ColumnLayout { + id: root + required property var controller + readonly property Item settingsTrigger: settingsButton + signal settingsRequested(Item trigger) + SharedWidgetBusyButton { + caption: "Web UI" + help: "Open the Syncthing Web UI" + disabled: !root.controller.service.online || root.controller.busy + onClicked: root.controller.service.openWebUi() + } + RowLayout { + Layout.fillWidth: true + SharedWidgetBusyButton { + caption: "Rescan all" + busyCaption: "Rescanning..." + busy: root.controller.service.busy && root.controller.service._actionName === "folder.rescan-all" + help: !root.controller.fresh ? "Refresh current status before rescanning" : "Rescan every linked folder" + disabled: !root.controller.fresh || root.controller.busy || !root.controller.service.folders.some(f => !f.paused) + onClicked: root.controller.service.rescanAllFolders() + } + SharedWidgetBusyButton { + caption: "Refresh" + busy: root.controller.service.refreshing + disabled: root.controller.service.busy + onClicked: root.controller.service.refresh() + } + Item { + Layout.fillWidth: true + } + SharedWidgetSquareActionButton { + id: settingsButton + icon: "settings" + help: "Settings" + disabled: root.controller.busy + onClicked: root.settingsRequested(settingsButton) + } + } +} diff --git a/hosts/caelestia/ui/FooterShortcutHint.qml b/hosts/caelestia/ui/FooterShortcutHint.qml new file mode 100644 index 00000000..0a77c8b5 --- /dev/null +++ b/hosts/caelestia/ui/FooterShortcutHint.qml @@ -0,0 +1,8 @@ +import QtQuick +import Caelestia.Config +import qs.components + +StyledText { + text: "r rescan · w web · p pause · s settings · q close" + font: Tokens.font.label.small +} diff --git a/hosts/caelestia/ui/Header.qml b/hosts/caelestia/ui/Header.qml new file mode 100644 index 00000000..c45884f7 --- /dev/null +++ b/hosts/caelestia/ui/Header.qml @@ -0,0 +1,94 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import Caelestia.Config +import qs.components +import qs.components.controls +import qs.services +import "." +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + property bool brandedIcon: false + readonly property var service: controller.service + readonly property var totals: Model.totals(service.folders) + readonly property string iconVariant: Model.statusVariant(service) + RowLayout { + spacing: Tokens.spacing.medium + Item { + implicitWidth: Tokens.font.icon.large.pointSize * 2 + implicitHeight: implicitWidth + opacity: root.iconVariant === "pause" || !root.service.online ? 0.5 : 1 + SharedWidgetMonoIcon { + anchors.fill: parent + visible: !root.brandedIcon + source: Model.statusIconUrl(root.service.bundleRoot, root.iconVariant, true) + tint: Colours.palette.m3onSurface + } + Image { + anchors.fill: parent + visible: root.brandedIcon + source: root.brandedIcon ? Model.statusIconUrl(root.service.bundleRoot, root.iconVariant, false) : "" + sourceSize.width: width + sourceSize.height: height + fillMode: Image.PreserveAspectFit + smooth: true + } + } + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + StyledText { + Layout.fillWidth: true + text: "Syncthing" + font: Tokens.font.title.medium + } + RowLayout { + Layout.fillWidth: true + spacing: Tokens.spacing.small + StyledText { + Layout.preferredWidth: implicitWidth + Layout.minimumWidth: 0 + text: root.service.device(root.service.localDeviceId)?.name || "This device" + textFormat: Text.PlainText + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.label.medium + elide: Text.ElideRight + } + SharedWidgetIdCopyButton { + value: root.service.localDeviceId + caption: "device ID" + help: "Copy device ID" + } + } + } + // Omarchy hides the toggle when this host may not control the service. + StyledSwitch { + visible: root.service.canControlService + checked: root.service.lifecycle.active === true + disabled: root.controller.busy || !!root.controller.view.form || !!root.controller.view.confirmation + onToggled: { + root.controller.requestServiceToggle(); + checked = Qt.binding(() => root.service.lifecycle.active === true); + } + } + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Folders" + value: String(root.service.folderCount) + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Devices" + value: root.service.connectedDeviceCount + " of " + root.service.deviceCount + " connected" + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Tracked" + value: Model.formatCount(root.totals.files) + " files · " + Model.bytes(root.totals.bytes) + } +} diff --git a/hosts/caelestia/ui/SettingsPage.qml b/hosts/caelestia/ui/SettingsPage.qml new file mode 100644 index 00000000..d3157301 --- /dev/null +++ b/hosts/caelestia/ui/SettingsPage.qml @@ -0,0 +1,184 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.components.controls +import "." +import "../models/PanelModel.js" as Model + +// Caelestia opens settings as a side-card form, not as Omarchy's in-panel +// SettingsMenu; hence the different file name. +ColumnLayout { + id: root + required property var owner + required property var controller + property string error: "" + readonly property var draft: controller.view.settingsDraft || ({}) + function setValue(key, value) { + var next = Object.assign({}, draft); + next[key] = value; + controller.update({ + settingsDraft: next + }); + } + BodyFormHeader { + Layout.fillWidth: true + title: "Syncshell settings" + busy: root.controller.busy + onCancelled: { + root.controller.update({ + settingsDraft: null + }); + root.controller.cancelForm(); + } + } + StyledText { + text: "Bar icon" + } + SharedWidgetDropdown { + Layout.fillWidth: true + options: [["themed", "Syncthing (themed)"], ["branded", "Syncthing (branded)"], ["sync", "Glyph: sync"], ["cloud_sync", "Glyph: cloud_sync"], ["folder", "Glyph: folder"]].map(([value, label]) => ({ + value: value, + label: label + })) + value: root.draft.icon || "themed" + onChosen: value => root.setValue("icon", value) + } + Repeater { + model: [ + { + key: "probeSeconds", + title: "Probe interval (seconds)", + number: true + }, + { + key: "refreshSeconds", + title: "Refresh interval (seconds)", + number: true + }, + { + key: "configPath", + title: "Syncthing configuration path" + }, + { + key: "endpoint", + title: "Endpoint (optional)" + }, + { + key: "credentialFile", + title: "Credential file (optional)" + }, + { + key: "tlsCertificate", + title: "TLS certificate (optional)" + }, + { + key: "expectedDeviceId", + title: "Expected Device ID (optional)" + }, + { + key: "lifecycleUnit", + title: "Exact systemd user unit" + }, + { + key: "lifecycleConfig", + title: "Exact service configuration path" + } + ] + StyledTextField { + required property var modelData + Layout.fillWidth: true + placeholderText: modelData.title + text: String(root.draft[modelData.key] ?? "") + readOnly: root.controller.busy + onTextEdited: root.setValue(modelData.key, modelData.number ? Number(text) : text) + } + } + RowLayout { + StyledText { + Layout.fillWidth: true + text: "Authorize this exact service binding" + wrapMode: Text.Wrap + } + StyledSwitch { + checked: root.draft.lifecycleAuthorized === true + onToggled: root.setValue("lifecycleAuthorized", checked) + } + } + StyledText { + Layout.fillWidth: true + text: "External instances remain status-only. The core verifies that the unit owns the selected configuration." + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: "Save settings" + busy: root.controller.busy + onClicked: { + root.error = root.owner.preferences.save(root.draft); + if (!root.error) { + root.owner.adapter.core.restart(); + root.controller.update({ + settingsDraft: null + }); + root.controller.cancelForm(); + } + } + } + StyledText { + Layout.fillWidth: true + visible: !!root.error + text: root.error + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + SharedWidgetBusyButton { + caption: root.owner.adapter.lifecycle.unitFileState === "enabled" ? "Disable service autostart" : "Enable service autostart" + disabled: root.controller.busy || !root.owner.adapter.canControlService + onClicked: root.controller.confirm(root.owner.adapter.lifecycle.unitFileState === "enabled" ? "lifecycle.disable" : "lifecycle.enable", {}, caption + "?", "Change startup for the verified user service.") + } + StyledText { + text: "Syncthing Web UI" + } + SharedWidgetDropdown { + Layout.fillWidth: true + options: [ + { + value: "default", + label: "Default Syncthing UI" + }, + { + value: "modern", + label: "Modern UI" + }, + { + value: "themed", + label: "Caelestia theme" + } + ] + value: root.draft.webUiStyle || "default" + onChosen: value => root.setValue("webUiStyle", value) + } + SharedWidgetBusyButton { + caption: "Apply Web UI selection" + busy: root.controller.busy + onClicked: root.owner.applyWebUi(root.draft.webUiStyle) + } + SharedWidgetBusyButton { + caption: "Restore default UI and clean owned profiles" + label.width: width - horizontalPadding * 2 + label.wrapMode: Text.Wrap + Layout.fillWidth: true + busy: root.controller.busy + onClicked: root.controller.confirm("webui.remove-profile", {}, "Restore and clean profiles?", "Restore Syncthing's default Web UI and remove only Caelestia-owned profiles. Do this before uninstalling the plugin.") + } + StyledText { + Layout.fillWidth: true + text: "Web UI changes are explicit. Palette updates apply only while this adapter's themed profile is selected." + wrapMode: Text.Wrap + } + Component.onCompleted: if (!controller.view.settingsDraft) + controller.update({ + settingsDraft: Model.clone(owner.preferences.values()) + }) +} diff --git a/hosts/caelestia/ui/SharedDialogConfirm.qml b/hosts/caelestia/ui/SharedDialogConfirm.qml new file mode 100644 index 00000000..bce1805d --- /dev/null +++ b/hosts/caelestia/ui/SharedDialogConfirm.qml @@ -0,0 +1,108 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC +import Caelestia.Config +import qs.components +import qs.components.controls +import qs.components.containers +import qs.services +import "." + +QQC.Popup { + id: root + required property var controller + // Popup items carry no screen; resolve tokens through the visual parent. + readonly property Item tokens: parent + modal: true + focus: true + closePolicy: QQC.Popup.NoAutoClose + width: Math.min(400, parent.width) + height: Math.min(parent.height, contentColumn.implicitHeight + padding * 2) + x: (parent.width - width) / 2 + y: Math.max(0, (parent.height - height) / 2) + padding: tokens.Tokens.padding.large + // Return focus to the control that asked for confirmation, not the tabs. + property Item returnFocus: null + onAboutToShow: returnFocus = parent?.Window.window?.activeFocusItem ?? null + onOpened: cancel.forceActiveFocus() + onClosed: { + const target = returnFocus; + returnFocus = null; + if (target) + Qt.callLater(() => { + if (target.visible && target.enabled) + target.forceActiveFocus(); + }); + } + background: StyledRect { + color: Colours.palette.m3surfaceContainerHigh + radius: root.tokens.Tokens.rounding.medium + } + contentItem: ColumnLayout { + id: contentColumn + StyledText { + Layout.fillWidth: true + text: root.controller.view.confirmation?.title || "" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledFlickable { + id: detailsScroll + Layout.fillWidth: true + Layout.fillHeight: true + implicitHeight: details.implicitHeight + contentWidth: width + contentHeight: details.implicitHeight + clip: true + interactive: contentHeight > height + QQC.ScrollBar.vertical: StyledScrollBar { + flickable: detailsScroll + } + ColumnLayout { + id: details + width: parent.width + StyledText { + Layout.fillWidth: true + text: root.controller.view.confirmation?.detail || "" + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: root.controller.error + textFormat: Text.PlainText + visible: !!text + wrapMode: Text.Wrap + color: Colours.palette.m3error + } + } + } + RowLayout { + SharedWidgetBusyButton { + id: cancel + caption: "Cancel" + disabled: root.controller.busy + onClicked: root.controller.cancelConfirmation() + } + SharedWidgetBusyButton { + caption: "Confirm" + busy: root.controller.busy + onClicked: root.controller.acceptConfirmation() + } + } + Keys.onEscapePressed: root.controller.cancelConfirmation() + } + Connections { + target: root.controller + function onViewChanged() { + if (root.controller.view.confirmation) + root.open(); + else + root.close(); + } + } + Component.onCompleted: if (controller.view.confirmation) + open() +} diff --git a/hosts/caelestia/ui/SharedWidgetBusyButton.qml b/hosts/caelestia/ui/SharedWidgetBusyButton.qml new file mode 100644 index 00000000..9050f955 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetBusyButton.qml @@ -0,0 +1,87 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import Quickshell +import qs.components.controls +import qs.services +import "." + +TextButton { + id: root + label.textFormat: Text.PlainText + property bool busy: false + property string caption: "" + property string busyCaption: "Working..." + property string help: "" + property string feedback: "" + property string copyValue: "" + text: feedback || (busy ? busyCaption : caption) + implicitWidth: Math.max(idleMetrics.width, busyMetrics.width, feedbackMetrics.width) + horizontalPadding * 2 + TextMetrics { + id: idleMetrics + font: root.font + text: root.caption + } + TextMetrics { + id: busyMetrics + font: root.font + text: root.busyCaption + } + TextMetrics { + id: feedbackMetrics + font: root.font + text: root.copyValue ? "Copied" : "" + } + SharedWidgetToolTip { + visible: (hover.hovered || root.activeFocus) && !!root.help + text: root.help + } + HoverHandler { + id: hover + enabled: !!root.help + } + Timer { + id: feedbackTimer + interval: 2000 + onTriggered: root.feedback = "" + } + onCopyValueChanged: feedback = "" + onClicked: if (copyValue) { + Quickshell.clipboardText = copyValue; + feedback = "Copied"; + feedbackTimer.restart(); + } + disabled: busy + enabled: !disabled && !busy + activeFocusOnTab: enabled + border.width: activeFocus ? 2 : 0 + border.color: Colours.palette.m3primary + Connections { + target: root + function onClicked() { + if (root.isToggle) + Qt.callLater(() => root.internalChecked = root.checked); + } + } + Keys.onPressed: event => { + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { + event.accepted = true; + if (!event.isAutoRepeat && !disabled && !busy) + clicked(); + } + } + onActiveFocusChanged: if (activeFocus) + ensureVisible() + function ensureVisible() { + var ancestor = parent; + while (ancestor) { + let viewport = ancestor as Flickable; + if (viewport) { + let position = mapToItem(viewport.contentItem, 0, 0).y; + viewport.contentY = Math.max(0, Math.min(position, Math.max(viewport.contentY, position + height - viewport.height), viewport.contentHeight - viewport.height)); + break; + } + ancestor = ancestor.parent; + } + } +} diff --git a/hosts/caelestia/ui/SharedWidgetDropdown.qml b/hosts/caelestia/ui/SharedWidgetDropdown.qml new file mode 100644 index 00000000..0f9bed96 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetDropdown.qml @@ -0,0 +1,177 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC +import Caelestia.Config +import qs.components +import qs.components.controls +import qs.components.containers +import qs.services +import "." +import "../models/PanelModel.js" as Model + +Item { + id: root + implicitWidth: trigger.implicitWidth + implicitHeight: trigger.implicitHeight + readonly property Item boundary: { + var item = parent; + while (item && item.objectName !== "syncshellPanel") + item = item.parent; + return item; + } + property bool alive: true + Component.onDestruction: alive = false + property var options: [] + property string value: "" + property string placeholder: "Select" + property bool disabled: false + property bool multiple: false + property var selectedIds: [] + property var searchOwner: null + property var filterController: null + property int totalCount: options.length + property bool filtersOpen: false + property string localQuery: "" + readonly property string query: searchOwner ? searchOwner.view.search : localQuery + readonly property var filtered: options.filter(o => Model.matchesOption(o, query)) + signal chosen(string value) + signal toggled(string value) + + SharedWidgetBusyButton { + id: trigger + anchors.fill: parent + caption: root.multiple ? (root.selectedIds.length ? root.selectedIds.length + " selected" : root.placeholder) : (root.options.find(o => o.value === root.value)?.label || root.placeholder) + disabled: root.disabled + label.elide: Text.ElideRight + label.width: width - horizontalPadding * 2 + onClicked: menu.open() + } + QQC.Popup { + id: menu + parent: trigger + // mapToItem() does not notify when an enclosing flickable scrolls, so + // a binding kept the position from before focus scrolled the form. + function place() { + if (!root.boundary) { + y = trigger.height; + return; + } + const top = trigger.mapToItem(root.boundary, 0, 0).y; + y = Math.max(-top, Math.min(trigger.height, root.boundary.height - top - height)); + } + onAboutToShow: place() + onHeightChanged: if (visible) + place() + width: trigger.width + height: Math.min(root.boundary?.height || 540, 540, contentColumn.implicitHeight + padding * 2) + padding: root.Tokens.padding.medium + modal: true + focus: true + closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside + onOpened: { + search.forceActiveFocus(); + list.currentIndex = Math.max(0, root.filtered.findIndex(o => o.value === root.value)); + } + onClosed: if (root.alive && root.visible) + trigger.forceActiveFocus() + background: StyledRect { + color: Colours.palette.m3surfaceContainerHigh + radius: root.Tokens.rounding.medium + } + contentItem: ColumnLayout { + id: contentColumn + RowLayout { + Layout.fillWidth: true + StyledTextField { + id: search + Layout.fillWidth: true + placeholderText: "Search" + text: root.query + onTextEdited: { + if (root.searchOwner) + root.searchOwner.update({ + search: text + }); + else + root.localQuery = text; + } + Keys.onDownPressed: { + list.forceActiveFocus(); + list.currentIndex = 0; + } + } + SharedWidgetSquareActionButton { + visible: !!root.filterController + icon: "filter_list" + help: "Folder filters and sort order" + onClicked: root.filtersOpen = !root.filtersOpen + } + } + StyledText { + Layout.fillWidth: true + text: root.filtered.length + " of " + root.totalCount + " results" + color: Colours.palette.m3onSurfaceVariant + } + BodyTabFoldersViewOptions { + Layout.fillWidth: true + visible: !!root.filterController && root.filtersOpen + controller: root.filterController + } + StyledListView { + id: list + Layout.fillWidth: true + Layout.fillHeight: true + implicitHeight: Math.min(220, contentHeight) + clip: true + model: root.filtered + spacing: root.Tokens.spacing.extraSmall + keyNavigationEnabled: true + QQC.ScrollBar.vertical: StyledScrollBar { + flickable: list + } + delegate: SharedWidgetBusyButton { + required property var modelData + required property int index + width: ListView.view.width + caption: (root.multiple && root.selectedIds.includes(modelData.value) ? "[x] " : "") + modelData.label + (modelData.status ? " · " + modelData.status : "") + (modelData.detail ? "\n" + modelData.detail : "") + help: modelData.help || modelData.detail || "" + label.wrapMode: Text.Wrap + label.width: width - horizontalPadding * 2 + isToggle: true + type: TextButton.Tonal + checked: ListView.isCurrentItem + onClicked: { + list.currentIndex = index; + root.select(modelData.value); + } + } + Keys.onPressed: event => { + if ([Qt.Key_Return, Qt.Key_Enter, Qt.Key_Space].includes(event.key)) { + event.accepted = true; + if (!event.isAutoRepeat && root.filtered[currentIndex]) + root.select(root.filtered[currentIndex].value); + } + } + } + StyledText { + visible: !root.filtered.length + text: "No matches" + } + SharedWidgetBusyButton { + visible: root.multiple + caption: "Done" + onClicked: menu.close() + } + } + } + function select(id) { + if (multiple) + toggled(id); + else { + chosen(id); + menu.close(); + } + } +} diff --git a/hosts/caelestia/ui/SharedWidgetIdCopyButton.qml b/hosts/caelestia/ui/SharedWidgetIdCopyButton.qml new file mode 100644 index 00000000..cbfe8d92 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetIdCopyButton.qml @@ -0,0 +1,64 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import Quickshell +import Caelestia.Config +import qs.components +import qs.components.controls +import qs.services +import "." + +// Compact identifier copy chip; the identifier itself is never shown as a +// button caption. +IconTextButton { + id: root + property string value: "" + property string caption: "ID" + property string help: "Copy ID" + property bool copied: false + type: TextButton.Text + horizontalPadding: Tokens.padding.small + verticalPadding: 0 + icon: copied ? "check" : "content_copy" + text: copied ? "Copied" : caption + // Reserve the wider caption so feedback never resizes the row. + implicitWidth: Math.max(captionMetrics.advanceWidth, copiedMetrics.advanceWidth) + iconLabel.implicitWidth + spacing + horizontalPadding * 2 + disabled: !value + enabled: !disabled + activeFocusOnTab: enabled + border.width: activeFocus ? 2 : 0 + border.color: Colours.palette.m3primary + Accessible.name: help + TextMetrics { + id: captionMetrics + font: root.label.font + text: root.caption + } + TextMetrics { + id: copiedMetrics + font: root.label.font + text: "Copied" + } + SharedWidgetToolTip { + visible: root.hovered || root.activeFocus + text: root.copied ? "Copied" : root.help + } + Timer { + id: reset + interval: 2000 + onTriggered: root.copied = false + } + onValueChanged: copied = false + onClicked: { + Quickshell.clipboardText = value; + copied = true; + reset.restart(); + } + Keys.onPressed: event => { + if ([Qt.Key_Return, Qt.Key_Enter, Qt.Key_Space].includes(event.key)) { + event.accepted = true; + if (!event.isAutoRepeat && enabled) + clicked(); + } + } +} diff --git a/hosts/caelestia/ui/SharedWidgetInfoPair.qml b/hosts/caelestia/ui/SharedWidgetInfoPair.qml new file mode 100644 index 00000000..cc44a951 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetInfoPair.qml @@ -0,0 +1,22 @@ +import QtQuick +import QtQuick.Layouts +import qs.components +import qs.services + +RowLayout { + id: root + property string label: "" + property string value: "" + StyledText { + text: root.label + textFormat: Text.PlainText + color: Colours.palette.m3onSurfaceVariant + } + StyledText { + Layout.fillWidth: true + text: root.value + textFormat: Text.PlainText + elide: Text.ElideRight + horizontalAlignment: Text.AlignRight + } +} diff --git a/hosts/caelestia/ui/SharedWidgetMonoIcon.qml b/hosts/caelestia/ui/SharedWidgetMonoIcon.qml new file mode 100644 index 00000000..4fef84b2 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetMonoIcon.qml @@ -0,0 +1,25 @@ +import QtQuick +import QtQuick.Effects + +Item { + id: root + property url source + property color tint: "#ffffff" + Image { + id: image + anchors.fill: parent + source: root.source + sourceSize.width: width + sourceSize.height: height + fillMode: Image.PreserveAspectFit + smooth: true + visible: false + layer.enabled: true + } + MultiEffect { + anchors.fill: image + source: image + colorization: 1.0 + colorizationColor: root.tint + } +} diff --git a/hosts/caelestia/ui/SharedWidgetSquareActionButton.qml b/hosts/caelestia/ui/SharedWidgetSquareActionButton.qml new file mode 100644 index 00000000..f7e9b620 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetSquareActionButton.qml @@ -0,0 +1,27 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import qs.components.controls +import qs.services +import "." + +IconButton { + id: root + property string help: "" + enabled: !disabled + activeFocusOnTab: enabled + border.width: activeFocus ? 2 : 0 + border.color: Colours.palette.m3primary + SharedWidgetToolTip { + visible: (root.hovered || root.activeFocus) && !!root.help + text: root.help + } + Accessible.name: help + Keys.onPressed: event => { + if ([Qt.Key_Return, Qt.Key_Enter, Qt.Key_Space].includes(event.key)) { + event.accepted = true; + if (!event.isAutoRepeat && !disabled) + clicked(); + } + } +} diff --git a/hosts/caelestia/ui/SharedWidgetToolTip.qml b/hosts/caelestia/ui/SharedWidgetToolTip.qml new file mode 100644 index 00000000..6e87e504 --- /dev/null +++ b/hosts/caelestia/ui/SharedWidgetToolTip.qml @@ -0,0 +1,26 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls as QQC +import Caelestia.Config +import qs.components +import qs.services + +QQC.ToolTip { + id: root + // Popup items carry no screen; resolve tokens through the visual parent. + readonly property Item tokens: parent + delay: 500 + padding: tokens.Tokens.padding.medium + width: Math.min(tokens.Tokens.font.body.small.pointSize * 36, label.implicitWidth + padding * 2) + contentItem: StyledText { + id: label + text: root.text + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + background: StyledRect { + color: Colours.palette.m3surfaceContainerHigh + radius: root.tokens.Tokens.rounding.medium + } +} diff --git a/hosts/caelestia/ui/SyncshellPanelPopup.qml b/hosts/caelestia/ui/SyncshellPanelPopup.qml new file mode 100644 index 00000000..0289a369 --- /dev/null +++ b/hosts/caelestia/ui/SyncshellPanelPopup.qml @@ -0,0 +1,335 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC +import Caelestia.Config +import qs.components +import qs.components.controls +import qs.components.containers +import qs.services +import "." +import "../models/PanelModel.js" as Model + +FocusScope { + id: root + objectName: "syncshellPanel" + required property var controller + required property var owner + required property real availableWidth + required property real availableHeight + required property real anchorCenter + property var formTrigger: null + property real mainWidth: Math.min(availableWidth - 32, Tokens.font.body.small.pointSize * 40) + property real formWidth: Tokens.font.body.small.pointSize * 36 + readonly property real gap: Tokens.spacing.large + readonly property bool hasForm: !!controller.view.form + readonly property real mainNaturalHeight: header.implicitHeight + bodyContent.implicitHeight + footer.implicitHeight + gap * 2 + readonly property var geometry: Model.geometry(mainWidth, mainNaturalHeight, hasForm ? formWidth : 0, sideContent.implicitHeight + gap * 2, controller.view.formAnchor, availableWidth, availableHeight, anchorCenter, gap) + signal dismissed + implicitWidth: Math.max(1, geometry.width) + implicitHeight: Math.max(1, geometry.height) + + function form(kind, target, trigger) { + formTrigger = trigger; + controller.openForm(kind, target, trigger.mapToItem(mainPane, 0, 0).y); + } + function focusFirst(item) { + if (!item || !item.visible || !item.enabled) + return false; + if (item.activeFocusOnTab) { + item.forceActiveFocus(); + return true; + } + for (let child of item.children || []) + if (focusFirst(child)) + return true; + return false; + } + function focusEditor(item) { + if (!item || !item.visible || !item.enabled) + return false; + if (item.objectName === "syncshellInitialFocus") { + item.forceActiveFocus(); + return true; + } + for (let child of item.children || []) + if (focusEditor(child)) + return true; + return false; + } + function restore(name) { + if (controller.view.confirmation) + return; + Qt.callLater(() => { + if (!root.visible) + return; + if (name === "form" && root.hasForm) { + if (!focusEditor(sideContent)) + focusFirst(sideContent); + } else if (name === "formTrigger" && root.formTrigger?.enabled) + root.formTrigger.forceActiveFocus(); + else + folderTab.forceActiveFocus(); + }); + } + Keys.onPressed: event => { + if (event.key === Qt.Key_Escape) { + event.accepted = true; + if (controller.view.confirmation) + controller.cancelConfirmation(); + else if (controller.view.picking) + controller.update({ + picking: false + }); + else if (hasForm) + controller.cancelForm(); + else + dismissed(); + return; + } + var editor = root.Window.window?.activeFocusItem; + if (editor && (editor.cursorPosition !== undefined || editor.inputMethodComposing !== undefined)) + return; + if ([Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right].includes(event.key)) { + let candidate = editor; + let forward = event.key === Qt.Key_Down || event.key === Qt.Key_Right; + for (let i = 0; candidate && i < 150; i++) { + candidate = candidate.nextItemInFocusChain(forward); + let ancestor = candidate; + while (ancestor && ancestor !== root) + ancestor = ancestor.parent; + if (ancestor === root && candidate.activeFocusOnTab && candidate.enabled && candidate.visible) { + candidate.forceActiveFocus(); + event.accepted = true; + return; + } + } + } + if (event.isAutoRepeat || controller.busy || controller.view.confirmation || hasForm) + return; + if (event.key === Qt.Key_R) + controller.service.rescanAllFolders(); + else if (event.key === Qt.Key_W) + controller.service.openWebUi(); + else if (event.key === Qt.Key_P) + controller.requestServiceToggle(); + else if (event.key === Qt.Key_S) + form("settings", null, footerActions.settingsTrigger); + else if (event.key === Qt.Key_Q) + dismissed(); + else + return; + event.accepted = true; + } + StyledFlickable { + id: outerScroll + anchors.fill: parent + contentWidth: width + contentHeight: root.geometry.stacked ? root.geometry.formY + root.geometry.formHeight : height + interactive: root.geometry.stacked && contentHeight > height + clip: true + QQC.ScrollBar.vertical: StyledScrollBar { + flickable: outerScroll + } + ColumnLayout { + id: mainPane + x: 0 + y: root.geometry.mainY + width: Math.min(root.mainWidth, root.width) + height: root.geometry.mainHeight + spacing: root.gap + Header { + id: header + Layout.fillWidth: true + controller: root.controller + brandedIcon: root.owner.settings?.icon === "branded" + } + StyledFlickable { + id: bodyScroll + Layout.fillWidth: true + Layout.fillHeight: true + implicitHeight: bodyContent.implicitHeight + contentWidth: width + contentHeight: bodyContent.implicitHeight + clip: true + interactive: contentHeight > height + QQC.ScrollBar.vertical: StyledScrollBar { + flickable: bodyScroll + } + ColumnLayout { + id: bodyContent + width: parent.width + spacing: root.gap + RowLayout { + SharedWidgetBusyButton { + id: folderTab + caption: "Folders (" + root.controller.service.folderCount + ")" + isToggle: true + type: TextButton.Tonal + checked: root.controller.view.tab === "folders" + onClicked: root.controller.update({ + tab: "folders" + }) + } + SharedWidgetBusyButton { + caption: "Devices (" + root.controller.service.remoteDevices().length + ")" + isToggle: true + type: TextButton.Tonal + checked: root.controller.view.tab === "devices" + onClicked: root.controller.update({ + tab: "devices" + }) + } + } + RowLayout { + SharedWidgetDropdown { + id: mainSelector + Layout.fillWidth: true + searchOwner: root.controller + filterController: root.controller.view.tab === "folders" ? root.controller : null + totalCount: root.controller.view.tab === "folders" ? root.controller.service.folders.length : root.controller.service.remoteDevices().length + options: root.controller.view.tab === "folders" ? root.controller.folderOptions : root.controller.deviceOptions + value: root.controller.view.tab === "folders" ? root.controller.view.folderId : root.controller.view.deviceId + placeholder: "No matching items" + onChosen: value => root.controller.update(root.controller.view.tab === "folders" ? { + folderId: value + } : { + deviceId: value + }) + } + SharedWidgetSquareActionButton { + id: add + icon: "add" + help: "Add " + (root.controller.view.tab === "folders" ? "folder" : "device") + disabled: !root.controller.fresh || root.controller.busy + onClicked: root.form(root.controller.view.tab === "folders" ? "add-folder" : "add-device", null, add) + } + SharedWidgetSquareActionButton { + id: share + icon: root.controller.view.tab === "folders" ? "share" : "folder_shared" + help: root.controller.view.tab === "folders" ? "Share folder" : "Review device folders" + disabled: !root.controller.fresh || root.controller.busy || !(root.controller.view.tab === "folders" ? root.controller.folder : root.controller.device) + onClicked: root.form(root.controller.view.tab === "folders" ? "share-folder" : "device-folders", root.controller.view.tab === "folders" ? root.controller.folder : root.controller.device, share) + } + SharedWidgetSquareActionButton { + visible: root.controller.view.tab === "folders" + icon: root.controller.folder?.paused ? "link" : "link_off" + help: root.controller.folder?.paused ? "Link folder" : "Unlink folder" + disabled: !root.controller.folder || !root.controller.fresh || root.controller.busy + onClicked: root.controller.send(root.controller.folder.paused ? "folder.resume" : "folder.pause", { + folderId: root.controller.folder.id + }) + } + } + StyledText { + Layout.fillWidth: true + visible: root.controller.view.tab === "folders" && !!root.controller.folder && !mainSelector.filtered.some(o => o.value === root.controller.view.folderId) + text: "Selected folder is hidden by the filter" + wrapMode: Text.Wrap + } + BodyTabFoldersCard { + Layout.fillWidth: true + controller: root.controller + visible: root.controller.view.tab === "folders" + } + BodyTabDevicesCard { + Layout.fillWidth: true + controller: root.controller + visible: root.controller.view.tab === "devices" + } + BodyInvitations { + Layout.fillWidth: true + controller: root.controller + onFormRequested: (kind, target, trigger) => root.form(kind, target, trigger) + } + // A disclosure, as in Omarchy: chevron plus More/Less. + IconTextButton { + id: moreToggle + type: TextButton.Text + icon: root.controller.view.more ? "expand_less" : "expand_more" + text: root.controller.view.more ? "Less" : "More" + activeFocusOnTab: true + border.width: activeFocus ? 2 : 0 + border.color: Colours.palette.m3primary + Accessible.role: Accessible.Button + Accessible.name: root.controller.view.more ? "Hide details" : "Show details" + onClicked: root.controller.update({ + more: !root.controller.view.more + }) + Keys.onPressed: event => { + if ([Qt.Key_Return, Qt.Key_Enter, Qt.Key_Space].includes(event.key)) { + event.accepted = true; + if (!event.isAutoRepeat) + clicked(); + } + } + } + BodyMore { + Layout.fillWidth: true + controller: root.controller + visible: root.controller.view.more + } + } + } + ColumnLayout { + id: footer + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: root.controller.error || root.owner.preferences.error || root.controller.service.lastError || root.controller.service.actionNotice + textFormat: Text.PlainText + visible: !!text + wrapMode: Text.Wrap + } + FooterActions { + id: footerActions + Layout.fillWidth: true + controller: root.controller + onSettingsRequested: trigger => root.form("settings", null, trigger) + } + FooterShortcutHint {} + } + } + StyledRect { + id: sideSurface + visible: root.hasForm + x: root.geometry.stacked ? 0 : root.mainWidth + root.gap + y: root.geometry.formY + width: root.geometry.stacked ? root.width : root.formWidth + height: root.geometry.formHeight + radius: Tokens.rounding.medium + color: Colours.palette.m3surfaceContainer + StyledFlickable { + id: sideScroll + anchors.fill: parent + anchors.margins: root.gap + contentWidth: width + contentHeight: sideContent.implicitHeight + clip: true + interactive: contentHeight > height + QQC.ScrollBar.vertical: StyledScrollBar { + flickable: sideScroll + } + BodyFormSideCard { + id: sideContent + width: parent.width + controller: root.controller + owner: root.owner + visible: root.hasForm + } + } + } + } + SharedDialogConfirm { + parent: root + controller: root.controller + } + Connections { + target: root.controller + function onRestoreFocus(name) { + root.restore(name); + } + } + Component.onCompleted: restore(controller.view.form ? "form" : "main") +} diff --git a/hosts/dankmaterialshell/README.md b/hosts/dankmaterialshell/README.md deleted file mode 100644 index b77335a0..00000000 --- a/hosts/dankmaterialshell/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# DankMaterialShell host - -An alpha native DankMaterialShell adapter is under development in this -repository. It is not part of the supported Syncshell release and has no -published installation contract yet. diff --git a/hosts/dux-shell/DuxShellPanel.qml b/hosts/dux-shell/DuxShellPanel.qml new file mode 100644 index 00000000..43a90dbc --- /dev/null +++ b/hosts/dux-shell/DuxShellPanel.qml @@ -0,0 +1,101 @@ +import QtQuick +import qs.Common +import qs.Widgets +import qs.Modules.Plugins +import "controllers" +import "ui" +import "models/PanelModel.js" as Model + +PluginComponent { + id: root + layerNamespacePlugin: "syncshell" + popoutWidth: 384 * Math.max(1, Theme.fontScale) + Theme.spacingS * 2 + property var service: null + property var host: null + readonly property string iconVariant: Model.statusVariant(service) + readonly property bool themedIcon: !host || host.settings.values.iconStyle !== "branded" + pillRightClickAction: function () { + root.triggerPopout(); + } + + function resolveService() { + service = pluginService && pluginId ? pluginService.getGlobalVar(pluginId, "service", null) : null; + host = pluginService && pluginId ? pluginService.getGlobalVar(pluginId, "host", null) : null; + } + Component.onCompleted: resolveService() + onPluginServiceChanged: resolveService() + onPluginIdChanged: resolveService() + Connections { + target: root.pluginService + function onGlobalVarChanged(id, name) { + if (id === root.pluginId && (name === "service" || name === "host")) + root.resolveService(); + } + } + PanelController { + id: panelController + service: root.service + } + // Hover shows a status tooltip like Omarchy's bar; it never opens the panel. + function showTooltip(item, hovered) { + var pill = item; + while (pill && pill.popoutTarget === undefined) + pill = pill.parent; + if (!hovered || (pill && pill.popoutTarget && pill.popoutTarget.shouldBeVisible)) { + if (tooltipLoader.item) + tooltipLoader.item.hide(); + tooltipLoader.active = false; + return; + } + tooltipLoader.active = true; + var screen = root.parentScreen || Screen; + var text = Model.barTooltip(root.service); + if (root.isVertical) { + var mid = item.mapToItem(null, item.width / 2, item.height / 2); + var left = root.axis?.edge === "left"; + var x = left ? root.barThickness + root.barSpacing + Theme.spacingXS : screen.width - root.barThickness - root.barSpacing - Theme.spacingXS; + tooltipLoader.item.show(text, x, mid.y, screen, left, !left); + } else { + var top = item.mapToItem(null, item.width / 2, 0); + var bottom = root.axis?.edge === "bottom"; + var y = bottom ? screen.height - root.barThickness - root.barSpacing - Theme.spacingXS - (Theme.fontSizeSmall * 1.5 + Theme.spacingS * 2) : root.barThickness + root.barSpacing + Theme.spacingXS; + tooltipLoader.item.show(text, top.x, y, screen, false, false); + } + } + Loader { + id: tooltipLoader + active: false + sourceComponent: DTooltip {} + } + horizontalBarPill: Component { + SharedWidgetMonoIcon { + id: pillIcon + size: root.iconSize + variant: root.iconVariant + themed: root.themedIcon + tint: Theme.onSurface + HoverHandler { + onHoveredChanged: root.showTooltip(pillIcon, hovered) + } + } + } + verticalBarPill: Component { + SharedWidgetMonoIcon { + id: pillIcon + size: root.iconSize + variant: root.iconVariant + themed: root.themedIcon + tint: Theme.onSurface + HoverHandler { + onHoveredChanged: root.showTooltip(pillIcon, hovered) + } + } + } + popoutContent: Component { + SyncshellPanelPopup { + controller: panelController + host: root.host + pluginId: root.pluginId + } + } +} diff --git a/hosts/dux-shell/DuxShellService.qml b/hosts/dux-shell/DuxShellService.qml new file mode 100644 index 00000000..ead4e115 --- /dev/null +++ b/hosts/dux-shell/DuxShellService.qml @@ -0,0 +1,99 @@ +import QtQuick +import qs.Modules.Plugins +import "../../shared" as Shared +import "../../shared/Paths.js" as Paths +import "controllers" + +PluginComponent { + id: root + + readonly property string bundleRoot: Paths.localFilePath(Qt.resolvedUrl("../..")) + readonly property var service: serviceLoader.item + readonly property var settings: settingsController + readonly property var theme: themeController + property string collisionError: "" + property bool ownsService: false + readonly property string error: collisionError || settings.validationError + readonly property string connectionKey: JSON.stringify([settings.values.configPath, settings.values.endpoint, settings.values.credentialFile, settings.values.tlsCertificate, settings.values.expectedDeviceId, settings.values.lifecycleAuthorized, settings.values.lifecycleUnit, settings.values.lifecycleConfig]) + + function publish() { + if (!pluginService || !pluginId) + return; + var existing = pluginService.getGlobalVar(pluginId, "host", null); + var existingService = pluginService.getGlobalVar(pluginId, "service", null); + if (existing && existing !== root || !existing && existingService && existingService !== service) { + collisionError = "Another Syncshell service already owns this plugin ID"; + return; + } + ownsService = true; + pluginService.setGlobalVar(pluginId, "host", root); + pluginService.setGlobalVar(pluginId, "service", service); + } + + Component.onCompleted: publish() + onPluginServiceChanged: publish() + onPluginIdChanged: publish() + onServiceChanged: publish() + Component.onDestruction: { + if (pluginService && pluginService.getGlobalVar(pluginId, "host", null) === root) { + pluginService.setGlobalVar(pluginId, "service", null); + pluginService.setGlobalVar(pluginId, "host", null); + } + } + + SettingsController { + id: settingsController + pluginService: root.pluginService + pluginId: root.pluginId + pluginData: root.pluginData + } + + ThemePaletteController { + id: themeController + service: root.service + settings: settingsController + } + + Loader { + id: serviceLoader + active: root.ownsService && settingsController.valid && !root.collisionError + sourceComponent: Shared.AdapterService { + bundleRoot: root.bundleRoot + probeIntervalSeconds: settingsController.values.probeIntervalSeconds + refreshIntervalSeconds: settingsController.values.refreshIntervalSeconds + desiredServiceState: settingsController.values.desiredServiceState + lifecyclePolicy: ({ + kind: "systemd-user", + authorized: settingsController.values.lifecycleAuthorized, + unit: settingsController.values.lifecycleUnit, + configPath: settingsController.values.lifecycleConfig + }) + desktopAuthorized: true + profilePolicy: ({ + authorized: true, + owner: "dms", + bundle: root.bundleRoot + "/webui" + }) + configPath: settingsController.values.configPath + endpoint: settingsController.values.endpoint + credentialFile: settingsController.values.credentialFile + tlsCertificate: settingsController.values.tlsCertificate + expectedDeviceId: settingsController.values.expectedDeviceId + + onActionFinished: function (action, ok, data, failure) { + if (ok && (action === "lifecycle.enable" || action === "lifecycle.disable")) + settingsController.save("desiredServiceState", action === "lifecycle.enable" ? "enabled" : "disabled"); + } + } + } + + onConnectionKeyChanged: if (service) + restartTimer.restart() + + Timer { + id: restartTimer + interval: 100 + onTriggered: if (root.service) + root.service.core.restart() + } +} diff --git a/hosts/dux-shell/README.md b/hosts/dux-shell/README.md new file mode 100644 index 00000000..b33ba71c --- /dev/null +++ b/hosts/dux-shell/README.md @@ -0,0 +1,115 @@ +# DMS (Dux Shell) host + +This is the in-development adapter for DMS 2.0.0, formerly DankMaterialShell +and now Dux Shell. It shares the native Syncshell worker with the other +adapters and uses DMS plugin lifecycle, `qs.DCommon.Widgets` controls and +the 2.0 surface roles (`cardSurface`, `chipSurface`). Earlier DMS releases +are not supported. +It has not yet passed native desktop acceptance or been submitted to the +registry. Do not interpret assembly or unit tests as visual acceptance. + +## Development package + +From the source repository, assemble into an empty absolute directory: + +```sh +bash integrations/dux-shell/assemble.sh /absolute/path/to/Syncshell +``` + +Assembly requires Bash, Node.js and the usual GNU file utilities. The installed +plugin does not require Node.js, a Go toolchain or install-time downloads. +It includes the Linux x86_64/aarch64 workers, assets and licenses; Syncthing +must be installed separately. No bar placement or service configuration is +changed by assembly. + +For a manual DMS test, copy the complete `dist/dux-shell/` directory +to a new `Syncshell` directory inside DMS's plugin directory, normally +`~/.config/dms/plugins/`. Do not copy just the manifest or link +the repository root. Enable Syncshell in DMS plugin settings and add its +widget to the desired bar. Check for another `syncshell` installation and +back up its settings first; never overwrite it with this package. + +Nix users can import `integrations/dux-shell/home-manager.nix` alongside DMS's +Home Manager module and set `programs.syncshell-dux-shell.enable`. The recipe +assembles the same payload and registers it through DMS's plugin option. It does +not enable DMS itself, place a bar widget, manage Syncthing's service or +overwrite plugin settings. The recipe has not been built or tested on NixOS; no +NixOS support claim is made yet. + +The DMS plugin manager owns enable/disable and removal. One daemon owns the +worker regardless of bar or monitor count. Both mouse buttons open the panel. +Shortcuts outside text fields are `r` (rescan), `w` (Web UI), `p` (start/stop +the authorized service), `s` (settings) and `q` (close). Escape closes the +innermost menu, confirmation or form first. + +Settings live in DMS plugin settings under the `syncshell` object, with an +explicit schema and owner. An incompatible schema or another plugin's data +is rejected without migration or overwrite. Back up another same-ID plugin +and its settings before installing this adapter; do not install both under +`syncshell`. + +Lifecycle control is off until explicitly authorized in settings. The worker +must verify that the selected Syncthing instance matches that exact systemd +user unit before allowing control. Other instances remain monitorable and +manageable through the Syncthing API, without granting service authority. + +## Customization map + +Paths below are relative to `hosts/dux-shell/`. Equivalent QML host +responsibilities use the same filenames; native APIs are not interchangeable. + +| Area | Files | +| -------------------------- | -------------------------------------------------------------------- | +| Bar and popout composition | `DuxShellPanel.qml`, `ui/SyncshellPanelPopup.qml` | +| Worker and settings | `DuxShellService.qml`, `controllers/SettingsController.qml` | +| Selection and drafts | `controllers/PanelController.qml`, `models/PanelModel.js` | +| Header and More | `ui/Header.qml`, `ui/BodyMore.qml` | +| Footer | `ui/FooterActions.qml`, `ui/FooterShortcutHint.qml` | +| Folder/device cards | `ui/BodyTabFoldersCard.qml`, `ui/BodyTabDevicesCard.qml` | +| Folder creation | `ui/BodyTabFoldersAddForm.qml` | +| Device creation/acceptance | `ui/BodyTabDevicesAddForm.qml`, `ui/BodyTabDevicesAcceptForm.qml` | +| Sharing forms | `ui/BodyTabFoldersShareForm.qml`, `ui/BodyTabDevicesFoldersForm.qml` | +| Selection and filters | `ui/SharedWidgetDropdown.qml`, `ui/SharedWidgetMultiSelect.qml` | +| View options | `ui/BodyTabFoldersViewOptions.qml` | +| Side forms/confirmations | `ui/BodyFormSideCard.qml`, `ui/SharedDialogConfirm.qml` | +| Settings presentation | `ui/SettingsMenu.qml`, gear in `ui/FooterActions.qml` | + +`SharedWidgetMultiSelect.qml` is `SharedWidgetDropdown.qml` in its `multiple` +mode, which retains checked IDs while filtering. `SettingsMenu.qml` is the page +DMS shows in its own Settings window. Omarchy files without a DMS twin: the DMS +plugin manager owns removal (`SettingsSelfRemovalDialog`), and no host dialog +needs `SharedDialogChoice`. The panel follows Omarchy's three parts: `Header`, a +rule, the `Body*` area, and `FooterActions`, which starts with the second rule. +Control sizes come from `ui/UiConstants.js`; the compact buttons keep their own +wrappers because `DButton` and `DIconButton` start at 32 and 40 px. + +Status colors follow `docs/status-colors.md`: Omarchy's meanings with DMS's +`success`, `warning`, `error`, `info` and `onSurfaceVariant` roles. + +DMS paints one popout rectangle at the requested size, so side forms open on +their own content-sized layer surface, attached to the popout at the row +that opened them, as in Omarchy. The popout registers it as a transient +surface and releases its keyboard while a form is open; the form takes the +keyboard with a brief exclusive request, because an exclusive layer receives +all pointer input on Hyprland. A masked full-screen catcher then dismisses +outside clicks. Confirmations dim the panel and centre over it instead. + +## Web UI profiles and removal + +The default Web UI is left alone on first startup. Selecting Modern or DMS +theme installs a checksummed, adapter-owned profile for the verified local +Syncthing configuration. DMS palette changes update the selected DMS profile; +the imported Web UI templates remain unchanged. Explicit remote endpoints +without a local configuration do not receive filesystem profile authority. + +Before removal, use **Prepare plugin removal** in Syncshell settings and +confirm restoration of the default Web UI. Cleanup removes only the marked +`syncshell-dms-modern` and `syncshell-dms-themed` directories from Syncthing's +GUI asset directory. It leaves configuration, synchronized files and other +adapters' profiles intact. Remove the plugin through DMS afterward. + +DMS has no guaranteed hook for direct directory deletion. If the plugin was +already removed, select Syncthing's default Web UI first, then remove only +those two profile directories after checking their `.syncshell-profile.json` +owner is `dms`. Alternatively, re-enable this adapter and use its cleanup +action. Do not remove the enclosing GUI asset directory. diff --git a/hosts/dux-shell/controllers/PanelController.qml b/hosts/dux-shell/controllers/PanelController.qml new file mode 100644 index 00000000..c25c74d7 --- /dev/null +++ b/hosts/dux-shell/controllers/PanelController.qml @@ -0,0 +1,373 @@ +import QtQuick +import "../models/PanelModel.js" as Model + +QtObject { + id: root + + property var service: null + property string tab: "folders" + property string folderSearch: "" + property string deviceSearch: "" + property string selectedFolderId: "" + property string selectedDeviceId: "" + property var groups: ["ready", "active", "errors", "paused", "unknown"] + property string sort: "name" + property bool moreOpen: false + property string form: "" + property var draft: ({}) + property var originalShareIds: [] + property var confirmation: null + property bool submitting: false + property string pendingAction: "" + property var submittedDraft: null + property string error: "" + property bool idSuggestionPending: false + property var returnFocus: null + + readonly property var folder: service ? service.folder(selectedFolderId) : null + readonly property var device: service ? service.device(selectedDeviceId) : null + readonly property bool fresh: !!service && service.online && service.connection.fresh === true + readonly property var folderOptions: Model.folderOptions(service ? service.folders : [], fresh, groups, sort, folder => root.folderStatus(folder)) + readonly property var deviceOptions: Model.deviceOptions(service ? service.remoteDevices() : [], fresh) + readonly property var shareableDeviceOptions: Model.deviceOptions(service ? service.shareableDevices() : [], fresh) + readonly property bool busy: submitting || !!service && (service.busy || service.refreshing) + + property string recentlyLinkedFolderId: "" + property Timer linkedFeedback: Timer { + interval: 10000 + onTriggered: root.recentlyLinkedFolderId = "" + } + function folderActivity(folder) { + return Model.folderActivity(folder, fresh, service ? service.currentActivity : null); + } + function rescanning(folder) { + if (!service || !folder || folder.paused || !service.busy) + return false; + if (service._actionName === "folder.rescan") + return service._actionTargetId === folder.id; + return service._actionName === "folder.rescan-all" && (service.scanning(folder.id) || service.scanningFolderIds().length === 0); + } + function folderStatus(folder) { + return Model.folderStatus(folder, fresh, recentlyLinkedFolderId, !!folderActivity(folder), rescanning(folder)); + } + + signal focusRequested(var target) + signal directoryPickerRequested + + function reconcile() { + if (!service) + return; + if (form === "device-folders" && !submitting && !confirmation) { + var current = service.folderIdsForDevice(draft.deviceId); + setDraft("ids", current.filter(id => originalShareIds.indexOf(id) < 0 || draft.ids.indexOf(id) >= 0)); + originalShareIds = current.slice(); + } + selectedFolderId = Model.retainedSelection(service.folders, selectedFolderId); + selectedDeviceId = Model.retainedSelection(service.remoteDevices(), selectedDeviceId); + } + + property string linkingFolderId: "" + function toggleFolder() { + if (!folder || !fresh || busy || confirmation || form) + return false; + linkingFolderId = folder.paused ? folder.id : ""; + var accepted = service.setFolderPaused(folder.id, !folder.paused); + if (!accepted) + linkingFolderId = ""; + return accepted; + } + function resetFilters() { + groups = ["ready", "active", "errors", "paused", "unknown"]; + sort = "name"; + } + + function toggleGroup(group) { + groups = Model.toggled(groups, group); + } + + function setDraft(key, value) { + // DMS 2.0 text fields report programmatic changes as edits too. + if ((draft[key] === undefined ? "" : draft[key]) === value) + return; + if (key === "folderId") + idSuggestionPending = false; + var next = Object.assign({}, draft); + next[key] = value; + draft = next; + } + + function toggleDraft(id) { + setDraft("ids", Model.toggled(draft.ids || [], id)); + } + + function begin(nextForm, value, trigger) { + if (busy || confirmation) + return false; + if (form) { + error = "Finish or cancel the current form first"; + return false; + } + var target = value || {}; + error = ""; + confirmation = null; + returnFocus = trigger || null; + originalShareIds = []; + if (nextForm === "add-folder") { + draft = { + path: "", + label: String(target.label || ""), + folderId: String(target.folderId || ""), + pendingDeviceId: String(target.deviceId || ""), + ids: target.deviceId ? [target.deviceId] : [] + }; + } else if (nextForm === "add-device" || nextForm === "accept-device") { + draft = { + deviceId: String(target.id || ""), + name: String(target.name || ""), + address: String(target.address || "") + }; + } else if (nextForm === "share-folder") { + if (!service || !service.folder(target.id)) + return false; + draft = { + folderId: target.id, + ids: service.remoteDeviceIdsForFolder(target.id).slice() + }; + } else if (nextForm === "device-folders") { + if (!service || !service.device(target.id)) + return false; + originalShareIds = service.folderIdsForDevice(target.id).slice(); + draft = { + deviceId: target.id, + name: target.name, + ids: originalShareIds.slice() + }; + } else { + return false; + } + form = nextForm; + if (nextForm === "add-folder" && !draft.folderId) + suggestFolderId(); + return true; + } + + function suggestFolderId() { + if (!service || busy || confirmation || form !== "add-folder" || draft.pendingDeviceId) + return false; + error = ""; + idSuggestionPending = service.requestFolderIdSuggestion(); + if (!idSuggestionPending) + error = service.actionError || "Could not generate a folder ID"; + return idSuggestionPending; + } + + function connectionChanged() { + if (submitting || confirmation || form) { + submitting = false; + pendingAction = ""; + submittedDraft = null; + confirmation = null; + error = "The connection changed or an operation was interrupted. Refresh and review your draft before retrying."; + } + idSuggestionPending = false; + linkingFolderId = ""; + recentlyLinkedFolderId = ""; + } + + function closeForm() { + if (submitting) + return false; + confirmation = null; + idSuggestionPending = false; + form = ""; + draft = ({}); + originalShareIds = []; + error = ""; + focusRequested(returnFocus); + returnFocus = null; + return true; + } + + function cancelConfirmation() { + if (submitting) + return false; + confirmation = null; + focusRequested(returnFocus); + return true; + } + + function requestConfirmation(action, target, trigger) { + if (busy || confirmation) + return false; + if (form && !(form === "add-folder" && action === "folder.add-existing")) { + error = "Finish or cancel the current form first"; + return false; + } + confirmation = { + action: action, + target: JSON.parse(JSON.stringify(target || {})) + }; + returnFocus = trigger || returnFocus; + error = ""; + return true; + } + + function reject(message) { + error = message; + submitting = false; + pendingAction = ""; + return false; + } + + function validFolderOffer(target) { + return !target.pendingDeviceId || service.pendingFolderOffers().some(offer => offer.folderId === target.folderId && offer.deviceId === target.pendingDeviceId && !offer.encrypted); + } + + function submit() { + if (busy || !service || confirmation || !form) + return false; + if (!fresh) + return reject("Status is stale; refresh before changing Syncthing"); + if (form === "add-folder" && !validFolderOffer(draft)) + return reject("The invitation changed or disappeared; your draft has been kept"); + if (form === "accept-device" && !service.pendingDevices.some(device => device.id === draft.deviceId)) + return reject("The device invitation disappeared; your draft has been kept"); + if (form === "device-folders" && Model.removedShares(originalShareIds, draft.ids).length === 0) + return reject("Uncheck a folder to remove its share"); + error = ""; + submitting = true; + submittedDraft = JSON.parse(JSON.stringify(draft)); + var accepted = false; + if (form === "add-folder") { + submittedDraft.path = String(draft.path || "").trim(); + submittedDraft.folderId = String(draft.folderId || "").trim(); + if (!submittedDraft.path || !submittedDraft.folderId) + return reject("Directory and Folder ID are required"); + pendingAction = "folder.add-existing"; + accepted = service.addFolder(Object.assign({}, submittedDraft, { + deviceIds: draft.ids.slice() + })); + } else if (form === "add-device" || form === "accept-device") { + var deviceId = String(draft.deviceId || "").trim(); + if (!deviceId) + return reject("Device ID is required"); + pendingAction = "device.add"; + accepted = service.addDevice(deviceId, draft.name); + } else if (form === "share-folder") { + if (!service.folder(draft.folderId)) + return reject("This folder no longer exists; your draft has been kept"); + pendingAction = "folder.set-sharing"; + accepted = service.setFolderSharing(draft.folderId, draft.ids.slice()); + } else if (form === "device-folders") { + if (!service.device(draft.deviceId)) + return reject("This device no longer exists; your draft has been kept"); + pendingAction = "device.remove-folder-shares"; + accepted = service.removeDeviceFolderShares(draft.deviceId, Model.removedShares(originalShareIds, draft.ids), draft.name); + } + if (!accepted) + return reject(service.actionError || "Action is unavailable"); + return true; + } + + function requestServiceToggle(trigger) { + if (!service || !service.canControlService || busy || form || confirmation) + return false; + return requestConfirmation(service.lifecycle.active ? "lifecycle.stop" : "lifecycle.start", {}, trigger); + } + + function confirm() { + if (busy || !confirmation || !service) + return false; + var request = confirmation; + var target = request.target; + var action = request.action; + var accepted = false; + if (action.indexOf("lifecycle.") !== 0 && !fresh) + return reject("Status is stale; refresh before changing Syncthing"); + if (action === "folder.add-existing" && !validFolderOffer(target)) + return reject("The invitation changed or disappeared; your draft has been kept"); + if (action === "device.dismiss-pending" && !service.pendingDevices.some(device => device.id === target.id) || action === "folder.dismiss-pending" && !service.pendingFolderOffers().some(offer => offer.folderId === target.folderId && offer.deviceId === target.deviceId)) + return reject("The invitation disappeared; nothing was changed"); + if (action === "folder.forget" && !service.folder(target.id) || action === "device.remove" && !service.device(target.id)) + return reject("This target no longer exists; nothing was changed"); + submitting = true; + pendingAction = action; + if (action === "folder.forget") + accepted = service.forgetFolder(target.id); + else if (action === "device.remove") + accepted = service.removeDevice(target.id, target.name); + else if (action === "device.dismiss-pending") + accepted = service.dismissPendingDevice(target.id, target.name); + else if (action === "folder.dismiss-pending") + accepted = service.dismissPendingFolder(target.folderId, target.deviceId); + else if (action === "folder.add-existing") + accepted = service.addFolder(Object.assign({}, target, { + createDirectory: true + })); + else if (action === "lifecycle.start" || action === "lifecycle.stop") + accepted = service.runAction(action, {}, action === "lifecycle.start" ? "Syncthing started" : "Syncthing stopped", ""); + if (!accepted) + return reject(service.actionError || "Action is unavailable"); + return true; + } + + function settled(action, ok, data, failure) { + if (action === "folder.resume") { + if (ok && linkingFolderId) { + recentlyLinkedFolderId = linkingFolderId; + linkedFeedback.restart(); + } + linkingFolderId = ""; + } + if (action === "folder.suggest-id") { + var applySuggestion = idSuggestionPending && form === "add-folder" && !draft.pendingDeviceId; + idSuggestionPending = false; + if (applySuggestion) { + if (ok && data && data.folderId) + setDraft("folderId", String(data.folderId)); + else + error = failure && failure.message || "Could not generate a folder ID"; + } + return; + } + if (!pendingAction || action !== pendingAction) + return; + submitting = false; + pendingAction = ""; + if (!ok) { + error = String(failure && failure.message || "Action failed; your draft has been kept"); + if (action === "folder.add-existing" && failure && failure.code === "path_missing" && !confirmation) { + requestConfirmation("folder.add-existing", Object.assign({}, submittedDraft, { + deviceIds: (submittedDraft.ids || []).slice() + }), returnFocus); + } + return; + } + confirmation = null; + closeForm(); + } + + onServiceChanged: { + connectionChanged(); + reconcile(); + } + property Connections coreGeneration: Connections { + target: root.service ? root.service.core || null : null + function onGenerationChanged() { + root.connectionChanged(); + } + } + + property Connections serviceConnections: Connections { + target: root.service + function onFoldersChanged() { + root.reconcile(); + } + function onDevicesChanged() { + root.reconcile(); + } + function onActionFinished(action, ok, data, error) { + root.settled(action, ok, data, error); + } + } +} diff --git a/hosts/dux-shell/controllers/SettingsController.qml b/hosts/dux-shell/controllers/SettingsController.qml new file mode 100644 index 00000000..d76d721f --- /dev/null +++ b/hosts/dux-shell/controllers/SettingsController.qml @@ -0,0 +1,78 @@ +import QtQuick + +QtObject { + id: root + + property var pluginService: null + property string pluginId: "syncshell" + property var pluginData: ({}) + readonly property string owner: "omarchy-QOL/syncshell" + readonly property var defaults: ({ + schema: 1, + owner: root.owner, + iconStyle: "themed", + webUiTheme: "default", + probeIntervalSeconds: 15, + refreshIntervalSeconds: 60, + lifecycleAuthorized: false, + lifecycleUnit: "syncthing.service", + lifecycleConfig: "", + desiredServiceState: "enabled", + configPath: "", + endpoint: "", + credentialFile: "", + tlsCertificate: "", + expectedDeviceId: "" + }) + readonly property string validationError: validate(pluginData) + readonly property bool valid: validationError === "" + readonly property var values: valid ? Object.assign({}, defaults, pluginData.syncshell || {}) : defaults + property string writeError: "" + + function validate(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) + return "Invalid Syncshell settings; no settings were changed"; + var keys = Object.keys(data); + for (var index = 0; index < keys.length; index++) { + if (["syncshell", "enabled", "variants", "displayPreferences"].indexOf(keys[index]) < 0) + return "Unrecognized settings for plugin ID syncshell. Back up and remove the other installation first"; + } + if (data.syncshell === undefined) + return ""; + var config = data.syncshell; + if (!config || config.schema !== 1 || config.owner !== owner) + return "These settings belong to another Syncshell version or plugin; automatic migration is disabled"; + var configKeys = Object.keys(config); + for (var keyIndex = 0; keyIndex < configKeys.length; keyIndex++) { + var key = configKeys[keyIndex]; + if (!Object.prototype.hasOwnProperty.call(defaults, key) || typeof config[key] !== typeof defaults[key]) + return "Unsupported Syncshell setting: " + key; + } + var value = Object.assign({}, defaults, config); + if (["themed", "branded"].indexOf(value.iconStyle) < 0 || ["default", "modern", "dms"].indexOf(value.webUiTheme) < 0) + return "Unsupported icon or Web UI theme"; + if (!Number.isInteger(value.probeIntervalSeconds) || value.probeIntervalSeconds < 1 || value.probeIntervalSeconds > 3600) + return "Probe interval must be whole seconds between 1 and 3600"; + if (!Number.isInteger(value.refreshIntervalSeconds) || value.refreshIntervalSeconds < 60 || value.refreshIntervalSeconds > 3600) + return "Refresh interval must be whole seconds between 60 and 3600"; + if (["enabled", "disabled"].indexOf(value.desiredServiceState) < 0) + return "Unsupported desired service state"; + if (value.lifecycleAuthorized && !/^[A-Za-z0-9_.@:-]+\.service$/.test(value.lifecycleUnit)) + return "Choose an exact systemd user service unit"; + return ""; + } + + function save(key, value) { + if (!valid || !pluginService) + return false; + var next = Object.assign({}, values); + next[key] = value; + writeError = validate({ + syncshell: next + }); + if (writeError) + return false; + pluginService.savePluginData(pluginId, "syncshell", next); + return true; + } +} diff --git a/hosts/dux-shell/controllers/ThemePaletteController.qml b/hosts/dux-shell/controllers/ThemePaletteController.qml new file mode 100644 index 00000000..6e2cc7d5 --- /dev/null +++ b/hosts/dux-shell/controllers/ThemePaletteController.qml @@ -0,0 +1,131 @@ +import QtQuick +import qs.Common + +QtObject { + id: root + property var service: null + property var settings: null + readonly property string selection: settings ? settings.values.webUiTheme : "default" + readonly property var palette: ({ + mode: Theme.isLightMode ? "light" : "dark", + background: rgb(Theme.hostSurface), + surface: rgb(Theme.cardSurface), + surfaceVariant: rgb(Theme.chipSurface), + foreground: rgb(Theme.onSurface), + muted: rgb(Theme.onSurfaceVariant), + accent: rgb(Theme.primary), + success: rgb(Theme.success), + warning: rgb(Theme.warning), + danger: rgb(Theme.error), + border: rgb(Theme.outline), + info: rgb(Theme.info) + }) + readonly property string key: selection + (selection === "dms" ? JSON.stringify(palette) : "") + property string pendingKey: "" + property string pendingSelection: "" + property string error: "" + property bool dirty: false + property bool paletteOnly: false + property bool initialized: false + readonly property bool busy: pendingKey !== "" + + function rgb(color) { + function channel(value) { + return Math.round(value * 255).toString(16).padStart(2, "0"); + } + return "#" + channel(color.r) + channel(color.g) + channel(color.b); + } + + function schedule(paletteChange) { + if (!dirty || !paletteChange) + paletteOnly = paletteChange === true; + dirty = true; + debounce.restart(); + } + + function apply() { + if (!dirty || !service || !service.online || service.busy || service.refreshing || busy) + return; + var noLongerSelected = paletteOnly && (selection !== "dms" || service.webUi.theme !== "syncshell-dms-themed"); + dirty = false; + paletteOnly = false; + if (noLongerSelected) + return; + pendingKey = key; + pendingSelection = selection; + error = ""; + var accepted = selection === "default" ? service.setWebUiTheme("default") : service.applyWebProfile(selection === "dms" ? "themed" : "modern", selection === "dms" ? palette : {}); + if (!accepted) { + pendingKey = ""; + error = service.actionError || "Web UI profile could not be applied"; + } + } + + function cleanup() { + if (!service || !service.online || service.busy || service.refreshing || busy) + return false; + dirty = false; + pendingKey = "remove"; + error = ""; + if (service.removeWebProfile()) + return true; + pendingKey = ""; + error = service.actionError || "Profile cleanup could not start"; + return false; + } + + Component.onCompleted: { + initialized = true; + if (selection !== "default") + schedule(); + } + onSelectionChanged: if (initialized) + schedule() + onServiceChanged: { + if (busy) { + pendingKey = ""; + error = "The native worker changed before the profile operation completed"; + } + if (initialized && service && selection !== "default") + schedule(); + } + onPaletteChanged: { + if (initialized && selection === "dms" && service && service.webUi.theme === "syncshell-dms-themed") + schedule(true); + } + property Timer debounce: Timer { + interval: 200 + onTriggered: root.apply() + } + property Connections serviceConnections: Connections { + target: root.service + function onOnlineChanged() { + if (root.dirty) + root.debounce.restart(); + } + function onBusyChanged() { + if (root.dirty) + root.debounce.restart(); + } + function onRefreshingChanged() { + if (root.dirty) + root.debounce.restart(); + } + function onActionFinished(action, ok, data, failure) { + if (!root.busy || ["webui.apply-profile", "webui.set-theme", "webui.remove-profile"].indexOf(action) < 0) + return; + var completed = root.pendingKey; + var completedSelection = root.pendingSelection; + root.pendingKey = ""; + if (!ok) { + root.error = String(failure && failure.message || "Web UI profile operation failed"); + return; + } + if (completed === "remove") { + root.settings.save("webUiTheme", "default"); + } else if (root.key !== completed) { + root.schedule(root.selection === completedSelection); + } + } + } +} diff --git a/hosts/dux-shell/models/PanelModel.js b/hosts/dux-shell/models/PanelModel.js new file mode 100644 index 00000000..367933be --- /dev/null +++ b/hosts/dux-shell/models/PanelModel.js @@ -0,0 +1,300 @@ +.pragma library + +// Omarchy names folders by their directory; the configured label follows in the meta line. +function folderName(folder) { + var path = String(folder.path || ""); + var trimmed = path.replace(/\/+$/, ""); + if (path.charAt(0) === "/" && trimmed === "") + return "/"; + return trimmed.split("/").pop() || String(folder.label || folder.id || "Unnamed folder"); +} + +function matchesSearch(label, query) { + var text = String(label || "").toLowerCase(); + var needle = String(query || "").trim().toLowerCase(); + var position = 0; + for (var index = 0; index < needle.length; index++) { + position = text.indexOf(needle[index], position); + if (position < 0) + return false; + position++; + } + return true; +} + +function matchesOption(option, query) { + return [option.label, option.value, option.description, option.keywords].some(function (text) { + return matchesSearch(text, query); + }); +} + +function folderGroup(folder, fresh) { + if (!fresh) + return "unknown"; + if (folder.paused) + return "paused"; + var status = folder.status || {}; + if (status.error || status.pullErrors > 0 || (status.errors || []).length || status.state === "error") + return "errors"; + if (status.state === "syncing" || String(status.state).indexOf("scan") === 0 + || status.needTotalItems > 0) + return "active"; + return status.state === "idle" ? "ready" : "unknown"; +} + + + +function folderOptions(folders, fresh, groups, sort, presentation) { + var rows = (folders || []).map(function (folder) { + var status = folder.status || {}; + return { + value: folder.id, + label: folderName(folder), + keywords: String(folder.label || ""), + description: String(folder.path || ""), + group: folderGroup(folder, fresh), + status: presentation ? presentation(folder) : folderStatus(folder, fresh), + statusRole: folderStateRole(presentation ? presentation(folder) : folderStatus(folder, fresh)), + help: stateHelp(presentation ? presentation(folder) : folderStatus(folder, fresh)) + "\n" + String(status.error || (status.errors || []).map(function (error) { + return error.path + ": " + error.error; + }).join("\n")) + }; + }).filter(function (row) { + return !groups || groups.indexOf(row.group) >= 0; + }); + rows.sort(function (left, right) { + var priority = sort === "active" || sort === "errors" ? sort : ""; + if (priority && (left.group === priority) !== (right.group === priority)) + return left.group === priority ? -1 : 1; + var a = left.label.toLowerCase(); + var b = right.label.toLowerCase(); + return a < b ? -1 : a > b ? 1 + : left.value < right.value ? -1 : left.value > right.value ? 1 : 0; + }); + return rows; +} + +function deviceStatus(device, fresh) { + if (!device) + return ""; + return !fresh ? "UNKNOWN" + : device.paused ? "PAUSED" : device.connected ? "CONNECTED" : "DISCONNECTED"; +} + +// Omarchy's state colours as DMS Theme roles: green when settled, yellow +// while moving or paused, red on errors, muted when unknown or away. +function folderStateRole(state) { + if (state === "SYNCED" || state === "LINKED") + return "success"; + if (state === "ERROR") + return "error"; + if (["UNLINKED", "SCANNING", "SCAN+SYNC", "SYNCING"].indexOf(state) >= 0) + return "warning"; + return "onSurfaceVariant"; +} + +function deviceStateRole(state) { + return state === "CONNECTED" ? "success" : state === "PAUSED" ? "warning" : "onSurfaceVariant"; +} + +// Omarchy's activity colours: cyan syncing (DMS info), red removing, green upload. +function activityRole(action) { + return action === "removing" ? "error" : action === "upload" ? "success" : "info"; +} + +function deviceOptions(devices, fresh) { + return (devices || []).map(function (device) { + return { + value: device.id, + label: String(device.name || device.id), + description: String(device.address || device.id), + status: deviceStatus(device, fresh), + statusRole: deviceStateRole(deviceStatus(device, fresh)) + }; + }); +} + +function retainedSelection(rows, selectedId) { + for (var index = 0; index < rows.length; index++) { + if (rows[index].id === selectedId) + return selectedId; + } + return rows.length ? rows[0].id : ""; +} + +function toggled(ids, id) { + var result = ids.slice(); + var index = result.indexOf(id); + if (index < 0) + result.push(id); + else + result.splice(index, 1); + return result; +} + +function removedShares(originalIds, draftIds) { + return originalIds.filter(function (id) { return draftIds.indexOf(id) < 0; }); +} + +function bytes(value) { + var number = Math.max(0, Number(value || 0)); + var units = ["B", "KiB", "MiB", "GiB", "TiB"]; + var unit = 0; + while (number >= 1024 && unit < units.length - 1) { + number /= 1024; + unit++; + } + return (unit === 0 ? String(Math.round(number)) : number.toFixed(number >= 10 ? 0 : 1)) + + " " + units[unit]; +} + +function totals(folders) { + var result = { files: 0, bytes: 0 }; + for (var index = 0; index < folders.length; index++) { + var status = folders[index].status || {}; + result.files += Number(status.globalFiles || 0); + result.bytes += Number(status.globalBytes || 0); + } + return result; +} + +function sidePlacement(screenWidth, mainX, mainWidth, sideWidth, gap, clearance) { + var left = mainX - clearance >= sideWidth + gap; + var right = screenWidth - clearance - mainX - mainWidth >= sideWidth + gap; + if (left && (!right || mainX + mainWidth / 2 >= screenWidth / 2)) + return "left"; + return right ? "right" : "stack"; +} + +// The side form is its own surface beside the popout, top-aligned with the +// row that opened it as in Omarchy, and kept inside the usable screen area. +function sideWindowPlacement(screenWidth, screenHeight, popout, formWidth, formHeight, rowY, gap, clearance, usableTop) { + var side = sidePlacement(screenWidth, popout.x, popout.width, formWidth, gap, clearance); + var x = side === "left" ? popout.x - gap - formWidth + : side === "right" ? popout.x + popout.width + gap + : Math.max(clearance, popout.x + (popout.width - formWidth) / 2); + var y = Math.max(usableTop, Math.min(screenHeight - clearance - formHeight, popout.y + rowY)); + return { side: side, x: x, y: y }; +} + +function folderStatus(folder, fresh, recentlyLinkedId, activity, rescanning) { + if (!folder || !fresh) return "UNKNOWN"; + if (folder.paused) return "UNLINKED"; + var s = folder.status || {}; + if (s.error || s.pullErrors > 0 || (s.errors || []).length || s.state === "error") return "ERROR"; + var syncing = s.needTotalItems > 0 || s.state === "syncing" || !!activity; + if (rescanning || String(s.state).indexOf("scan") === 0) + return syncing ? "SCAN+SYNC" : "SCANNING"; + if (folder.id === recentlyLinkedId) return "LINKED"; + if (syncing) return "SYNCING"; + return s.state === "idle" ? "SYNCED" : "UNKNOWN"; +} +function stateHelp(state) { + return state + " · " + ({ UNKNOWN: "Status unavailable", UNLINKED: "Syncing paused", + ERROR: "Needs attention", SCANNING: "Rescanning local files", + SYNCING: "Applying changes", "SCAN+SYNC": "Rescanning and syncing", + LINKED: "Newly linked", SYNCED: "Up to date" }[state] || "Status unavailable"); +} +function folderMeta(folder, fresh, localDeviceId, rescanning) { + if (!folder) return ""; + var s = folder.status || {}; + var suffix = folder.label && folder.label !== folderName(folder) ? " · " + folder.label : ""; + if (!fresh) return "Last reported: " + (s.globalFiles || 0) + " files · " + bytes(s.globalBytes) + suffix; + if (s.error || s.pullErrors > 0 || (s.errors || []).length || s.state === "error") + return (s.error || (s.errors || [])[0]?.error || "Folder needs attention") + suffix; + if (folder.paused) return "Syncing paused" + suffix; + if (rescanning || String(s.state).indexOf("scan") === 0) return "Scanning local changes" + suffix; + if (s.needTotalItems > 0 || s.state === "syncing") + return (s.needTotalItems || 0) + " item" + (s.needTotalItems === 1 ? "" : "s") + " remaining" + + (s.needBytes > 0 ? " · " + bytes(s.needBytes) : "") + suffix; + var localOnly = !(folder.devices || []).some(d => d.id && d.id !== localDeviceId); + return (s.globalFiles || 0) + " files · " + (localOnly ? "local only" : bytes(s.globalBytes)) + suffix; +} +function folderActivity(folder, fresh, activity) { + return folder && fresh && activity && activity.folderId === folder.id && activity.detail + ? String(activity.action || "Syncing") + " " + activity.detail : ""; +} + +function remoteShare(folder, device, fresh) { + var member = (folder.devices || []).find(d => d.id === device.id); + return fresh && device.connected && !device.paused && member ? member.remoteState || "unknown" : "unknown"; +} +function remoteShareDescription(state) { + return ({ valid: "Remote share confirmed", paused: "Remote folder paused", + notSharing: "Remote is not sharing back" })[state] || "Remote acceptance unconfirmed"; +} + +function hasErrors(folder) { + var s = folder && folder.status || {}; + return !!(s.error || s.pullErrors > 0 || (s.errors || []).length || s.state === "error"); +} +function errorDetails(folder) { + if (!hasErrors(folder)) return ""; + var s = folder.status || {}, groups = Object.create(null); + var errors = s.errors || []; + errors.forEach(e => { + var reason = e.error || "Unknown error"; + if (!groups[reason]) groups[reason] = []; + if (e.path) groups[reason].push(e.path); + }); + var details = Object.keys(groups).map(reason => reason + (groups[reason].length ? "\n" + groups[reason].join("\n") : "")); + if (s.error) details.unshift(s.error); + var count = Math.max(Number(s.pullErrors || 0), errors.length); + var summary = count ? "Showing " + errors.length + " of " + count + " current error" + (count === 1 ? "" : "s") + "." : ""; + if (errors.length < count) summary += " Open Web UI for the full list."; + return (details.join("\n\n") || "Syncthing reported no error details.") + (summary ? "\n\n" + summary : ""); +} + +function syncInProgress(a) { + return !!a && a.online && (a.syncingFolderCount > 0 || !!(a.currentActivity && a.currentActivity.detail) + || (a.busy && String(a._actionName).indexOf("folder.rescan") === 0)); +} +// Same precedence as Omarchy's iconVariant. +function statusVariant(a) { + if (!a || String(a.phase).indexOf("core-") === 0) return "notify"; + if (a.canControlService && a.lifecycle && a.lifecycle.active === false) return "pause"; + if (!a.online) return a.phase === "discovering" || a.phase === "loading" ? "sync" : "notify"; + if (a.folderProblemCount > 0) return "notify"; + if (a.refreshing || syncInProgress(a)) return "sync"; + return "default"; +} +function barTooltip(a) { + if (!a) return "Syncthing unavailable"; + if (a.installation && a.installation.available === false) return "Syncthing: Syncthing is not installed"; + if (a.canControlService && a.lifecycle && a.lifecycle.active === false) return "Syncthing: Syncing stopped"; + if (syncInProgress(a)) return "Syncthing: Sync in progress..."; + return "Syncthing: " + a.summaryText; +} +function formatCount(value) { + var count = Math.max(0, Number(value || 0)); + if (count >= 1000000) return (count / 1000000).toFixed(1) + "m"; + if (count >= 1000) return (count / 1000).toFixed(count >= 10000 ? 0 : 1) + "k"; + return String(Math.round(count)); +} +// Omarchy's confirmation wording; the DMS dialog only supplies the chrome. +function confirmText(action, target) { + var text = confirmWording(action, target || {}); + return { title: text.title, message: text.message, confirm: text.confirm || "Yes", + cancel: text.cancel || "No", destructive: text.destructive !== false }; +} + +function confirmWording(action, t) { + var name = t.name || t.label || t.deviceId || t.id || ""; + if (action === "folder.add-existing") + return { title: "Create directory?", message: "Create " + t.path + " and add it to Syncthing?", + confirm: "Create and add", cancel: "Cancel", destructive: false }; + if (action === "folder.forget") + return { title: "Forget " + folderName(t) + " (" + t.id + ")?", + message: "This removes only its Syncthing configuration. The directory and data files will not be deleted. " + + (t.markerName === ".stfolder" ? "Syncthing will also attempt to remove its internal .stfolder marker. " : "") + + "Rejoining the same remote folder requires this exact Folder ID." }; + if (action === "device.remove") + return { title: "Remove " + name + " from this device?", + message: "Folder sharing with it will be removed locally. Local folders and files remain. The other device is unchanged." }; + if (action === "device.dismiss-pending") + return { title: "Dismiss pending request from " + name + "?", message: "It can reappear if the device connects again." }; + if (action.indexOf("lifecycle.") === 0) + return { title: "Change Syncthing service?", message: "This changes the authorized systemd user service for this Syncthing instance.", + confirm: "Yes", destructive: false }; + return { title: "Dismiss invitation?", message: "Dismiss this folder invitation from " + name + "? It can reappear if the device offers it again." }; +} diff --git a/hosts/dux-shell/ui/BodyFormHeader.qml b/hosts/dux-shell/ui/BodyFormHeader.qml new file mode 100644 index 00000000..1b45cb4d --- /dev/null +++ b/hosts/dux-shell/ui/BodyFormHeader.qml @@ -0,0 +1,21 @@ +import QtQuick +import QtQuick.Layouts +import qs.DCommon.Widgets + +RowLayout { + id: root + property string title: "" + signal cancelled + StyledText { + text: root.title + textFormat: Text.PlainText + font.weight: Font.Medium + Layout.fillWidth: true + wrapMode: Text.NoWrap + elide: Text.ElideRight + } + SharedWidgetTooltipButton { + text: "Cancel" + onClicked: root.cancelled() + } +} diff --git a/hosts/dux-shell/ui/BodyFormSideCard.qml b/hosts/dux-shell/ui/BodyFormSideCard.qml new file mode 100644 index 00000000..4c4c0f35 --- /dev/null +++ b/hosts/dux-shell/ui/BodyFormSideCard.qml @@ -0,0 +1,80 @@ +import QtQuick +import qs.Common +import qs.DCommon.Widgets +import "UiConstants.js" as UiConstants + +StyledRect { + id: root + required property var controller + property var parentPopout: null + property real maximumHeight: 800 + function focusContent() { + if (!formLoader.item) + return false; + if (formLoader.item.focusFirst) + formLoader.item.focusFirst(); + else + formLoader.item.forceActiveFocus(); + return true; + } + // The edge that touches the popout, so the form reads as opening out of it. + property string joinedEdge: "" + // A form reaching past the popout's bottom keeps that corner rounded. + property bool joinedBottom: true + // Drawn as its own surface beside the popout, so it takes the popout chrome. + implicitHeight: Math.min(maximumHeight, formLoader.implicitHeight + PopoutMetrics.contentPadding * 2) + radius: Theme.windowRadius + topRightRadius: joinedEdge === "right" ? 0 : radius + bottomRightRadius: joinedEdge === "right" && joinedBottom ? 0 : radius + topLeftRadius: joinedEdge === "left" ? 0 : radius + bottomLeftRadius: joinedEdge === "left" && joinedBottom ? 0 : radius + color: parentPopout ? parentPopout.surfaceColor : Theme.hostSurface + DFlickable { + anchors.fill: parent + anchors.margins: PopoutMetrics.contentPadding - UiConstants.FOCUS_RING_ROOM + contentHeight: formLoader.implicitHeight + UiConstants.FOCUS_RING_ROOM * 2 + clip: true + Loader { + id: formLoader + x: UiConstants.FOCUS_RING_ROOM + y: UiConstants.FOCUS_RING_ROOM + width: parent.width - UiConstants.FOCUS_RING_ROOM * 2 + onLoaded: Qt.callLater(root.focusContent) + sourceComponent: root.controller.form === "add-folder" ? folder : root.controller.form === "add-device" ? device : root.controller.form === "accept-device" ? accept : root.controller.form === "share-folder" ? sharing : root.controller.form === "device-folders" ? deviceFolders : null + } + } + Component { + id: folder + BodyTabFoldersAddForm { + controller: root.controller + parentPopout: root.parentPopout + } + } + Component { + id: device + BodyTabDevicesAddForm { + controller: root.controller + parentPopout: root.parentPopout + } + } + Component { + id: accept + BodyTabDevicesAcceptForm { + controller: root.controller + } + } + Component { + id: sharing + BodyTabFoldersShareForm { + controller: root.controller + parentPopout: root.parentPopout + } + } + Component { + id: deviceFolders + BodyTabDevicesFoldersForm { + controller: root.controller + parentPopout: root.parentPopout + } + } +} diff --git a/hosts/dux-shell/ui/BodyMore.qml b/hosts/dux-shell/ui/BodyMore.qml new file mode 100644 index 00000000..e293b24b --- /dev/null +++ b/hosts/dux-shell/ui/BodyMore.qml @@ -0,0 +1,156 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model + +// Omarchy's More: a full-width disclosure, the Syncthing status word, errors +// per affected folder and the installation row. The footer's refresh +// rechecks errors, so there is no separate recheck button. +ColumnLayout { + id: root + required property var controller + readonly property var service: controller.service + readonly property var problemFolders: service ? service.folders.filter(folder => Model.hasErrors(folder)) : [] + readonly property string statusWord: problemFolders.length > 0 ? "errors" : root.controller.fresh ? "clean" : "unavailable" + readonly property var installation: service ? service.installation : ({}) + spacing: Theme.spacingS + SharedWidgetTooltipButton { + Layout.fillWidth: true + flat: true + leftAlign: true + text: root.controller.moreOpen ? "Less" : "More" + iconName: root.controller.moreOpen ? "expand_less" : "expand_more" + Accessible.name: root.controller.moreOpen ? "Hide details" : "Show details" + onClicked: root.controller.moreOpen = !root.controller.moreOpen + } + ColumnLayout { + Layout.fillWidth: true + Layout.leftMargin: Theme.spacingS + Layout.rightMargin: Theme.spacingS + visible: root.controller.moreOpen + spacing: Theme.spacingS + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingS + StyledText { + text: "Syncthing status" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + StyledText { + text: root.statusWord + font.pixelSize: Theme.fontSizeSmall + font.weight: Font.Bold + color: root.statusWord === "errors" ? Theme.error : root.statusWord === "clean" ? Theme.success : Theme.onSurfaceVariant + } + } + StyledText { + Layout.fillWidth: true + visible: !root.controller.fresh + text: root.problemFolders.length > 0 ? "Last reported errors; current status is unavailable." : "Current Syncthing status is unavailable." + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + wrapMode: Text.Wrap + } + Repeater { + model: root.problemFolders + ColumnLayout { + required property var modelData + Layout.fillWidth: true + spacing: 2 + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingXS + DIcon { + name: "folder" + size: Theme.fontSizeSmall + 2 + color: Theme.onSurfaceVariant + } + StyledText { + Layout.fillWidth: true + text: "affected: " + (modelData.path || modelData.id) + textFormat: Text.PlainText + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + wrapMode: Text.NoWrap + elide: Text.ElideLeft + } + } + StyledText { + Layout.fillWidth: true + text: Model.errorDetails(modelData) + textFormat: Text.PlainText + font.pixelSize: Theme.fontSizeSmall + wrapMode: Text.Wrap + color: Theme.error + } + } + } + Rectangle { + Layout.fillWidth: true + implicitHeight: Theme.outlineWidth + color: Theme.outlineVariant + } + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingS + StyledText { + text: "Installation" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + DIcon { + name: "info" + size: Theme.fontSizeSmall + 4 + color: !root.service ? Theme.onSurfaceVariant : root.installation.available ? Theme.success : Theme.warning + SharedWidgetToolTip { + anchors.fill: parent + text: !root.service ? "Unavailable" : root.installation.available ? "Existing installation found: executable" : "Syncthing executable not found" + } + } + StyledText { + Layout.fillWidth: true + text: root.installation.executablePath || "—" + textFormat: Text.PlainText + font.pixelSize: Theme.fontSizeSmall + wrapMode: Text.NoWrap + elide: Text.ElideMiddle + SharedWidgetToolTip { + anchors.fill: parent + text: root.installation.executablePath || "" + } + } + SharedWidgetSquareActionButton { + iconName: "help" + help: "Open Syncthing installation\nand removal documentation" + onClicked: Qt.openUrlExternally("https://docs.syncthing.net/intro/getting-started.html") + } + } + StyledText { + Layout.fillWidth: true + visible: !!root.service && !root.installation.available + text: "Install Syncthing with your distribution's package manager, then refresh." + font.pixelSize: Theme.fontSizeSmall + color: Theme.warning + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: root.service && root.service.lifecycle.error || "" + visible: text !== "" + textFormat: Text.PlainText + font.pixelSize: Theme.fontSizeSmall + color: Theme.warning + wrapMode: Text.Wrap + } + StyledText { + Layout.fillWidth: true + text: "Some entries are omitted by the core's display limits. Open Web UI for the full list." + visible: !!root.service && Object.values(root.service.truncation).some(n => n > 0) + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + wrapMode: Text.Wrap + } + } +} diff --git a/hosts/dux-shell/ui/BodyTabDevices.qml b/hosts/dux-shell/ui/BodyTabDevices.qml new file mode 100644 index 00000000..8553a2c7 --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabDevices.qml @@ -0,0 +1,77 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets + +ColumnLayout { + id: root + required property var controller + property var parentPopout: null + spacing: Theme.spacingS + function focusSelector() { + selector.focusTrigger(); + } + RowLayout { + Layout.fillWidth: true + SharedWidgetDropdown { + id: selector + Layout.fillWidth: true + searchOwner: root.controller + searchKey: "deviceSearch" + options: root.controller.deviceOptions + value: root.controller.selectedDeviceId + placeholder: "No remote device" + parentPopout: root.parentPopout + onSelected: value => root.controller.selectedDeviceId = value + } + SharedWidgetSquareActionButton { + iconName: "add" + help: "Add remote device" + enabled: root.controller.fresh && !root.controller.busy + onClicked: root.controller.begin("add-device", {}, this) + } + SharedWidgetSquareActionButton { + iconName: "folder_shared" + help: "Review this device's folder shares" + enabled: !!root.controller.device && root.controller.fresh && !root.controller.busy + onClicked: root.controller.begin("device-folders", root.controller.device, this) + } + SharedWidgetSquareActionButton { + iconName: "close" + danger: true + help: "Remove device and its shares; keep files" + enabled: !!root.controller.device && root.controller.fresh && !root.controller.busy + onClicked: root.controller.requestConfirmation("device.remove", root.controller.device, this) + } + } + BodyTabDevicesCard { + Layout.fillWidth: true + Layout.fillHeight: true + controller: root.controller + } + Repeater { + model: root.controller.service ? root.controller.service.pendingDevices : [] + ColumnLayout { + required property var modelData + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: "Device invitation: " + (modelData.name || modelData.id) + textFormat: Text.PlainText + } + RowLayout { + SharedWidgetTooltipButton { + primary: true + text: "Accept" + enabled: root.controller.fresh && !root.controller.busy + onClicked: root.controller.begin("accept-device", modelData, this) + } + SharedWidgetTooltipButton { + text: "Dismiss" + enabled: root.controller.fresh && !root.controller.busy + onClicked: root.controller.requestConfirmation("device.dismiss-pending", modelData, this) + } + } + } + } +} diff --git a/hosts/dux-shell/ui/BodyTabDevicesAcceptForm.qml b/hosts/dux-shell/ui/BodyTabDevicesAcceptForm.qml new file mode 100644 index 00000000..e8af3d3e --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabDevicesAcceptForm.qml @@ -0,0 +1,61 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "UiConstants.js" as UiConstants + +ColumnLayout { + id: root + required property var controller + function focusFirst() { + nameField.forceActiveFocus(); + } + spacing: Theme.spacingS + BodyFormHeader { + Layout.fillWidth: true + title: "Accept remote device" + enabled: !root.controller.submitting + onCancelled: root.controller.closeForm() + } + StyledText { + text: "Remote device name" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + DTextField { + id: nameField + Layout.fillWidth: true + implicitHeight: UiConstants.CONTROL_HEIGHT + 4 + topPadding: 2 + bottomPadding: 2 + font.pixelSize: Theme.fontSizeSmall + text: root.controller.draft.name || "" + enabled: !root.controller.busy + onTextEdited: root.controller.setDraft("name", text) + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Address" + value: root.controller.draft.address || "Unknown" + } + StyledText { + Layout.fillWidth: true + text: root.controller.draft.deviceId || "" + textFormat: Text.PlainText + wrapMode: Text.WrapAnywhere + elide: Text.ElideNone + } + SharedWidgetIdCopyButton { + value: root.controller.draft.deviceId || "" + caption: "device ID" + helpText: "Copy device ID" + } + SharedWidgetBusyButton { + Layout.fillWidth: true + text: "Accept device" + primary: true + busy: root.controller.submitting + enabled: !!root.controller.service && root.controller.service.online + onClicked: root.controller.submit() + } +} diff --git a/hosts/dux-shell/ui/BodyTabDevicesAddForm.qml b/hosts/dux-shell/ui/BodyTabDevicesAddForm.qml new file mode 100644 index 00000000..c2f927c5 --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabDevicesAddForm.qml @@ -0,0 +1,91 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "UiConstants.js" as UiConstants + +ColumnLayout { + id: root + required property var controller + property var parentPopout: null + function focusFirst() { + deviceIdField.forceActiveFocus(); + } + spacing: Theme.spacingS + BodyFormHeader { + Layout.fillWidth: true + title: "Add remote device" + enabled: !root.controller.submitting + onCancelled: root.controller.closeForm() + } + StyledText { + text: "Device source" + } + SharedWidgetDropdown { + Layout.fillWidth: true + parentPopout: root.parentPopout + placeholder: "Custom device ID" + value: root.controller.draft.deviceId || "" + options: [ + { + value: "", + label: "Custom device ID" + } + ].concat((root.controller.service ? root.controller.service.nearbyDevices : []).map(function (device) { + return { + value: device.id, + label: device.id, + description: (device.addresses || []).join(", ") + }; + })) + enabled: !root.controller.busy + onSelected: value => root.controller.setDraft("deviceId", value) + } + StyledText { + text: "Device ID" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + DTextField { + id: deviceIdField + Layout.fillWidth: true + implicitHeight: UiConstants.CONTROL_HEIGHT + 4 + topPadding: 2 + bottomPadding: 2 + font.pixelSize: Theme.fontSizeSmall + text: root.controller.draft.deviceId || "" + placeholderText: "XXXXXXX-XXXXXXX-..." + enabled: !root.controller.busy + onTextEdited: root.controller.setDraft("deviceId", text) + } + StyledText { + Layout.fillWidth: true + visible: !!root.controller.service && root.controller.service.nearbyDevices.length === 0 + text: "No nearby device found. Use the device ID." + color: Theme.warning + } + StyledText { + text: "Remote device name" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + DTextField { + Layout.fillWidth: true + implicitHeight: UiConstants.CONTROL_HEIGHT + 4 + topPadding: 2 + bottomPadding: 2 + font.pixelSize: Theme.fontSizeSmall + text: root.controller.draft.name || "" + placeholderText: "Optional" + enabled: !root.controller.busy + onTextEdited: root.controller.setDraft("name", text) + } + SharedWidgetBusyButton { + Layout.fillWidth: true + text: "Add remote device" + primary: true + busy: root.controller.submitting + enabled: !!root.controller.service && root.controller.service.online && !!root.controller.draft.deviceId + onClicked: root.controller.submit() + } +} diff --git a/hosts/dux-shell/ui/BodyTabDevicesCard.qml b/hosts/dux-shell/ui/BodyTabDevicesCard.qml new file mode 100644 index 00000000..667cb96b --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabDevicesCard.qml @@ -0,0 +1,128 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model +import "UiConstants.js" as UiConstants + +StyledRect { + id: root + required property var controller + readonly property var device: controller.device + readonly property int sharedCount: device && controller.service ? controller.service.folderIdsForDevice(device.id).length : 0 + readonly property int totalCount: controller.service ? controller.service.folders.length : 0 + function rate(key) { + return device && controller.fresh ? Model.bytes(device[key]) + "/s" : "Unknown"; + } + implicitHeight: content.implicitHeight + Theme.spacingM * 2 + radius: Theme.cornerRadius + color: Theme.cardSurface + border.width: Theme.outlineWidth + border.color: Theme.outlineVariant + ColumnLayout { + id: content + anchors.fill: parent + anchors.margins: Theme.spacingM + spacing: Theme.spacingS + // Omarchy's card head: name button, ID copy button, state on the right. + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingXS + SharedWidgetTooltipButton { + id: nameButton + Layout.maximumWidth: content.width - copyButton.width - stateText.implicitWidth - Theme.spacingXS * 2 - Theme.spacingM + leftAlign: true + iconName: "computer" + fontSize: Theme.fontSizeMedium + text: root.device ? root.device.name || "Unnamed device" : "No remote device" + help: "Open this device in the Web UI" + enabled: !!root.device && !!root.controller.service && root.controller.service.online + onClicked: root.controller.service.openWebUi() + } + SharedWidgetIdCopyButton { + id: copyButton + controlHeight: nameButton.height + caption: "" + value: root.device ? root.device.id : "" + helpText: "Copy device ID" + } + Item { + Layout.fillWidth: true + } + StyledText { + id: stateText + text: Model.deviceStatus(root.device, root.controller.fresh) + font.pixelSize: Theme.fontSizeSmall + font.weight: Font.Bold + color: Theme[Model.deviceStateRole(text)] + } + } + ColumnLayout { + Layout.fillWidth: true + Layout.leftMargin: Theme.spacingS + spacing: 2 + visible: !!root.device + Repeater { + model: [ + { icon: "folder", text: root.sharedCount + "/" + root.totalCount + " folder" + (root.totalCount === 1 ? "" : "s") + " shared" }, + { icon: "download", text: root.rate("downloadBps"), icon2: "upload", text2: root.rate("uploadBps") }, + { icon: "lan", text: root.device ? root.device.address || "Address unavailable" : "" } + ] + delegate: RowLayout { + required property var modelData + Layout.fillWidth: true + spacing: Theme.spacingXS + DIcon { + name: modelData.icon + size: Theme.fontSizeSmall + 2 + color: Theme.onSurfaceVariant + } + StyledText { + Layout.fillWidth: !modelData.icon2 + text: modelData.text + textFormat: Text.PlainText + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + wrapMode: Text.NoWrap + elide: Text.ElideMiddle + } + DIcon { + visible: !!modelData.icon2 + Layout.leftMargin: Theme.spacingS + name: modelData.icon2 || "" + size: Theme.fontSizeSmall + 2 + color: Theme.onSurfaceVariant + } + StyledText { + visible: !!modelData.icon2 + Layout.fillWidth: true + text: modelData.text2 || "" + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + } + } + } + } + StyledText { + Layout.fillWidth: true + visible: !root.device + text: "Add a remote device to share folders." + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + } + Item { + Layout.fillHeight: true + } + SharedWidgetBusyButton { + Layout.alignment: Qt.AlignRight + controlHeight: UiConstants.SMALL_CONTROL_HEIGHT + iconName: root.device && root.device.paused ? "play_arrow" : "pause" + text: root.device && root.device.paused ? "Resume" : "Pause" + busyText: root.device && root.device.paused ? "Resuming" : "Pausing" + help: root.device && root.device.paused ? "Resume synchronization with this device" : "Pause synchronization with this device" + busy: !!root.device && !!root.controller.service && root.controller.service.busy && ["device.pause", "device.resume"].indexOf(root.controller.service._actionName) >= 0 && root.controller.service._actionTargetId === root.device.id + enabled: !!root.device && root.controller.fresh && !root.controller.busy + onClicked: root.controller.service.setDevicePaused(root.device.id, !root.device.paused, root.device.name) + } + } +} diff --git a/hosts/dux-shell/ui/BodyTabDevicesFoldersForm.qml b/hosts/dux-shell/ui/BodyTabDevicesFoldersForm.qml new file mode 100644 index 00000000..5bc82f90 --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabDevicesFoldersForm.qml @@ -0,0 +1,71 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + property var parentPopout: null + readonly property var device: controller.service ? controller.service.device(controller.draft.deviceId) : null + function options(confirmed) { + return controller.originalShareIds.map(id => controller.service.folder(id)).filter(Boolean).filter(f => ["valid", "paused"].includes(Model.remoteShare(f, device || {}, controller.fresh)) === confirmed).map(f => ({ + value: f.id, + label: Model.folderName(f), + description: [f.path, f.id, Model.remoteShareDescription(Model.remoteShare(f, device || {}, controller.fresh))].filter(Boolean).join(" · ") + })); + } + spacing: Theme.spacingS + BodyFormHeader { + Layout.fillWidth: true + title: "Shared with " + (root.controller.draft.name || root.controller.draft.deviceId || "device") + enabled: !root.controller.submitting + onCancelled: root.controller.closeForm() + } + StyledText { + text: "Existing shares" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + SharedWidgetMultiSelect { + Layout.fillWidth: true + placeholder: "No folders shared" + parentPopout: root.parentPopout + options: root.options(true) + selectedValues: (root.controller.draft.ids || []).filter(id => options.some(o => o.value === id)) + enabled: !root.controller.busy + onToggled: value => root.controller.toggleDraft(value) + } + StyledText { + Layout.fillWidth: true + text: "Unconfirmed shares (acceptance pending/device offline)" + wrapMode: Text.WordWrap + font.pixelSize: Theme.fontSizeSmall + color: Theme.warning + } + SharedWidgetMultiSelect { + Layout.fillWidth: true + placeholder: "No folders shared" + parentPopout: root.parentPopout + options: root.options(false) + selectedValues: (root.controller.draft.ids || []).filter(id => options.some(o => o.value === id)) + enabled: !root.controller.busy + onToggled: value => root.controller.toggleDraft(value) + } + StyledText { + Layout.fillWidth: true + text: "Uncheck folders to remove their shares with this device. Files are kept; newly added shares are not changed." + wrapMode: Text.WordWrap + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + SharedWidgetBusyButton { + Layout.fillWidth: true + text: "Save sharing" + primary: true + busy: root.controller.submitting + enabled: root.controller.fresh && !root.controller.busy && Model.removedShares(root.controller.originalShareIds, root.controller.draft.ids || []).length > 0 + onClicked: root.controller.submit() + } +} diff --git a/hosts/dux-shell/ui/BodyTabFolders.qml b/hosts/dux-shell/ui/BodyTabFolders.qml new file mode 100644 index 00000000..b550ba8b --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFolders.qml @@ -0,0 +1,83 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets + +ColumnLayout { + id: root + required property var controller + property var parentPopout: null + spacing: Theme.spacingS + function focusSelector() { + selector.focusTrigger(); + } + RowLayout { + Layout.fillWidth: true + BodyTabFoldersSelector { + id: selector + Layout.fillWidth: true + controller: root.controller + parentPopout: root.parentPopout + } + SharedWidgetSquareActionButton { + iconName: "add" + help: "Add folder" + enabled: root.controller.fresh && !root.controller.busy + onClicked: root.controller.begin("add-folder", {}, this) + } + SharedWidgetSquareActionButton { + iconName: "share" + help: "Choose this folder's devices" + enabled: !!root.controller.folder && root.controller.fresh && !root.controller.busy + onClicked: root.controller.begin("share-folder", root.controller.folder, this) + } + SharedWidgetSquareActionButton { + iconName: root.controller.folder && root.controller.folder.paused ? "link" : "link_off" + help: root.controller.folder && root.controller.folder.paused ? "Resume folder synchronization" : "Pause folder synchronization; keep its files and shares" + busy: !!root.controller.service && root.controller.service.busy + enabled: !!root.controller.folder && root.controller.fresh + onClicked: root.controller.toggleFolder() + } + } + BodyTabFoldersCard { + Layout.fillWidth: true + Layout.fillHeight: true + controller: root.controller + } + Repeater { + model: root.controller.service ? root.controller.service.pendingFolderOffers() : [] + ColumnLayout { + required property var modelData + Layout.fillWidth: true + StyledText { + Layout.fillWidth: true + text: "Folder invitation: " + modelData.label + " from " + root.controller.service.deviceName(modelData.deviceId) + textFormat: Text.PlainText + } + StyledText { + Layout.fillWidth: true + visible: modelData.encrypted + text: "Encrypted or untrusted shares require setup in Web UI." + wrapMode: Text.Wrap + } + RowLayout { + SharedWidgetTooltipButton { + primary: true + text: modelData.encrypted ? "Open Web UI" : "Accept" + enabled: root.controller.fresh && !root.controller.busy + onClicked: { + if (modelData.encrypted) + root.controller.service.openWebUi(); + else + root.controller.begin("add-folder", modelData, this); + } + } + SharedWidgetTooltipButton { + text: "Dismiss" + enabled: root.controller.fresh && !root.controller.busy + onClicked: root.controller.requestConfirmation("folder.dismiss-pending", modelData, this) + } + } + } + } +} diff --git a/hosts/dux-shell/ui/BodyTabFoldersAddForm.qml b/hosts/dux-shell/ui/BodyTabFoldersAddForm.qml new file mode 100644 index 00000000..c1c02f45 --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFoldersAddForm.qml @@ -0,0 +1,122 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "UiConstants.js" as UiConstants + +ColumnLayout { + id: root + required property var controller + property var parentPopout: null + function focusFirst() { + pathField.forceActiveFocus(); + } + spacing: Theme.spacingS + BodyFormHeader { + Layout.fillWidth: true + title: "Add folder" + enabled: !root.controller.submitting + onCancelled: root.controller.closeForm() + } + StyledText { + text: "Local directory" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + RowLayout { + Layout.fillWidth: true + DTextField { + id: pathField + Layout.fillWidth: true + implicitHeight: UiConstants.CONTROL_HEIGHT + 4 + topPadding: 2 + bottomPadding: 2 + font.pixelSize: Theme.fontSizeSmall + text: root.controller.draft.path || "" + placeholderText: "/path/to/my/folder" + enabled: !root.controller.busy + onTextEdited: root.controller.setDraft("path", text) + } + SharedWidgetSquareActionButton { + iconName: "folder_open" + help: "Browse for directory" + enabled: !root.controller.busy + onClicked: root.controller.directoryPickerRequested() + } + } + StyledText { + text: "Label" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + DTextField { + Layout.fillWidth: true + implicitHeight: UiConstants.CONTROL_HEIGHT + 4 + topPadding: 2 + bottomPadding: 2 + font.pixelSize: Theme.fontSizeSmall + text: root.controller.draft.label || "" + placeholderText: "Derived from directory when empty" + enabled: !root.controller.busy + onTextEdited: root.controller.setDraft("label", text) + } + StyledText { + text: "Folder ID" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + RowLayout { + Layout.fillWidth: true + DTextField { + Layout.fillWidth: true + implicitHeight: UiConstants.CONTROL_HEIGHT + 4 + topPadding: 2 + bottomPadding: 2 + font.pixelSize: Theme.fontSizeSmall + text: root.controller.draft.folderId || "" + enabled: !root.controller.busy && !root.controller.draft.pendingDeviceId + onTextEdited: root.controller.setDraft("folderId", text) + } + SharedWidgetSquareActionButton { + iconName: "refresh" + help: "Generate a new folder ID" + enabled: !root.controller.busy && !root.controller.draft.pendingDeviceId + onClicked: root.controller.suggestFolderId() + } + } + StyledText { + Layout.fillWidth: true + text: "Reuse the exact ID to join an existing folder. A new ID creates a different folder identity." + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + wrapMode: Text.WordWrap + } + StyledText { + text: "Share with devices" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + SharedWidgetMultiSelect { + Layout.fillWidth: true + placeholder: "Local only" + parentPopout: root.parentPopout + options: root.controller.shareableDeviceOptions + selectedValues: root.controller.draft.ids || [] + enabled: !root.controller.busy + onToggled: value => root.controller.toggleDraft(value) + } + StyledText { + Layout.fillWidth: true + text: (root.controller.draft.ids || []).length ? "Only the selected devices will share this folder." : "Local only: not shared with other devices." + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + } + SharedWidgetBusyButton { + Layout.fillWidth: true + text: "Add folder" + primary: true + busy: root.controller.submitting + enabled: !!root.controller.service && root.controller.service.online && !!root.controller.draft.path && !!root.controller.draft.folderId + onClicked: root.controller.submit() + } +} diff --git a/hosts/dux-shell/ui/BodyTabFoldersCard.qml b/hosts/dux-shell/ui/BodyTabFoldersCard.qml new file mode 100644 index 00000000..81d43bcf --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFoldersCard.qml @@ -0,0 +1,128 @@ +import QtQuick +import QtQuick.Layouts +import Quickshell +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model +import "UiConstants.js" as UiConstants + +StyledRect { + id: root + required property var controller + readonly property var folder: controller.folder + readonly property var status: folder ? folder.status || {} : ({}) + implicitHeight: content.implicitHeight + Theme.spacingM * 2 + radius: Theme.cornerRadius + color: Theme.cardSurface + border.width: Theme.outlineWidth + border.color: Theme.outlineVariant + ColumnLayout { + id: content + anchors.fill: parent + anchors.margins: Theme.spacingM + spacing: Theme.spacingS + // Omarchy's card head: name button, ID copy button, state on the right. + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingXS + SharedWidgetTooltipButton { + id: nameButton + Layout.maximumWidth: content.width - copyButton.width - stateText.implicitWidth - Theme.spacingXS * 2 - Theme.spacingM + leftAlign: true + iconName: "folder" + fontSize: Theme.fontSizeMedium + text: root.folder ? Model.folderName(root.folder) : "No folder selected" + help: root.folder && root.folder.path ? "Open " + root.folder.path : "Folder unavailable" + enabled: !!root.folder && !!root.folder.path + onClicked: Quickshell.execDetached(["dms", "open", root.folder.path]) + } + SharedWidgetIdCopyButton { + id: copyButton + controlHeight: nameButton.height + caption: "" + value: root.folder ? root.folder.id : "" + helpText: "Copy folder ID" + } + Item { + Layout.fillWidth: true + } + StyledText { + id: stateText + text: root.folder ? root.controller.folderStatus(root.folder) : "" + color: Theme[Model.folderStateRole(text)] + font.pixelSize: Theme.fontSizeSmall + font.weight: Font.Bold + } + } + BodyTabFoldersCardActivity { + Layout.fillWidth: true + service: root.controller.service + folderId: root.folder ? root.folder.id : "" + } + // Spare tab height stays inside the card, above the details, so both + // tabs keep one panel height. + Item { + Layout.fillHeight: true + } + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingS + ColumnLayout { + Layout.fillWidth: true + Layout.leftMargin: Theme.spacingS + spacing: 2 + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingXS + StyledText { + Layout.fillWidth: true + text: Model.folderMeta(root.folder, root.controller.fresh, root.controller.service ? root.controller.service.localDeviceId : "", root.controller.rescanning(root.folder)) + textFormat: Text.PlainText + color: Model.hasErrors(root.folder) ? Theme.error : Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + wrapMode: Text.NoWrap + elide: Text.ElideRight + } + SharedWidgetTooltipButton { + visible: Model.hasErrors(root.folder) + flat: true + controlHeight: Theme.fontSizeSmall + 4 + text: '(see "More" below)' + help: "Show folder errors" + onClicked: root.controller.moreOpen = true + } + } + StyledText { + Layout.fillWidth: true + visible: !!root.folder && !!root.folder.path + text: root.folder ? root.folder.path : "" + textFormat: Text.PlainText + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + wrapMode: Text.NoWrap + elide: Text.ElideLeft + SharedWidgetToolTip { + anchors.fill: parent + text: parent.text + } + } + } + SharedWidgetBusyButton { + Layout.alignment: Qt.AlignBottom + controlHeight: UiConstants.SMALL_CONTROL_HEIGHT + iconName: root.folder && root.folder.paused ? "delete" : "refresh" + text: root.folder && root.folder.paused ? "Forget" : "Rescan" + busyText: root.folder && root.folder.paused ? "Forgetting" : "Rescanning" + help: !root.controller.fresh ? "Refresh current status before changing this folder" : root.folder && root.folder.paused ? "Remove only this unlinked Syncthing configuration" : "Rescan this folder for local changes" + busy: root.controller.rescanning(root.folder) || root.controller.pendingAction === "folder.forget" + enabled: !!root.folder && root.controller.fresh && !root.controller.busy + onClicked: { + if (root.folder.paused) + root.controller.requestConfirmation("folder.forget", root.folder, this); + else + root.controller.service.rescanFolder(root.folder.id); + } + } + } + } +} diff --git a/hosts/dux-shell/ui/BodyTabFoldersCardActivity.qml b/hosts/dux-shell/ui/BodyTabFoldersCardActivity.qml new file mode 100644 index 00000000..10d5125e --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFoldersCardActivity.qml @@ -0,0 +1,20 @@ +import QtQuick +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model + +StyledText { + id: root + property var service: null + property string folderId: "" + text: service && service.online && service.connection.fresh && folderId && service.currentActivity.folderId === folderId ? service.activityText : "" + textFormat: Text.PlainText + wrapMode: Text.NoWrap + elide: Text.ElideMiddle + color: Theme[Model.activityRole(service ? service.currentActivity.action : "")] + visible: text !== "" + SharedWidgetToolTip { + anchors.fill: parent + text: root.text + } +} diff --git a/hosts/dux-shell/ui/BodyTabFoldersSelector.qml b/hosts/dux-shell/ui/BodyTabFoldersSelector.qml new file mode 100644 index 00000000..4f3272ba --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFoldersSelector.qml @@ -0,0 +1,32 @@ +import QtQuick +import qs.Common +import "../models/PanelModel.js" as Model + +SharedWidgetDropdown { + id: root + required property var controller + property bool filtersOpen: false + searchOwner: controller + searchKey: "folderSearch" + totalCount: controller.service ? controller.service.folders.length : 0 + options: controller.folderOptions + value: controller.selectedFolderId + placeholder: controller.folder ? Model.folderName(controller.folder) : "No matching folders" + onSelected: value => controller.selectedFolderId = value + accessory: Component { + Column { + width: parent.width + spacing: Theme.spacingS + SharedWidgetTooltipButton { + iconName: "filter_list" + text: root.filtersOpen ? "Hide filters" : "Filter and sort" + onClicked: root.filtersOpen = !root.filtersOpen + } + BodyTabFoldersViewOptions { + width: parent.width + controller: root.controller + visible: root.filtersOpen + } + } + } +} diff --git a/hosts/dux-shell/ui/BodyTabFoldersShareForm.qml b/hosts/dux-shell/ui/BodyTabFoldersShareForm.qml new file mode 100644 index 00000000..9785070d --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFoldersShareForm.qml @@ -0,0 +1,47 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model + +ColumnLayout { + id: root + required property var controller + property var parentPopout: null + spacing: Theme.spacingS + BodyFormHeader { + Layout.fillWidth: true + title: "Share " + (root.controller.service && root.controller.service.folder(root.controller.draft.folderId) ? Model.folderName(root.controller.service.folder(root.controller.draft.folderId)) : "folder") + enabled: !root.controller.submitting + onCancelled: root.controller.closeForm() + } + StyledText { + text: "Share with devices" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + SharedWidgetMultiSelect { + Layout.fillWidth: true + placeholder: "Local only" + parentPopout: root.parentPopout + options: root.controller.shareableDeviceOptions + selectedValues: root.controller.draft.ids || [] + enabled: !root.controller.busy + onToggled: value => root.controller.toggleDraft(value) + } + StyledText { + Layout.fillWidth: true + text: "Select the devices that should share this folder. Saving an empty selection makes it local only." + wrapMode: Text.WordWrap + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + SharedWidgetBusyButton { + Layout.fillWidth: true + text: "Save sharing" + primary: true + busy: root.controller.submitting + enabled: !!root.controller.service && root.controller.service.online + onClicked: root.controller.submit() + } +} diff --git a/hosts/dux-shell/ui/BodyTabFoldersViewOptions.qml b/hosts/dux-shell/ui/BodyTabFoldersViewOptions.qml new file mode 100644 index 00000000..4170764a --- /dev/null +++ b/hosts/dux-shell/ui/BodyTabFoldersViewOptions.qml @@ -0,0 +1,56 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets + +ColumnLayout { + id: root + required property var controller + GridLayout { + columns: 2 + Layout.fillWidth: true + DToggle { + text: root.controller.groups.length > 0 && root.controller.groups.length < 5 ? "All (mixed)" : "All" + checked: root.controller.groups.length === 5 + onToggled: checked => root.controller.groups = checked ? ["ready", "active", "errors", "paused", "unknown"] : [] + } + Repeater { + model: ["ready", "active", "errors", "paused", "unknown"] + DToggle { + required property string modelData + text: modelData.charAt(0).toUpperCase() + modelData.slice(1) + checked: root.controller.groups.indexOf(modelData) >= 0 + onToggled: root.controller.toggleGroup(modelData) + } + } + } + RowLayout { + Layout.fillWidth: true + Repeater { + model: [ + { + value: "name", + label: "Name" + }, + { + value: "active", + label: "Active first" + }, + { + value: "errors", + label: "Errors first" + } + ] + SharedWidgetTooltipButton { + required property var modelData + text: modelData.label + checked: root.controller.sort === modelData.value + onClicked: root.controller.sort = modelData.value + } + } + } + SharedWidgetTooltipButton { + text: "Reset filters" + onClicked: root.controller.resetFilters() + } +} diff --git a/hosts/dux-shell/ui/FooterActions.qml b/hosts/dux-shell/ui/FooterActions.qml new file mode 100644 index 00000000..b2d0c559 --- /dev/null +++ b/hosts/dux-shell/ui/FooterActions.qml @@ -0,0 +1,80 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.Services +import "UiConstants.js" as UiConstants + +ColumnLayout { + id: root + required property var controller + property string pluginId: "syncshell" + property bool settingsWaiting: false + signal settingsOpening + // DMS owns plugin settings in its own window; the gear opens them there + // instead of Omarchy's in-panel SettingsMenu. + function openSettings() { + settingsOpening(); + settingsWaiting = true; + PopoutService.openSettingsWithTab("plugins"); + finishSettings(); + } + function finishSettings() { + if (settingsWaiting && PopoutService.settingsModal) { + PopoutService.settingsModal.openPluginSettings(pluginId); + settingsWaiting = false; + } + } + spacing: UiConstants.SECTION_SPACING + Connections { + target: PopoutService + function onSettingsModalChanged() { + root.finishSettings(); + } + } + Rectangle { + Layout.fillWidth: true + implicitHeight: Theme.outlineWidth + color: Theme.outlineVariant + } + SharedWidgetTooltipButton { + text: "Web UI" + iconName: "open_in_new" + help: "Open the Syncthing Web UI" + enabled: !!root.controller.service && root.controller.service.online && !root.controller.busy + onClicked: root.controller.service.openWebUi() + } + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingS + // Equal halves: natural widths shift with busy captions and starved + // the rescan label. + SharedWidgetBusyButton { + Layout.fillWidth: true + Layout.preferredWidth: 1 + text: "Rescan all folders" + busyText: "Rescanning..." + iconName: "refresh" + busy: !!root.controller.service && root.controller.service.busy && root.controller.service._actionName === "folder.rescan-all" + enabled: root.controller.fresh && !root.controller.busy && root.controller.service.folders.some(f => !f.paused) + help: !root.controller.fresh ? "Refresh current status before rescanning" : "Rescan all folders for local changes." + onClicked: root.controller.service.rescanAllFolders() + } + SharedWidgetBusyButton { + Layout.fillWidth: true + Layout.preferredWidth: 1 + text: "Refresh Sync.status" + busyText: "Rechecking Syncthing" + iconName: "monitor_heart" + help: "Request latest Syncthing state.\nActive folders with current errors\nrescanned and errors rechecked." + busy: !!root.controller.service && (root.controller.service.refreshing || root.controller.service.busy && root.controller.service._actionName === "folder.recheck-errors") + enabled: !!root.controller.service && !root.controller.busy + // Omarchy rechecks folder errors instead of a plain refresh when any exist. + onClicked: root.controller.service.folderProblemCount > 0 ? root.controller.service.recheckErrors() : root.controller.service.refresh() + } + SharedWidgetSquareActionButton { + iconName: "settings" + help: "Syncshell settings" + onClicked: root.openSettings() + } + } +} diff --git a/hosts/dux-shell/ui/FooterShortcutHint.qml b/hosts/dux-shell/ui/FooterShortcutHint.qml new file mode 100644 index 00000000..31219497 --- /dev/null +++ b/hosts/dux-shell/ui/FooterShortcutHint.qml @@ -0,0 +1,12 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets + +StyledText { + Layout.alignment: Qt.AlignHCenter + horizontalAlignment: Text.AlignHCenter + text: "[r]escan [w]ebUI [p]ause/continue [s]ettings" + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant +} diff --git a/hosts/dux-shell/ui/Header.qml b/hosts/dux-shell/ui/Header.qml new file mode 100644 index 00000000..2889c645 --- /dev/null +++ b/hosts/dux-shell/ui/Header.qml @@ -0,0 +1,132 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model +import "UiConstants.js" as UiConstants + +ColumnLayout { + id: root + required property var controller + property string iconStyle: "themed" + readonly property var service: controller.service + readonly property var totals: Model.totals(service ? service.folders : []) + RowLayout { + Layout.fillWidth: true + SharedWidgetMonoIcon { + size: 36 + variant: Model.statusVariant(root.service) + themed: root.iconStyle === "themed" + opacity: !root.service || !root.service.online || variant === "pause" ? 0.5 : 1 + } + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + StyledText { + text: "Syncthing" + font.pixelSize: Theme.fontSizeMedium + font.weight: Font.Medium + } + RowLayout { + Layout.fillWidth: true + StyledText { + text: root.service ? root.service.deviceName(root.service.localDeviceId) : "Starting" + textFormat: Text.PlainText + wrapMode: Text.NoWrap + Layout.preferredWidth: implicitWidth + Layout.minimumWidth: 0 + elide: Text.ElideRight + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurfaceVariant + } + SharedWidgetIdCopyButton { + value: root.service ? root.service.localDeviceId : "" + caption: "device ID" + helpText: "Copy device ID" + } + } + } + Item { + Layout.fillWidth: true + } + // Omarchy hides the toggle when this host may not control the service. + DToggle { + visible: !!root.service && root.service.canControlService + hideText: true + checked: !!root.service && root.service.lifecycle.active === true + enabled: !!root.service && root.service.canControlService && !root.controller.busy && !root.controller.form && !root.controller.confirmation + onToggled: root.controller.requestServiceToggle(this) + SharedWidgetToolTip { + anchors.fill: parent + text: root.service && root.service.canControlService ? "Start or stop Syncthing without changing autostart" : "Externally managed. Authorize the matching user service in Syncshell settings to control it here." + } + } + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Folders" + value: root.service ? String(root.service.folderCount) : "-" + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Devices" + value: root.controller.fresh ? root.service.connectedDeviceCount + " of " + root.service.deviceCount + " connected" : "Connection unknown" + } + SharedWidgetInfoPair { + Layout.fillWidth: true + label: "Tracked" + value: Model.formatCount(root.totals.files) + " files · " + Model.bytes(root.totals.bytes) + } + StyledText { + Layout.fillWidth: true + text: root.service ? root.service.lastError || (!root.service.online ? root.service.summaryText : "") : "Starting Syncshell" + textFormat: Text.PlainText + wrapMode: Text.WordWrap + elide: Text.ElideNone + visible: text !== "" + color: root.service && root.service.lastError ? Theme.error : Theme.onSurfaceVariant + } + // Omarchy shows an action notice in green for a while, then fades it out + // instead of keeping it in the header. + property string shownNotice: "" + property bool noticeShown: false + Connections { + target: root.service + function onActionNoticeChanged() { + if (!root.service.actionNotice) + return; + root.shownNotice = root.service.actionNotice; + root.noticeShown = true; + noticeFade.stop(); + noticeDisplay.restart(); + } + } + Timer { + id: noticeDisplay + interval: UiConstants.NOTICE_VISIBLE_MS + onTriggered: { + root.noticeShown = false; + noticeFade.restart(); + } + } + Timer { + id: noticeFade + interval: UiConstants.NOTICE_FADE_MS + onTriggered: if (!root.noticeShown) + root.shownNotice = "" + } + StyledText { + Layout.fillWidth: true + visible: root.shownNotice !== "" + text: root.shownNotice + textFormat: Text.PlainText + color: Theme.success + opacity: root.noticeShown ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: root.noticeShown ? 0 : UiConstants.NOTICE_FADE_MS + easing.type: Easing.OutCubic + } + } + } +} diff --git a/hosts/dux-shell/ui/SettingsMenu.qml b/hosts/dux-shell/ui/SettingsMenu.qml new file mode 100644 index 00000000..9f009c00 --- /dev/null +++ b/hosts/dux-shell/ui/SettingsMenu.qml @@ -0,0 +1,195 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets +import qs.Modules.Plugins as Plugins +import "../controllers" + +// DMS shows plugin settings as a page in its settings window, not as +// Omarchy's in-panel SettingsMenu; hence the different file name. +Plugins.PluginSettings { + id: root + property var savedSettings: SettingsData.getPluginSettingsForPlugin(pluginId) + property var host: pluginService ? pluginService.getGlobalVar(pluginId, "host", null) : null + property bool confirmCleanup: false + property SettingsController settings: SettingsController { + pluginId: root.pluginId + pluginService: root.pluginService + pluginData: root.savedSettings + } + property Connections settingsConnections: Connections { + target: root.pluginService + function onPluginDataChanged(id) { + if (id === root.pluginId) + root.savedSettings = SettingsData.getPluginSettingsForPlugin(root.pluginId); + } + function onGlobalVarChanged(id, name) { + if (id === root.pluginId && name === "host") + root.host = root.pluginService.getGlobalVar(id, "host", null); + } + } + + ColumnLayout { + width: parent.width + spacing: Theme.spacingM + StyledText { + Layout.fillWidth: true + text: root.settings.validationError || root.settings.writeError + textFormat: Text.PlainText + visible: text !== "" + color: Theme.error + wrapMode: Text.WordWrap + } + ColumnLayout { + Layout.fillWidth: true + enabled: root.settings.valid + spacing: Theme.spacingM + DDropdown { + Layout.fillWidth: true + text: "Icon" + options: ["Themed", "Branded"] + currentValue: root.settings.values.iconStyle === "themed" ? "Themed" : "Branded" + onValueChanged: value => root.settings.save("iconStyle", value === "Themed" ? "themed" : "branded") + } + DDropdown { + Layout.fillWidth: true + text: "Web UI" + options: ["Syncthing default", "Modern", "DMS theme"] + currentValue: ({ + default: "Syncthing default", + modern: "Modern", + dms: "DMS theme" + })[root.settings.values.webUiTheme] + onValueChanged: value => root.settings.save("webUiTheme", value === "Modern" ? "modern" : value === "DMS theme" ? "dms" : "default") + } + StyledText { + Layout.fillWidth: true + text: root.host ? root.host.theme.error : "Enable the plugin to apply Web UI profiles." + visible: text !== "" + textFormat: Text.PlainText + color: Theme.warning + } + SharedWidgetBusyButton { + text: "Apply Web UI selection" + busy: !!root.host && root.host.theme.busy + enabled: !!root.host && !!root.host.service && root.host.service.online + onClicked: root.host.theme.schedule() + } + RowLayout { + Layout.fillWidth: true + DTextField { + Layout.fillWidth: true + labelText: "Probe interval (seconds)" + text: String(root.settings.values.probeIntervalSeconds) + validator: IntValidator { + bottom: 1 + top: 3600 + } + onEditingFinished: root.settings.save("probeIntervalSeconds", Number(text)) + } + DTextField { + Layout.fillWidth: true + labelText: "Refresh interval (seconds)" + text: String(root.settings.values.refreshIntervalSeconds) + validator: IntValidator { + bottom: 60 + top: 3600 + } + onEditingFinished: root.settings.save("refreshIntervalSeconds", Number(text)) + } + } + StyledText { + Layout.fillWidth: true + text: "Service control is optional. Authorize only the exact user service belonging to this Syncthing instance. The core verifies the match before allowing changes." + wrapMode: Text.WordWrap + color: Theme.onSurfaceVariant + } + DTextField { + Layout.fillWidth: true + labelText: "Systemd user unit" + text: root.settings.values.lifecycleUnit + onEditingFinished: root.settings.save("lifecycleUnit", text) + } + DTextField { + Layout.fillWidth: true + labelText: "Service-bound config path (optional)" + text: root.settings.values.lifecycleConfig + onEditingFinished: root.settings.save("lifecycleConfig", text) + } + DToggle { + Layout.fillWidth: true + text: "Authorize user service control" + description: "Permits the matching service to follow the saved enabled/disabled state." + checked: root.settings.values.lifecycleAuthorized + onToggled: checked => root.settings.save("lifecycleAuthorized", checked) + } + StyledText { + text: "Connection" + font.weight: Font.Medium + } + StyledText { + Layout.fillWidth: true + text: "Leave these fields empty for local discovery. Credentials stay in a private file read by the native core, never in plugin settings. Connection changes restart only the Syncshell worker." + color: Theme.onSurfaceVariant + wrapMode: Text.WordWrap + } + Repeater { + model: [ + { + key: "configPath", + label: "Syncthing config path" + }, + { + key: "endpoint", + label: "API endpoint" + }, + { + key: "credentialFile", + label: "Private credential file path" + }, + { + key: "tlsCertificate", + label: "Pinned TLS certificate path" + }, + { + key: "expectedDeviceId", + label: "Expected device ID" + } + ] + DTextField { + required property var modelData + Layout.fillWidth: true + labelText: modelData.label + text: root.settings.values[modelData.key] + onEditingFinished: root.settings.save(modelData.key, text) + } + } + StyledText { + Layout.fillWidth: true + text: "Before removing Syncshell, restore the default Web UI and remove this adapter's generated profiles. This keeps Syncthing's files, configuration and other adapters' profiles. Then remove Syncshell through DMS's plugin manager." + wrapMode: Text.WordWrap + color: Theme.onSurfaceVariant + } + DButton { + text: "Prepare plugin removal" + enabled: !!root.host && !!root.host.service && root.host.service.online && !root.host.theme.busy + onClicked: root.confirmCleanup = true + } + RowLayout { + visible: root.confirmCleanup + DButton { + text: "Cancel" + onClicked: root.confirmCleanup = false + } + SharedWidgetBusyButton { + text: "Restore default and clean profiles" + busy: !!root.host && root.host.theme.busy + onClicked: { + if (root.host && root.host.theme.cleanup()) + root.confirmCleanup = false; + } + } + } + } + } +} diff --git a/hosts/dux-shell/ui/SharedDialogConfirm.qml b/hosts/dux-shell/ui/SharedDialogConfirm.qml new file mode 100644 index 00000000..37d3aa68 --- /dev/null +++ b/hosts/dux-shell/ui/SharedDialogConfirm.qml @@ -0,0 +1,107 @@ +import QtQuick +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model + +// Omarchy's confirmation: confirm first, equal widths, the safe answer +// preselected. DConfirmDialogContent fixes Cancel first, so this composes +// the same DMS controls in Omarchy's order. +FocusScope { + id: root + property var controller: null + readonly property var request: controller ? controller.confirmation : null + readonly property var target: request ? request.target : ({}) + readonly property string action: request ? request.action : "" + readonly property var text: Model.confirmText(action, target) + // 0 confirms, 1 cancels. + property int selectedButton: 1 + implicitHeight: content.implicitHeight + focus: true + function selectCancel() { + selectedButton = 1; + cancelButton.forceActiveFocus(Qt.TabFocusReason); + } + function activate(button) { + if (!root.controller || root.controller.busy) + return; + if (button === 0) + root.controller.confirm(); + else + root.controller.cancelConfirmation(); + } + Component.onCompleted: selectCancel() + onRequestChanged: selectCancel() + Keys.onPressed: event => { + if (event.isAutoRepeat || controller.busy) { + event.accepted = true; + return; + } + switch (event.key) { + case Qt.Key_Escape: + controller.cancelConfirmation(); + break; + case Qt.Key_Left: + case Qt.Key_Right: + selectedButton = event.key === Qt.Key_Left ? 0 : 1; + (selectedButton === 0 ? confirmButton : cancelButton).forceActiveFocus(Qt.TabFocusReason); + break; + case Qt.Key_Return: + case Qt.Key_Enter: + activate(selectedButton); + break; + default: + return; + } + event.accepted = true; + } + Column { + id: content + width: parent.width + spacing: Theme.spacingL + enabled: !root.controller || !root.controller.busy + StyledText { + width: parent.width + text: root.text.title + textFormat: Text.PlainText + font.pixelSize: Theme.fontSizeLarge + font.weight: Theme.fontWeightMedium + color: Theme.onSurface + wrapMode: Text.Wrap + } + StyledText { + width: parent.width + text: root.text.message + textFormat: Text.PlainText + color: Theme.onSurfaceVariant + wrapMode: Text.Wrap + } + Row { + width: parent.width + spacing: Theme.spacingS + DButton { + id: confirmButton + width: (parent.width - parent.spacing) / 2 + maximumWidth: width + text: root.text.confirm + backgroundColor: root.text.destructive ? Theme.errorContainer : Theme.primary + textColor: root.text.destructive ? Theme.onErrorContainer : Theme.onPrimary + KeyNavigation.tab: cancelButton + onActiveFocusChanged: if (activeFocus) + root.selectedButton = 0 + onClicked: root.activate(0) + } + DButton { + id: cancelButton + width: (parent.width - parent.spacing) / 2 + maximumWidth: width + text: root.text.cancel + backgroundColor: Theme.secondaryContainer + textColor: Theme.onSecondaryContainer + KeyNavigation.tab: confirmButton + onActiveFocusChanged: if (activeFocus) + root.selectedButton = 1 + onClicked: root.activate(1) + } + } + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetBusyButton.qml b/hosts/dux-shell/ui/SharedWidgetBusyButton.qml new file mode 100644 index 00000000..507fcc8d --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetBusyButton.qml @@ -0,0 +1,56 @@ +import QtQuick +import QtQuick.Controls +import qs.Common +import "UiConstants.js" as UiConstants + +// Text action whose width covers both captions, so busy text never resizes it. +FocusScope { + id: root + property string text: "" + property string busyText: "Working" + property string iconName: "" + property bool busy: false + property string help: "" + property bool primary: false + property real controlHeight: UiConstants.CONTROL_HEIGHT + signal clicked + + function activateKey(event) { + if ([Qt.Key_Space, Qt.Key_Return, Qt.Key_Enter].indexOf(event.key) < 0) + return; + event.accepted = true; + if (!event.isAutoRepeat && enabled && !busy) + clicked(); + } + Keys.onPressed: event => activateKey(event) + implicitWidth: Math.max(button.implicitWidth, busyMetrics.advanceWidth + Theme.spacingM * 2 + (iconName ? Theme.fontSizeSmall + 4 + Theme.spacingXS : 0)) + implicitHeight: controlHeight + TextMetrics { + id: busyMetrics + text: root.busyText + font.pixelSize: Theme.fontSizeSmall + } + SharedWidgetTooltipButton { + id: button + focus: true + anchors.fill: parent + controlHeight: root.controlHeight + text: root.busy ? root.busyText : root.text + iconName: root.busy ? "" : root.iconName + help: root.help + primary: root.primary + handlesKeys: false + enabled: root.enabled && !root.busy + onClicked: if (!root.busy) + root.clicked() + } + BusyIndicator { + anchors.right: parent.right + anchors.rightMargin: Theme.spacingXS + anchors.verticalCenter: parent.verticalCenter + width: root.controlHeight * 0.6 + height: width + visible: root.busy + running: root.busy + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetDropdown.qml b/hosts/dux-shell/ui/SharedWidgetDropdown.qml new file mode 100644 index 00000000..3bb76830 --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetDropdown.qml @@ -0,0 +1,293 @@ +import QtQuick +import QtQuick.Layouts +import Quickshell +import qs.Common +import qs.DCommon.Widgets +import "../models/PanelModel.js" as Model +import "UiConstants.js" as UiConstants + +// SharedWidgetMultiSelect wraps the `multiple` mode under Omarchy's name. +Item { + id: root + property var options: [] + property string value: "" + property string placeholder: "Choose" + property string localSearchText: "" + property var searchOwner: null + property string searchKey: "" + readonly property string searchText: searchOwner ? searchOwner[searchKey] : localSearchText + property int totalCount: options.length + property bool multiple: false + property var selectedValues: [] + property var parentPopout: null + property Component accessory: null + property bool opened: false + readonly property var tracker: parentPopout ? parentPopout.transientSurfaceTracker : null + readonly property var filteredOptions: options.filter(function (option) { + return Model.matchesOption(option, root.searchText); + }) + readonly property string displayText: { + if (multiple) + return selectedValues.length ? selectedValues.length + " selected" : placeholder; + for (var index = 0; index < options.length; index++) { + if (options[index].value === value) + return options[index].label; + } + return placeholder; + } + implicitHeight: UiConstants.CONTROL_HEIGHT + implicitWidth: 220 + signal selected(string value) + signal toggled(string value) + + function close() { + if (!opened) + return; + opened = false; + trigger.forceActiveFocus(); + } + + function choose(index) { + var row = filteredOptions[index]; + if (!row) + return; + if (multiple) + toggled(row.value); + else { + selected(row.value); + close(); + } + } + + function focusTrigger() { + trigger.forceActiveFocus(Qt.TabFocusReason); + } + + function open() { + if (opened) { + close(); + return; + } + var host = root.QsWindow.window; + if (!host) + return; + menu.anchor.window = host; + menu.anchor.rect.x = 0; + menu.anchor.rect.y = 0; + menu.anchor.edges = Edges.Top | Edges.Left; + menu.anchor.gravity = Edges.Bottom | Edges.Right; + menu.anchor.adjustment = PopupAdjustment.None; + var point = root.QsWindow.itemPosition(trigger); + // A short host, such as a content-sized side form, would force the + // list over the form; the popup may extend past it to open below. + var listHeight = Math.min(content.implicitHeight + Theme.spacingM * 2, 420); + menu.implicitWidth = Math.max(host.width, point.x + Math.max(root.width, 310)); + menu.implicitHeight = Math.max(host.height, point.y + root.height + listHeight + Theme.spacingS); + menu.originX = point.x; + menu.originY = point.y; + menu.anchor.updateAnchor(); + opened = true; + Qt.callLater(function () { + search.forceActiveFocus(); + }); + } + + onOpenedChanged: if (tracker) + tracker.setActive(root, opened, opened ? menu : null) + Component.onDestruction: if (tracker) + tracker.unregister(root) + Connections { + target: root.tracker + function onCloseRequested() { + root.close(); + } + } + + // Tonal field at Omarchy's control height; a filled DButton made the + // selected label hard to read. + FocusScope { + id: trigger + width: parent.width + height: root.implicitHeight + activeFocusOnTab: root.enabled + Keys.onPressed: event => { + if ([Qt.Key_Space, Qt.Key_Return, Qt.Key_Enter, Qt.Key_Down].indexOf(event.key) < 0) + return; + event.accepted = true; + if (!event.isAutoRepeat && root.enabled) + root.open(); + } + StyledRect { + anchors.fill: parent + radius: Theme.cornerRadiusXS + color: Theme.chipSurface + border.width: root.opened ? Theme.outlineWidthFocused : 0 + border.color: Theme.primary + opacity: root.enabled ? 1 : 0.5 + FocusRing { + visible: trigger.activeFocus + } + RowLayout { + anchors.fill: parent + anchors.leftMargin: Theme.spacingM + anchors.rightMargin: Theme.spacingS + StyledText { + text: root.displayText + textFormat: Text.PlainText + font.pixelSize: Theme.fontSizeSmall + color: Theme.onSurface + wrapMode: Text.NoWrap + elide: Text.ElideRight + Layout.fillWidth: true + } + DIcon { + name: root.opened ? "expand_less" : "expand_more" + size: 16 + color: Theme.onSurfaceVariant + } + } + StateLayer { + anchors.fill: parent + disabled: !root.enabled + onClicked: root.open() + } + } + } + + PopupWindow { + id: menu + property real originX: 0 + property real originY: 0 + visible: root.opened + color: "transparent" + MouseArea { + anchors.fill: parent + onClicked: root.close() + } + StyledRect { + width: Math.min(menu.width, Math.max(root.width, 310)) + height: Math.min(menu.height, content.implicitHeight + Theme.spacingM * 2) + x: Math.max(0, Math.min(menu.width - width, menu.originX)) + y: Math.max(0, Math.min(menu.height - height, menu.originY + root.height + height <= menu.height ? menu.originY + root.height : menu.originY - height)) + color: Theme.floatingSurface + radius: Theme.cornerRadiusM + MouseArea { + anchors.fill: parent + } + Keys.onPressed: event => { + if (event.key === Qt.Key_Escape) { + root.close(); + event.accepted = true; + } + } + ColumnLayout { + id: content + anchors.fill: parent + anchors.margins: Theme.spacingM + spacing: Theme.spacingS + DTextField { + id: search + Layout.fillWidth: true + placeholderText: "Search" + text: root.searchText + onTextEdited: { + if (root.searchOwner) + root.searchOwner[root.searchKey] = text; + else + root.localSearchText = text; + } + Keys.onDownPressed: { + list.currentIndex = 0; + list.forceActiveFocus(); + } + } + StyledText { + Layout.fillWidth: true + text: root.filteredOptions.length + " of " + root.totalCount + " results" + color: Theme.onSurfaceVariant + } + Loader { + Layout.fillWidth: true + sourceComponent: root.accessory + visible: sourceComponent !== null + } + StyledText { + Layout.fillWidth: true + visible: root.filteredOptions.length === 0 + text: "No matching entries" + color: Theme.onSurfaceVariant + } + DListView { + id: list + Layout.fillWidth: true + Layout.fillHeight: true + Layout.preferredHeight: Math.min(300, contentHeight) + clip: true + model: root.filteredOptions + currentIndex: -1 + keyNavigationEnabled: true + Keys.onPressed: event => { + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { + if (!event.isAutoRepeat) + root.choose(currentIndex); + event.accepted = true; + } + } + delegate: StyledRect { + required property var modelData + required property int index + width: list.width + height: row.implicitHeight + Theme.spacingS * 2 + color: ListView.isCurrentItem ? Theme.chipSurface : "transparent" + radius: Theme.cornerRadiusS + RowLayout { + id: row + anchors.fill: parent + anchors.margins: Theme.spacingS + DIcon { + visible: root.multiple + name: root.selectedValues.indexOf(modelData.value) >= 0 ? "check_box" : "check_box_outline_blank" + size: 20 + } + ColumnLayout { + Layout.fillWidth: true + spacing: 2 + StyledText { + text: modelData.label + textFormat: Text.PlainText + Layout.fillWidth: true + wrapMode: Text.NoWrap + } + StyledText { + text: modelData.description || modelData.value + textFormat: Text.PlainText + color: Theme.onSurfaceVariant + font.pixelSize: Theme.fontSizeSmall + Layout.fillWidth: true + wrapMode: Text.NoWrap + elide: Text.ElideMiddle + } + } + StyledText { + text: modelData.status || "" + color: Theme[modelData.statusRole || "onSurfaceVariant"] + font.pixelSize: Theme.fontSizeSmall + textFormat: Text.PlainText + } + } + MouseArea { + anchors.fill: parent + hoverEnabled: true + onEntered: list.currentIndex = index + onClicked: root.choose(index) + } + SharedWidgetToolTip { + anchors.fill: parent + text: modelData.help || "" + } + } + } + } + } + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetIdCopyButton.qml b/hosts/dux-shell/ui/SharedWidgetIdCopyButton.qml new file mode 100644 index 00000000..f1a95628 --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetIdCopyButton.qml @@ -0,0 +1,51 @@ +import QtQuick +import Quickshell.Io +import qs.Common +import "UiConstants.js" as UiConstants + +// Compact "copy ID" chip as in Omarchy: icon plus a short caption, never the +// ID. Without a caption it is the square icon button Omarchy puts beside names. +SharedWidgetTooltipButton { + id: root + property string value: "" + property string caption: "ID" + property string helpText: "Copy ID" + property bool copied: false + property string error: "" + controlHeight: UiConstants.SMALL_CONTROL_HEIGHT + flat: caption !== "" + iconName: copied ? "check" : "content_copy" + text: caption === "" ? "" : copied ? "Copied" : caption + help: error || (copied ? "Copied" : helpText) + enabled: value !== "" && !copy.running + implicitWidth: caption === "" ? controlHeight : Math.max(captionMetrics.advanceWidth, copiedMetrics.advanceWidth) + Theme.fontSizeSmall + 4 + Theme.spacingXS + Theme.spacingM * 2 + TextMetrics { + id: captionMetrics + text: root.caption + font.pixelSize: Theme.fontSizeSmall + } + TextMetrics { + id: copiedMetrics + text: "Copied" + font.pixelSize: Theme.fontSizeSmall + } + onValueChanged: copied = false + onClicked: { + error = ""; + copy.command = ["dms", "cl", "copy", value]; + copy.running = true; + } + Process { + id: copy + onExited: function (code) { + root.copied = code === 0; + root.error = code === 0 ? "" : "Could not copy the ID"; + reset.restart(); + } + } + Timer { + id: reset + interval: UiConstants.COPY_FEEDBACK_MS + onTriggered: root.copied = false + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetInfoPair.qml b/hosts/dux-shell/ui/SharedWidgetInfoPair.qml new file mode 100644 index 00000000..84b24543 --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetInfoPair.qml @@ -0,0 +1,25 @@ +import QtQuick +import QtQuick.Layouts +import qs.Common +import qs.DCommon.Widgets + +RowLayout { + property string label: "" + property string value: "" + property color valueColor: Theme.onSurface + spacing: Theme.spacingS + StyledText { + text: label + color: Theme.onSurfaceVariant + textFormat: Text.PlainText + } + StyledText { + text: value + color: valueColor + textFormat: Text.PlainText + Layout.fillWidth: true + horizontalAlignment: Text.AlignRight + elide: Text.ElideMiddle + wrapMode: Text.NoWrap + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetMonoIcon.qml b/hosts/dux-shell/ui/SharedWidgetMonoIcon.qml new file mode 100644 index 00000000..c0554e13 --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetMonoIcon.qml @@ -0,0 +1,20 @@ +import QtQuick +import qs.Common +import qs.DCommon.Widgets + +// Syncthing status mark: tinted mono asset when themed, full colour when branded. +Item { + id: root + property string variant: "default" + property bool themed: true + property color tint: Theme.onSurface + property int size: 24 + implicitWidth: size + implicitHeight: size + DSVGIcon { + anchors.centerIn: parent + size: root.size + source: Qt.resolvedUrl("../../../assets/" + (root.themed ? "mono/" : "") + "status-" + root.variant + ".svg") + colorOverride: root.themed ? root.tint : "transparent" + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetMultiSelect.qml b/hosts/dux-shell/ui/SharedWidgetMultiSelect.qml new file mode 100644 index 00000000..cb8a85be --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetMultiSelect.qml @@ -0,0 +1,6 @@ +import QtQuick + +// Omarchy's checked multi-select: the shared dropdown in its multiple mode. +SharedWidgetDropdown { + multiple: true +} diff --git a/hosts/dux-shell/ui/SharedWidgetSquareActionButton.qml b/hosts/dux-shell/ui/SharedWidgetSquareActionButton.qml new file mode 100644 index 00000000..4eb7ac80 --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetSquareActionButton.qml @@ -0,0 +1,44 @@ +import QtQuick +import QtQuick.Controls +import "UiConstants.js" as UiConstants + +// Toolbar square action (add, share, link) with a busy state. +FocusScope { + id: root + property string iconName: "" + property string help: "" + property bool busy: false + property bool danger: false + property real size: UiConstants.CONTROL_HEIGHT + signal clicked + + function activateKey(event) { + if ([Qt.Key_Space, Qt.Key_Return, Qt.Key_Enter].indexOf(event.key) < 0) + return; + event.accepted = true; + if (!event.isAutoRepeat && enabled && !busy) + clicked(); + } + Keys.onPressed: event => activateKey(event) + implicitWidth: button.implicitWidth + implicitHeight: button.implicitHeight + SharedWidgetTooltipActionButton { + id: button + focus: true + anchors.fill: parent + size: root.size + iconName: root.busy ? "" : root.iconName + help: root.help + danger: root.danger + handlesKeys: false + enabled: root.enabled && !root.busy + onClicked: root.clicked() + } + BusyIndicator { + anchors.centerIn: parent + width: root.size * 0.7 + height: width + running: root.busy + visible: root.busy + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetToolTip.qml b/hosts/dux-shell/ui/SharedWidgetToolTip.qml new file mode 100644 index 00000000..0243cd1f --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetToolTip.qml @@ -0,0 +1,32 @@ +import QtQuick +import QtQuick.Controls +import qs.Common +import qs.DCommon.Widgets + +Item { + id: root + property string text: "" + HoverHandler { + id: hover + enabled: root.text !== "" + } + ToolTip { + visible: hover.hovered && root.text !== "" + delay: 500 + width: Math.min(360, label.implicitWidth + Theme.spacingM * 2) + padding: Theme.spacingM + contentItem: StyledText { + id: label + text: root.text + textFormat: Text.PlainText + wrapMode: Text.Wrap + elide: Text.ElideNone + maximumLineCount: 14 + color: Theme.inverseOnSurface + } + background: StyledRect { + color: Theme.inverseSurface + radius: Theme.cornerRadiusXS + } + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetTooltipActionButton.qml b/hosts/dux-shell/ui/SharedWidgetTooltipActionButton.qml new file mode 100644 index 00000000..4c88cdcd --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetTooltipActionButton.qml @@ -0,0 +1,51 @@ +import QtQuick +import qs.Common +import qs.DCommon.Widgets +import "UiConstants.js" as UiConstants + +// Icon-only button at Omarchy's control size; DIconButton starts at 40 px. +FocusScope { + id: root + property string iconName: "" + property string help: "" + property bool danger: false + property real size: UiConstants.CONTROL_HEIGHT + property bool handlesKeys: true + signal clicked + + activeFocusOnTab: enabled + implicitWidth: size + implicitHeight: size + Accessible.role: Accessible.Button + Accessible.name: help + Keys.onPressed: event => { + if (!handlesKeys) + return; + if ([Qt.Key_Space, Qt.Key_Return, Qt.Key_Enter].indexOf(event.key) < 0) + return; + event.accepted = true; + if (!event.isAutoRepeat && enabled) + clicked(); + } + StyledRect { + anchors.fill: parent + radius: stateLayer.pressed ? Theme.buttonRadius(width, height, root.size, true, false) : Theme.fullRadius(width, height) + color: root.enabled ? Theme.chipSurface : Theme.onSurface_12 + FocusRing { + visible: root.activeFocus + } + DIcon { + anchors.centerIn: parent + name: root.iconName + size: Math.round(root.size * 0.6) + color: !root.enabled ? Theme.onSurface_38 : root.danger ? Theme.error : Theme.onSurfaceVariant + } + StateLayer { + id: stateLayer + anchors.fill: parent + disabled: !root.enabled + tooltipText: root.help || null + onClicked: root.clicked() + } + } +} diff --git a/hosts/dux-shell/ui/SharedWidgetTooltipButton.qml b/hosts/dux-shell/ui/SharedWidgetTooltipButton.qml new file mode 100644 index 00000000..6b655834 --- /dev/null +++ b/hosts/dux-shell/ui/SharedWidgetTooltipButton.qml @@ -0,0 +1,88 @@ +import QtQuick +import qs.Common +import qs.DCommon.Widgets +import "UiConstants.js" as UiConstants + +// Compact text button at Omarchy's control size. DButton fixes a 14 px label +// and a 32 px minimum, so this keeps DButton's tokens on a smaller control. +// Tonal by default; `primary` marks the emphasized action, `flat` drops the fill. +FocusScope { + id: root + property string text: "" + property string iconName: "" + property string help: "" + property bool primary: false + property bool flat: false + property bool checked: false + property bool leftAlign: false + property real controlHeight: UiConstants.CONTROL_HEIGHT + property real fontSize: Theme.fontSizeSmall + // Wrappers with their own busy rules handle keys themselves. + property bool handlesKeys: true + readonly property color foreground: !enabled ? Theme.onSurface_38 : primary || checked ? Theme.onPrimary : Theme.onSurface + signal clicked + + function activateKey(event) { + if ([Qt.Key_Space, Qt.Key_Return, Qt.Key_Enter].indexOf(event.key) < 0) + return; + event.accepted = true; + if (!event.isAutoRepeat && enabled) + clicked(); + } + activeFocusOnTab: enabled + readonly property real iconRoom: iconName !== "" ? fontSize + 4 + (text !== "" ? Theme.spacingXS : 0) : 0 + implicitWidth: iconRoom + (text !== "" ? label.implicitWidth : 0) + Theme.spacingM * 2 + implicitHeight: controlHeight + Keys.onPressed: event => { + if (handlesKeys) + activateKey(event); + } + Accessible.role: Accessible.Button + Accessible.name: help || text + StyledRect { + id: surface + anchors.fill: parent + radius: Theme.buttonRadius(width, height, root.controlHeight, stateLayer.pressed, !root.flat) + color: !root.enabled && !root.flat ? Theme.onSurface_12 : root.primary || root.checked ? Theme.primary : root.flat ? "transparent" : Theme.chipSurface + FocusRing { + visible: root.activeFocus + } + Row { + id: row + anchors.verticalCenter: parent.verticalCenter + x: root.leftAlign ? Theme.spacingM : (parent.width - width) / 2 + spacing: root.iconName !== "" && root.text !== "" ? Theme.spacingXS : 0 + DIcon { + id: icon + anchors.verticalCenter: parent.verticalCenter + visible: root.iconName !== "" + name: root.iconName + size: root.fontSize + 4 + color: root.foreground + } + // Width from the text and the room left, not from a layout's + // cached hint, so swapped busy captions never stay cut. + StyledText { + id: label + anchors.verticalCenter: parent.verticalCenter + visible: root.text !== "" + width: Math.min(implicitWidth, Math.max(0, surface.width - Theme.spacingM * 2 - root.iconRoom)) + // StyledText wraps by default; a label must elide on one line. + wrapMode: Text.NoWrap + elide: Text.ElideRight + text: root.text + textFormat: Text.PlainText + font.pixelSize: root.fontSize + color: root.foreground + } + } + StateLayer { + id: stateLayer + anchors.fill: parent + disabled: !root.enabled + stateColor: root.foreground + tooltipText: root.help || null + onClicked: root.clicked() + } + } +} diff --git a/hosts/dux-shell/ui/SyncshellPanelPopup.qml b/hosts/dux-shell/ui/SyncshellPanelPopup.qml new file mode 100644 index 00000000..00421cfe --- /dev/null +++ b/hosts/dux-shell/ui/SyncshellPanelPopup.qml @@ -0,0 +1,442 @@ +import QtQuick +import QtQuick.Layouts +import QtQuick.Window +import Quickshell +import Quickshell.Wayland +import qs.Common +import qs.DCommon.Widgets +import qs.Modals.FileBrowser +import "../models/PanelModel.js" as Model +import "UiConstants.js" as UiConstants + +FocusScope { + id: root + required property var controller + property var host: null + property var parentPopout: null + property var closePopout: function () {} + property string pluginId: "syncshell" + property real mainWidth: UiConstants.CONTENT_WIDTH * Math.max(1, Theme.fontScale) + property real sideWidth: 360 * Math.max(1, Theme.fontScale) + property real triggerRowY: 0 + readonly property bool sideOpen: controller.form !== "" + readonly property bool confirming: controller.confirmation !== null + readonly property real screenWidth: parentPopout && parentPopout.screen ? parentPopout.screen.width : 1920 + readonly property real screenHeight: parentPopout && parentPopout.screen ? parentPopout.screen.height : 1080 + readonly property int barPosition: parentPopout ? parentPopout.effectiveBarPosition : 0 + readonly property real usableTop: Theme.spacingL + (barPosition === 0 && parentPopout ? parentPopout.storedBarThickness + parentPopout.storedBarSpacing * 2 : 0) + readonly property real availableHeight: Math.max(140, screenHeight - (barPosition <= 1 && parentPopout ? parentPopout.storedBarThickness + parentPopout.storedBarSpacing * 2 : 0) - Theme.spacingL * 2) + readonly property var sidePlacement: parentPopout ? Model.sideWindowPlacement(screenWidth, screenHeight, { + x: parentPopout.alignedX, + y: parentPopout.alignedY, + width: parentPopout.alignedWidth + }, sideWidth, sideWindow.implicitHeight, PopoutMetrics.contentPadding + triggerRowY, 0, Theme.spacingL, usableTop) : ({ + side: "left", + x: 0, + y: 0 + }) + + implicitHeight: Math.min(availableHeight, mainPane.implicitHeight) + + // Hyprland moves the keyboard past the popout's focus grab only while the + // popout releases it, so it does while a form is open, like DMS's own + // surface modals. The form claims the keyboard with a brief exclusive + // request (exclusive layers also take all pointer input), then stays + // on-demand so the panel and the dismiss catcher keep their clicks. + property bool claimingKeyboard: false + function claimKeyboard() { + releasePopoutKeyboard(); + claimingKeyboard = sideWindow.visible && !confirming; + if (claimingKeyboard) + keyboardClaim.restart(); + } + function releasePopoutKeyboard() { + if (parentPopout) + parentPopout.customKeyboardFocus = sideWindow.visible && !confirming ? WlrKeyboardFocus.None : null; + } + Timer { + id: keyboardClaim + interval: 300 + onTriggered: root.claimingKeyboard = false + } + + function closeInner() { + if (picker.shouldBeVisible) { + picker.close(); + return; + } + if (controller.confirmation) + controller.cancelConfirmation(); + else if (controller.form) + controller.closeForm(); + else + closePopout(); + } + + function restoreFocus() { + if (!parentPopout || !parentPopout.shouldBeVisible) + return; + if (confirming && confirmLoader.item) + confirmLoader.item.selectCancel(); + else if (!sideOpen || !sidePane.focusContent()) + focusSelector(); + } + + // Omarchy starts keyboard navigation at the current tab's selector. + function focusSelector() { + var tab = controller.tab === "folders" ? foldersTab : devicesTab; + if (tab.visible) + tab.focusSelector(); + else + forceActiveFocus(); + } + + function handleKey(event) { + if (event.key === Qt.Key_Escape) { + closeInner(); + event.accepted = true; + return; + } + var item = root.Window.window ? root.Window.window.activeFocusItem : null; + while (item && item !== root) { + if ("cursorPosition" in item) + return; + item = item.parent; + } + if (event.isAutoRepeat || controller.busy || controller.confirmation || controller.form) + return; + var service = controller.service; + switch (event.key) { + case Qt.Key_R: + if (service) + service.rescanAllFolders(); + break; + case Qt.Key_W: + if (service) + service.openWebUi(); + break; + case Qt.Key_P: + controller.requestServiceToggle(null); + break; + case Qt.Key_S: + footerActions.openSettings(); + break; + case Qt.Key_Q: + closeInner(); + break; + default: + return; + } + event.accepted = true; + } + + Keys.onPressed: event => handleKey(event) + onSideOpenChanged: { + if (sideOpen && controller.returnFocus && controller.returnFocus.mapToItem) + triggerRowY = controller.returnFocus.mapToItem(root, 0, 0).y; + } + onConfirmingChanged: { + claimKeyboard(); + Qt.callLater(restoreFocus); + } + Component.onCompleted: forceActiveFocus() + + Connections { + target: root.parentPopout + function onOpened() { + Qt.callLater(root.restoreFocus); + } + function onPopoutClosed() { + root.parentPopout.transientSurfaceTracker.closeAll(); + } + } + Connections { + target: root.controller + function onFocusRequested(target) { + if (target && target.forceActiveFocus) + target.forceActiveFocus(); + else + root.forceActiveFocus(); + } + function onDirectoryPickerRequested() { + picker.open(); + } + } + // The surface modal sits on the overlay layer, above this popout; a plain + // FileBrowserModal is a tiled window that the popout would cover. + FileBrowserSurfaceModal { + id: picker + folderMode: true + browserTitle: "Syncshell folder" + parentPopout: root.parentPopout + onOpened: if (root.parentPopout) + root.parentPopout.transientSurfaceTracker.setActive(picker, true, picker.contentWindow) + onFileSelected: path => root.controller.setDraft("path", path) + onDialogClosed: { + if (root.parentPopout) + root.parentPopout.transientSurfaceTracker.unregister(picker); + // The picker hands the popout its keyboard back; the form reclaims it. + Qt.callLater(root.claimKeyboard); + Qt.callLater(root.restoreFocus); + } + Component.onDestruction: if (root.parentPopout) + root.parentPopout.transientSurfaceTracker.unregister(picker) + } + Connections { + target: root.parentPopout ? root.parentPopout.transientSurfaceTracker : null + function onCloseRequested() { + if (picker.shouldBeVisible) + picker.close(); + } + } + + ColumnLayout { + id: mainPane + width: root.width + height: root.height + spacing: UiConstants.SECTION_SPACING + // The clipped body reaches past the content edges by the focus ring + // room and insets its content by the same amount, so rings show whole + // while everything stays aligned with the footer. + DFlickable { + Layout.fillWidth: true + Layout.fillHeight: true + Layout.leftMargin: -UiConstants.FOCUS_RING_ROOM + Layout.rightMargin: -UiConstants.FOCUS_RING_ROOM + Layout.topMargin: -UiConstants.FOCUS_RING_ROOM + Layout.bottomMargin: -UiConstants.FOCUS_RING_ROOM + Layout.preferredHeight: body.implicitHeight + UiConstants.FOCUS_RING_ROOM * 2 + contentHeight: body.implicitHeight + UiConstants.FOCUS_RING_ROOM * 2 + clip: true + ColumnLayout { + id: body + x: UiConstants.FOCUS_RING_ROOM + y: UiConstants.FOCUS_RING_ROOM + width: parent.width - UiConstants.FOCUS_RING_ROOM * 2 + spacing: UiConstants.SECTION_SPACING + Header { + Layout.fillWidth: true + controller: root.controller + iconStyle: root.host ? root.host.settings.values.iconStyle : "themed" + } + StyledText { + Layout.fillWidth: true + text: root.host ? root.host.error : "" + visible: text !== "" + textFormat: Text.PlainText + color: Theme.error + } + // Header, then a rule, then the body; FooterActions opens with + // the second rule, as in Omarchy's three-part panel. + Rectangle { + Layout.fillWidth: true + implicitHeight: Theme.outlineWidth + color: Theme.outlineVariant + } + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacingS + SharedWidgetTooltipButton { + text: "Folders (" + (root.controller.service ? root.controller.service.folders.length : 0) + ")" + checked: root.controller.tab === "folders" + onClicked: root.controller.tab = "folders" + } + SharedWidgetTooltipButton { + text: "Devices (" + (root.controller.service ? root.controller.service.remoteDevices().length : 0) + ")" + checked: root.controller.tab === "devices" + onClicked: root.controller.tab = "devices" + } + Item { + Layout.fillWidth: true + } + } + // A stack sizes to the taller tab, so switching tabs keeps the + // panel height like Omarchy's. + StackLayout { + Layout.fillWidth: true + currentIndex: root.controller.tab === "folders" ? 0 : 1 + BodyTabFolders { + id: foldersTab + Layout.fillWidth: true + controller: root.controller + parentPopout: root.parentPopout + } + BodyTabDevices { + id: devicesTab + Layout.fillWidth: true + controller: root.controller + parentPopout: root.parentPopout + } + } + BodyMore { + Layout.fillWidth: true + controller: root.controller + } + } + } + ColumnLayout { + id: footer + Layout.fillWidth: true + spacing: UiConstants.SECTION_SPACING + FooterActions { + id: footerActions + Layout.fillWidth: true + controller: root.controller + pluginId: root.pluginId + onSettingsOpening: root.closePopout() + } + FooterShortcutHint { + Layout.fillWidth: true + } + StyledText { + Layout.fillWidth: true + text: root.controller.error + textFormat: Text.PlainText + color: Theme.error + visible: text !== "" + } + } + } + // Omarchy confirms over the dimmed panel rather than in a side form. + Rectangle { + anchors.fill: parent + anchors.margins: -PopoutMetrics.contentPadding + visible: root.confirming + radius: Theme.windowRadius + color: Qt.rgba(0, 0, 0, Theme.scrimAlpha) + MouseArea { + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.AllButtons + } + StyledRect { + anchors.centerIn: parent + width: root.width - Theme.spacingL * 2 + height: confirmLoader.implicitHeight + Theme.spacingL * 2 + radius: Theme.cornerRadiusL + color: Theme.floatingSurfaceHigh + Loader { + id: confirmLoader + active: root.confirming + x: Theme.spacingL + y: Theme.spacingL + width: parent.width - Theme.spacingL * 2 + onLoaded: Qt.callLater(root.restoreFocus) + sourceComponent: SharedDialogConfirm { + controller: root.controller + } + } + } + } + // With the popout's focus grab released for the form, Hyprland dismisses + // nothing on outside clicks; this catcher does, like the popout's own + // background window, leaving the bar, popout and form clickable. + PanelWindow { + id: dismissCatcher + screen: sideWindow.screen + visible: sideWindow.visible + color: "transparent" + anchors { + top: true + bottom: true + left: true + right: true + } + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Top + WlrLayershell.namespace: "dms:plugins:syncshell:dismiss" + WlrLayershell.keyboardFocus: WlrKeyboardFocus.None + mask: Region { + item: catcherArea + Region { + item: barHole + intersection: Intersection.Subtract + } + Region { + item: popoutHole + intersection: Intersection.Subtract + } + Region { + item: formHole + intersection: Intersection.Subtract + } + } + Item { + id: catcherArea + anchors.fill: parent + } + Item { + id: barHole + readonly property real thickness: root.parentPopout ? root.parentPopout.storedBarThickness + root.parentPopout.storedBarSpacing * 2 : 0 + x: root.barPosition === 3 ? parent.width - thickness : 0 + y: root.barPosition === 1 ? parent.height - thickness : 0 + width: root.barPosition >= 2 ? thickness : parent.width + height: root.barPosition >= 2 ? parent.height : thickness + } + Item { + id: popoutHole + x: root.parentPopout ? root.parentPopout.alignedX : 0 + y: root.parentPopout ? root.parentPopout.alignedY : 0 + width: root.parentPopout ? root.parentPopout.alignedWidth : 0 + height: root.parentPopout ? root.parentPopout.alignedHeight : 0 + } + Item { + id: formHole + x: root.sidePlacement.x + y: root.sidePlacement.y + width: sideWindow.implicitWidth + height: sideWindow.implicitHeight + } + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton + onClicked: root.closePopout() + } + } + // DMS paints one popout rectangle at the requested size, so the side form + // gets its own content-sized surface beside it, as Omarchy's does. The + // popout's focus grab admits it as a transient surface. + PanelWindow { + id: sideWindow + screen: root.parentPopout ? root.parentPopout.screen : null + visible: root.sideOpen && !!root.parentPopout && root.parentPopout.shouldBeVisible + color: "transparent" + implicitWidth: root.sideWidth + implicitHeight: Math.min(root.availableHeight, sidePane.implicitHeight) + anchors { + top: true + left: true + } + margins { + top: root.sidePlacement.y + left: root.sidePlacement.x + } + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Top + WlrLayershell.namespace: "dms:plugins:syncshell:form" + WlrLayershell.keyboardFocus: !visible || root.confirming ? WlrKeyboardFocus.None : root.claimingKeyboard ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.OnDemand + onVisibleChanged: { + if (root.parentPopout) + root.parentPopout.transientSurfaceTracker.setActive(sideWindow, visible, visible ? sideWindow : null); + root.claimKeyboard(); + if (visible) + Qt.callLater(root.restoreFocus); + } + Component.onDestruction: if (root.parentPopout) + root.parentPopout.transientSurfaceTracker.unregister(sideWindow) + FocusScope { + anchors.fill: parent + focus: true + Keys.onPressed: event => root.handleKey(event) + BodyFormSideCard { + id: sidePane + anchors.fill: parent + controller: root.controller + parentPopout: root.parentPopout + maximumHeight: root.availableHeight + joinedEdge: root.sidePlacement.side === "left" ? "right" : root.sidePlacement.side === "right" ? "left" : "" + joinedBottom: !!root.parentPopout && root.sidePlacement.y + sideWindow.implicitHeight <= root.parentPopout.alignedY + root.parentPopout.alignedHeight - Theme.windowRadius + } + } + } +} diff --git a/hosts/dux-shell/ui/UiConstants.js b/hosts/dux-shell/ui/UiConstants.js new file mode 100644 index 00000000..49af5064 --- /dev/null +++ b/hosts/dux-shell/ui/UiConstants.js @@ -0,0 +1,13 @@ +.pragma library + +// Control sizes measured from the Omarchy panel at scale 1, in logical px. +var CONTROL_HEIGHT = 28; +var SMALL_CONTROL_HEIGHT = 22; +var CONTENT_WIDTH = 384; +var SECTION_SPACING = 12; +var COPY_FEEDBACK_MS = 1800; +// Room for DMS focus rings (offset 3 + width up to 3) inside clipped views. +var FOCUS_RING_ROOM = 6; +// Omarchy's action notices stay this long, then fade out. +var NOTICE_VISIBLE_MS = 10000; +var NOTICE_FADE_MS = 350; diff --git a/hosts/omarchy/OmarchyPanel.qml b/hosts/omarchy/OmarchyPanel.qml index 7d45340f..ba2bfcfd 100644 --- a/hosts/omarchy/OmarchyPanel.qml +++ b/hosts/omarchy/OmarchyPanel.qml @@ -1,6 +1,7 @@ pragma ComponentBehavior: Bound import QtQuick +import QtQuick.Window import Quickshell import Quickshell.Io import qs.Commons @@ -45,6 +46,10 @@ Panel { property bool folderShowPaused: true property bool folderShowUnknown: true property string folderSortMode: "name" + // A view changed here is saved when its menu or the panel closes; until + // then a settings reload must not undo it. + property bool folderViewDirty: false + property bool applyingSavedFolderView: false property string selectedPendingOffer: "" property string folderConfirmAction: "" property string folderConfirmId: "" @@ -62,7 +67,6 @@ Panel { property bool noticeShown: false readonly property var folderRows: buildFolderRows() readonly property var currentFolderRow: folderById(currentFolderId) - readonly property var visibleFolderRows: currentFolderRow ? [currentFolderRow] : [] readonly property var pendingOfferRows: pendingOfferOptions() readonly property double trackedBytes: folderTotal("globalBytes") readonly property int trackedFiles: folderTotal("globalFiles") @@ -313,6 +317,55 @@ Panel { folderSortMode = "name"; } + function shownFolderGroups() { + var shown = []; + if (folderShowReady) + shown.push("ready"); + if (folderShowActive) + shown.push("active"); + if (folderShowErrors) + shown.push("errors"); + if (folderShowPaused) + shown.push("paused"); + if (folderShowUnknown) + shown.push("unknown"); + return shown; + } + + function applySavedFolderView() { + if (!syncthing || folderViewDirty) + return; + var groups = syncthing.folderFilters || []; + applyingSavedFolderView = true; + folderSortMode = syncthing.folderSort === "active-first" ? "active" : syncthing.folderSort === "errors-first" ? "errors" : "name"; + folderShowReady = groups.indexOf("ready") >= 0; + folderShowActive = groups.indexOf("active") >= 0; + folderShowErrors = groups.indexOf("errors") >= 0; + folderShowPaused = groups.indexOf("paused") >= 0; + folderShowUnknown = groups.indexOf("unknown") >= 0; + applyingSavedFolderView = false; + } + + function persistFolderView() { + if (!syncthing || !folderViewDirty) + return; + var sort = folderSortMode === "active" ? "active-first" : folderSortMode === "errors" ? "errors-first" : "name"; + if (syncthing.setFolderView(sort, shownFolderGroups())) + folderViewDirty = false; + } + + function markFolderViewChanged() { + if (!applyingSavedFolderView) + folderViewDirty = true; + } + + onFolderSortModeChanged: markFolderViewChanged() + onFolderShowReadyChanged: markFolderViewChanged() + onFolderShowActiveChanged: markFolderViewChanged() + onFolderShowErrorsChanged: markFolderViewChanged() + onFolderShowPausedChanged: markFolderViewChanged() + onFolderShowUnknownChanged: markFolderViewChanged() + function folderViewOptions() { var labels = folderOptions(); var options = []; @@ -716,13 +769,19 @@ Panel { Qt.callLater(function () { popup.focusPanel(); }); - } else if (!preserveStateForFolderPicker) { + } else { + persistFolderView(); + } + if (!opened && !preserveStateForFolderPicker) { if (settingsMigrationOpen) syncthing.cancelSettingsMigration(); resetTransientState(); } } - Component.onCompleted: configureService() + Component.onCompleted: { + configureService(); + applySavedFolderView(); + } Timer { id: noticeDisplayTimer @@ -755,6 +814,14 @@ Panel { Connections { target: root.syncthing + function onFolderSortChanged() { + root.applySavedFolderView(); + } + + function onFolderFiltersChanged() { + root.applySavedFolderView(); + } + function onFolderDirectoryRequired(args) { root.addSubmissionPending = false; if (!root.addOpen || !root.opened) @@ -827,31 +894,67 @@ Panel { onTriggered: root.showBarTooltip() } - BarIconButton { + // WidgetButton, not BarIconButton: the host fits the mark's width, which + // includes the side nodes, so its ring would draw smaller than round glyphs. + // Sizing the ring to the theme's icon size keeps it optically level. + WidgetButton { id: button anchors.fill: parent bar: root.bar - iconComponent: Component { - Item { - opacity: root.syncthing && root.syncthing.online ? 1.0 : 0.55 - - // Keep the effect warm under the brand icon for reliable live switches. - MonoIcon { - anchors.fill: parent - source: root.themedIconSource - tint: button.foreground - } + labelVisible: false + hasVisualContent: true + fixedWidth: vertical ? -1 : Style.bar.iconSlot + fixedHeight: vertical ? Style.bar.iconSlot : -1 + + Item { + id: iconBox + // A raster drawn at fractional device pixels is resampled and blurs, + // so size and place it on whole pixels. Qt's Screen ratio is + // integral; the window carries the fractional one. + readonly property real dpr: Window.window ? Window.window.devicePixelRatio : 1 + // The mono view box is 14.5 units; the ring spans 13.31 of them. The + // branded disc shares the box so both styles read the same size. + readonly property real logicalSize: Style.bar.iconSize * 14.5 / 13.31 + property real snapX: 0 + property real snapY: 0 + + function align() { + var p = button.mapToItem(null, (button.width - width) / 2, (button.height - height) / 2); + snapX = Math.round(p.x * dpr) / dpr - p.x; + snapY = Math.round(p.y * dpr) / dpr - p.y; + } - Image { - anchors.fill: parent - source: root.syncthingIconSource - sourceSize.width: width - sourceSize.height: height - fillMode: Image.PreserveAspectFit - smooth: true - visible: !root.themedIcon + width: Math.round(logicalSize * dpr) / dpr + height: width + x: (button.width - width) / 2 + snapX + y: (button.height - height) / 2 + snapY + scale: button.pressScale + opacity: root.syncthing && root.syncthing.online ? 1.0 : 0.55 + + // The bar moves widgets as neighbours resize; re-snap before each frame. + Connections { + target: iconBox.Window.window + function onAfterAnimating() { + iconBox.align(); } } + + // Keep the effect warm under the brand icon for reliable live switches. + SharedWidgetMonoIcon { + anchors.fill: parent + source: root.themedIconSource + tint: button.foreground + } + + Image { + anchors.fill: parent + source: root.syncthingIconSource + sourceSize.width: width + sourceSize.height: height + fillMode: Image.PreserveAspectFit + smooth: true + visible: !root.themedIcon + } } active: root.hasProblems tooltipText: "" @@ -867,7 +970,7 @@ Panel { onPressed: root.toggle() } - SyncthingPanelPopup { + SyncshellPanelPopup { id: popup anchorItem: button controller: root diff --git a/hosts/omarchy/OmarchyService.qml b/hosts/omarchy/OmarchyService.qml index 295f9396..8e2f53f3 100644 --- a/hosts/omarchy/OmarchyService.qml +++ b/hosts/omarchy/OmarchyService.qml @@ -62,6 +62,8 @@ QtObject { property string controlError: "" readonly property string configuredServiceState: settings.serviceState readonly property int probeIntervalSeconds: settings.probeIntervalSeconds + readonly property string folderSort: settings.folderSort + readonly property var folderFilters: settings.folderFilters readonly property string serviceUnitFileState: String(lifecycle.unitFileState || "") readonly property var serviceStateDecision: FacadeModel.driftDecision(configuredServiceState, lifecycle) readonly property bool serviceStateDrift: settingsReady && canControlService && serviceStateDecision.status === "drift" @@ -566,6 +568,10 @@ QtObject { function cancelSettingsMigration() { settings.cancelMigration(); } + + function setFolderView(sort, groups) { + return settings.setFolderView(sort, groups); + } function clearSettingsNotice() { settings.clearNotice(); } diff --git a/hosts/omarchy/config/settings.toml b/hosts/omarchy/config/settings.toml index 6da0dbc5..0853d60c 100644 --- a/hosts/omarchy/config/settings.toml +++ b/hosts/omarchy/config/settings.toml @@ -12,3 +12,12 @@ web_ui_theme = "omarchy" service_state = "enabled" # Seconds between probes for external systemd state changes probe_interval_seconds = 15 + +[view] +# "name": alphabetical by folder name +# "active-first": syncing or scanning folders first +# "errors-first": folders with errors first +folder_sort = "name" +# Folder groups the selector shows: ["all"], or a list of one or more of +# "ready", "active", "errors", "paused", "unknown"; [] shows none +folder_filters = ["all"] diff --git a/hosts/omarchy/controllers/SettingsController.qml b/hosts/omarchy/controllers/SettingsController.qml index 7aae7a8f..00f0d760 100644 --- a/hosts/omarchy/controllers/SettingsController.qml +++ b/hosts/omarchy/controllers/SettingsController.qml @@ -24,6 +24,14 @@ QtObject { property string webUiTheme: SettingsModel.DefaultWebUiTheme property string serviceState: SettingsModel.DefaultServiceState property int probeIntervalSeconds: SettingsModel.DefaultProbeIntervalSeconds + property string folderSort: SettingsModel.DefaultFolderSort + property var folderFilters: SettingsModel.DefaultFolderFilters.slice() + // Latest requested value per kind; writes run one at a time from the + // newest file text. + property var _pendingWrites: ({}) + property var _retryWrite: null + property var _activeWrite: null + property bool _awaitingReload: false property string currentWebUiTheme: "" property string guiAssetsPath: "" property string error: "" @@ -85,6 +93,11 @@ QtObject { migrationOpen = false; if (parsed.error) { _settingsValid = false; + _awaitingReload = false; + if (_retryWrite) { + _retryWrite = null; + busy = false; + } error = _migrationCanceled && migrationRequired ? canceledMessage() : "Settings not applied: " + parsed.error; if (migrationRequired && !_migrationPrompted) { _migrationPrompted = true; @@ -101,14 +114,25 @@ QtObject { webUiTheme = parsed.webUiTheme; serviceState = parsed.serviceState; probeIntervalSeconds = parsed.probeIntervalSeconds; + folderSort = parsed.folderSort; + folderFilters = parsed.folderFilters; _settingsValid = true; error = ""; scheduleReconcile(); + _awaitingReload = false; + var retry = _retryWrite; + _retryWrite = null; + if (retry) + startWrite(retry.kind, retry.value, true); + else + flushWrites(); } function useImplicitDefaults() { var values = SettingsModel.defaults(); settingsExists = false; + _settingsRaw = ""; + _awaitingReload = false; settingsVersion = SettingsModel.SupportedVersion; migrationOpen = false; migration = ({}); @@ -122,8 +146,11 @@ QtObject { webUiTheme = values.webUiTheme; serviceState = values.serviceState; probeIntervalSeconds = values.probeIntervalSeconds; + folderSort = values.folderSort; + folderFilters = values.folderFilters; error = ""; scheduleReconcile(); + flushWrites(); } function openSettings() { @@ -199,14 +226,75 @@ QtObject { var desired = String(state || ""); if (["enabled", "disabled"].indexOf(desired) < 0 || !settingsReady || busy || settingsProcess.running) return false; - _settingsAction = "service-state"; busy = true; error = ""; - settingsProcess.command = ["bash", settingsHelperPath, "set-service-state", settingsTemplatePath, settingsPath, iconStyle, desired]; - settingsProcess.running = true; + queueWrite("service", desired); + return true; + } + + // The view is saved when its menu or the panel closes, not on every click. + function setFolderView(sort, groups) { + if (!settingsReady || SettingsModel.FolderSorts.indexOf(sort) < 0) + return false; + queueWrite("view", { + sort: sort, + groups: groups + }); return true; } + function queueWrite(kind, value) { + var pending = Object.assign({}, _pendingWrites); + pending[kind] = value; + _pendingWrites = pending; + flushWrites(); + } + + function flushWrites() { + if (settingsProcess.running || _awaitingReload || !settingsReady) + return; + var kind = _pendingWrites.service !== undefined ? "service" : _pendingWrites.view !== undefined ? "view" : ""; + if (!kind) + return; + if (!settingsExists) { + // Seed the file first; the write runs once it has been read. + _settingsAction = "ensure-write"; + settingsProcess.command = ["bash", settingsHelperPath, "ensure", settingsTemplatePath, settingsPath, iconStyle]; + settingsProcess.running = true; + return; + } + var pending = Object.assign({}, _pendingWrites); + var value = pending[kind]; + delete pending[kind]; + _pendingWrites = pending; + startWrite(kind, value, false); + } + + function startWrite(kind, value, retried) { + var template = templateFile.text(); + var result = kind === "service" ? SettingsModel.withServiceState(_settingsRaw, value, template) : SettingsModel.withView(_settingsRaw, value.sort, value.groups, template); + if (result.error || result.text === _settingsRaw) { + if (result.error) + error = "Settings not saved: " + result.error; + if (kind === "service") + busy = false; + flushWrites(); + return; + } + _activeWrite = { + kind: kind, + value: value, + retried: retried + }; + _settingsInput = JSON.stringify({ + original: _settingsRaw, + replacement: result.text + }); + _settingsAction = kind === "service" ? "service-state" : "view"; + settingsProcess.command = ["bash", settingsHelperPath, "replace", settingsPath]; + settingsProcess.running = true; + } + function clearNotice() { notice = ""; } @@ -344,6 +432,7 @@ QtObject { printErrors: false onLoaded: root.loadSettings(text()) onLoadFailed: function (fileError) { + root._awaitingReload = false; if (fileError === FileViewError.FileNotFound) root.useImplicitDefaults(); else { @@ -355,6 +444,13 @@ QtObject { onFileChanged: reload() } + // Missing sections are copied from the template, comments included. + property FileView templateFile: FileView { + path: root.settingsTemplatePath + blockLoading: true + printErrors: false + } + property Process backupLocationProcess: Process { command: ["realpath", "-e", root.settingsPath] stdout: StdioCollector { @@ -373,14 +469,30 @@ QtObject { id: settingsErrors } onStarted: { - if (root._settingsAction === "migrate") + if (["migrate", "service-state", "view"].indexOf(root._settingsAction) >= 0) write(root._settingsInput + "\n"); root._settingsInput = ""; } onExited: function (exitCode) { var action = root._settingsAction; - root.busy = false; + var write = root._activeWrite; + root._activeWrite = null; + if (exitCode === 3 && write && !write.retried) { + // The file changed since it was read: reread it and try once more. + root._retryWrite = write; + root._awaitingReload = true; + root._settingsAction = ""; + root.settingsFile.reload(); + return; + } + if (action === "ensure-write" && exitCode !== 0) { + // Without a file there is nothing to write into; drop the queue. + root._pendingWrites = ({}); + } + if (action !== "view" && !(action === "ensure-write" && exitCode === 0)) + root.busy = false; if (exitCode === 0) { + root._awaitingReload = true; root.settingsFile.reload(); if (root._openAfterEnsure) { Quickshell.execDetached(["omarchy", "launch", "config-editor", root.settingsPath]); @@ -392,6 +504,8 @@ QtObject { } else if (action === "compare") { root.notice = "Save your settings to recheck them. " + "The temporary template is only a reference."; } + } else if (action === "view") { + root.error = settingsErrors.text.trim() || "Could not save the folder view"; } else { root.error = settingsErrors.text.trim() || (action === "service-state" ? "Could not update Syncthing service preference" : "Could not prepare Syncthing plugin settings"); if (action === "migrate" || action === "compare") @@ -399,6 +513,8 @@ QtObject { } root._openAfterEnsure = false; root._settingsAction = ""; + if (exitCode !== 0) + root.flushWrites(); } } diff --git a/hosts/omarchy/models/SettingsModel.js b/hosts/omarchy/models/SettingsModel.js index fffcfdad..87fc8357 100644 --- a/hosts/omarchy/models/SettingsModel.js +++ b/hosts/omarchy/models/SettingsModel.js @@ -7,6 +7,10 @@ var DefaultProbeIntervalSeconds = 15; var MinimumProbeIntervalSeconds = 1; var MaximumProbeIntervalSeconds = 3600; var SupportedVersion = 2; +var FolderSorts = ["name", "active-first", "errors-first"]; +var FolderGroups = ["ready", "active", "errors", "paused", "unknown"]; +var DefaultFolderSort = "name"; +var DefaultFolderFilters = FolderGroups.slice(); function stripComment(line) { var quote = ""; @@ -29,6 +33,37 @@ function parseValue(raw) { return match ? match[2] : null; } +// A quoted value or a one-line list of them; "ready" and ["ready"] are the same. +function parseList(raw) { + var value = String(raw || "").trim(); + var single = parseValue(value); + if (single !== null) + return [single]; + if (!/^\[(\s*(["'])[^"']*\2\s*,)*(\s*(["'])[^"']*\4\s*)?,?\s*\]$/.test(value)) + return null; + var items = []; + var item = /(["'])([^"']*)\1/g; + var found; + while ((found = item.exec(value)) !== null) + items.push(found[2]); + return items; +} + +// "all" anywhere in the list, or every group named, shows every group. +function folderGroups(items) { + if (items.indexOf("all") >= 0) + return FolderGroups.slice(); + return FolderGroups.filter(group => items.indexOf(group) >= 0); +} + +// The plugin always writes a list: ["all"], ["ready"], ["ready", "errors"] or []. +function formatFolderFilters(groups) { + var shown = FolderGroups.filter(group => (groups || []).indexOf(group) >= 0); + if (shown.length === FolderGroups.length) + return '["all"]'; + return "[" + shown.map(group => '"' + group + '"').join(", ") + "]"; +} + function parseInteger(raw) { var value = String(raw || "").trim(); return /^(0|[1-9][0-9]*)$/.test(value) ? Number(value) : null; @@ -47,6 +82,7 @@ function parse(raw, allowOlder) { } var styleSectionSeen = false; var serviceSectionSeen = false; + var viewSectionSeen = false; var rootStyleSetting = false; for (let i = 0; i < lines.length; i++) { @@ -56,16 +92,18 @@ function parse(raw, allowOlder) { let header = line.match(/^\[([A-Za-z_][A-Za-z0-9_-]*)\]$/); if (header) { section = header[1]; - if (section !== "style" && section !== "service") { + if (section !== "style" && section !== "service" && section !== "view") { return invalid("Unknown settings section " + section + " on line " + (i + 1)); } - if ((section === "style" && styleSectionSeen) || (section === "service" && serviceSectionSeen)) { + if ((section === "style" && styleSectionSeen) || (section === "service" && serviceSectionSeen) || (section === "view" && viewSectionSeen)) { return invalid("Duplicate settings section " + section + " on line " + (i + 1)); } if (section === "style") styleSectionSeen = true; else if (section === "service") serviceSectionSeen = true; + else + viewSectionSeen = true; continue; } let assignment = line.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(.+)$/); @@ -85,7 +123,8 @@ function parse(raw, allowOlder) { } let styleSetting = key === "icon_style" || key === "web_ui_theme"; let serviceSetting = key === "service_state" || key === "probe_interval_seconds"; - if ((section === "service" && !serviceSetting) || (section !== "service" && !styleSetting)) { + let viewSetting = key === "folder_sort" || key === "folder_filters"; + if ((section === "service" && !serviceSetting) || (section === "view" && !viewSetting) || (section !== "service" && section !== "view" && !styleSetting)) { return invalid("Unknown setting " + (section ? section + "." : "") + key + " on line " + (i + 1)); } if (!section && styleSetting) @@ -99,6 +138,14 @@ function parse(raw, allowOlder) { return invalid("probe_interval_seconds must be an integer between " + MinimumProbeIntervalSeconds + " and " + MaximumProbeIntervalSeconds); } values[key] = interval; + } else if (key === "folder_filters") { + let items = parseList(assignment[2]); + if (items === null) + return invalid("folder_filters must be a quoted value or a list of them on one line"); + let unknown = items.filter(item => item !== "all" && FolderGroups.indexOf(item) < 0); + if (unknown.length) + return invalid("folder_filters accepts all, " + FolderGroups.join(", ") + "; not " + unknown.join(", ")); + values[key] = folderGroups(items); } else { let value = parseValue(assignment[2]); if (value === null) { @@ -143,6 +190,14 @@ function parse(raw, allowOlder) { if (values.probe_interval_seconds === undefined) { values.probe_interval_seconds = sourceVersion < 2 ? 15 : DefaultProbeIntervalSeconds; } + // [view] is optional: files written before it keep working with the defaults. + if (values.folder_sort === undefined) + values.folder_sort = DefaultFolderSort; + if (FolderSorts.indexOf(values.folder_sort) < 0) { + return invalid("folder_sort must be " + FolderSorts.join(", ").replace(/, ([^,]*)$/, ", or $1")); + } + if (values.folder_filters === undefined) + values.folder_filters = DefaultFolderFilters.slice(); return { error: "", @@ -150,7 +205,9 @@ function parse(raw, allowOlder) { iconStyle: values.icon_style, webUiTheme: values.web_ui_theme, serviceState: values.service_state, - probeIntervalSeconds: values.probe_interval_seconds + probeIntervalSeconds: values.probe_interval_seconds, + folderSort: values.folder_sort, + folderFilters: values.folder_filters }; } @@ -188,7 +245,7 @@ function migrate(raw) { raw.split(/\r?\n/).forEach(function (line) { var code = stripComment(line).trim(); - if (code === "[style]" || code === "[service]") { + if (code === "[style]" || code === "[service]" || code === "[view]") { if (inService) addServiceDefaults(); inService = code === "[service]"; @@ -226,11 +283,139 @@ function migrate(raw) { }; } +// The lines of one [section] in a template, comments included, without the +// blank lines that separate it from the next section. +function templateSection(templateRaw, section) { + var lines = String(templateRaw || "").split(/\r?\n/); + var block = []; + var inside = false; + for (let i = 0; i < lines.length; i++) { + let header = stripComment(lines[i]).trim().match(/^\[([^\]]+)\]$/); + if (header) { + if (inside) + break; + inside = header[1] === section; + } + if (inside) + block.push(lines[i]); + } + while (block.length && !block[block.length - 1].trim()) + block.pop(); + return block; +} + +// Rewrites only the values of `entries` ([key, formatted value] pairs) inside +// [section], so comments, spacing, key order and line endings survive a save. +function editSection(raw, section, entries, templateRaw) { + var text = String(raw || ""); + var newline = text.indexOf("\r\n") >= 0 ? "\r\n" : "\n"; + var lines = text.length ? text.split(/\r?\n/) : []; + var finalNewline = !text.length || /\n$/.test(text); + if (finalNewline && lines.length) + lines.pop(); + var keys = entries.map(entry => entry[0]); + var values = ({}); + entries.forEach(entry => values[entry[0]] = entry[1]); + + function edit(block, start, end) { + var seen = ({}); + var last = start; + for (let i = start; i < end; i++) { + let code = stripComment(block[i]); + if (code.trim()) + last = i + 1; + let assignment = code.match(/^(\s*([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*)(.*?)(\s*)$/); + if (!assignment || keys.indexOf(assignment[2]) < 0) + continue; + block[i] = assignment[1] + values[assignment[2]] + assignment[4] + block[i].slice(code.length); + seen[assignment[2]] = true; + } + var missing = keys.filter(key => !seen[key]).map(key => key + " = " + values[key]); + block.splice.apply(block, [last, 0].concat(missing)); + } + + var start = -1; + var end = lines.length; + for (let i = 0; i < lines.length; i++) { + let header = stripComment(lines[i]).trim().match(/^\[([^\]]+)\]$/); + if (!header) + continue; + if (start >= 0) { + end = i; + break; + } + if (header[1] === section) + start = i + 1; + } + if (start >= 0) { + edit(lines, start, end); + } else { + // A missing section comes from the template, comments included. + let block = templateSection(templateRaw, section); + if (!block.length) + block = ["[" + section + "]"]; + edit(block, 1, block.length); + while (lines.length && !lines[lines.length - 1].trim()) + lines.pop(); + if (lines.length) + lines.push(""); + lines = lines.concat(block); + } + var result = lines.join(newline); + return finalNewline ? result + newline : result; +} + +// Returns the complete new file, or an error; a file that does not parse is +// never rewritten, and neither is a result that would not parse back. +function rewrite(raw, section, entries, templateRaw, expect) { + var current = parse(raw); + if (current.error) + return { + error: current.error + }; + var text = editSection(raw, section, entries, templateRaw); + var checked = parse(text); + if (checked.error) + return { + error: checked.error + }; + if (!expect(checked)) + return { + error: "Could not update " + section + " settings safely" + }; + return { + error: "", + text: text, + values: checked + }; +} + +function withServiceState(raw, state, templateRaw) { + if (["enabled", "disabled"].indexOf(state) < 0) + return { + error: "service_state must be enabled or disabled" + }; + return rewrite(raw, "service", [["service_state", '"' + state + '"']], templateRaw, checked => checked.serviceState === state); +} + +function withView(raw, sort, groups, templateRaw) { + if (FolderSorts.indexOf(sort) < 0) + return { + error: "folder_sort must be " + FolderSorts.join(", ") + }; + var filters = formatFolderFilters(groups); + return rewrite(raw, "view", [["folder_sort", '"' + sort + '"'], ["folder_filters", filters]], templateRaw, function (checked) { + return checked.folderSort === sort && formatFolderFilters(checked.folderFilters) === filters; + }); +} + function defaults() { return { iconStyle: DefaultIconStyle, webUiTheme: DefaultWebUiTheme, serviceState: DefaultServiceState, - probeIntervalSeconds: DefaultProbeIntervalSeconds + probeIntervalSeconds: DefaultProbeIntervalSeconds, + folderSort: DefaultFolderSort, + folderFilters: DefaultFolderFilters.slice() }; } diff --git a/hosts/omarchy/scripts/syncthing-install.sh b/hosts/omarchy/scripts/syncthing-install.sh index 84b4c0b8..1fdecadb 100755 --- a/hosts/omarchy/scripts/syncthing-install.sh +++ b/hosts/omarchy/scripts/syncthing-install.sh @@ -81,6 +81,11 @@ ensure_initial_install() { install_package() { ensure_initial_install require_command omarchy + # A fresh offline Omarchy install has no sync databases until its first + # update, and pacman then only says "target not found". + pacman -Si syncthing >/dev/null 2>&1 || fail \ + "Arch package lists are missing or outdated." \ + "Run Omarchy's Update first (omarchy update), then install again." step "Installing the official Arch package through Omarchy" omarchy pkg add syncthing diff --git a/hosts/omarchy/scripts/syncthing-settings.sh b/hosts/omarchy/scripts/syncthing-settings.sh index 508acab3..e8f0ec42 100755 --- a/hosts/omarchy/scripts/syncthing-settings.sh +++ b/hosts/omarchy/scripts/syncthing-settings.sh @@ -14,7 +14,7 @@ trap cleanup EXIT usage() { printf '%s\n' \ 'Usage: syncthing-settings.sh ensure
" + root.escapeStyled(folder.label) + " (folder ID: " + root.escapeStyled(folder.id) + ")?

Syncthing will resume synchronization for this folder."; if (root.controller.folderConfirmAction === "unlink") - return "Unlink " + folder.label + " (" + folder.id + ")?\n\nSyncthing will pause synchronization. Its configuration " + "and local files remain."; - return "Forget " + folder.label + " (" + folder.id + ")?\n\n" + "This removes only its Syncthing configuration. The " + "directory and data files will not be deleted. " + (folder.markerName === ".stfolder" ? "Syncthing will also attempt to remove its internal " + ".stfolder marker. " : "") + "Rejoining the same remote folder requires this exact " + "Folder ID."; + return "Unlink folder: " + root.escapeStyled(folder.label) + " (folder ID: " + root.escapeStyled(folder.id) + ")?

Syncthing will pause synchronization. Its configuration " + "and local files remain."; + return "Forget folder: " + root.escapeStyled(folder.label) + " (folder ID: " + root.escapeStyled(folder.id) + ")?

" + "This removes only its Syncthing configuration. The " + "directory and data files will not be deleted. " + (folder.markerName === ".stfolder" ? "Syncthing will also attempt to remove its internal " + ".stfolder marker. " : "") + "Rejoining the same remote folder requires this exact " + "Folder ID."; } + messageFormat: ["link", "unlink", "forget"].indexOf(root.controller.folderConfirmAction) >= 0 ? Text.StyledText : Text.PlainText confirmText: root.controller.folderConfirmAction === "create" ? "Create and add" : "Yes" cancelText: root.controller.folderConfirmAction === "create" ? "Cancel" : "No" background: Commons.Color.popups.background @@ -686,7 +541,7 @@ KeyboardPanel { onConfirmed: root.controller.confirmFolderAction() } - CompactConfirmDialog { + SharedDialogConfirm { id: deviceConfirmDialog implicitWidth: Style.space(root.controller.deviceConfirmAction === "remove" ? 320 : 390) parent: keyCatcher @@ -706,7 +561,7 @@ KeyboardPanel { onConfirmed: root.controller.confirmDeviceAction() } - SelfRemovalDialog { + SettingsSelfRemovalDialog { id: removalDialog parent: keyCatcher anchors.fill: parent diff --git a/install.sh b/install.sh index cf30d08e..c8cdb04c 100755 --- a/install.sh +++ b/install.sh @@ -83,7 +83,7 @@ wait_dms_plugin() { } configure_dms_widget() { - local settings="$HOME/.config/DankMaterialShell/settings.json" + local settings="$HOME/.config/dms/settings.json" local position result temporary if [[ ! -s $settings ]]; then @@ -100,7 +100,7 @@ configure_dms_widget() { done fi [[ -s $settings ]] - temporary=$(mktemp "$HOME/.config/DankMaterialShell/.settings.XXXXXX") + temporary=$(mktemp "$HOME/.config/dms/.settings.XXXXXX") jq ' .barConfigs = ((.barConfigs // []) | map( if .id == "default" then @@ -113,13 +113,13 @@ configure_dms_widget() { install_dms() { local assembled="$work/Syncshell" - local target="$HOME/.config/DankMaterialShell/plugins/Syncshell" + local target="$HOME/.config/dms/plugins/Syncshell" local backup for command_name in dms jq; do require_command "$command_name" done - bash "$repo_root/integrations/dankmaterialshell/assemble.sh" "$assembled" + bash "$repo_root/integrations/dux-shell/assemble.sh" "$assembled" mkdir -p -- "$(dirname -- "$target")" "$state_root/backups" if [[ -e $target ]]; then backup="$state_root/backups/dms-$(date -u +%Y%m%dT%H%M%SZ)" @@ -177,24 +177,13 @@ install_ii() { } install_caelestia() { - local checkout="$work/caelestia" - readonly caelestia_commit=1d0e5a588c61f1d905eba5fe8446ec222d37f50c - - for command_name in cmake git ninja patch; do - require_command "$command_name" - done - clone_pinned https://github.com/caelestia-dots/shell.git \ - "$caelestia_commit" "$checkout" - bash "$repo_root/integrations/caelestia/apply.sh" "$checkout" - cmake -S "$checkout" -B "$checkout/build" -G Ninja \ - -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/ -DVERSION=2.3.0 \ - -DGIT_REVISION="$caelestia_commit" \ - -DINSTALL_QSCONFDIR="$HOME/.config/quickshell/caelestia" - cmake --build "$checkout/build" - sudo cmake --install "$checkout/build" - sudo chown -R "$(id -u):$(id -g)" \ - "$HOME/.config/quickshell/caelestia" - restart_vm_shell + local target="${XDG_DATA_HOME:-$HOME/.local/share}/caelestia/plugins/syncshell" + [[ ! -e $target && ! -L $target ]] || { + printf 'plugin target already exists: %s\n' "$target" >&2 + return 1 + } + bash "$repo_root/integrations/caelestia/assemble.sh" "$target" + printf 'Enable syncshell/syncshell in Caelestia plugins and add the syncshell bar entry\n' } install_waybar() { diff --git a/integrations/assemble-qml.mjs b/integrations/assemble-qml.mjs new file mode 100644 index 00000000..8a35caed --- /dev/null +++ b/integrations/assemble-qml.mjs @@ -0,0 +1,31 @@ +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, relative, resolve, sep } from "node:path"; + +const [packageRoot, fileList, importMapPath] = process.argv.slice(2); +if (!packageRoot || !fileList || !importMapPath) + throw Error("usage: assemble-qml.mjs PACKAGE FILE_LIST IMPORT_MAP"); +const root = resolve(packageRoot); +const imports = JSON.parse(readFileSync(importMapPath, "utf8")); +const files = readFileSync(fileList, "utf8").trim().split("\n"); + +for (const file of files) { + const path = resolve(root, file); + if (relative(root, path).startsWith(`..${sep}`)) + throw Error(`package path escapes root: ${file}`); + const text = readFileSync(path, "utf8"); + const mapped = text.replace(/^(\s*\.?import\s+)("[^"\n]+"|[\w.]+)/gm, + (line, prefix, source) => { + const mapping = imports[dirname(file)] || imports; + if (!Object.hasOwn(mapping, source)) + throw Error(`unmapped import in ${file}: ${source}`); + const target = mapping[source]; + if (target.startsWith('"')) { + const imported = resolve(dirname(path), JSON.parse(target)); + if (relative(root, imported).startsWith(`..${sep}`) || !existsSync(imported)) + throw Error(`missing or escaped packaged import in ${file}: ${target}`); + } + return prefix + target; + }); + if (mapped !== text) + writeFileSync(path, mapped); +} diff --git a/integrations/caelestia/Settings.qml b/integrations/caelestia/Settings.qml new file mode 100644 index 00000000..aa9a970f --- /dev/null +++ b/integrations/caelestia/Settings.qml @@ -0,0 +1,17 @@ +import Caelestia.Plugins + +SettingsObject { + property int schemaVersion: 1 + property string icon: "themed" + property int probeSeconds: 15 + property int refreshSeconds: 60 + property string webUiStyle: "default" + property bool lifecycleAuthorized: false + property string lifecycleUnit: "syncthing.service" + property string lifecycleConfig: "" + property string configPath: "" + property string endpoint: "" + property string credentialFile: "" + property string tlsCertificate: "" + property string expectedDeviceId: "" +} diff --git a/integrations/caelestia/apply.sh b/integrations/caelestia/apply.sh deleted file mode 100755 index c6cb4c3c..00000000 --- a/integrations/caelestia/apply.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash -set -euo pipefail - -readonly expected_commit=1d0e5a588c61f1d905eba5fe8446ec222d37f50c -integration_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) -repo_root=$(cd -- "$integration_root/../.." && pwd) -target=${1:-} - -[[ -n $target && -d $target/.git ]] || { - printf 'usage: %s CAELESTIA_CHECKOUT\n' "$0" >&2 - exit 2 -} -[[ $(git -C "$target" rev-parse HEAD) == "$expected_commit" ]] \ - || { printf 'Caelestia checkout has the wrong commit\n' >&2; exit 1; } -[[ -z $(git -C "$target" status --porcelain) ]] \ - || { printf 'Caelestia checkout must be clean\n' >&2; exit 1; } - -patch --dry-run --silent -d "$target" -p1 <"$integration_root/overlay.patch" -patch --silent -d "$target" -p1 <"$integration_root/overlay.patch" -install -d -- "$target/syncshell/shared" \ - "$target/syncshell/bin/x86_64" "$target/syncshell/bin/aarch64" -install -m 0644 -- "$repo_root/shared/CoreProcess.qml" \ - "$repo_root/shared/AdapterService.qml" \ - "$repo_root/shared/DeviceWorkflow.qml" \ - "$repo_root/shared/RescanTracker.qml" \ - "$repo_root/shared/Paths.js" "$target/syncshell/shared/" -install -m 0755 -- "$repo_root/bin/syncshell-core" \ - "$target/syncshell/bin/syncshell-core" -install -m 0755 -- "$repo_root/bin/x86_64/syncshell-core" \ - "$target/syncshell/bin/x86_64/syncshell-core" -install -m 0755 -- "$repo_root/bin/aarch64/syncshell-core" \ - "$target/syncshell/bin/aarch64/syncshell-core" -install -m 0644 -- "$integration_root/files/SyncshellService.qml.in" \ - "$target/services/Syncshell.qml" -install -m 0644 -- "$integration_root/files/SyncshellStatus.qml.in" \ - "$target/modules/bar/components/status/SyncshellStatus.qml" -install -m 0644 -- "$integration_root/files/SyncshellPopout.qml.in" \ - "$target/modules/bar/popouts/SyncshellPopout.qml" -(cd -- "$repo_root" && \ - sha256sum --check packaging/bundled/SHA256SUMS >/dev/null) -printf '[ok] applied Caelestia adapter\n' diff --git a/integrations/caelestia/assemble.sh b/integrations/caelestia/assemble.sh new file mode 100755 index 00000000..98723320 --- /dev/null +++ b/integrations/caelestia/assemble.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +target=${1:-"$root/dist/caelestia"} +[[ $target == /* ]] || { printf 'target must be absolute\n' >&2; exit 2; } +mkdir -p -- "$target" +[[ -z $(find "$target" -mindepth 1 -maxdepth 1 -print -quit) ]] || { + printf 'target must be empty\n' >&2; exit 1; +} +(cd -- "$root" && sha256sum --check packaging/bundled/SHA256SUMS >/dev/null) +while IFS= read -r file; do + install -Dm644 -- "$root/$file" "$target/$file" +done < "$root/integrations/caelestia/qml-files.txt" +node "$root/integrations/assemble-qml.mjs" "$target" \ + "$root/integrations/caelestia/qml-files.txt" \ + "$root/integrations/caelestia/import-map.json" +install -Dm644 -- "$root/integrations/caelestia/manifest.json" "$target/manifest.json" +for file in syncshell-core x86_64/syncshell-core aarch64/syncshell-core; do + install -Dm755 -- "$root/bin/$file" "$target/bin/$file" +done +cp -a -- "$root/webui" "$target/webui" +for variant in default notify pause sync; do + install -Dm644 -- "$root/assets/status-$variant.svg" "$target/assets/status-$variant.svg" + install -Dm644 -- "$root/assets/mono/status-$variant.svg" "$target/assets/mono/status-$variant.svg" +done +install -Dm644 -- "$root/assets/LICENSE.md" "$target/assets/LICENSE.md" +install -m644 -- "$root/LICENSE" "$root/CHANGELOG.md" "$target/" +install -m644 -- "$root/hosts/caelestia/README.md" "$target/README.md" +printf '%s\n' 'caelestia-shell 4e288c54a3b039154d19fe8a2064a174eb634405' \ + "syncshell-base $(git -C "$root" rev-parse HEAD)" > "$target/PROVENANCE" +(cd -- "$target" && find . -type f ! -name SHA256SUMS -print0 | LC_ALL=C sort -z | xargs -0 sha256sum > SHA256SUMS) +printf '[ok] assembled Caelestia plugin at %s\n' "$target" diff --git a/integrations/caelestia/files/SyncshellPopout.qml.in b/integrations/caelestia/files/SyncshellPopout.qml.in deleted file mode 100644 index acdeda6d..00000000 --- a/integrations/caelestia/files/SyncshellPopout.qml.in +++ /dev/null @@ -1,569 +0,0 @@ -pragma ComponentBehavior: Bound - -import QtQuick -import QtQuick.Layouts -import Caelestia.Config -import qs.components -import qs.components as Components -import qs.components.controls -import qs.components.controls as Controls -import qs.services -import "../../../syncshell/shared" - -ColumnLayout { - id: root - - component StyledText: Components.StyledText { - textFormat: Text.PlainText - } - - component TextButton: Controls.TextButton { - label.textFormat: Text.PlainText - } - implicitWidth: 420 - spacing: Tokens.spacing.medium - property bool moreOpen: false - property bool addOpen: false - property string pendingForgetId: "" - property string pendingForgetLabel: "" - property DeviceWorkflow deviceFlow: DeviceWorkflow { service: Syncshell } - - function requestForget(folder) { - pendingForgetId = String(folder.id || "") - pendingForgetLabel = String(folder.label || folder.id || "folder") - } - - function confirmForget() { - if (pendingForgetId === "") return - if (Syncshell.forgetFolder(pendingForgetId)) pendingForgetId = "" - } - - Keys.onPressed: function(event) { - if (event.key === Qt.Key_Escape && pendingForgetId !== "") { - pendingForgetId = "" - event.accepted = true - } else if (event.key === Qt.Key_Escape && deviceFlow.view !== "") { - deviceFlow.close() - event.accepted = true - } else { - event.accepted = false - } - } - - StyledText { - Layout.fillWidth: true - text: qsTr("Syncshell") - color: Colours.palette.m3primary - font: Tokens.font.title.medium - } - - StyledText { - Layout.fillWidth: true - text: Syncshell.summaryText - } - - StyledText { - Layout.fillWidth: true - visible: text.length > 0 - text: Syncshell.lastError || Syncshell.actionNotice - color: Syncshell.lastError ? Colours.palette.m3error - : Colours.palette.m3primary - wrapMode: Text.Wrap - } - - StyledText { - visible: root.deviceFlow.view === "" - Layout.fillWidth: true - text: qsTr("FOLDERS") - color: Colours.palette.m3onSurfaceVariant - } - - Flickable { - visible: root.deviceFlow.view === "" - id: folderView - Layout.fillWidth: true - Layout.preferredHeight: Math.min(300, - Math.max(60, folderColumn.implicitHeight)) - clip: true - contentWidth: width - contentHeight: folderColumn.implicitHeight - boundsBehavior: Flickable.StopAtBounds - - Column { - id: folderColumn - width: folderView.width - spacing: Tokens.spacing.small - - StyledText { - width: parent.width - visible: Syncshell.folders.length === 0 - text: Syncshell.summaryText - color: Colours.palette.m3onSurfaceVariant - horizontalAlignment: Text.AlignHCenter - } - - Repeater { - model: Syncshell.folders - delegate: StyledRect { - id: folderCard - required property var modelData - width: folderColumn.width - height: details.implicitHeight + Tokens.padding.medium * 2 - color: Colours.tPalette.m3surfaceContainer - radius: Tokens.rounding.medium - - ColumnLayout { - id: details - anchors.fill: parent - anchors.margins: Tokens.padding.medium - spacing: Tokens.spacing.small - StyledText { - Layout.fillWidth: true - text: String(folderCard.modelData.label - || folderCard.modelData.id) - font: Tokens.font.label.large - } - StyledText { - Layout.fillWidth: true - text: String(folderCard.modelData.path || "") - color: Colours.palette.m3onSurfaceVariant - elide: Text.ElideMiddle - } - StyledText { - Layout.fillWidth: true - text: String(folderCard.modelData.status - && (folderCard.modelData.status.error - || folderCard.modelData.status.state) || "unknown") - color: folderCard.modelData.status - && folderCard.modelData.status.error - ? Colours.palette.m3error : Colours.palette.m3onSurfaceVariant - elide: Text.ElideRight - } - RowLayout { - TextButton { - visible: root.moreOpen - text: folderCard.modelData.paused - ? qsTr("Link") : qsTr("Unlink") - enabled: Syncshell.online && !Syncshell.busy - onClicked: Syncshell.setFolderPaused( - folderCard.modelData.id, !folderCard.modelData.paused) - } - TextButton { - visible: root.moreOpen - && Syncshell.shareableDevices().length > 0 - text: qsTr("Share") - enabled: Syncshell.online && !Syncshell.busy - onClicked: { - root.addOpen = false - root.deviceFlow.beginFolderSharing(folderCard.modelData) - } - } - TextButton { - text: folderCard.modelData.paused - ? qsTr("Forget") : qsTr("Rescan") - enabled: Syncshell.online && !Syncshell.busy - onClicked: { - if (folderCard.modelData.paused) - root.requestForget(folderCard.modelData) - else Syncshell.rescanFolder(folderCard.modelData.id) - } - } - } - } - } - } - } - } - - TextButton { - visible: root.deviceFlow.view === "" - Layout.fillWidth: true - text: root.moreOpen ? qsTr("Less") : qsTr("More") - onClicked: root.moreOpen = !root.moreOpen - } - - ColumnLayout { - visible: root.moreOpen - Layout.fillWidth: true - - TextButton { - visible: root.deviceFlow.view === "" - Layout.fillWidth: true - text: root.addOpen ? qsTr("Cancel add folder") : qsTr("Add folder") - enabled: Syncshell.online && !Syncshell.busy - onClicked: { - root.deviceFlow.close() - root.deviceFlow.resetFolderDraft() - root.addOpen = !root.addOpen - } - } - - ColumnLayout { - visible: root.addOpen && root.deviceFlow.view === "" - Layout.fillWidth: true - - StyledText { - Layout.fillWidth: true - text: qsTr("ADD FOLDER") - color: Colours.palette.m3onSurfaceVariant - } - Repeater { - model: Syncshell.pendingFolderOffers() - delegate: TextButton { - required property var modelData - Layout.fillWidth: true - text: (modelData.encrypted ? "Encrypted offer: " : "Accept ") - + modelData.label + " from " - + Syncshell.deviceName(modelData.deviceId) - enabled: !modelData.encrypted - onClicked: idField.text - = root.deviceFlow.selectPendingFolder(modelData) - } - } - StyledTextField { - id: pathField - Layout.fillWidth: true - placeholderText: qsTr("/path/to/existing/folder") - } - StyledTextField { - id: labelField - Layout.fillWidth: true - placeholderText: qsTr("Label") - } - RowLayout { - Layout.fillWidth: true - StyledTextField { - id: idField - Layout.fillWidth: true - placeholderText: qsTr("Folder ID") - } - TextButton { - text: qsTr("New ID") - enabled: Syncshell.online && !Syncshell.busy - onClicked: Syncshell.requestFolderIdSuggestion() - } - } - StyledText { - Layout.fillWidth: true - text: qsTr("Reuse the exact ID to rejoin a remote folder. " - + "A new ID creates a different folder identity.") - color: Colours.palette.m3onSurfaceVariant - wrapMode: Text.Wrap - } - Repeater { - model: Syncshell.shareableDevices() - delegate: TextButton { - required property var modelData - Layout.fillWidth: true - text: (root.deviceFlow.draftIds.indexOf(modelData.id) >= 0 - ? "[x] Share with " : "[ ] Share with ") - + String(modelData.name || root.deviceFlow.shortId(modelData.id)) - onClicked: root.deviceFlow.toggleDraft(String(modelData.id || "")) - } - } - TextButton { - Layout.fillWidth: true - text: Syncshell.busy ? qsTr("Adding...") : qsTr("Add folder") - enabled: Syncshell.online && !Syncshell.busy - && pathField.text.length > 0 && idField.text.length > 0 - onClicked: Syncshell.addFolder({ - path: pathField.text, - label: labelField.text, - folderId: idField.text, - deviceIds: root.deviceFlow.draftIds, - pendingDeviceId: root.deviceFlow.pendingDeviceId(idField.text) - }) - } - } - - StyledText { - visible: root.deviceFlow.view === "" - Layout.fillWidth: true - text: qsTr("REMOTE DEVICES") - color: Colours.palette.m3onSurfaceVariant - } - - Repeater { - model: root.deviceFlow.view === "" ? Syncshell.remoteDevices() : [] - delegate: RowLayout { - required property var modelData - Layout.fillWidth: true - StyledText { - Layout.fillWidth: true - text: String(modelData.name || root.deviceFlow.shortId(modelData.id)) - + " · " + Syncshell.folderIdsForDevice(modelData.id).length - + " folders · " - + (modelData.connected ? "connected" : "disconnected") - color: modelData.connected ? Colours.palette.m3primary - : Colours.palette.m3onSurfaceVariant - elide: Text.ElideRight - } - TextButton { - text: qsTr("Folders") - enabled: !Syncshell.busy - onClicked: { - root.addOpen = false - root.deviceFlow.beginDeviceFolders(modelData) - } - } - } - } - - TextButton { - visible: root.deviceFlow.view === "" - Layout.fillWidth: true - text: qsTr("Add remote device") - enabled: Syncshell.online && !Syncshell.busy - onClicked: { - root.addOpen = false - root.deviceFlow.beginAddDevice(null) - } - } - - Repeater { - model: root.deviceFlow.view === "" ? Syncshell.pendingDevices : [] - delegate: RowLayout { - required property var modelData - Layout.fillWidth: true - StyledText { - Layout.fillWidth: true - text: String(modelData.name || root.deviceFlow.shortId(modelData.id)) - + " wants to connect" - elide: Text.ElideRight - } - TextButton { - text: qsTr("Accept") - enabled: !Syncshell.busy - onClicked: { - root.addOpen = false - root.deviceFlow.beginAddDevice(modelData) - } - } - TextButton { - text: qsTr("Dismiss") - enabled: !Syncshell.busy - onClicked: { - root.addOpen = false - root.deviceFlow.beginDismissDevice(modelData) - } - } - } - } - - ColumnLayout { - visible: root.deviceFlow.view === "add-device" - Layout.fillWidth: true - StyledText { - Layout.fillWidth: true - text: qsTr("ADD REMOTE DEVICE") - color: Colours.palette.m3onSurfaceVariant - } - Repeater { - model: Syncshell.nearbyDevices - delegate: TextButton { - required property var modelData - Layout.fillWidth: true - text: "Use nearby " + root.deviceFlow.shortId(modelData.id) - onClicked: root.deviceFlow.targetDeviceId = String(modelData.id || "") - } - } - StyledTextField { - Layout.fillWidth: true - placeholderText: qsTr("Device ID") - text: root.deviceFlow.targetDeviceId - onTextChanged: root.deviceFlow.targetDeviceId = text.toUpperCase() - } - StyledTextField { - Layout.fillWidth: true - placeholderText: qsTr("Remote device name (optional)") - text: root.deviceFlow.targetDeviceName - onTextChanged: root.deviceFlow.targetDeviceName = text - } - RowLayout { - TextButton { - text: qsTr("Cancel") - onClicked: root.deviceFlow.close() - } - TextButton { - text: Syncshell.busy ? qsTr("Adding...") : qsTr("Add") - enabled: !Syncshell.busy && root.deviceFlow.targetDeviceId !== "" - onClicked: Syncshell.addDevice(root.deviceFlow.targetDeviceId, - root.deviceFlow.targetDeviceName) - } - } - } - - ColumnLayout { - visible: root.deviceFlow.view === "share-folder" - Layout.fillWidth: true - StyledText { - Layout.fillWidth: true - text: "SHARE " + Syncshell.folderLabel(root.deviceFlow.targetFolderId) - color: Colours.palette.m3onSurfaceVariant - } - Repeater { - model: Syncshell.shareableDevices() - delegate: TextButton { - required property var modelData - Layout.fillWidth: true - text: (root.deviceFlow.draftIds.indexOf(modelData.id) >= 0 - ? "[x] " : "[ ] ") - + String(modelData.name || root.deviceFlow.shortId(modelData.id)) - onClicked: root.deviceFlow.toggleDraft(String(modelData.id || "")) - } - } - RowLayout { - TextButton { - text: qsTr("Cancel") - onClicked: root.deviceFlow.close() - } - TextButton { - text: qsTr("Save sharing") - enabled: !Syncshell.busy - onClicked: Syncshell.setFolderSharing( - root.deviceFlow.targetFolderId, root.deviceFlow.draftIds) - } - } - } - - ColumnLayout { - visible: root.deviceFlow.view === "device-folders" - Layout.fillWidth: true - StyledText { - Layout.fillWidth: true - text: "SHARED WITH " + (root.deviceFlow.targetDeviceName - || root.deviceFlow.shortId(root.deviceFlow.targetDeviceId)) - color: Colours.palette.m3onSurfaceVariant - } - Repeater { - model: Syncshell.folderIdsForDevice(root.deviceFlow.targetDeviceId) - delegate: TextButton { - required property var modelData - Layout.fillWidth: true - text: (root.deviceFlow.draftIds.indexOf(modelData) >= 0 - ? "[x] " : "[ ] ") + Syncshell.folderLabel(modelData) - onClicked: root.deviceFlow.toggleDraft(String(modelData || "")) - } - } - RowLayout { - TextButton { - text: qsTr("Cancel") - onClicked: root.deviceFlow.close() - } - TextButton { - text: qsTr("Save sharing") - enabled: !Syncshell.busy && root.deviceFlow.removedFolderIds().length > 0 - onClicked: Syncshell.removeDeviceFolderShares( - root.deviceFlow.targetDeviceId, root.deviceFlow.removedFolderIds(), - root.deviceFlow.targetDeviceName) - } - } - } - - StyledRect { - visible: root.deviceFlow.view === "dismiss-device" - Layout.fillWidth: true - implicitHeight: dismissDeviceContent.implicitHeight - + Tokens.padding.medium * 2 - color: Colours.tPalette.m3surfaceContainer - radius: Tokens.rounding.medium - border.width: 1 - border.color: Colours.palette.m3error - ColumnLayout { - id: dismissDeviceContent - anchors.fill: parent - anchors.margins: Tokens.padding.medium - StyledText { - Layout.fillWidth: true - text: "Dismiss pending request from " - + (root.deviceFlow.targetDeviceName - || root.deviceFlow.shortId(root.deviceFlow.targetDeviceId)) + "?" - color: Colours.palette.m3error - } - RowLayout { - TextButton { - text: qsTr("Cancel") - onClicked: root.deviceFlow.close() - } - TextButton { - text: qsTr("Dismiss") - enabled: !Syncshell.busy - onClicked: Syncshell.dismissPendingDevice( - root.deviceFlow.targetDeviceId, root.deviceFlow.targetDeviceName) - } - } - } - } - } - - StyledRect { - visible: root.pendingForgetId !== "" - Layout.fillWidth: true - implicitHeight: forgetContent.implicitHeight + Tokens.padding.medium * 2 - color: Colours.tPalette.m3surfaceContainer - radius: Tokens.rounding.medium - border.width: 1 - border.color: Colours.palette.m3error - - ColumnLayout { - id: forgetContent - anchors.fill: parent - anchors.margins: Tokens.padding.medium - - StyledText { - Layout.fillWidth: true - text: "Forget " + root.pendingForgetLabel + " (" - + root.pendingForgetId + ")? The directory and data files will " - + "not be deleted. Rejoining requires this Folder ID." - color: Colours.palette.m3error - wrapMode: Text.Wrap - } - RowLayout { - TextButton { - text: qsTr("Cancel") - onClicked: root.pendingForgetId = "" - } - TextButton { - text: qsTr("Forget") - enabled: !Syncshell.busy - onClicked: root.confirmForget() - } - } - } - } - - RowLayout { - Layout.fillWidth: true - TextButton { - text: qsTr("Web UI") - enabled: Syncshell.online - onClicked: Syncshell.openWebUi() - } - } - - RowLayout { - Layout.fillWidth: true - TextButton { - text: qsTr("Rescan all") - enabled: Syncshell.online && !Syncshell.busy - && Syncshell.folderCount > 0 - onClicked: Syncshell.rescanAllFolders() - } - TextButton { - text: qsTr("Refresh status") - enabled: !Syncshell.refreshing && !Syncshell.busy - onClicked: Syncshell.refresh() - } - } - - Connections { - target: Syncshell - function onFolderIdSuggestionChanged() { - if (!idField.activeFocus && Syncshell.folderIdSuggestion) - idField.text = Syncshell.folderIdSuggestion - } - function onActionFinished(action, ok) { - root.deviceFlow.actionFinished(action, ok) - } - } -} diff --git a/integrations/caelestia/files/SyncshellService.qml.in b/integrations/caelestia/files/SyncshellService.qml.in deleted file mode 100644 index f5f27a2b..00000000 --- a/integrations/caelestia/files/SyncshellService.qml.in +++ /dev/null @@ -1,6 +0,0 @@ -pragma Singleton - -import QtQuick -import "../syncshell/shared" - -AdapterService {} diff --git a/integrations/caelestia/files/SyncshellStatus.qml.in b/integrations/caelestia/files/SyncshellStatus.qml.in deleted file mode 100644 index 45419807..00000000 --- a/integrations/caelestia/files/SyncshellStatus.qml.in +++ /dev/null @@ -1,14 +0,0 @@ -import QtQuick -import Caelestia.Config -import qs.components -import qs.services - -MaterialIcon { - property color colour: Colours.palette.m3secondary - animate: true - text: !Syncshell.online ? "sync_problem" - : Syncshell.syncingFolderCount > 0 ? "sync" : "sync_alt" - color: Syncshell.folderProblemCount > 0 - ? Colours.palette.m3error : colour - fill: Syncshell.online ? 1 : 0 -} diff --git a/integrations/caelestia/import-map.json b/integrations/caelestia/import-map.json new file mode 100644 index 00000000..aaa1a732 --- /dev/null +++ b/integrations/caelestia/import-map.json @@ -0,0 +1,52 @@ +{ + "hosts/caelestia": { + "QtQuick": "QtQuick", + "Quickshell": "Quickshell", + "Caelestia.Plugins": "Caelestia.Plugins", + "Caelestia.Config": "Caelestia.Config", + "qs.components": "qs.components", + "qs.services": "qs.services", + "\".\"": "syncshell.syncshell.hosts.caelestia", + "Quickshell.Wayland": "Quickshell.Wayland", + "Quickshell.Hyprland": "Quickshell.Hyprland", + "\"ui\"": "syncshell.syncshell.hosts.caelestia.ui", + "\"../../shared\"": "syncshell.syncshell.shared", + "\"controllers\"": "syncshell.syncshell.hosts.caelestia.controllers", + "\"models/Ownership.js\"": "\"models/Ownership.js\"", + "\"models/PanelModel.js\"": "\"models/PanelModel.js\"" + }, + "hosts/caelestia/controllers": { + "QtQuick": "QtQuick", + "\"../models/PanelModel.js\"": "\"../models/PanelModel.js\"", + "\"../models/Ownership.js\"": "\"../models/Ownership.js\"", + "qs.services": "qs.services", + "\"../../../shared/Paths.js\"": "\"../../../shared/Paths.js\"" + }, + "hosts/caelestia/models": {}, + "hosts/caelestia/ui": { + "QtQuick": "QtQuick", + "QtQuick.Layouts": "QtQuick.Layouts", + "qs.components": "qs.components", + "qs.components.controls": "qs.components.controls", + "\".\"": "syncshell.syncshell.hosts.caelestia.ui", + "\"../models/PanelModel.js\"": "\"../models/PanelModel.js\"", + "QtQuick.Controls": "QtQuick.Controls", + "Caelestia.Config": "Caelestia.Config", + "qs.services": "qs.services", + "Quickshell": "Quickshell", + "Qt.labs.folderlistmodel": "Qt.labs.folderlistmodel", + "qs.components.containers": "qs.components.containers", + "\"../../../shared/Paths.js\"": "\"../../../shared/Paths.js\"", + "QtQuick.Effects": "QtQuick.Effects" + }, + "shared": { + "QtQuick": "QtQuick", + "Quickshell": "Quickshell", + "\".\"": "syncshell.syncshell.shared", + "\"Paths.js\"": "\"Paths.js\"", + "Quickshell.Io": "Quickshell.Io" + }, + "integrations/caelestia": { + "Caelestia.Plugins": "Caelestia.Plugins" + } +} diff --git a/integrations/caelestia/manifest.json b/integrations/caelestia/manifest.json index 48f37403..dbb86e94 100644 --- a/integrations/caelestia/manifest.json +++ b/integrations/caelestia/manifest.json @@ -1,10 +1,25 @@ { - "schemaVersion": 1, - "integration": "caelestia", - "repository": "https://github.com/caelestia-dots/shell.git", - "commit": "1d0e5a588c61f1d905eba5fe8446ec222d37f50c", - "cliCommit": "7401d9e3a371e583bc0b42dc1a139d01e278e6c1", - "quickshellCommit": "0fed22a2c47d9568ddf13cf61586b3f2ac4378a2", - "host": "Arch Linux with Hyprland", - "patch": "overlay.patch" + "name": "Syncshell", + "author": "syncshell", + "version": "0.2.2", + "description": "Native Syncthing controls for Caelestia (experimental loader)", + "icon": "sync", + "requires": ">=2.2.0", + "settings": "integrations/caelestia/Settings.qml", + "entryPoints": [ + { + "type": "bar-entry", + "source": "hosts/caelestia/CaelestiaBarEntry.qml", + "properties": { + "name": "syncshell" + } + }, + { + "type": "bar-popout", + "source": "hosts/caelestia/CaelestiaPanel.qml", + "properties": { + "entry": "syncshell-overview" + } + } + ] } diff --git a/integrations/caelestia/overlay.patch b/integrations/caelestia/overlay.patch deleted file mode 100644 index f8d43994..00000000 --- a/integrations/caelestia/overlay.patch +++ /dev/null @@ -1,51 +0,0 @@ -diff --git a/CMakeLists.txt b/CMakeLists.txt ---- a/CMakeLists.txt -+++ b/CMakeLists.txt -@@ -70,0 +71,2 @@ -+ -+ install(DIRECTORY syncshell DESTINATION "${INSTALL_QSCONFDIR}" USE_SOURCE_PERMISSIONS) -diff --git a/modules/ServiceLoader.qml b/modules/ServiceLoader.qml ---- a/modules/ServiceLoader.qml -+++ b/modules/ServiceLoader.qml -@@ -14,0 +15 @@ Scope { -+ Syncshell; -diff --git a/modules/bar/components/StatusIcons.qml b/modules/bar/components/StatusIcons.qml ---- a/modules/bar/components/StatusIcons.qml -+++ b/modules/bar/components/StatusIcons.qml -@@ -144,0 +145,8 @@ StyledRect { -+ DelegateChoice { -+ roleValue: "syncshell" -+ delegate: EntryWrapper { -+ SyncshellStatus { -+ colour: root.colour -+ } -+ } -+ } -diff --git a/modules/bar/popouts/Content.qml b/modules/bar/popouts/Content.qml ---- a/modules/bar/popouts/Content.qml -+++ b/modules/bar/popouts/Content.qml -@@ -121,0 +122,5 @@ Item { -+ Popout { -+ name: "syncshell" -+ sourceComponent: SyncshellPopout {} -+ } -+ -diff --git a/modules/bar/popouts/Wrapper.qml b/modules/bar/popouts/Wrapper.qml ---- a/modules/bar/popouts/Wrapper.qml -+++ b/modules/bar/popouts/Wrapper.qml -@@ -100 +100,2 @@ Item { -- when: root.isDetached || (root.hasCurrent && root.currentName === "wirelesspassword") -+ when: root.isDetached || (root.hasCurrent -+ && ["wirelesspassword", "syncshell"].includes(root.currentName)) -diff --git a/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml b/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml ---- a/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml -+++ b/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml -@@ -17 +17,2 @@ PageBase { -- battery: qsTr("Battery") -+ battery: qsTr("Battery"), -+ syncshell: qsTr("Syncshell") -diff --git a/plugin/src/Caelestia/Config/barconfig.hpp b/plugin/src/Caelestia/Config/barconfig.hpp ---- a/plugin/src/Caelestia/Config/barconfig.hpp -+++ b/plugin/src/Caelestia/Config/barconfig.hpp -@@ -109,0 +110 @@ class BarConfig : public settings::ObjectNode { -+ LIST_ENTRY(syncshell, true), diff --git a/integrations/caelestia/qml-files.txt b/integrations/caelestia/qml-files.txt new file mode 100644 index 00000000..c84a268d --- /dev/null +++ b/integrations/caelestia/qml-files.txt @@ -0,0 +1,38 @@ +hosts/caelestia/CaelestiaBarEntry.qml +hosts/caelestia/CaelestiaPanel.qml +hosts/caelestia/CaelestiaService.qml +hosts/caelestia/controllers/PanelController.qml +hosts/caelestia/controllers/SettingsController.qml +hosts/caelestia/controllers/ThemePaletteController.qml +hosts/caelestia/models/Ownership.js +hosts/caelestia/models/PanelModel.js +hosts/caelestia/ui/BodyFormHeader.qml +hosts/caelestia/ui/BodyFormSideCard.qml +hosts/caelestia/ui/BodyInvitations.qml +hosts/caelestia/ui/BodyMore.qml +hosts/caelestia/ui/BodyTabDevicesAddForm.qml +hosts/caelestia/ui/BodyTabDevicesCard.qml +hosts/caelestia/ui/BodyTabDevicesFoldersForm.qml +hosts/caelestia/ui/BodyTabFoldersAddForm.qml +hosts/caelestia/ui/BodyTabFoldersAddFormPicker.qml +hosts/caelestia/ui/BodyTabFoldersCard.qml +hosts/caelestia/ui/BodyTabFoldersShareForm.qml +hosts/caelestia/ui/BodyTabFoldersViewOptions.qml +hosts/caelestia/ui/FooterActions.qml +hosts/caelestia/ui/FooterShortcutHint.qml +hosts/caelestia/ui/Header.qml +hosts/caelestia/ui/SettingsPage.qml +hosts/caelestia/ui/SharedDialogConfirm.qml +hosts/caelestia/ui/SharedWidgetBusyButton.qml +hosts/caelestia/ui/SharedWidgetDropdown.qml +hosts/caelestia/ui/SharedWidgetIdCopyButton.qml +hosts/caelestia/ui/SharedWidgetInfoPair.qml +hosts/caelestia/ui/SharedWidgetMonoIcon.qml +hosts/caelestia/ui/SharedWidgetSquareActionButton.qml +hosts/caelestia/ui/SharedWidgetToolTip.qml +hosts/caelestia/ui/SyncshellPanelPopup.qml +shared/AdapterService.qml +shared/CoreProcess.qml +shared/RescanTracker.qml +shared/Paths.js +integrations/caelestia/Settings.qml diff --git a/integrations/dankmaterialshell/SyncshellDaemon.qml b/integrations/dankmaterialshell/SyncshellDaemon.qml deleted file mode 100644 index 2cca9e21..00000000 --- a/integrations/dankmaterialshell/SyncshellDaemon.qml +++ /dev/null @@ -1,25 +0,0 @@ -import QtQuick -import qs.Modules.Plugins -import "shared" - -PluginComponent { - id: root - - property var popoutService: null - property AdapterService service: AdapterService { - refreshIntervalSeconds: Math.max(60, Number(root.pluginData.refreshIntervalSec || 60)) - } - - function publishService() { - if (pluginService && pluginId) - pluginService.setGlobalVar(pluginId, "service", service); - } - - Component.onCompleted: publishService() - Component.onDestruction: { - if (pluginService && pluginId && pluginService.getGlobalVar(pluginId, "service", null) === service) - pluginService.setGlobalVar(pluginId, "service", null); - } - onPluginServiceChanged: publishService() - onPluginIdChanged: publishService() -} diff --git a/integrations/dankmaterialshell/SyncshellWidget.qml b/integrations/dankmaterialshell/SyncshellWidget.qml deleted file mode 100644 index 3be98d42..00000000 --- a/integrations/dankmaterialshell/SyncshellWidget.qml +++ /dev/null @@ -1,647 +0,0 @@ -import QtQuick -import QtQuick.Layouts -import qs.Common -import qs.Widgets -import qs.Widgets as Widgets -import qs.Modules.Plugins -import "shared" - -PluginComponent { - id: root - - component StyledText: Widgets.StyledText { - textFormat: Text.PlainText - } - - layerNamespacePlugin: "syncshell" - popoutWidth: 480 - popoutHeight: 680 - property var service: null - property bool moreOpen: false - property bool addOpen: false - property string pendingForgetId: "" - property string pendingForgetLabel: "" - property DeviceWorkflow deviceFlow: DeviceWorkflow { - service: root.service - } - - function requestForget(folder) { - pendingForgetId = String(folder.id || ""); - pendingForgetLabel = String(folder.label || folder.id || "folder"); - } - - function confirmForget() { - if (pendingForgetId === "" || !service) - return; - if (service.forgetFolder(pendingForgetId)) - pendingForgetId = ""; - } - - function resolveService() { - service = pluginService && pluginId ? pluginService.getGlobalVar(pluginId, "service", null) : null; - } - - function stateIcon() { - if (!service || !service.online) - return "cloud_off"; - if (service.folderProblemCount > 0) - return "sync_problem"; - return service.syncingFolderCount > 0 ? "sync" : "cloud_done"; - } - - Component.onCompleted: resolveService() - onPluginServiceChanged: resolveService() - onPluginIdChanged: resolveService() - - Connections { - target: root.pluginService - function onGlobalVarChanged(changedPluginId, variableName) { - if (changedPluginId === root.pluginId && variableName === "service") - root.resolveService(); - } - } - - Timer { - interval: 50 - repeat: true - running: !root.service - onTriggered: root.resolveService() - } - - horizontalBarPill: Component { - Row { - spacing: Theme.spacingXS - DankIcon { - anchors.verticalCenter: parent.verticalCenter - name: root.stateIcon() - color: root.service && root.service.folderProblemCount > 0 ? Theme.error : Theme.primary - size: Theme.iconSize - 4 - } - StyledText { - anchors.verticalCenter: parent.verticalCenter - text: root.service ? String(root.service.folderCount) : "-" - color: Theme.surfaceText - font.pixelSize: Theme.fontSizeMedium - } - } - } - - verticalBarPill: Component { - Column { - spacing: Theme.spacingXS - DankIcon { - anchors.horizontalCenter: parent.horizontalCenter - name: root.stateIcon() - color: root.service && root.service.folderProblemCount > 0 ? Theme.error : Theme.primary - size: Theme.iconSize - 4 - } - StyledText { - anchors.horizontalCenter: parent.horizontalCenter - text: root.service ? String(root.service.folderCount) : "-" - color: Theme.surfaceText - font.pixelSize: Theme.fontSizeSmall - } - } - } - - popoutContent: Component { - PopoutComponent { - headerText: "Syncshell" - detailsText: root.service ? root.service.summaryText : "Starting native core" - showCloseButton: true - - Column { - width: parent.width - spacing: Theme.spacingS - - StyledText { - width: parent.width - visible: text !== "" - text: root.service ? root.service.lastError || root.service.actionNotice : "" - color: root.service && root.service.lastError ? Theme.error : Theme.primary - wrapMode: Text.WordWrap - } - - StyledText { - width: parent.width - visible: root.service && root.service.activityText !== "" - text: root.service ? root.service.activityText : "" - color: Theme.surfaceVariantText - elide: Text.ElideMiddle - } - - StyledText { - visible: root.deviceFlow.view === "" - text: "FOLDERS" - color: Theme.surfaceVariantText - font.weight: Font.DemiBold - } - - Flickable { - visible: root.deviceFlow.view === "" - width: parent.width - height: 330 - clip: true - contentWidth: width - contentHeight: folderColumn.implicitHeight - - Column { - id: folderColumn - width: parent.width - spacing: Theme.spacingS - - StyledText { - width: parent.width - visible: !root.service || root.service.folders.length === 0 - text: root.service ? root.service.summaryText : "Starting native core" - color: Theme.surfaceVariantText - horizontalAlignment: Text.AlignHCenter - } - - Repeater { - model: root.service ? root.service.folders : [] - delegate: StyledRect { - required property var modelData - width: folderColumn.width - height: details.implicitHeight + Theme.spacingM * 2 - radius: Theme.cornerRadius - color: Theme.surfaceContainerHigh - - Column { - id: details - anchors.fill: parent - anchors.margins: Theme.spacingM - spacing: Theme.spacingXS - StyledText { - width: parent.width - text: String(modelData.label || modelData.id) - color: Theme.surfaceText - font.weight: Font.DemiBold - } - StyledText { - width: parent.width - text: String(modelData.path || "") - color: Theme.surfaceVariantText - elide: Text.ElideMiddle - } - StyledText { - width: parent.width - text: String(modelData.status && modelData.status.error || modelData.status && modelData.status.state || "unknown") - color: modelData.status && modelData.status.error ? Theme.error : Theme.surfaceVariantText - elide: Text.ElideRight - } - Row { - spacing: Theme.spacingXS - DankButton { - visible: root.moreOpen - text: modelData.paused ? "Link" : "Unlink" - buttonHeight: 30 - enabled: root.service && root.service.online && !root.service.busy - onClicked: root.service.setFolderPaused(modelData.id, !modelData.paused) - } - DankButton { - visible: root.moreOpen && root.service.shareableDevices().length > 0 - text: "Share" - buttonHeight: 30 - enabled: root.service.online && !root.service.busy - onClicked: { - root.addOpen = false; - root.deviceFlow.beginFolderSharing(modelData); - } - } - DankButton { - text: modelData.paused ? "Forget" : "Rescan" - buttonHeight: 30 - enabled: root.service && root.service.online && !root.service.busy - onClicked: { - if (modelData.paused) - root.requestForget(modelData); - else - root.service.rescanFolder(modelData.id); - } - } - } - } - } - } - } - } - - DankButton { - visible: root.deviceFlow.view === "" - width: parent.width - text: root.moreOpen ? "Less" : "More" - iconName: root.moreOpen ? "expand_less" : "expand_more" - buttonHeight: 34 - onClicked: root.moreOpen = !root.moreOpen - } - - Column { - visible: root.moreOpen - width: parent.width - spacing: Theme.spacingS - - DankButton { - visible: root.deviceFlow.view === "" - width: parent.width - text: root.addOpen ? "Cancel add folder" : "Add folder" - buttonHeight: 34 - enabled: root.service && root.service.online && !root.service.busy - onClicked: { - root.deviceFlow.close(); - root.deviceFlow.resetFolderDraft(); - root.addOpen = !root.addOpen; - } - } - - Column { - visible: root.addOpen && root.deviceFlow.view === "" - width: parent.width - spacing: Theme.spacingS - - StyledText { - text: "ADD FOLDER" - color: Theme.surfaceText - font.weight: Font.DemiBold - } - Repeater { - model: root.service ? root.service.pendingFolderOffers() : [] - delegate: DankButton { - required property var modelData - width: parent.width - text: (modelData.encrypted ? "Encrypted offer: " : "Accept ") + modelData.label + " from " + root.service.deviceName(modelData.deviceId) - buttonHeight: 30 - enabled: !modelData.encrypted - onClicked: idField.text = root.deviceFlow.selectPendingFolder(modelData) - } - } - DankTextField { - id: pathField - width: parent.width - placeholderText: "/path/to/existing/folder" - leftIconName: "folder" - showClearButton: true - } - DankTextField { - id: labelField - width: parent.width - placeholderText: "Label" - } - Row { - width: parent.width - spacing: Theme.spacingS - DankTextField { - id: idField - width: parent.width - suggestButton.width - parent.spacing - placeholderText: "Folder ID" - } - DankButton { - id: suggestButton - text: "New ID" - buttonHeight: 34 - enabled: root.service && root.service.online && !root.service.busy - onClicked: root.service.requestFolderIdSuggestion() - } - } - StyledText { - width: parent.width - text: "Reuse the exact ID to rejoin a remote folder. " + "A new ID creates a different folder identity." - color: Theme.surfaceVariantText - wrapMode: Text.WordWrap - } - Repeater { - model: root.service ? root.service.shareableDevices() : [] - delegate: DankButton { - required property var modelData - width: parent.width - text: (root.deviceFlow.draftIds.indexOf(modelData.id) >= 0 ? "[x] Share with " : "[ ] Share with ") + String(modelData.name || root.deviceFlow.shortId(modelData.id)) - buttonHeight: 30 - onClicked: root.deviceFlow.toggleDraft(String(modelData.id || "")) - } - } - DankButton { - width: parent.width - text: root.service && root.service.busy ? "Adding..." : "Add folder" - buttonHeight: 34 - enabled: root.service && root.service.online && pathField.text !== "" && idField.text !== "" && !root.service.busy - onClicked: root.service.addFolder({ - path: pathField.text, - label: labelField.text, - folderId: idField.text, - deviceIds: root.deviceFlow.draftIds, - pendingDeviceId: root.deviceFlow.pendingDeviceId(idField.text) - }) - } - } - - StyledText { - visible: root.deviceFlow.view === "" - text: "REMOTE DEVICES" - color: Theme.surfaceVariantText - font.weight: Font.DemiBold - } - - Repeater { - model: root.deviceFlow.view === "" && root.service ? root.service.remoteDevices() : [] - delegate: Row { - required property var modelData - width: parent.width - spacing: Theme.spacingS - StyledText { - width: parent.width - foldersButton.width - parent.spacing - text: String(modelData.name || root.deviceFlow.shortId(modelData.id)) + " · " + root.service.folderIdsForDevice(modelData.id).length + " folders · " + (modelData.connected ? "connected" : "disconnected") - color: modelData.connected ? Theme.primary : Theme.surfaceVariantText - elide: Text.ElideRight - } - DankButton { - id: foldersButton - text: "Folders" - buttonHeight: 30 - enabled: !root.service.busy - onClicked: { - root.addOpen = false; - root.deviceFlow.beginDeviceFolders(modelData); - } - } - } - } - - DankButton { - visible: root.deviceFlow.view === "" - width: parent.width - text: "Add remote device" - buttonHeight: 34 - enabled: root.service && root.service.online && !root.service.busy - onClicked: { - root.addOpen = false; - root.deviceFlow.beginAddDevice(null); - } - } - - Repeater { - model: root.deviceFlow.view === "" && root.service ? root.service.pendingDevices : [] - delegate: Row { - required property var modelData - width: parent.width - spacing: Theme.spacingS - StyledText { - width: parent.width - acceptButton.width - dismissButton.width - parent.spacing * 2 - text: String(modelData.name || root.deviceFlow.shortId(modelData.id)) + " wants to connect" - color: Theme.surfaceText - elide: Text.ElideRight - } - DankButton { - id: acceptButton - text: "Accept" - buttonHeight: 30 - enabled: !root.service.busy - onClicked: { - root.addOpen = false; - root.deviceFlow.beginAddDevice(modelData); - } - } - DankButton { - id: dismissButton - text: "Dismiss" - buttonHeight: 30 - enabled: !root.service.busy - onClicked: { - root.addOpen = false; - root.deviceFlow.beginDismissDevice(modelData); - } - } - } - } - - Column { - visible: root.deviceFlow.view === "add-device" - width: parent.width - spacing: Theme.spacingS - StyledText { - text: "ADD REMOTE DEVICE" - color: Theme.surfaceText - font.weight: Font.DemiBold - } - Repeater { - model: root.service ? root.service.nearbyDevices : [] - delegate: DankButton { - required property var modelData - width: parent.width - text: "Use nearby " + root.deviceFlow.shortId(modelData.id) - buttonHeight: 30 - onClicked: root.deviceFlow.targetDeviceId = String(modelData.id || "") - } - } - DankTextField { - id: deviceIdField - width: parent.width - placeholderText: "Device ID" - text: root.deviceFlow.targetDeviceId - onTextChanged: root.deviceFlow.targetDeviceId = text.toUpperCase() - } - DankTextField { - width: parent.width - placeholderText: "Remote device name (optional)" - text: root.deviceFlow.targetDeviceName - onTextChanged: root.deviceFlow.targetDeviceName = text - } - Row { - spacing: Theme.spacingS - DankButton { - text: "Cancel" - buttonHeight: 32 - onClicked: root.deviceFlow.close() - } - DankButton { - text: root.service && root.service.busy ? "Adding..." : "Add" - buttonHeight: 32 - enabled: root.service && !root.service.busy && root.deviceFlow.targetDeviceId !== "" - onClicked: root.service.addDevice(root.deviceFlow.targetDeviceId, root.deviceFlow.targetDeviceName) - } - } - } - - Column { - visible: root.deviceFlow.view === "share-folder" - width: parent.width - spacing: Theme.spacingS - StyledText { - text: "SHARE " + root.service.folderLabel(root.deviceFlow.targetFolderId) - color: Theme.surfaceText - font.weight: Font.DemiBold - } - Repeater { - model: root.service ? root.service.shareableDevices() : [] - delegate: DankButton { - required property var modelData - width: parent.width - text: (root.deviceFlow.draftIds.indexOf(modelData.id) >= 0 ? "[x] " : "[ ] ") + String(modelData.name || root.deviceFlow.shortId(modelData.id)) - buttonHeight: 30 - onClicked: root.deviceFlow.toggleDraft(String(modelData.id || "")) - } - } - Row { - spacing: Theme.spacingS - DankButton { - text: "Cancel" - buttonHeight: 32 - onClicked: root.deviceFlow.close() - } - DankButton { - text: "Save sharing" - buttonHeight: 32 - enabled: root.service && !root.service.busy - onClicked: root.service.setFolderSharing(root.deviceFlow.targetFolderId, root.deviceFlow.draftIds) - } - } - } - - Column { - visible: root.deviceFlow.view === "device-folders" - width: parent.width - spacing: Theme.spacingS - StyledText { - text: "SHARED WITH " + (root.deviceFlow.targetDeviceName || root.deviceFlow.shortId(root.deviceFlow.targetDeviceId)) - color: Theme.surfaceText - font.weight: Font.DemiBold - } - Repeater { - model: root.service ? root.service.folderIdsForDevice(root.deviceFlow.targetDeviceId) : [] - delegate: DankButton { - required property string modelData - width: parent.width - text: (root.deviceFlow.draftIds.indexOf(modelData) >= 0 ? "[x] " : "[ ] ") + root.service.folderLabel(modelData) - buttonHeight: 30 - onClicked: root.deviceFlow.toggleDraft(modelData) - } - } - Row { - spacing: Theme.spacingS - DankButton { - text: "Cancel" - buttonHeight: 32 - onClicked: root.deviceFlow.close() - } - DankButton { - text: "Save sharing" - buttonHeight: 32 - enabled: root.service && !root.service.busy && root.deviceFlow.removedFolderIds().length > 0 - onClicked: root.service.removeDeviceFolderShares(root.deviceFlow.targetDeviceId, root.deviceFlow.removedFolderIds(), root.deviceFlow.targetDeviceName) - } - } - } - - StyledRect { - visible: root.deviceFlow.view === "dismiss-device" - width: parent.width - height: dismissContent.implicitHeight + Theme.spacingM * 2 - radius: Theme.cornerRadius - color: Theme.surfaceContainerHigh - Column { - id: dismissContent - anchors.fill: parent - anchors.margins: Theme.spacingM - spacing: Theme.spacingS - StyledText { - text: "Dismiss pending request from " + (root.deviceFlow.targetDeviceName || root.deviceFlow.shortId(root.deviceFlow.targetDeviceId)) + "?" - color: Theme.error - } - Row { - spacing: Theme.spacingS - DankButton { - text: "Cancel" - buttonHeight: 32 - onClicked: root.deviceFlow.close() - } - DankButton { - text: "Dismiss" - buttonHeight: 32 - enabled: root.service && !root.service.busy - onClicked: root.service.dismissPendingDevice(root.deviceFlow.targetDeviceId, root.deviceFlow.targetDeviceName) - } - } - } - } - } - - StyledRect { - visible: root.pendingForgetId !== "" - width: parent.width - height: forgetContent.implicitHeight + Theme.spacingM * 2 - radius: Theme.cornerRadius - color: Theme.surfaceContainerHigh - - Column { - id: forgetContent - anchors.fill: parent - anchors.margins: Theme.spacingM - spacing: Theme.spacingS - - StyledText { - width: parent.width - text: "Forget " + root.pendingForgetLabel + " (" + root.pendingForgetId + ")? The directory and data files " + "will not be deleted. Rejoining requires this Folder ID." - color: Theme.error - wrapMode: Text.WordWrap - } - Row { - spacing: Theme.spacingS - DankButton { - text: "Cancel" - buttonHeight: 32 - onClicked: root.pendingForgetId = "" - } - DankButton { - text: "Forget" - buttonHeight: 32 - enabled: root.service && !root.service.busy - onClicked: root.confirmForget() - } - } - } - } - - Row { - width: parent.width - spacing: Theme.spacingS - DankButton { - text: "Web UI" - iconName: "open_in_new" - buttonHeight: 34 - enabled: root.service && root.service.online - onClicked: root.service.openWebUi() - } - } - - Row { - width: parent.width - spacing: Theme.spacingS - DankButton { - text: "Rescan all" - iconName: "sync" - buttonHeight: 34 - enabled: root.service && root.service.online && !root.service.busy && root.service.folderCount > 0 - onClicked: root.service.rescanAllFolders() - } - DankButton { - text: "Refresh status" - iconName: "refresh" - buttonHeight: 34 - enabled: root.service && !root.service.busy && !root.service.refreshing - onClicked: root.service.refresh() - } - } - } - - Connections { - target: root.service - function onFolderIdSuggestionChanged() { - if (!idField.getActiveFocus() && root.service.folderIdSuggestion) - idField.text = root.service.folderIdSuggestion; - } - function onActionFinished(action, ok) { - root.deviceFlow.actionFinished(action, ok); - } - } - } - } -} diff --git a/integrations/dankmaterialshell/assemble.sh b/integrations/dankmaterialshell/assemble.sh deleted file mode 100755 index 0351e1cb..00000000 --- a/integrations/dankmaterialshell/assemble.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/bash -set -euo pipefail - -integration_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) -repo_root=$(cd -- "$integration_root/../.." && pwd) -target=${1:-} - -[[ -n $target && $target == /* ]] || { - printf 'usage: %s EMPTY_ABSOLUTE_DIRECTORY\n' "$0" >&2 - exit 2 -} -mkdir -p -- "$target" -[[ -z $(find "$target" -mindepth 1 -maxdepth 1 -print -quit) ]] || { - printf 'DankMaterialShell target must be empty\n' >&2 - exit 1 -} - -install -d -- "$target/shared" "$target/bin/x86_64" "$target/bin/aarch64" -install -m 0644 -- "$integration_root/plugin.json" \ - "$integration_root/SyncshellDaemon.qml" \ - "$integration_root/SyncshellWidget.qml" "$target/" -install -m 0644 -- "$repo_root/shared/CoreProcess.qml" \ - "$repo_root/shared/AdapterService.qml" \ - "$repo_root/shared/DeviceWorkflow.qml" \ - "$repo_root/shared/RescanTracker.qml" \ - "$repo_root/shared/Paths.js" "$target/shared/" -install -m 0755 -- "$repo_root/bin/syncshell-core" \ - "$target/bin/syncshell-core" -install -m 0755 -- "$repo_root/bin/x86_64/syncshell-core" \ - "$target/bin/x86_64/syncshell-core" -install -m 0755 -- "$repo_root/bin/aarch64/syncshell-core" \ - "$target/bin/aarch64/syncshell-core" -(cd -- "$repo_root" && \ - sha256sum --check packaging/bundled/SHA256SUMS >/dev/null) -printf '[ok] assembled DMS adapter\n' diff --git a/integrations/dankmaterialshell/plugin.json b/integrations/dankmaterialshell/plugin.json deleted file mode 100644 index c34d5f1a..00000000 --- a/integrations/dankmaterialshell/plugin.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "id": "syncshell", - "name": "Syncshell", - "description": "Monitor Syncthing and safely manage synchronized folders", - "version": "0.2.4", - "author": "ilyaZar", - "type": "composite", - "capabilities": ["daemon", "dankbar-widget", "monitoring"], - "icon": "sync", - "components": { - "daemon": "./SyncshellDaemon.qml", - "widget": "./SyncshellWidget.qml" - }, - "requires_dms": ">=1.5.3", - "dependencies": ["syncthing"], - "permissions": ["process", "network"] -} diff --git a/integrations/dux-shell/assemble.sh b/integrations/dux-shell/assemble.sh new file mode 100755 index 00000000..ad854296 --- /dev/null +++ b/integrations/dux-shell/assemble.sh @@ -0,0 +1,77 @@ +#!/bin/bash +set -euo pipefail + +integration_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +repo_root=$(cd -- "$integration_root/../.." && pwd) +target=${1:-} + +[[ -n $target && $target == /* ]] || { + printf 'usage: %s EMPTY_ABSOLUTE_DIRECTORY\n' "$0" >&2 + exit 2 +} +mkdir -p -- "$target" +[[ -z $(find "$target" -mindepth 1 -maxdepth 1 -print -quit) ]] || { + printf 'DMS target must be empty\n' >&2 + exit 1 +} + +(cd -- "$repo_root" && \ + sha256sum --check packaging/bundled/SHA256SUMS >/dev/null) +(cd -- "$repo_root/webui" && sha256sum --quiet --check SHA256SUMS) + +while IFS= read -r path; do + [[ $path != /* && $path != *..* && -f $repo_root/$path ]] || { + printf 'invalid package source: %s\n' "$path" >&2 + exit 1 + } + install -Dm0644 -- "$repo_root/$path" "$target/$path" +done <"$integration_root/qml-files.txt" +node "$repo_root/integrations/assemble-qml.mjs" "$target" \ + "$integration_root/qml-files.txt" "$integration_root/import-map.json" + +install -d -- "$target/bin/x86_64" "$target/bin/aarch64" \ + "$target/assets/mono" "$target/packaging/bundled" +install -m 0644 -- "$integration_root/plugin.json" "$target/plugin.json" +install -m 0644 -- "$repo_root/hosts/dux-shell/README.md" "$target/README.md" +install -m 0644 -- "$repo_root/LICENSE" "$repo_root/CHANGELOG.md" "$target/" +install -m 0644 -- "$repo_root/packaging/bundled/LICENSE.golang" \ + "$repo_root/packaging/bundled/SHA256SUMS" "$target/packaging/bundled/" +for icon in status-default.svg status-notify.svg status-pause.svg status-sync.svg; do + install -m 0644 -- "$repo_root/assets/$icon" "$target/assets/$icon" + install -m 0644 -- "$repo_root/assets/mono/$icon" "$target/assets/mono/$icon" +done +install -m 0644 -- "$repo_root/assets/LICENSE.md" "$target/assets/LICENSE.md" +cp -a -- "$repo_root/webui" "$target/webui" +install -m 0755 -- "$repo_root/bin/syncshell-core" \ + "$target/bin/syncshell-core" +install -m 0755 -- "$repo_root/bin/x86_64/syncshell-core" \ + "$target/bin/x86_64/syncshell-core" +install -m 0755 -- "$repo_root/bin/aarch64/syncshell-core" \ + "$target/bin/aarch64/syncshell-core" +node - "$repo_root" "$target" <<'NODE' +const fs = require("node:fs"); +const path = require("node:path"); +const crypto = require("node:crypto"); +const [source, output] = process.argv.slice(2); +const recipe = crypto.createHash("sha256"); +for (const file of ["integrations/dux-shell/assemble.sh", + "integrations/dux-shell/qml-files.txt", "integrations/dux-shell/import-map.json", + "integrations/assemble-qml.mjs"]) + recipe.update(file + "\n").update(fs.readFileSync(path.join(source, file))); +const provenance = { + format: 1, + repository: "https://github.com/omarchy-QOL/syncshell", + version: JSON.parse(fs.readFileSync(path.join(output, "plugin.json"))).version, + dmsSDK: "2.0.0", + coreToolchain: "go" + fs.readFileSync(path.join(source, "core/go.mod"), "utf8").match(/^go (.+)$/m)[1], + recipeSha256: recipe.digest("hex"), + webUi: JSON.parse(fs.readFileSync(path.join(output, "webui/manifest.json"))) +}; +fs.writeFileSync(path.join(output, "ASSEMBLY.json"), JSON.stringify(provenance, null, 2) + "\n"); +NODE +( + cd -- "$target" + find . -type f ! -name PACKAGE-SHA256SUMS -print0 \ + | LC_ALL=C sort -z | xargs -0 sha256sum >PACKAGE-SHA256SUMS +) +printf '[ok] assembled DMS adapter\n' diff --git a/integrations/dux-shell/home-manager.nix b/integrations/dux-shell/home-manager.nix new file mode 100644 index 00000000..dfc0c1b3 --- /dev/null +++ b/integrations/dux-shell/home-manager.nix @@ -0,0 +1,20 @@ +{ config, lib, pkgs, ... }: +let + cfg = config.programs.syncshell-dux-shell; +in { + options.programs.syncshell-dux-shell = { + enable = lib.mkEnableOption "the Syncshell DMS plugin"; + package = lib.mkOption { + type = lib.types.package; + default = pkgs.callPackage ./package.nix { }; + description = "Self-contained Syncshell DMS plugin package"; + }; + }; + config = lib.mkIf cfg.enable { + programs.dank-material-shell.plugins.syncshell = { + enable = true; + src = cfg.package; + }; + home.packages = [ pkgs.bash pkgs.coreutils pkgs.findutils ]; + }; +} diff --git a/integrations/dux-shell/import-map.json b/integrations/dux-shell/import-map.json new file mode 100644 index 00000000..74d2284d --- /dev/null +++ b/integrations/dux-shell/import-map.json @@ -0,0 +1,25 @@ +{ + "QtQuick": "QtQuick", + "QtQuick.Controls": "QtQuick.Controls", + "QtQuick.Layouts": "QtQuick.Layouts", + "QtQuick.Window": "QtQuick.Window", + "Quickshell": "Quickshell", + "Quickshell.Wayland": "Quickshell.Wayland", + "Quickshell.Io": "Quickshell.Io", + "qs.Common": "qs.Common", + "qs.DCommon.Widgets": "qs.DCommon.Widgets", + "qs.Widgets": "qs.Widgets", + "qs.Services": "qs.Services", + "qs.Modules.Plugins": "qs.Modules.Plugins", + "qs.Modals.FileBrowser": "qs.Modals.FileBrowser", + "\".\"": "\".\"", + "\"Paths.js\"": "\"Paths.js\"", + "\"../../shared\"": "\"../../shared\"", + "\"../../shared/Paths.js\"": "\"../../shared/Paths.js\"", + "\"controllers\"": "\"controllers\"", + "\"ui\"": "\"ui\"", + "\"../controllers\"": "\"../controllers\"", + "\"../models/PanelModel.js\"": "\"../models/PanelModel.js\"", + "\"models/PanelModel.js\"": "\"models/PanelModel.js\"", + "\"UiConstants.js\"": "\"UiConstants.js\"" +} diff --git a/integrations/dux-shell/package.nix b/integrations/dux-shell/package.nix new file mode 100644 index 00000000..52a7aa23 --- /dev/null +++ b/integrations/dux-shell/package.nix @@ -0,0 +1,42 @@ +{ lib, stdenvNoCC, nodejs, bash, coreutils, findutils }: +stdenvNoCC.mkDerivation { + pname = "syncshell-dux-shell"; + version = (builtins.fromJSON (builtins.readFile ./plugin.json)).version; + src = lib.fileset.toSource { + root = ../..; + fileset = lib.fileset.unions [ + ../../shared + ../../hosts/dux-shell + ../../integrations/assemble-qml.mjs + ./assemble.sh + ./plugin.json + ./qml-files.txt + ./import-map.json + ../../bin + ../../webui + ../../packaging/bundled + ../../core/go.mod + ../../LICENSE + ../../CHANGELOG.md + ../../assets/LICENSE.md + ../../assets/mono + ../../assets/status-default.svg + ../../assets/status-notify.svg + ../../assets/status-pause.svg + ../../assets/status-sync.svg + ]; + }; + nativeBuildInputs = [ nodejs bash coreutils findutils ]; + dontBuild = true; + dontFixup = true; + installPhase = '' + runHook preInstall + bash integrations/dux-shell/assemble.sh "$out" + runHook postInstall + ''; + meta = { + description = "Syncthing folder and device management for DMS (Dux Shell)"; + license = with lib.licenses; [ mit mpl20 ofl bsd3 ]; + platforms = [ "x86_64-linux" "aarch64-linux" ]; + }; +} diff --git a/integrations/dux-shell/plugin.json b/integrations/dux-shell/plugin.json new file mode 100644 index 00000000..1d868fc2 --- /dev/null +++ b/integrations/dux-shell/plugin.json @@ -0,0 +1,18 @@ +{ + "id": "syncshell", + "name": "Syncshell", + "description": "Monitor synchronization and manage folders, devices, sharing, and invitations from DMS (Dux Shell)", + "version": "0.2.4", + "author": "ilyaZar", + "type": "composite", + "capabilities": ["daemon", "dankbar-widget", "monitoring"], + "icon": "sync", + "components": { + "daemon": "./hosts/dux-shell/DuxShellService.qml", + "widget": "./hosts/dux-shell/DuxShellPanel.qml" + }, + "settings": "./hosts/dux-shell/ui/SettingsMenu.qml", + "requires_dms": ">=2.0.0", + "dependencies": ["syncthing"], + "permissions": ["process", "network", "settings_read", "settings_write"] +} diff --git a/integrations/dux-shell/qml-files.txt b/integrations/dux-shell/qml-files.txt new file mode 100644 index 00000000..f2a9acaf --- /dev/null +++ b/integrations/dux-shell/qml-files.txt @@ -0,0 +1,42 @@ +shared/AdapterService.qml +shared/CoreProcess.qml +shared/Paths.js +shared/RescanTracker.qml +hosts/dux-shell/DuxShellPanel.qml +hosts/dux-shell/DuxShellService.qml +hosts/dux-shell/controllers/PanelController.qml +hosts/dux-shell/controllers/SettingsController.qml +hosts/dux-shell/controllers/ThemePaletteController.qml +hosts/dux-shell/models/PanelModel.js +hosts/dux-shell/ui/BodyFormHeader.qml +hosts/dux-shell/ui/BodyFormSideCard.qml +hosts/dux-shell/ui/BodyMore.qml +hosts/dux-shell/ui/BodyTabDevices.qml +hosts/dux-shell/ui/BodyTabDevicesAcceptForm.qml +hosts/dux-shell/ui/BodyTabDevicesAddForm.qml +hosts/dux-shell/ui/BodyTabDevicesCard.qml +hosts/dux-shell/ui/BodyTabDevicesFoldersForm.qml +hosts/dux-shell/ui/BodyTabFolders.qml +hosts/dux-shell/ui/BodyTabFoldersAddForm.qml +hosts/dux-shell/ui/BodyTabFoldersCard.qml +hosts/dux-shell/ui/BodyTabFoldersCardActivity.qml +hosts/dux-shell/ui/BodyTabFoldersSelector.qml +hosts/dux-shell/ui/BodyTabFoldersShareForm.qml +hosts/dux-shell/ui/BodyTabFoldersViewOptions.qml +hosts/dux-shell/ui/FooterActions.qml +hosts/dux-shell/ui/FooterShortcutHint.qml +hosts/dux-shell/ui/Header.qml +hosts/dux-shell/ui/SettingsMenu.qml +hosts/dux-shell/ui/SharedDialogConfirm.qml +hosts/dux-shell/ui/SharedWidgetBusyButton.qml +hosts/dux-shell/ui/SharedWidgetDropdown.qml +hosts/dux-shell/ui/SharedWidgetIdCopyButton.qml +hosts/dux-shell/ui/SharedWidgetInfoPair.qml +hosts/dux-shell/ui/SharedWidgetMonoIcon.qml +hosts/dux-shell/ui/SharedWidgetMultiSelect.qml +hosts/dux-shell/ui/SharedWidgetSquareActionButton.qml +hosts/dux-shell/ui/SharedWidgetToolTip.qml +hosts/dux-shell/ui/SharedWidgetTooltipActionButton.qml +hosts/dux-shell/ui/SharedWidgetTooltipButton.qml +hosts/dux-shell/ui/SyncshellPanelPopup.qml +hosts/dux-shell/ui/UiConstants.js diff --git a/packaging/bundled/SHA256SUMS b/packaging/bundled/SHA256SUMS index c351f947..71a7a018 100644 --- a/packaging/bundled/SHA256SUMS +++ b/packaging/bundled/SHA256SUMS @@ -1,3 +1,3 @@ -ff1a30e27af91678877df6ae65e6e9a3bded047b6ac1efd484bd94f5daf1f7c8 bin/syncshell-core -b472a55f7edc422c56fd964f27b8668a0c8b7a462f79349a96076aa10fa1e9d5 bin/x86_64/syncshell-core -080201dc245258103ca283ce2562b6205bf743943ffeaca4056a233cad90292d bin/aarch64/syncshell-core +314a89c32525c5b746f50a52b65967ed301e11f12bbbf5f3d44e387a10d540fc bin/syncshell-core +2b441a4caa43466eef0153dfd4b47a5fb19c21909a6a1fed37ba614cd2bf49c0 bin/x86_64/syncshell-core +15b98c1a07cbf67b7e634d117d698425dc89ba6d51f8663b31864eb3550bb4ce bin/aarch64/syncshell-core diff --git a/packaging/bundled/build.sh b/packaging/bundled/build.sh index da8c3763..c442072e 100755 --- a/packaging/bundled/build.sh +++ b/packaging/bundled/build.sh @@ -8,22 +8,25 @@ required_go=$(awk '$1 == "go" { print "go" $2 }' "$root/core/go.mod") exit 1 } +# Pin the instruction-set baselines instead of inheriting Go's defaults: v1 +# runs on every x86_64 machine, including old Intel Macs, and v8.0 on every +# aarch64 one, from Raspberry Pis to Apple Silicon Macs and Snapdragon laptops. build_core() { - local directory=$1 goarch=$2 + local directory=$1 goarch=$2 baseline=$3 local output="$root/bin/$directory/syncshell-core" mkdir -p -- "$(dirname -- "$output")" ( cd -- "$root/core" - GOOS=linux GOARCH="$goarch" CGO_ENABLED=0 \ + env GOOS=linux GOARCH="$goarch" "$baseline" CGO_ENABLED=0 \ go build -mod=readonly -trimpath -buildvcs=false \ -ldflags='-buildid=' -o "$output" ./cmd/syncshell-core ) chmod 755 -- "$output" } -build_core x86_64 amd64 -build_core aarch64 arm64 +build_core x86_64 amd64 GOAMD64=v1 +build_core aarch64 arm64 GOARM64=v8.0 chmod 755 -- "$root/bin/syncshell-core" ( cd -- "$root" diff --git a/packaging/bundled/verify.sh b/packaging/bundled/verify.sh index 4e9c472a..c5509396 100755 --- a/packaging/bundled/verify.sh +++ b/packaging/bundled/verify.sh @@ -18,8 +18,8 @@ verify_mode() { } verify_binary() { - local relative=$1 file_arch=$2 goarch=$3 - local binary="$root/$relative" metadata build_metadata + local relative=$1 file_arch=$2 goarch=$3 baseline=$4 page=$5 + local binary="$root/$relative" metadata build_metadata alignment align [[ -f $binary && ! -L $binary && -x $binary ]] \ || fail "$relative is not a regular executable" @@ -36,6 +36,17 @@ verify_binary() { || fail "$relative Go architecture metadata is unexpected" grep -Fq $'build\tGOOS=linux' <<<"$build_metadata" \ || fail "$relative Go operating-system metadata is unexpected" + grep -Fq $'build\t'"$baseline" <<<"$build_metadata" \ + || fail "$relative instruction-set baseline is not $baseline" + # Every loadable segment must be aligned to the largest page size the + # architecture's kernels use: 4K on x86_64, but 16K on Apple Silicon and 64K + # on some ARM servers. + alignment=$(readelf -lW -- "$binary" | awk '$1 == "LOAD" { print $NF }') + [[ -n $alignment ]] || fail "$relative has no loadable segments" + for align in $alignment; do + (( align >= page )) \ + || fail "$relative segments are not aligned for $((page / 1024))K pages" + done if strings -- "$binary" \ | rg -n '/home/iz|/home-hdd-cold|BEGIN (RSA |OPENSSH )?PRIVATE KEY' \ >/dev/null; then @@ -52,8 +63,8 @@ bash -n "$root/$launcher" cd -- "$root" sha256sum --check packaging/bundled/SHA256SUMS ) -verify_binary bin/x86_64/syncshell-core x86-64 amd64 -verify_binary bin/aarch64/syncshell-core "ARM aarch64" arm64 +verify_binary bin/x86_64/syncshell-core x86-64 amd64 GOAMD64=v1 0x1000 +verify_binary bin/aarch64/syncshell-core "ARM aarch64" arm64 GOARM64=v8.0 0x10000 config="$test_root/config.xml" printf '%s\n' \ diff --git a/shared/AdapterService.qml b/shared/AdapterService.qml index 7551e494..2d63eaeb 100644 --- a/shared/AdapterService.qml +++ b/shared/AdapterService.qml @@ -8,6 +8,17 @@ QtObject { property int probeIntervalSeconds: 15 property int refreshIntervalSeconds: 60 + property bool startCore: true + property string bundleRoot: Paths.localFilePath(Qt.resolvedUrl("..")) + property var lifecyclePolicy: ({}) + property string desiredServiceState: "disabled" + property bool desktopAuthorized: false + property var profilePolicy: ({}) + property string configPath: "" + property string endpoint: "" + property string credentialFile: "" + property string tlsCertificate: "" + property string expectedDeviceId: "" readonly property string homePath: Quickshell.env("HOME") || "" readonly property var state: core.snapshot || ({}) @@ -18,6 +29,13 @@ QtObject { readonly property var activity: state.activity || ({}) readonly property var currentActivity: activity.current || ({}) readonly property var webUi: state.webUi || ({}) + readonly property var lifecycle: state.lifecycle || ({}) + readonly property var installation: state.installation || ({}) + readonly property bool lifecycleAuthorized: lifecyclePolicy.authorized === true + && lifecyclePolicy.kind === "systemd-user" && !!lifecyclePolicy.unit + readonly property bool canControlService: lifecycleAuthorized + && lifecycle.authorized === true && lifecycle.canControl === true + readonly property bool canStartService: canControlService && lifecycle.canStart === true readonly property var folders: state.folders || [] readonly property var devices: state.devices || [] readonly property var pendingFolders: state.pendingFolders || ({}) @@ -167,9 +185,11 @@ QtObject { } function refresh() { - if (!core.protocolReady || refreshing || busy) + if (refreshing || busy) return false; actionError = ""; + if (!core.protocolReady) + return core.restart(); _refreshRequest = core.refresh(function (ok, data, error) { root._refreshRequest = ""; if (!ok) @@ -179,8 +199,14 @@ QtObject { } function runAction(name, args, notice, targetId) { - if (!online || busy || refreshing) { - actionError = online ? "Another operation is already running" : "Syncthing must be online"; + var lifecycleAction = name.indexOf("lifecycle.") === 0; + var available = core.protocolReady && (online || lifecycleAction && canStartService); + if (!available || busy || refreshing) { + actionError = available ? "Another operation is already running" : "Syncthing must be online"; + return false; + } + if (lifecycleAction && !canControlService) { + actionError = "This Syncthing instance is externally managed"; return false; } actionError = ""; @@ -254,7 +280,7 @@ QtObject { function setFolderPaused(folderId, paused) { return runAction(paused ? "folder.pause" : "folder.resume", { folderId: folderId - }, paused ? "Paused " + folderLabel(folderId) : "Resumed " + folderLabel(folderId), folderId); + }, paused ? "Synchronization for " + folderLabel(folderId) + " paused. The folder ID, device associations, and data remain." : "Linked " + folderLabel(folderId) + ". Syncthing resumed the folder with its existing sharing configuration.", folderId); } function rescanFolder(folderId) { @@ -270,7 +296,7 @@ QtObject { function forgetFolder(folderId) { return runAction("folder.forget", { folderId: folderId - }, "Forgot " + folderLabel(folderId) + "; directory contents were kept", folderId); + }, "Removed from Syncthing configuration and the plugin view. The directory and its data files were not deleted. Re-add Folder ID " + folderId + " to rejoin the same remote folder.", folderId); } function requestFolderIdSuggestion() { @@ -280,20 +306,33 @@ QtObject { function addFolder(values) { var input = values || ({}); + var folderId = String(input.folderId || input.id || ""); + var deviceIds = (input.deviceIds || input.selectedDeviceIds || []).slice(); return runAction("folder.add-existing", { folderId: String(input.folderId || input.id || ""), path: Paths.resolveFolderPath(input.path, homePath), + createDirectory: input.createDirectory === true, label: String(input.label || ""), - deviceIds: input.deviceIds || input.selectedDeviceIds || [], + deviceIds: (input.deviceIds || input.selectedDeviceIds || []).slice(), pendingDeviceId: String(input.pendingDeviceId || "") - }, "Added existing directory", String(input.folderId || input.id || "")); + }, deviceIds.length > 0 ? "Remote devices may have to accept the folder." : "Added " + (String(input.label || "") || folderId) + " locally. It is linked but not shared with another device.", folderId); } + // Omarchy's wording: first share waits for acceptance, later ones update. function setFolderSharing(folderId, deviceIds) { + var shared = deviceIds || []; + var current = folder(folderId); + var previous = (current && current.devices || []).filter(member => member.id && member.id !== localDeviceId); + var names = shared.map(id => deviceName(id)).join(", "); + var notice = "Folder sharing removed. The local folder remains configured."; + if (shared.length > 0 && previous.length === 0) + notice = folderLabel(folderId) + " shared with " + names + "; waiting for " + names + " to accept."; + else if (shared.length > 0) + notice = "Sharing with " + names + " updated."; return runAction("folder.set-sharing", { folderId: String(folderId || ""), - deviceIds: deviceIds || [] - }, "Folder sharing updated", String(folderId || "")); + deviceIds: shared + }, notice, String(folderId || "")); } function addDevice(deviceId, name) { @@ -301,28 +340,28 @@ QtObject { return runAction("device.add", { deviceId: String(deviceId || ""), deviceName: String(name || "") - }, label + " added; add this device there to complete the connection", String(deviceId || "")); + }, label + " added. Add this device on " + label + " to complete connection.", String(deviceId || "")); } function dismissPendingDevice(deviceId, name) { var label = String(name || "").trim() || String(deviceId || "").slice(0, 7); return runAction("device.dismiss-pending", { deviceId: String(deviceId || "") - }, "Dismissed pending request from " + label, String(deviceId || "")); + }, "Dismissed pending request from " + label + ".", String(deviceId || "")); } function setDevicePaused(deviceId, paused, name) { var label = String(name || "").trim() || "Device " + String(deviceId || "").slice(0, 7); return runAction(paused ? "device.pause" : "device.resume", { deviceId: String(deviceId || "") - }, paused ? "Paused synchronization with " + label : "Resumed synchronization with " + label, String(deviceId || "")); + }, paused ? "Paused synchronization with " + label + "." : "Resumed synchronization with " + label + ".", String(deviceId || "")); } function removeDevice(deviceId, name) { var label = String(name || "").trim() || "Device " + String(deviceId || "").slice(0, 7); return runAction("device.remove", { deviceId: String(deviceId || "") - }, label + " removed from this device", String(deviceId || "")); + }, label + " removed from this device.", String(deviceId || "")); } function removeDeviceFolderShares(deviceId, folderIds, name) { @@ -330,25 +369,87 @@ QtObject { return runAction("device.remove-folder-shares", { deviceId: String(deviceId || ""), folderIds: folderIds || [] - }, "Selected folder shares removed from " + label, String(deviceId || "")); + }, "Selected folder shares removed from " + label + ".", String(deviceId || "")); } function openWebUi() { if (!online || !baseUrl) return false; + if (desktopAuthorized) + return runAction("webui.open", {}, "", ""); return Qt.openUrlExternally(baseUrl); } + function dismissPendingFolder(folderId, deviceId) { + var offer = pendingFolderOffers().find(item => item.folderId === String(folderId || "") && item.deviceId === String(deviceId || "")); + return runAction("folder.dismiss-pending", { + folderId: String(folderId || ""), + pendingDeviceId: String(deviceId || "") + }, "Rejected folder request for " + (offer ? offer.label : String(folderId || "")) + ".", String(folderId || "")); + } + + function recheckErrors() { + return runAction("folder.recheck-errors", {}, "Folder errors checked", ""); + } + + function setWebUiTheme(theme) { + return runAction("webui.set-theme", { theme: String(theme || "") }, "Web UI theme updated", ""); + } + + function applyWebProfile(style, palette) { + return runAction("webui.apply-profile", { + profile: style, palette: palette || ({}) + }, "Web UI profile updated", ""); + } + + function removeWebProfile() { + return runAction("webui.remove-profile", {}, "This adapter's Web UI profiles removed", ""); + } + + function setServiceEnabled(enabled) { + return runAction(enabled ? "lifecycle.enable" : "lifecycle.disable", {}, + enabled ? "Syncthing enabled" : "Syncthing disabled", ""); + } + + function startupArguments() { + var args = ["--probe-interval-seconds", String(probeIntervalSeconds), + "--desired-service-state", desiredServiceState]; + if (lifecycleAuthorized) { + args.push("--lifecycle-kind", lifecyclePolicy.kind, + "--lifecycle-authorized", "--lifecycle-unit", lifecyclePolicy.unit); + if (lifecyclePolicy.configPath) + args.push("--lifecycle-config", lifecyclePolicy.configPath); + } + if (desktopAuthorized) + args.push("--desktop-authorized"); + if (profilePolicy.authorized === true) + args.push("--web-profile-authorized", "--web-profile-owner", profilePolicy.owner, + "--web-profile-bundle", profilePolicy.bundle); + var targets = [ + ["--config", configPath], ["--endpoint", endpoint], + ["--credential-file", credentialFile], ["--tls-certificate", tlsCertificate], + ["--expected-device-id", expectedDeviceId] + ]; + for (let index = 0; index < targets.length; index++) { + if (targets[index][1]) + args.push(targets[index][0], targets[index][1]); + } + return args; + } + function configureCore() { - if (!core.protocolReady) + if (!core || !core.protocolReady) return; core.configure({ probeIntervalSeconds: probeIntervalSeconds, refreshIntervalSeconds: refreshIntervalSeconds, - desiredServiceState: "enabled" + desiredServiceState: desiredServiceState }); } + onProbeIntervalSecondsChanged: configureCore() + onRefreshIntervalSecondsChanged: configureCore() + onDesiredServiceStateChanged: configureCore() onFoldersChanged: rescanTracker.reconcile(scanningFolderIds()) onOnlineChanged: { if (!online && busy && (_actionName === "folder.rescan" || _actionName === "folder.rescan-all") && rescanTracker.runningFolderIds.length > 0) { @@ -364,7 +465,9 @@ QtObject { } property CoreProcess core: CoreProcess { - startupArguments: ["--probe-interval-seconds", String(root.probeIntervalSeconds), "--desired-service-state", "enabled", "--lifecycle-kind", "systemd-user", "--lifecycle-authorized", "--lifecycle-unit", "syncthing.service"] + desiredRunning: root.startCore + corePath: root.bundleRoot.replace(/\/$/, "") + "/bin/syncshell-core" + startupArguments: root.startupArguments() onProtocolReadyChanged: if (protocolReady) root.configureCore() onRunningChanged: if (!running) { diff --git a/shared/CoreProcess.qml b/shared/CoreProcess.qml index c30492ee..52f2f598 100644 --- a/shared/CoreProcess.qml +++ b/shared/CoreProcess.qml @@ -6,7 +6,7 @@ QtObject { id: root property var startupArguments: [] - readonly property string corePath: Paths.localFilePath(Qt.resolvedUrl("../bin/syncshell-core")) + property string corePath: Paths.localFilePath(Qt.resolvedUrl("../bin/syncshell-core")) property bool executableReady: false property bool starting: true property bool desiredRunning: true @@ -43,6 +43,8 @@ QtObject { } function terminate() { + restartTimer.stop(); + shutdownTimer.stop(); _restartRequested = false; _expectedStop = true; desiredRunning = false; @@ -53,6 +55,7 @@ QtObject { function restart() { if (!executableReady) return false; + incompatible = false; restartAttempts = 0; _restartRequested = true; _expectedStop = true; @@ -299,7 +302,7 @@ QtObject { } property Process executableProcess: Process { - command: ["/usr/bin/find", root.corePath, "-maxdepth", "0", "-type", "f", "-executable", "-print"] + command: ["find", root.corePath, "-maxdepth", "0", "-type", "f", "-executable", "-print"] stdout: StdioCollector { waitForEnd: true @@ -327,7 +330,8 @@ QtObject { root._expectedStop = false; root.desiredRunning = false; Qt.callLater(function () { - root.desiredRunning = true; + if (!root._expectedStop) + root.desiredRunning = true; }); } } diff --git a/tests/adapter-contract.test.mjs b/tests/adapter-contract.test.mjs new file mode 100644 index 00000000..0b3182a2 --- /dev/null +++ b/tests/adapter-contract.test.mjs @@ -0,0 +1,170 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const source = readFileSync(new URL("../shared/AdapterService.qml", + import.meta.url), "utf8"); + +function service(overrides = {}) { + const context = vm.createContext({ + probeIntervalSeconds: 15, refreshIntervalSeconds: 60, + desiredServiceState: "disabled", lifecyclePolicy: {}, + lifecycleAuthorized: false, desktopAuthorized: false, + profilePolicy: {}, + configPath: "", endpoint: "", credentialFile: "", tlsCertificate: "", + expectedDeviceId: "", canControlService: false, canStartService: false, + online: true, busy: false, refreshing: false, baseUrl: "http://127.0.0.1:8384", + homePath: "/home/test", actionError: "", actionNotice: "", + folders: [], devices: [], pendingFolders: {}, localDeviceId: "", + Paths: { resolveFolderPath: path => path }, + core: { protocolReady: true }, + rescanTracker: { reset() {} }, + Qt: { openUrlExternally() { throw Error("unexpected external open"); } }, + ...overrides, + }); + context.root = context; + for (const match of source.matchAll(/^ function \w+\([^]*?^ }/gm)) + vm.runInContext(match[0], context); + return context; +} + +test("omitted host policy grants no lifecycle or desktop authority", () => { + const host = service(); + const args = Array.from(host.startupArguments()); + assert.deepEqual(args, ["--probe-interval-seconds", "15", + "--desired-service-state", "disabled"]); + assert.match(source, /property var lifecyclePolicy: \(\{\}\)/); + assert.match(source, /property bool desktopAuthorized: false/); + assert.equal(host.setServiceEnabled(true), false); + assert.match(host.actionError, /externally managed/); +}); + +test("host passes the exact authorized binding and private target paths", () => { + const host = service({ + lifecycleAuthorized: true, + lifecyclePolicy: { kind: "systemd-user", unit: "syncthing-test.service", + configPath: "/private/config.xml" }, + desktopAuthorized: true, configPath: "/private/config.xml", + endpoint: "https://localhost:8384", credentialFile: "/private/key", + tlsCertificate: "/private/cert", expectedDeviceId: "TARGET", + }); + assert.deepEqual(Array.from(host.startupArguments()), [ + "--probe-interval-seconds", "15", "--desired-service-state", "disabled", + "--lifecycle-kind", "systemd-user", "--lifecycle-authorized", + "--lifecycle-unit", "syncthing-test.service", + "--lifecycle-config", "/private/config.xml", "--desktop-authorized", + "--config", "/private/config.xml", "--endpoint", "https://localhost:8384", + "--credential-file", "/private/key", "--tls-certificate", "/private/cert", + "--expected-device-id", "TARGET", + ]); +}); + +test("only verified lifecycle authority permits starting an offline instance", () => { + let sent; + const host = service({ online: false, canStartService: true, + canControlService: true, core: { protocolReady: true, + action(name, args) { sent = name; return "1"; } }, + }); + assert.equal(host.setServiceEnabled(true), true); + assert.equal(sent, "lifecycle.enable"); + assert.equal(host.rescanAllFolders(), false); + host.canStartService = false; + assert.equal(host.setServiceEnabled(true), false); +}); + +test("confirmed directory creation and invitation target survive dispatch", () => { + let sent; + const host = service(); + host.runAction = (name, args) => { sent = { name, args }; return true; }; + const deviceIds = ["REMOTE"]; + host.addFolder({ path: "/tmp/missing", folderId: "docs", deviceIds, + pendingDeviceId: "REMOTE" }); + assert.equal(sent.args.createDirectory, false); + host.addFolder({ path: "/tmp/missing", folderId: "docs", deviceIds, + pendingDeviceId: "REMOTE", createDirectory: true }); + deviceIds.push("OTHER"); + assert.equal(sent.args.createDirectory, true); + assert.deepEqual(Array.from(sent.args.deviceIds), ["REMOTE"]); + assert.equal(sent.args.pendingDeviceId, "REMOTE"); + host.dismissPendingFolder("offer", "SENDER"); + assert.equal(sent.name, "folder.dismiss-pending"); + assert.equal(sent.args.folderId, "offer"); + assert.equal(sent.args.pendingDeviceId, "SENDER"); + host.recheckErrors(); + assert.equal(sent.name, "folder.recheck-errors"); +}); + +test("authorized Web UI uses the core desktop bridge", () => { + let action; + const host = service({ desktopAuthorized: true }); + host.runAction = name => { action = name; return true; }; + assert.equal(host.openWebUi(), true); + assert.equal(action, "webui.open"); +}); + +test("manual refresh retries a stopped worker after installation or startup failure", () => { + let restarted = 0; + const host = service({ core: { protocolReady: false, + restart() { restarted++; return true; } } }); + assert.equal(host.refresh(), true); + assert.equal(restarted, 1); + host.busy = true; + assert.equal(host.refresh(), false); + assert.equal(restarted, 1); +}); + +test("action success, failure and duplicate submissions settle once", () => { + let reply; + const finished = []; + const host = service({ + core: { protocolReady: true, + action(name, args, callback) { reply = callback; return "1"; } }, + actionFinished: (...args) => finished.push(args), + }); + Object.defineProperty(host, "busy", { get: () => !!host._actionRequest }); + assert.equal(host.recheckErrors(), true); + assert.equal(host.busy, true); + assert.equal(host.recheckErrors(), false); + reply(false, null, { code: "offline", message: "Lost connection" }); + assert.equal(host.busy, false); + assert.equal(host.actionError, "Lost connection"); + assert.equal(finished.length, 1); + host.recheckErrors(); + reply(true, {}, null); + assert.equal(host.busy, false); + assert.equal(host.actionNotice, "Folder errors checked"); + assert.equal(finished.length, 2); +}); + +test("action notices use Omarchy's wording", () => { + const host = service({ + localDeviceId: "LOCAL", + folders: [{ id: "docs", label: "Docs", devices: [{ id: "LOCAL" }] }, + { id: "work", label: "Work", devices: [{ id: "LOCAL" }, { id: "PEER" }] }], + devices: [{ id: "PEER", name: "laptop" }], + pendingFolders: { offer: { offeredBy: { PEER: { label: "Photos" } } } }, + core: { protocolReady: true, + action(name, args, callback) { callback(true, {}, null); return "1"; } }, + actionFinished() {}, + }); + const notice = run => (run(), host.actionNotice); + assert.equal(notice(() => host.setFolderPaused("docs", true)), + "Synchronization for Docs paused. The folder ID, device associations, and data remain."); + assert.equal(notice(() => host.setFolderPaused("docs", false)), + "Linked Docs. Syncthing resumed the folder with its existing sharing configuration."); + assert.match(notice(() => host.forgetFolder("docs")), /^Removed from Syncthing configuration.*Re-add Folder ID docs/); + assert.equal(notice(() => host.addFolder({ folderId: "new", label: "New", path: "/n" })), + "Added New locally. It is linked but not shared with another device."); + assert.equal(notice(() => host.addFolder({ folderId: "new", path: "/n", deviceIds: ["PEER"] })), + "Remote devices may have to accept the folder."); + assert.equal(notice(() => host.setFolderSharing("docs", ["PEER"])), + "Docs shared with laptop; waiting for laptop to accept."); + assert.equal(notice(() => host.setFolderSharing("work", ["PEER"])), "Sharing with laptop updated."); + assert.equal(notice(() => host.setFolderSharing("work", [])), + "Folder sharing removed. The local folder remains configured."); + assert.equal(notice(() => host.dismissPendingFolder("offer", "PEER")), "Rejected folder request for Photos."); + assert.equal(notice(() => host.addDevice("PEER", "laptop")), + "laptop added. Add this device on laptop to complete connection."); + assert.equal(notice(() => host.removeDevice("PEER", "laptop")), "laptop removed from this device."); +}); diff --git a/tests/busy-button.qml b/tests/busy-button.qml index a5d317ab..0cb2905a 100644 --- a/tests/busy-button.qml +++ b/tests/busy-button.qml @@ -25,7 +25,7 @@ ShellRoot { anchors.centerIn: parent spacing: 16 - BusyButton { + SharedWidgetBusyButton { id: button text: "RESCAN" busyText: "RESCANNING A LONG FOLDER LABEL" @@ -36,7 +36,7 @@ ShellRoot { onClicked: root.activations++ } - BusyButton { + SharedWidgetBusyButton { id: pulseButton text: "Refresh Sync.status" busyText: "Rechecking Syncthing" diff --git a/tests/busy-button.test.sh b/tests/busy-button.test.sh index 4a61c9bc..f7e86e5d 100755 --- a/tests/busy-button.test.sh +++ b/tests/busy-button.test.sh @@ -6,8 +6,8 @@ source "$(dirname -- "${BASH_SOURCE[0]}")/qml-test-helper.sh" configure_visual_test "$@" stage_omarchy_test busy-button \ - hosts/omarchy/ui/BusyButton.qml \ - hosts/omarchy/ui/SyncshellToolTip.qml \ + hosts/omarchy/ui/SharedWidgetBusyButton.qml \ + hosts/omarchy/ui/SharedWidgetToolTip.qml \ hosts/omarchy/ui/UiConstants.js \ tests/VisualPause.qml diff --git a/tests/caelestia-adapter.test.sh b/tests/caelestia-adapter.test.sh index cccbb7a4..6a657aaa 100755 --- a/tests/caelestia-adapter.test.sh +++ b/tests/caelestia-adapter.test.sh @@ -1,26 +1,77 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail - root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) -manifest="$root/integrations/caelestia/manifest.json" +sdk=${CAELESTIA_SDK:?set CAELESTIA_SDK to the pinned shell checkout} +build=${CAELESTIA_SDK_BUILD:?set CAELESTIA_SDK_BUILD to an out-of-tree build directory} +[[ $(git -C "$sdk" rev-parse HEAD) == 4e288c54a3b039154d19fe8a2064a174eb634405 ]] work=$(mktemp -d) -trap 'find "$work" -depth -delete' EXIT -commit=$(jq -er .commit "$manifest") -git -C "$work" init -q caelestia -git -C "$work/caelestia" remote add origin "$(jq -er .repository "$manifest")" -git -C "$work/caelestia" fetch -q --depth=1 origin "$commit" -git -C "$work/caelestia" checkout -q --detach FETCH_HEAD -bash "$root/integrations/caelestia/apply.sh" "$work/caelestia" -git -C "$work/caelestia" diff --check -test -x "$work/caelestia/syncshell/bin/syncshell-core" -test -x "$work/caelestia/syncshell/bin/x86_64/syncshell-core" -test -x "$work/caelestia/syncshell/bin/aarch64/syncshell-core" -test -f "$work/caelestia/syncshell/shared/DeviceWorkflow.qml" -test -f "$work/caelestia/syncshell/shared/RescanTracker.qml" -rg -q 'SyncshellStatus' \ - "$work/caelestia/modules/bar/components/StatusIcons.qml" -rg -q 'LIST_ENTRY\(syncshell, true\)' \ - "$work/caelestia/plugin/src/Caelestia/Config/barconfig.hpp" -rg -q 'DIRECTORY syncshell.*USE_SOURCE_PERMISSIONS' \ - "$work/caelestia/CMakeLists.txt" -printf '[ok] Caelestia adapter contract passed\n' +trap 'rm -rf -- "$work"' EXIT +cmake -S "$root/tests/caelestia-sdk" -B "$build" -G Ninja -DCAELESTIA_SDK="$sdk" >"$work/configure.log" +cmake --build "$build" -j 4 >"$work/build.log" 2>&1 || { cat "$work/build.log"; exit 1; } +for copy in first second; do + bash "$root/integrations/caelestia/assemble.sh" "$work/$copy" + (cd -- "$work/$copy" && sha256sum --quiet --check SHA256SUMS) +done +diff -qr "$work/first" "$work/second" +ln -s -- "$work/first" "$work/linked" +for package in "$work/first" "$work/linked"; do + "$build/syncshell-caelestia-probe" "$package" >"$work/types" + if "$package/bin/syncshell-core" stream --help >"$work/stdout" 2>"$work/stderr"; then + printf 'expected help to exit before starting a core session\n' >&2; exit 1 + fi + grep -q 'syncshell-core: invalid command arguments' "$work/stderr" +done +mkdir -p "$work/loader-plugins" "$work/config/caelestia" "$work/data" "$work/cache" +ln -s "$work/first" "$work/loader-plugins/syncshell" +printf '%s\n' '{"enabled":["syncshell/syncshell"],"settings":{}}' >"$work/config/caelestia/plugins.json" +cat >"$work/Injected.qml" <"$work/Loader.qml" </dev/null + lint_options=(--max-warnings 0 --unqualified disable) + # Quickshell's metadata omits QProcess::ExitStatus for these existing handlers. + if [[ $file == shared/CoreProcess.qml ]]; then + lint_options+=(--signal-handler-parameters info) + fi + /usr/lib/qt6/bin/qmllint "${lint_options[@]}" \ + -I "$work/imports" -I "$build/qml" \ + "$work/imports/syncshell/syncshell/$file" +done < "$root/integrations/caelestia/qml-files.txt" +# Run the actual controller against the named imports from the payload. +mkdir -p "$work/behavior" +for test_file in "$root"/tests/caelestia/tst_*.qml; do + sed 's|import "../../hosts/caelestia/controllers"|import syncshell.syncshell.hosts.caelestia.controllers|' \ + "$test_file" >"$work/behavior/$(basename "$test_file")" +done +QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner \ + -import "$work/imports" -input "$work/behavior" +node --test "$root/tests/caelestia-model.test.mjs" \ + "$root/tests/caelestia-ownership.test.mjs" "$root/tests/caelestia-shortcuts.test.mjs" "$root/tests/adapter-contract.test.mjs" +printf '[ok] Caelestia payload, SDK, behavior and reproducibility checks passed\n' diff --git a/tests/caelestia-imports.py b/tests/caelestia-imports.py new file mode 100644 index 00000000..93229d72 --- /dev/null +++ b/tests/caelestia-imports.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Generate tooling metadata from the exact source and assembled payload.""" +import pathlib +import shutil +import sys + +sdk, payload, target = map(pathlib.Path, sys.argv[1:]) +for source, destination, prefix in ( + (sdk, target / 'qs', 'qs'), + (payload, target / 'syncshell' / 'syncshell', 'syncshell.syncshell'), +): + for path in source.rglob('*'): + if path.suffix not in ('.qml', '.js') or '.git' in path.parts: + continue + relative = path.relative_to(source) + if source == sdk and relative.parts[0] not in ('components', 'services', 'modules', 'utils'): + continue + output = destination / relative + output.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, output) + for directory in [destination] + sorted(p for p in destination.rglob('*') if p.is_dir()): + relative = directory.relative_to(destination) + uri = '.'.join((prefix, *relative.parts)) + lines = ['module ' + uri] + for path in sorted(directory.glob('*.qml')): + if not path.stem[0].isupper(): + continue + singleton = 'singleton ' if 'pragma Singleton' in path.read_text() else '' + lines.append(singleton + path.stem + ' 1.0 ' + path.name) + (directory / 'qmldir').write_text('\n'.join(lines) + '\n') diff --git a/tests/caelestia-model.test.mjs b/tests/caelestia-model.test.mjs new file mode 100644 index 00000000..7541e4c9 --- /dev/null +++ b/tests/caelestia-model.test.mjs @@ -0,0 +1,188 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; +const model = vm.createContext({}); +vm.runInContext(readFileSync(new URL("../hosts/caelestia/models/PanelModel.js", import.meta.url), "utf8").replace(/^\.pragma library\n/, ""), model); +// Common parity cases from the DMS behavior fixtures; no host UI is imported. +const folders = [ + { id: "z", label: "Documents", path: "/work/docs", status: { state: "idle" } }, + { id: "a", label: "Documents", path: "/home/docs", status: { state: "idle" } }, + { id: "busy", label: "Uploads", status: { state: "syncing" } }, + { id: "error", label: "Broken", status: { state: "idle", pullErrors: 1 } }, + { id: "paused", label: "Archive", paused: true, status: { state: "idle" } }, + { id: "unknown", label: "Starting", status: {} }, +]; +const ids = rows => Array.from(rows, row => row.value); +test("fuzzy search matches the current Omarchy behavior", () => { + const source = readFileSync(new URL("../hosts/omarchy/ui/SharedWidgetDropdown.qml", import.meta.url), "utf8"); + const reference = vm.createContext({}); + vm.runInContext(source.match(/^ function matchesSearch\([^]*?^ }/m)[0], reference); + for (const label of ["Documents", "Archive 2026", "Shared Photos", "", "aabb"]) + for (const query of ["dcm", " DOC ", "ar26", "s p", "", "bbb", "nope"]) + assert.equal(model.matchesSearch(label, query), reference.matchesSearch(label, query)); +}); +test("duplicate labels, mixed filters, path search and priority sorting preserve IDs", () => { + assert.deepEqual(ids(model.options(folders, "dcm", null, "name", true)), ["a", "z"]); + assert.deepEqual(ids(model.options(folders, "", ["active", "errors"], "active", true)), ["busy", "error"]); + assert.deepEqual(ids(model.options(folders, "/work", null, "name", true)), ["z"]); + assert.equal(model.options(folders, "", [], "name", true).length, 0); + assert.equal(model.selectedId(folders.slice().reverse(), "a"), "a"); +}); +test("stale state never reports current folder or device status", () => { + assert.ok(folders.every(f => model.folderState(f, false) === "unknown")); + assert.equal(model.deviceStatus({ connected: true }, false), "Status unknown"); + assert.equal(model.selectedId([], "gone"), ""); +}); +test("searching a multiselect does not remove hidden selections", () => { + assert.deepEqual(Array.from(model.toggle(["a", "hidden"], "a")), ["hidden"]); +}); +test("every selector searches stable IDs even when labels and details omit them", () => { + const rows = [ + { value: "folder-a", label: "Documents", detail: "valid" }, + { value: "folder-b", label: "Documents", detail: "valid" }, + { value: "REMOTE-ID", label: "Laptop", detail: "tcp://192.0.2.1" }, + ]; + const matching = query => rows.filter(row => model.matchesOption(row, query)).map(row => row.value); + assert.deepEqual(matching("folder-b"), ["folder-b"]); + assert.deepEqual(matching("remote-id"), ["REMOTE-ID"]); + assert.deepEqual(matching("192.0.2.1"), ["REMOTE-ID"]); + assert.deepEqual(matching("dcm"), ["folder-a", "folder-b"]); + assert.deepEqual(matching("missing"), []); + assert.deepEqual(matching(""), rows.map(row => row.value)); +}); +test("taller side forms preserve the main screen anchor at both vertical edges", () => { + for (const center of [30, 350, 830]) { + const closed = model.geometry(400, 400, 0, 0, 0, 1100, 900, center, 12); + const open = model.geometry(400, 400, 360, 650, 150, 1100, 900, center, 12); + assert.equal(open.mainHeight, closed.mainHeight); + assert.equal(open.center - open.height / 2 + open.mainY, closed.center - closed.height / 2 + closed.mainY); + assert.ok(open.center - open.height / 2 >= 0); + assert.ok(open.formY >= 0 && open.formY + open.formHeight <= open.height); + } +}); +test("More grows naturally, overflow clamps, and narrow screens stack", () => { + const geometry = (h, w = 1100, side = 0) => model.geometry(400, h, side, 600, 60, w, 900, 400, 12); + assert.equal(geometry(300).height, 300); + assert.equal(geometry(500).height, 500); + assert.equal(geometry(1500).height, 876); + assert.equal(geometry(500, 700, 360).stacked, true); +}); + +test("count-only and state-only errors stay visible with fallback details", () => { + for (const status of [{ state: "error" }, { state: "idle", pullErrors: 4 }, + { state: "idle", errors: [{ path: "file", error: "denied" }] }]) { + const folder = { id: "broken", status }; + assert.equal(model.hasErrors(folder), true); + assert.ok(model.errorDetails(folder).length > 0); + } + assert.match(model.errorDetails({ status: { pullErrors: 4 } }), /no error details.*Showing 0 of 4 current errors/s); + assert.match(model.errorDetails({ status: { errors: [{ path: "file", error: "denied" }] } }), /denied\nfile/); + assert.equal(model.errorDetails({ status: { state: "idle" } }), ""); + assert.equal(model.hasErrors(null), false); +}); + +test("folder presentation preserves state precedence, local-only and remaining bytes", () => { + const folder = (status, extra = {}) => ({ id: "one", path: "/work/docs", label: "Archive", status, ...extra }); + const cases = [ + [folder({ state: "idle" }), false, "", false, false, "UNKNOWN"], + [folder({ state: "error" }, { paused: true }), true, "", false, false, "UNLINKED"], + [folder({ state: "idle", pullErrors: 1 }), true, "", false, false, "ERROR"], + [folder({ state: "scanning" }), true, "", false, false, "SCANNING"], + [folder({ state: "scanning", needTotalItems: 2 }), true, "", false, false, "SCAN+SYNC"], + [folder({ state: "idle" }), true, "", true, true, "SCAN+SYNC"], + [folder({ state: "syncing" }), true, "", false, false, "SYNCING"], + [folder({ state: "idle" }), true, "one", false, false, "LINKED"], + [folder({ state: "idle" }), true, "", false, false, "SYNCED"], + [folder({}), true, "", false, false, "UNKNOWN"], + ]; + for (const [f, fresh, linked, activity, scanning, expected] of cases) { + assert.equal(model.folderStatus(f, fresh, linked, activity, scanning), expected); + assert.ok(model.stateHelp(expected).startsWith(expected + " · ")); + } + assert.match(model.folderMeta(folder({ state: "syncing", needTotalItems: 2, needBytes: 2048 }), true, "local", false), /2 items remaining.*2.*KiB.*Archive/); + assert.match(model.folderMeta(folder({ state: "idle", globalFiles: 3 }, { devices: [{ id: "local" }] }), true, "local", false), /3 files.*local only/); + assert.match(model.folderMeta(folder({ state: "idle" }), false, "local", false), /^Last reported:/); +}); +test("activity is current and belongs to the displayed folder", () => { + const activity = { folderId: "one", action: "Uploading", detail: "photo.jpg" }; + assert.equal(model.folderActivity({ id: "one" }, true, activity), "Uploading photo.jpg"); + assert.equal(model.folderActivity({ id: "two" }, true, activity), ""); + assert.equal(model.folderActivity({ id: "one" }, false, activity), ""); + assert.equal(model.folderActivity(null, true, activity), ""); +}); +test("remote share confirmation requires fresh connected unpaused device state", () => { + for (const remoteState of ["valid", "paused", "unknown", "notSharing"]) { + const folder = { devices: [{ id: "peer", remoteState }] }; + assert.equal(model.remoteShare(folder, { id: "peer", connected: true }, true), remoteState); + assert.equal(model.remoteShare(folder, { id: "peer", connected: false }, true), "unknown"); + assert.equal(model.remoteShare(folder, { id: "peer", connected: true, paused: true }, true), "unknown"); + assert.equal(model.remoteShare(folder, { id: "peer", connected: true }, false), "unknown"); + } +}); + +test("error details group paths by reason and disclose bounded counts", () => { + const folder = { status: { pullErrors: 7, errors: [ + { path: "one", error: "denied" }, { path: "two", error: "denied" }, + { path: "three", error: "missing" } ] } }; + const detail = model.errorDetails(folder); + assert.match(detail, /denied\none\ntwo/); + assert.match(detail, /missing\nthree/); + assert.equal(detail.match(/denied/g).length, 1); + assert.match(detail, /Showing 3 of 7 current errors.*Open Web UI/s); + assert.equal(model.hasErrors({ status: { state: "error" } }), true); + assert.equal(model.hasErrors({ status: { errors: [{ error: "missing" }] } }), true); + assert.match(model.errorDetails({ status: { pullErrors: 4 } }), /no error details.*Showing 0 of 4/s); + assert.equal(model.errorDetails({ status: { state: "idle" } }), ""); +}); + +test("share descriptions preserve remote acceptance and pause explanations", () => { + for (const [state, expected] of Object.entries({ + valid: "Remote share confirmed", paused: "Remote folder paused", + notSharing: "Remote is not sharing back", unknown: "Remote acceptance unconfirmed", + })) { + const folder = { devices: [{ id: "peer", remoteState: state }] }; + assert.equal(model.remoteShareDescription(model.remoteShare(folder, + { id: "peer", connected: true }, true)), expected); + assert.equal(model.remoteShareDescription(model.remoteShare(folder, + { id: "peer", connected: true }, false)), "Remote acceptance unconfirmed"); + } +}); +test("hover cannot open the overview: Bar.checkPopout opens popouts whose entry equals a bar entry name", () => { + const manifest = JSON.parse(readFileSync(new URL("../integrations/caelestia/manifest.json", import.meta.url), "utf8")); + const bars = manifest.entryPoints.filter(e => e.type === "bar-entry").map(e => e.properties.name); + const popouts = manifest.entryPoints.filter(e => e.type === "bar-popout").map(e => e.properties.entry); + assert.deepEqual(popouts, [model.overviewPopout]); + assert.ok(popouts.every(entry => !bars.includes(entry))); +}); +test("status icon and tooltip follow Omarchy precedence without inventing success", () => { + const base = { phase: "ready", online: true, canControlService: false, lifecycle: {}, installation: { available: true }, + folderProblemCount: 0, syncingFolderCount: 0, refreshing: false, busy: false, currentActivity: {}, summaryText: "Up to date" }; + const s = over => Object.assign({}, base, over); + assert.equal(model.statusVariant(null), "notify"); + assert.equal(model.statusVariant(s({ phase: "core-unavailable", online: false })), "notify"); + assert.equal(model.statusVariant(s({ canControlService: true, lifecycle: { active: false }, online: false })), "pause"); + assert.equal(model.statusVariant(s({ online: false, phase: "discovering" })), "sync"); + assert.equal(model.statusVariant(s({ online: false, phase: "error" })), "notify"); + assert.equal(model.statusVariant(s({ folderProblemCount: 1, syncingFolderCount: 1 })), "notify"); + assert.equal(model.statusVariant(s({ refreshing: true })), "sync"); + assert.equal(model.statusVariant(s({})), "default"); + assert.equal(model.barTooltip(null), "Syncthing unavailable"); + assert.equal(model.barTooltip(s({})), "Syncthing: Up to date"); + assert.equal(model.barTooltip(s({ syncingFolderCount: 2 })), "Syncthing: Sync in progress..."); + // refreshing alone shows the sync icon but is not a sync in progress + assert.equal(model.barTooltip(s({ refreshing: true })), "Syncthing: Up to date"); + assert.equal(model.barTooltip(s({ online: false, syncingFolderCount: 2, summaryText: "Syncthing unavailable" })), "Syncthing: Syncthing unavailable"); + assert.equal(model.barTooltip(s({ installation: { available: false } })), "Syncthing: Syncthing is not installed"); + assert.equal(model.barTooltip(s({ canControlService: true, lifecycle: { active: false } })), "Syncthing: Syncing stopped"); +}); +test("counts are formatted and pluralized like Omarchy", () => { + const omarchy = vm.createContext({}); + // Only formatCount is compared; drop the QML JS directives. + vm.runInContext(readFileSync(new URL("../hosts/omarchy/models/PanelModel.js", import.meta.url), "utf8").replace(/^\.(pragma|import) .*$/gm, ""), omarchy); + for (const n of [0, 1, 999, 1000, 1500, 9999, 10000, 153000, 1250000]) + assert.equal(model.formatCount(n), omarchy.formatCount(n)); + assert.equal(model.plural(1, "shared folder"), "1 shared folder"); + assert.equal(model.plural(2, "shared folder"), "2 shared folders"); + assert.equal(model.statusIconUrl("/opt/p q", "sync", true), "file:///opt/p%20q/assets/mono/status-sync.svg"); +}); diff --git a/tests/caelestia-ownership.test.mjs b/tests/caelestia-ownership.test.mjs new file mode 100644 index 00000000..aa41e994 --- /dev/null +++ b/tests/caelestia-ownership.test.mjs @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; +const source = readFileSync(new URL("../hosts/caelestia/CaelestiaService.qml", import.meta.url), "utf8"); +function registry() { + const context = vm.createContext({}); + vm.runInContext(readFileSync(new URL("../hosts/caelestia/models/Ownership.js", import.meta.url), "utf8").replace(/^\.pragma library\n/, ""), context); + return context; +} +function owner(ownership) { + let running = false, starts = 0, stops = 0; + const service = vm.createContext({ + plugin: null, settings: null, ownerGeneration: -1, predecessor: null, + owners: [], retired: false, awaitingExit: false, views: {}, Ownership: ownership, + paletteUpdate: { stop() {} }, Qt: { callLater(fn) { fn(); } }, + adapter: { core: { + get running() { return running; }, + desiredRunning: false, + start() { this.desiredRunning = true; running = true; starts++; }, + terminate() { this.desiredRunning = false; stops++; }, + } }, + }); + service.root = service; + Object.defineProperty(service, "eligible", { get() { + return !!service.plugin && service.plugin.enabled && !service.retired + && service.plugin.generation === service.ownerGeneration && service.owners.length > 0; + } }); + for (const match of source.matchAll(/^ function \w+\([^]*?^ }/gm)) + vm.runInContext(match[0], service); + return { service, counts: () => ({ starts, stops }), exit() { running = false; } }; +} +test("two bars share ownership and final release requests shutdown", () => { + const host = owner(registry()); + const plugin = { enabled: true, generation: 1 }; + host.service.acquire({ plugin }, {}, "monitor-a"); + host.service.acquire({ plugin }, {}, "monitor-b"); + host.service.release("monitor-a"); + assert.equal(host.counts().stops, 0); + assert.equal(host.counts().starts, 1); + host.service.release("monitor-b"); + assert.equal(host.counts().stops, 1); + assert.equal(host.service.owners.length, 0); +}); +test("a new QML generation waits for the previous worker exit", () => { + const shared = registry(), old = owner(shared), next = owner(shared); + const plugin = { enabled: true, generation: 1 }; + old.service.acquire({ plugin }, {}, "old"); + plugin.generation = 2; + next.service.acquire({ plugin }, {}, "new"); + assert.equal(old.service.retired, true); + assert.equal(next.counts().starts, 0); + old.exit(); + next.service.maybeStart(); + assert.equal(next.counts().starts, 1); +}); +test("a disabled or released generation cannot restart", () => { + const host = owner(registry()), plugin = { enabled: true, generation: 1 }; + host.service.acquire({ plugin }, {}, "bar"); + host.service.release("bar"); host.exit(); host.service.maybeStart(); + assert.equal(host.counts().starts, 1); + plugin.enabled = false; + host.service.acquire({ plugin }, {}, "new"); + assert.equal(host.counts().starts, 1); +}); +test("explicit termination cancels scheduled crash recovery", () => { + const code = readFileSync(new URL("../shared/CoreProcess.qml", import.meta.url), "utf8"); + const context = vm.createContext({ + restartTimer: { stop() { context.recoveryStopped = true; } }, + shutdownTimer: { stop() {} }, coreProcess: { running: false }, + _restartRequested: true, _expectedStop: false, desiredRunning: true, + }); + vm.runInContext(code.match(/^ function terminate\([^]*?^ }/m)[0], context); + context.terminate(); + assert.equal(context.recoveryStopped, true); + assert.equal(context._expectedStop, true); + assert.equal(context.desiredRunning, false); +}); + +test("only the current eligible owner can request a Web UI profile", () => { + for (const inactive of ["disabled", "released", "retired", "replaced"]) { + const host = owner(registry()), plugin = { enabled: true, generation: 1 }; + let writes = 0; + host.service.theme = { palette: { accent: "#aabbcc" } }; + host.service.adapter.applyWebProfile = () => { writes++; return true; }; + host.service.adapter.setWebUiTheme = () => { writes++; return true; }; + host.service.acquire({ plugin }, {}, "bar"); + assert.equal(host.service.applyWebUi("themed"), true); + assert.equal(writes, 1); + if (inactive === "disabled") plugin.enabled = false; + if (inactive === "released") host.service.release("bar"); + if (inactive === "retired") host.service.retire(); + if (inactive === "replaced") plugin.generation++; + assert.equal(host.service.applyWebUi("themed"), false, inactive); + assert.equal(host.service.applyWebUi("default"), false, inactive); + assert.equal(writes, 1, inactive); + } +}); diff --git a/tests/caelestia-sdk/CMakeLists.txt b/tests/caelestia-sdk/CMakeLists.txt new file mode 100644 index 00000000..1b9eeb50 --- /dev/null +++ b/tests/caelestia-sdk/CMakeLists.txt @@ -0,0 +1,30 @@ +cmake_minimum_required(VERSION 3.19) +project(syncshell_caelestia_sdk VERSION 2.2.0 LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 20) +find_package(Qt6 REQUIRED COMPONENTS ShaderTools Core Qml Gui Quick QuickControls2 Concurrent Sql Network DBus) +find_package(PkgConfig REQUIRED) +pkg_check_modules(Qalculate IMPORTED_TARGET libqalculate REQUIRED) +set(QT_QML_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/qml") +set(INSTALL_QMLDIR lib/qt6/qml) +set(VERSION 2.2.0) +qt_standard_project_setup(REQUIRES 6.9) +include("${CAELESTIA_SDK}/plugin/cmake/pch.cmake") +include("${CAELESTIA_SDK}/plugin/cmake/qml-module.cmake") +foreach(module Config Plugins Components Internal Models Images Blobs) + add_subdirectory("${CAELESTIA_SDK}/plugin/src/Caelestia/${module}" "${module}") +endforeach() + +set(core_sources) +foreach(file cutils qalculator appdb requests toaster imageanalyser) + list(APPEND core_sources "${CAELESTIA_SDK}/plugin/src/Caelestia/${file}.cpp") +endforeach() +qml_module(caelestia-core URI Caelestia SOURCES ${core_sources} + LIBRARIES Qt::Gui Qt::Quick Qt::Concurrent Qt::Sql PkgConfig::Qalculate) +target_compile_definitions(caelestia-core PRIVATE CAELESTIA_VERSION="${VERSION}") +target_include_directories(caelestia-core PRIVATE "${CAELESTIA_SDK}/plugin/src/Caelestia") +add_executable(syncshell-caelestia-probe probe.cpp) +target_include_directories(syncshell-caelestia-probe PRIVATE "${CAELESTIA_SDK}/plugin/src/Caelestia/Plugins") +target_link_libraries(syncshell-caelestia-probe PRIVATE caelestia-plugins Qt::Core Qt::Qml Qt::Quick) +add_executable(syncshell-caelestia-loader loader.cpp) +target_include_directories(syncshell-caelestia-loader PRIVATE "${CAELESTIA_SDK}/plugin/src/Caelestia/Plugins") +target_link_libraries(syncshell-caelestia-loader PRIVATE caelestia-plugins Qt::Core Qt::Qml Qt::Quick) diff --git a/tests/caelestia-sdk/loader.cpp b/tests/caelestia-sdk/loader.cpp new file mode 100644 index 00000000..c96a0c14 --- /dev/null +++ b/tests/caelestia-sdk/loader.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include +#include "entrypointloader.hpp" +#include "pluginmanifest.hpp" + +int main(int argc, char **argv) { + QGuiApplication app(argc, argv); + if (argc != 2) return 2; + QQmlEngine engine; + QQmlComponent component(&engine, QUrl::fromLocalFile(QString::fromLocal8Bit(argv[1]))); + QScopedPointer object(component.create()); + if (!object) { + QTextStream(stderr) << component.errorString(); + return 1; + } + auto *loader = qobject_cast(object.get()); + if (!loader || !loader->item()) return 1; + const auto first = loader->item(); + QPointer oldSettings = first->property("settings").value(); + if (!oldSettings || oldSettings->property("schemaVersion").toInt() != 1) return 1; + oldSettings->setProperty("probeSeconds", 37); + const auto plugin = loader->entryPoint().plugin(); + if (!plugin || plugin->id() != "syncshell/syncshell") return 1; + plugin->setGeneration(plugin->generation() + 1); + if (!loader->item() || loader->item() == first) return 1; + const auto settings = loader->item()->property("settings").value(); + if (!settings || settings == oldSettings || settings->property("probeSeconds").toInt() != 37) return 1; + if (loader->item()->property("priorProbe").toInt() != 1) return 1; + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + if (oldSettings) return 1; + QTextStream(stdout) << "[ok] actual loader settings injection, generation rebinding and stable JS state\n"; + return 0; +} diff --git a/tests/caelestia-sdk/probe.cpp b/tests/caelestia-sdk/probe.cpp new file mode 100644 index 00000000..f8c2882e --- /dev/null +++ b/tests/caelestia-sdk/probe.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include "pluginmanifest.hpp" +#include "pluginmodule.hpp" + +int main(int argc, char **argv) { + QCoreApplication app(argc, argv); + if (argc != 2) return 2; + const auto directory = QDir(QString::fromLocal8Bit(argv[1])).absolutePath(); + caelestia::plugins::PluginManifest manifest(directory, directory + "/manifest.json"); + if (!manifest.valid()) { + QTextStream(stderr) << manifest.error() << '\n'; + return 1; + } + caelestia::plugins::PluginModule module(directory, manifest.moduleUri()); + module.scan({}); + for (const auto &warning : module.warnings()) { + if (!warning.contains("hot reloading is not supported for JavaScript files") + && !warning.startsWith("syncshell-modern: invalid subdirectory name")) { + QTextStream(stderr) << warning << '\n'; + return 1; + } + } + bool singleton = false; + for (const auto &type : module.types()) { + if (type.name == "CaelestiaService") singleton = type.singleton; + QTextStream(stdout) << type.uri << ' ' << type.name << '\n'; + } + if (!singleton) return 1; + for (const auto &entry : manifest.entryPoints()) { + if (!QFile::exists(directory + '/' + entry.source())) return 1; + } + return 0; +} diff --git a/tests/caelestia-shortcuts.test.mjs b/tests/caelestia-shortcuts.test.mjs new file mode 100644 index 00000000..29cb068c --- /dev/null +++ b/tests/caelestia-shortcuts.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; +const source = readFileSync(new URL("../hosts/caelestia/ui/SyncshellPanelPopup.qml", import.meta.url), "utf8"); +const handler = "(" + source.match(/^ Keys\.onPressed: (event => \{[^]*?^ \})/m)[1] + ")"; +const Qt = Object.fromEntries(["Escape", "Up", "Down", "Left", "Right", "R", "W", "P", "S", "Q"].map(k => ["Key_" + k, k])); +test("p requests the service toggle on either tab, even with no selection", () => { + for (const tab of ["folders", "devices"]) { + for (const selected of [null, { id: "retained", paused: false }]) { + let toggles = 0; + const controller = { tab, view: { tab }, folder: selected, device: selected, + requestServiceToggle() { toggles++; } }; + const root = { Window: { window: { activeFocusItem: null } } }; + const context = vm.createContext({ Qt, controller, root, hasForm: false }); + const run = vm.runInContext(handler, context); + const event = { key: "P", accepted: false }; + run(event); + assert.equal(toggles, 1); + assert.equal(event.accepted, true); + for (const guard of ["repeat", "busy", "form", "confirmation", "editor"]) { + toggles = 0; + controller.busy = guard === "busy"; + controller.form = guard === "form" ? "add-folder" : ""; + context.hasForm = guard === "form"; + controller.confirmation = controller.view.confirmation = guard === "confirmation" ? {} : null; + root.Window.window.activeFocusItem = guard === "editor" ? { cursorPosition: 1 } : null; + run({ key: "P", isAutoRepeat: guard === "repeat", accepted: false }); + assert.equal(toggles, 0, guard); + } + } + } +}); + +test("busy buttons reject held keys and busy activation even with custom disabled bindings", () => { + const source = readFileSync(new URL("../hosts/caelestia/ui/SharedWidgetBusyButton.qml", import.meta.url), "utf8"); + const handler = "(" + source.match(/^ Keys\.onPressed: (event => \{[^]*?^ \})/m)[1] + ")"; + let clicks = 0; + const context = vm.createContext({ Qt: { Key_Return: 13, Key_Enter: 10, Key_Space: 32 }, + disabled: false, busy: false, clicked() { clicks++; } }); + const run = vm.runInContext(handler, context); + run({ key: 13, isAutoRepeat: false }); + assert.equal(clicks, 1); + run({ key: 13, isAutoRepeat: true }); + assert.equal(clicks, 1); + context.busy = true; + run({ key: 32, isAutoRepeat: false }); + assert.equal(clicks, 1); +}); diff --git a/tests/caelestia/tst_panel.qml b/tests/caelestia/tst_panel.qml new file mode 100644 index 00000000..6022c069 --- /dev/null +++ b/tests/caelestia/tst_panel.qml @@ -0,0 +1,626 @@ +import QtQuick +import QtTest +import "../../hosts/caelestia/controllers" + +TestCase { + id: test + name: "CaelestiaPanelBehavior" + property var controller + QtObject { + id: backend + property var folders: [ + { + id: "a", + label: "same" + }, + { + id: "b", + label: "same" + } + ] + property var devices: [ + { + id: "one" + }, + { + id: "two" + } + ] + property var sharedFolders: ["a", "b"] + property var pendingDevices: [] + property var offers: [] + property QtObject core: QtObject { + property int generation: 1 + } + property bool online: true + property var connection: ({ + fresh: true + }) + property bool busy: false + property bool refreshing: false + property string homePath: "/home/test" + property var sent: null + signal actionFinished(string action, bool ok, var data, var error) + function remoteDevices() { + return devices; + } + function folder(id) { + return folders.find(f => f.id === id) || null; + } + function device(id) { + return devices.find(d => d.id === id) || null; + } + function pendingFolderOffers() { + return offers; + } + function folderIdsForDevice(id) { + return sharedFolders; + } + function remoteDeviceIdsForFolder(id) { + return ["one"]; + } + function folderLabel(id) { + return id; + } + property bool canControlService: true + property var lifecycle: ({ + active: false, + enabled: false + }) + property string actionError: "" + property string _actionName: "" + property string _actionTargetId: "" + property var scanningIds: [] + function scanning(id) { + return scanningIds.includes(id); + } + function scanningFolderIds() { + return scanningIds; + } + function requestFolderIdSuggestion() { + busy = true; + return true; + } + function runAction(action, args) { + sent = { + action: action, + args: JSON.parse(JSON.stringify(args)) + }; + busy = true; + return true; + } + } + Component { + id: factory + PanelController { + service: backend + screenName: "test" + } + } + function init() { + backend.folders = [ + { + id: "a", + label: "same" + }, + { + id: "b", + label: "same" + } + ]; + backend.pendingDevices = []; + backend.offers = []; + backend.canControlService = true; + backend.lifecycle = { + active: false, + enabled: false + }; + backend.busy = false; + backend.sent = null; + backend.sharedFolders = ["a", "b"]; + backend.connection = { + fresh: true + }; + controller = factory.createObject(test); + controller.update({ + form: "", + draft: {}, + confirmation: null, + folderId: "a" + }); + } + function cleanup() { + controller.destroy(); + } + function test_vanished_device_invitation_preserves_accept_draft() { + backend.pendingDevices = [ + { + id: "peer", + name: "Invited" + } + ]; + controller.openForm("accept-device", backend.pendingDevices[0], 0); + controller.draft({ + deviceName: "My name" + }); + backend.pendingDevices = [ + { + id: "another" + } + ]; + controller.submitForm(); + compare(backend.sent, null); + compare(controller.view.draft.deviceId, "peer"); + compare(controller.view.draft.deviceName, "My name"); + verify(controller.error.includes("invitation")); + compare(controller.submittedAction, ""); + } + function test_vanished_invitation_cannot_be_dismissed() { + for (var folder of [false, true]) { + backend.pendingDevices = [ + { + id: "peer" + } + ]; + backend.offers = [ + { + folderId: "offered", + deviceId: "peer", + encrypted: true + } + ]; + controller.confirm(folder ? "folder.dismiss-pending" : "device.dismiss-pending", folder ? { + folderId: "offered", + pendingDeviceId: "peer" + } : { + deviceId: "peer" + }, "Dismiss?", ""); + backend.pendingDevices = [ + { + id: "another" + } + ]; + backend.offers = [ + { + folderId: "offered", + deviceId: "another" + } + ]; + controller.acceptConfirmation(); + compare(backend.sent, null); + verify(controller.error.includes("invitation")); + controller.cancelConfirmation(); + } + } + function test_live_invitation_keeps_its_frozen_target() { + for (var folder of [false, true]) { + backend.pendingDevices = [ + { + id: "peer" + }, + { + id: "another" + } + ]; + backend.offers = [ + { + folderId: "offered", + deviceId: "peer", + encrypted: true + } + ]; + var args = folder ? { + folderId: "offered", + pendingDeviceId: "peer" + } : { + deviceId: "peer" + }; + controller.confirm(folder ? "folder.dismiss-pending" : "device.dismiss-pending", args, "Dismiss?", ""); + args.deviceId = "another"; + args.pendingDeviceId = "another"; + controller.acceptConfirmation(); + compare(backend.sent.args[folder ? "pendingDeviceId" : "deviceId"], "peer"); + backend.busy = false; + backend.actionFinished(backend.sent.action, true, {}, null); + } + controller.openForm("accept-device", backend.pendingDevices[0], 0); + controller.submitForm(); + compare(backend.sent.action, "device.add"); + compare(backend.sent.args.deviceId, "peer"); + } + function test_closed_form_cannot_submit() { + controller.submitForm(); + compare(backend.sent, null); + compare(controller.submittedAction, ""); + } + function test_retired_controller_cannot_write_or_dispatch() { + controller.openForm("add-device", null, 0); + controller.draft({ + deviceId: "old" + }); + controller.retire(); + var replacement = factory.createObject(test); + replacement.draft({ + deviceId: "new" + }); + controller.draft({ + deviceId: "late" + }); + controller.cancelForm(); + controller.submitForm(); + verify(!controller.send("device.add", { + deviceId: "late" + })); + compare(backend.sent, null); + replacement.retire(); + replacement.destroy(); + var reopened = factory.createObject(test); + compare(reopened.view.form, "add-device"); + compare(reopened.view.draft.deviceId, "new"); + reopened.destroy(); + } + function test_stable_selection_and_draft() { + controller.update({ + folderId: "b" + }); + controller.openForm("add-folder", null, 20); + controller.draft({ + path: "~/work", + folderId: "new", + label: "draft" + }); + backend.folders = [ + { + id: "b", + label: "renamed" + }, + { + id: "a", + label: "same" + } + ]; + compare(controller.view.folderId, "b"); + compare(controller.view.draft.label, "draft"); + controller.destroy(); + controller = factory.createObject(test); + compare(controller.view.draft.path, "~/work"); + } + function test_frozen_confirmation_and_duplicate_submit() { + controller.confirm("folder.forget", { + folderId: "b" + }, "Forget?", "keep files"); + controller.update({ + folderId: "a" + }); + controller.acceptConfirmation(); + compare(backend.sent.args.folderId, "b"); + controller.acceptConfirmation(); + compare(controller.submittedAction, "folder.forget"); + backend.busy = false; + backend.actionFinished("folder.forget", true, {}, null); + compare(controller.view.confirmation, null); + compare(controller.submittedAction, ""); + } + function test_missing_directory_requires_frozen_confirmation() { + controller.openForm("add-folder", null, 0); + backend.busy = false; + backend.actionFinished("folder.suggest-id", true, { + folderId: "suggested" + }, null); + controller.draft({ + path: "~/work", + folderId: "new", + label: "original" + }); + controller.submitForm(); + compare(backend.sent.args.path, "/home/test/work"); + backend.busy = false; + backend.actionFinished("folder.add-existing", false, null, { + code: "path_missing", + message: "missing" + }); + compare(controller.view.confirmation.args.createDirectory, true); + controller.draft({ + path: "/changed" + }); + controller.acceptConfirmation(); + compare(backend.sent.args.path, "/home/test/work"); + } + function test_vanished_target_is_rejected() { + controller.confirm("folder.forget", { + folderId: "b" + }, "Forget?", "keep files"); + backend.folders = [ + { + id: "a" + } + ]; + controller.acceptConfirmation(); + compare(backend.sent, null); + verify(controller.error.includes("disappeared")); + } + function test_new_shares_are_kept_during_a_draft() { + controller.openForm("device-folders", { + id: "one" + }, 0); + controller.draft({ + folderIds: ["b"] + }); + backend.sharedFolders = ["a", "b", "new"]; + backend.folders = backend.folders.concat([ + { + id: "new" + } + ]); + compare(controller.view.draft.folderIds.join(","), "b,new"); + controller.submitForm(); + controller.acceptConfirmation(); + compare(backend.sent.args.folderIds.join(","), "a"); + } + function test_stale_confirmation_is_not_submitted() { + controller.confirm("folder.forget", { + folderId: "a" + }, "Forget?", "keep files"); + backend.connection = { + fresh: false + }; + controller.acceptConfirmation(); + compare(backend.sent, null); + verify(controller.error.includes("stale")); + } + function test_cancel_discards_settings_draft() { + controller.openForm("settings", null, 0); + controller.update({ + settingsDraft: { + probeSeconds: 37 + } + }); + controller.cancelForm(); + compare(controller.view.settingsDraft, null); + compare(controller.view.form, ""); + } + function test_success_restores_form_trigger() { + var destinations = []; + controller.restoreFocus.connect(name => destinations.push(name)); + controller.openForm("add-device", null, 0); + controller.draft({ + deviceId: "new", + deviceName: "name" + }); + controller.submitForm(); + backend.busy = false; + backend.actionFinished("device.add", true, {}, null); + compare(controller.view.form, ""); + compare(destinations[destinations.length - 1], "formTrigger"); + } + function test_failed_action_retains_draft() { + controller.openForm("add-device", null, 0); + controller.draft({ + deviceId: "new", + deviceName: "name" + }); + controller.submitForm(); + backend.busy = false; + backend.actionFinished("device.add", false, null, { + message: "offline" + }); + compare(controller.view.form, "add-device"); + compare(controller.view.draft.deviceName, "name"); + compare(controller.error, "offline"); + } + function test_service_toggle_preserves_autostart() { + for (var active of [false, true]) { + for (var enabled of [false, true]) { + backend.lifecycle = { + active: active, + enabled: enabled + }; + controller.requestServiceToggle(); + compare(controller.view.confirmation.action, active ? "lifecycle.stop" : "lifecycle.start"); + controller.acceptConfirmation(); + compare(backend.sent.action, active ? "lifecycle.stop" : "lifecycle.start"); + compare(backend.lifecycle.enabled, enabled); + backend.busy = false; + backend.actionFinished(backend.sent.action, true, {}, null); + } + } + backend.sent = null; + backend.canControlService = false; + controller.requestServiceToggle(); + compare(controller.view.confirmation, null); + compare(backend.sent, null); + } + function test_service_toggle_does_not_replace_a_draft() { + controller.openForm("add-device", null, 0); + controller.requestServiceToggle(); + compare(controller.view.confirmation, null); + controller.cancelForm(); + controller.confirm("folder.forget", { + folderId: "a" + }, "Forget?", "kept"); + controller.requestServiceToggle(); + compare(controller.view.confirmation.action, "folder.forget"); + } + function test_explicit_folder_id_replaces_existing_id() { + controller.openForm("add-folder", null, 0); + backend.busy = false; + backend.actionFinished("folder.suggest-id", true, { + folderId: "first" + }, null); + compare(controller.view.draft.folderId, "first"); + verify(controller.suggestFolderId()); + compare(controller.view.draft.folderId, "first"); + backend.busy = false; + backend.actionFinished("folder.suggest-id", true, { + folderId: "second" + }, null); + compare(controller.view.draft.folderId, "second"); + verify(controller.suggestFolderId()); + backend.busy = false; + backend.actionFinished("folder.suggest-id", false, null, { + message: "offline" + }); + compare(controller.view.draft.folderId, "second"); + compare(controller.error, "offline"); + } + function test_late_suggestion_preserves_typing_and_cancel() { + controller.openForm("add-folder", null, 0); + controller.draft({ + folderId: "typed" + }); + backend.busy = false; + backend.actionFinished("folder.suggest-id", true, { + folderId: "late" + }, null); + compare(controller.view.draft.folderId, "typed"); + verify(controller.suggestFolderId()); + controller.cancelForm(); + backend.busy = false; + backend.actionFinished("folder.suggest-id", true, { + folderId: "late" + }, null); + compare(controller.view.form, ""); + compare(controller.view.draft.folderId, undefined); + } + function test_pending_offer_identity_cannot_be_regenerated() { + controller.openForm("add-folder", { + folderId: "exact", + deviceId: "one" + }, 0); + verify(!controller.suggestFolderId()); + backend.actionFinished("folder.suggest-id", true, { + folderId: "wrong" + }, null); + compare(controller.view.draft.folderId, "exact"); + } + function test_rescan_feedback_tracks_the_operation_and_target() { + var folder = { + id: "a", + status: { + state: "idle" + } + }; + backend.busy = true; + backend._actionName = "webui.open"; + verify(!controller.rescanning(folder)); + backend._actionName = "folder.rescan"; + backend._actionTargetId = "other"; + verify(!controller.rescanning(folder)); + backend._actionTargetId = "a"; + verify(controller.rescanning(folder)); + compare(controller.folderStatus(folder), "SCANNING"); + backend.busy = false; + verify(!controller.rescanning(folder)); + backend.busy = true; + backend._actionName = "folder.rescan-all"; + backend.scanningIds = []; + verify(controller.rescanning(folder)); + backend.scanningIds = ["other"]; + verify(!controller.rescanning(folder)); + backend.scanningIds = ["a"]; + verify(controller.rescanning(folder)); + verify(!controller.rescanning({ + id: "a", + paused: true + })); + backend.busy = false; + verify(!controller.rescanning(folder)); + } + function test_restart_drops_the_old_confirmation_and_keeps_input() { + controller.openForm("add-folder", null, 0); + backend.busy = false; + controller.draft({ + folderId: "id", + path: "/keep" + }); + controller.submitForm(); + backend.busy = false; + backend.actionFinished("folder.add-existing", false, null, { + code: "path_missing" + }); + verify(!!controller.view.confirmation); + backend.core.generation++; + compare(controller.view.confirmation, null); + compare(controller.view.draft.path, "/keep"); + compare(controller.submittedAction, ""); + verify(controller.view.interrupted); + verify(controller.error.includes("connection changed")); + } + function test_required_fields_reject_whitespace_without_losing_input() { + controller.openForm("add-folder", null, 0); + backend.busy = false; + controller.draft({ + folderId: "id", + path: " " + }); + controller.submitForm(); + compare(backend.sent, null); + compare(controller.view.draft.path, " "); + verify(controller.error.includes("required")); + controller.cancelForm(); + controller.openForm("add-device", null, 0); + controller.draft({ + deviceId: " " + }); + controller.submitForm(); + compare(backend.sent, null); + verify(controller.error.includes("required")); + } + function test_backend_rejections_preserve_input_and_do_not_confirm_creation() { + for (var failure of [ + { + code: "path_invalid", + message: "folder path must be a directory" + }, + { + code: "path_overlap", + message: "folder path overlaps a configured folder" + }, + { + code: "folder_exists", + message: "folder is already configured" + } + ]) { + controller.openForm("add-folder", null, 0); + backend.busy = false; + controller.draft({ + folderId: "id", + path: "/keep" + }); + controller.submitForm(); + backend.busy = false; + backend.actionFinished("folder.add-existing", false, null, failure); + compare(controller.view.confirmation, null); + compare(controller.view.draft.path, "/keep"); + compare(controller.error, failure.message); + controller.cancelForm(); + } + for (var failure of [ + { + code: "device_id_invalid", + message: "device ID is invalid" + }, + { + code: "device_self", + message: "this device cannot be added as a remote device" + }, + { + code: "device_exists", + message: "device is already configured" + } + ]) { + controller.openForm("add-device", null, 0); + controller.draft({ + deviceId: "input", + deviceName: "keep" + }); + controller.submitForm(); + backend.busy = false; + backend.actionFinished("device.add", false, null, failure); + compare(controller.view.draft.deviceId, "input"); + compare(controller.view.draft.deviceName, "keep"); + compare(controller.error, failure.message); + controller.cancelForm(); + } + } +} diff --git a/tests/caelestia/tst_settings.qml b/tests/caelestia/tst_settings.qml new file mode 100644 index 00000000..769e8625 --- /dev/null +++ b/tests/caelestia/tst_settings.qml @@ -0,0 +1,65 @@ +import QtQuick +import QtTest +import "../../hosts/caelestia/controllers" + +TestCase { + id: test + name: "CaelestiaSettingsValidation" + SettingsController { + id: settings + } + function values() { + return { + schemaVersion: 1, + icon: "sync", + probeSeconds: 15, + refreshSeconds: 60, + webUiStyle: "default", + lifecycleAuthorized: false, + lifecycleUnit: "syncthing.service", + lifecycleConfig: "/private/config.xml" + }; + } + function test_intervals_match_the_core_contract() { + for (var seconds of [1, 3600]) { + var value = values(); + value.probeSeconds = seconds; + compare(settings.validate(value), ""); + } + for (var seconds of [60, 3600]) { + var value = values(); + value.refreshSeconds = seconds; + compare(settings.validate(value), ""); + } + for (var seconds of [0, 59, 3601, 60.5]) { + var value = values(); + value.refreshSeconds = seconds; + verify(settings.validate(value).includes("Refresh interval")); + } + } + function test_service_authorization_rejects_patterns() { + for (var unit of ["syncthing*", "syncthing.service other.service", "syncthing", ""]) { + var value = values(); + value.lifecycleAuthorized = true; + value.lifecycleUnit = unit; + verify(settings.validate(value).includes("exact unit")); + } + var value = values(); + value.lifecycleAuthorized = true; + compare(settings.validate(value), ""); + } + function test_replacement_does_not_keep_a_stale_settings_object() { + var previous = values(); + settings.settings = previous; + var current = values(); + current.probeSeconds = 31; + settings.settings = current; + previous.probeSeconds = 200; + compare(settings.settings.probeSeconds, 31); + verify(settings.valid); + current = values(); + current.schemaVersion = 99; + settings.settings = current; + verify(!settings.valid); + } +} diff --git a/tests/core-process-mock.sh b/tests/core-process-mock.sh index 6fa49a80..f5268be6 100755 --- a/tests/core-process-mock.sh +++ b/tests/core-process-mock.sh @@ -4,10 +4,18 @@ set -euo pipefail [[ ${1:-} == stream ]] shift exit_on_request=false +exclusive_lock= for argument in "$@"; do [[ $argument != --test-exit-on-request ]] || exit_on_request=true + [[ $argument != --test-exclusive-lock=* ]] || exclusive_lock=${argument#*=} done +if [[ -n $exclusive_lock ]]; then + exec 9>"$exclusive_lock" + flock -n 9 || exit 88 + trap 'sleep 0.2; exit 0' TERM +fi + printf '%s\n' \ '{"v":2,"type":"hello","build":{"version":"test"}}' \ '{"v":2,"type":"snapshot","revision":1,"state":{"connection":{"online":true},"identity":{"deviceId":"TEST-ID"},"folders":[{"id":"folder"}]}}' diff --git a/tests/core-process.qml b/tests/core-process.qml index 99b2e1cf..dcb83805 100644 --- a/tests/core-process.qml +++ b/tests/core-process.qml @@ -15,11 +15,47 @@ ShellRoot { property bool pendingFailurePassed: false property bool crashCapPassed: false property bool manualRecoveryPassed: false + property bool stoppedRecoveryPassed: false + property var lifetimeWorker: null + property int lifetimePhase: 0 + property bool lifetimePassed: false + + function lifetimeReady(worker) { + if (worker.generation !== 1) { + fail("worker replacement needed a retry after an overlapping process"); + return; + } + if (lifetimePhase === 0) { + lifetimePhase = 1; + worker.destroy(); + replacement.start(); + } else { + lifetimePassed = true; + worker.terminate(); + } + } + property Component lifetimeFactory: Component { + CoreProcess { + id: lifetime + startupArguments: ["--test-exclusive-lock=" + corePath + ".lifetime-lock"] + onProtocolReadyChanged: if (protocolReady) + root.lifetimeReady(lifetime) + } + } + Timer { + id: replacement + interval: 0 + onTriggered: root.lifetimeWorker = root.lifetimeFactory.createObject(root) + } + Component.onCompleted: lifetimeWorker = lifetimeFactory.createObject(root) function fail(message) { console.error(message); core.terminate(); crashProbe.terminate(); + stoppedRecovery.terminate(); + if (lifetimeWorker) + lifetimeWorker.terminate(); Qt.exit(1); } @@ -113,6 +149,37 @@ ShellRoot { } } + CoreProcess { + id: stoppedRecovery + desiredRunning: false + onExecutableReadyChanged: { + if (!executableReady) + return; + restartTimer.interval = 20; + restartTimer.restart(); + terminate(); + stoppedCheck.restart(); + } + } + Timer { + id: stoppedCheck + interval: 60 + onTriggered: { + if (stoppedRecovery.running || stoppedRecovery.desiredRunning || stoppedRecovery.generation !== 0) { + root.fail("terminated recovery started a worker"); + return; + } + stoppedRecovery.restartTimer.triggered(); + stoppedRecovery.terminate(); + Qt.callLater(function () { + if (stoppedRecovery.desiredRunning || stoppedRecovery.generation !== 0) + root.fail("queued recovery revived a terminated worker"); + else + root.stoppedRecoveryPassed = true; + }); + } + } + Timer { id: completionTimer interval: 100 @@ -131,7 +198,7 @@ ShellRoot { crashProbe.startupArguments = []; crashProbe.restart(); } - if (core.running || !root.pendingFailurePassed || crashProbe.running || !root.manualRecoveryPassed) { + if (core.running || !root.pendingFailurePassed || crashProbe.running || !root.manualRecoveryPassed || !root.stoppedRecoveryPassed || !root.lifetimePassed || root.lifetimeWorker.running) { restart(); return; } diff --git a/tests/dankmaterialshell-adapter.test.sh b/tests/dankmaterialshell-adapter.test.sh deleted file mode 100755 index ba4210aa..00000000 --- a/tests/dankmaterialshell-adapter.test.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -set -euo pipefail - -root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) -work=$(mktemp -d) -trap 'find "$work" -depth -delete' EXIT - -bash "$root/integrations/dankmaterialshell/assemble.sh" "$work/Syncshell" -jq -e --arg version "$(jq -er .version "$root/manifest.json")" \ - '.version == $version and .requires_dms == ">=1.5.3"' \ - "$work/Syncshell/plugin.json" >/dev/null -test -x "$work/Syncshell/bin/syncshell-core" -test -x "$work/Syncshell/bin/x86_64/syncshell-core" -test -x "$work/Syncshell/bin/aarch64/syncshell-core" -test -f "$work/Syncshell/shared/AdapterService.qml" -test -f "$work/Syncshell/shared/DeviceWorkflow.qml" -test -f "$work/Syncshell/shared/RescanTracker.qml" -printf '[ok] DMS adapter bundle contract passed\n' diff --git a/tests/device-sharing.test.mjs b/tests/device-sharing.test.mjs index 38516f77..eee6b453 100644 --- a/tests/device-sharing.test.mjs +++ b/tests/device-sharing.test.mjs @@ -18,7 +18,7 @@ function model(name) { const facade = model("FacadeModel"); const panel = model("PanelModel"); const source = readFileSync(new URL( - "../hosts/omarchy/ui/DeviceFoldersForm.qml", import.meta.url), "utf8"); + "../hosts/omarchy/ui/BodyTabDevicesFoldersForm.qml", import.meta.url), "utf8"); function form(device) { const context = vm.createContext({ diff --git a/tests/dropdown-search.qml b/tests/dropdown-search.qml index 4e715def..4d78e027 100644 --- a/tests/dropdown-search.qml +++ b/tests/dropdown-search.qml @@ -18,7 +18,7 @@ ShellRoot { width: 420 height: 420 - SyncshellDropdown { + SharedWidgetDropdown { id: dropdown x: 20 y: 20 diff --git a/tests/dux-shell-adapter.test.sh b/tests/dux-shell-adapter.test.sh new file mode 100755 index 00000000..d9c53fbf --- /dev/null +++ b/tests/dux-shell-adapter.test.sh @@ -0,0 +1,41 @@ +#!/bin/bash +set -euo pipefail + +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +work=$(mktemp -d) +trap 'find "$work" -depth -delete' EXIT + +bash "$root/integrations/dux-shell/assemble.sh" "$work/Syncshell" +jq -e --arg version "$(jq -er .version "$root/manifest.json")" \ + '.version == $version and .requires_dms == ">=2.0.0" and + .type == "composite" and .id == "syncshell" and + (.permissions | index("settings_write")) != null' \ + "$work/Syncshell/plugin.json" >/dev/null +test -x "$work/Syncshell/bin/syncshell-core" +test -x "$work/Syncshell/bin/x86_64/syncshell-core" +test -x "$work/Syncshell/bin/aarch64/syncshell-core" +test -f "$work/Syncshell/shared/AdapterService.qml" +test -f "$work/Syncshell/shared/RescanTracker.qml" +while IFS= read -r path; do + test -f "$work/Syncshell/${path#./}" +done < <(jq -r '.components[], .settings' "$work/Syncshell/plugin.json") +test ! -e "$work/Syncshell/SyncshellWidget.qml" +test ! -e "$work/Syncshell/SyncshellDaemon.qml" +test -f "$work/Syncshell/assets/mono/status-default.svg" +test -f "$work/Syncshell/webui/manifest.json" +test -f "$work/Syncshell/LICENSE" +test -f "$work/Syncshell/packaging/bundled/LICENSE.golang" +jq -e '.format == 1 and .dmsSDK == "2.0.0" and + (.recipeSha256 | test("^[a-f0-9]{64}$")) and .webUi.version != null' \ + "$work/Syncshell/ASSEMBLY.json" >/dev/null +(cd -- "$work/Syncshell" && sha256sum --quiet --check PACKAGE-SHA256SUMS) +bash "$root/integrations/dux-shell/assemble.sh" "$work/repeated" +diff -qr "$work/Syncshell" "$work/repeated" +diff -qr "$work/Syncshell" "$root/dist/dux-shell" +if bash "$root/integrations/dux-shell/assemble.sh" "$work/Syncshell" 2>/dev/null; then + printf 'assembler overwrote a nonempty package\n' >&2 + exit 1 +fi +QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner -input "$root/tests/dux-shell" +node --test "$root/tests/adapter-contract.test.mjs" "$root"/tests/dux-shell-*.test.mjs +printf '[ok] DMS adapter bundle contract passed\n' diff --git a/tests/dux-shell-import-boundary.test.mjs b/tests/dux-shell-import-boundary.test.mjs new file mode 100644 index 00000000..5255d371 --- /dev/null +++ b/tests/dux-shell-import-boundary.test.mjs @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, cpSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const sourceMap = JSON.parse(readFileSync(join(root, + "integrations/dux-shell/import-map.json"), "utf8")); + +function fixture(t, map) { + const directory = mkdtempSync(join(tmpdir(), "syncshell-import-")); + t.after(() => rmSync(directory, { recursive: true, force: true })); + mkdirSync(join(directory, "shared")); + const names = ["AdapterService.qml", "CoreProcess.qml", "Paths.js", "RescanTracker.qml"]; + for (const name of names) + cpSync(join(root, "shared", name), join(directory, "shared", name)); + writeFileSync(join(directory, "files.txt"), names.map(name => `shared/${name}`).join("\n")); + writeFileSync(join(directory, "map.json"), JSON.stringify(map)); + const run = () => spawnSync(process.execPath, [resolve(root, "integrations/assemble-qml.mjs"), + directory, join(directory, "files.txt"), join(directory, "map.json")], { encoding: "utf8" }); + return { directory, run }; +} + +test("DMS preserves explicit relative imports in its packaged tree", t => { + const { directory, run } = fixture(t, sourceMap); + assert.equal(run().status, 0); + assert.equal(readFileSync(join(directory, "shared/AdapterService.qml"), "utf8"), + readFileSync(join(root, "shared/AdapterService.qml"), "utf8")); +}); + +test("Caelestia mapping gives shared QML an explicit named self-import", t => { + const map = { ...sourceMap, '"."': "ilyazar.syncshell.shared" }; + const { directory, run } = fixture(t, map); + const result = run(); + assert.equal(result.status, 0, result.stderr); + const generated = readFileSync(join(directory, "shared/AdapterService.qml"), "utf8"); + assert.match(generated, /^import ilyazar\.syncshell\.shared$/m); + assert.doesNotMatch(generated, /^import "\."$/m); + assert.equal(generated.replace("import ilyazar.syncshell.shared", 'import "."'), + readFileSync(join(root, "shared/AdapterService.qml"), "utf8")); +}); + +test("undeclared imports fail instead of silently leaking shell APIs", t => { + const map = { ...sourceMap }; + delete map.Quickshell; + const { run } = fixture(t, map); + const result = run(); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /unmapped import/); +}); + +test("missing packaged imports fail closed", t => { + const { directory, run } = fixture(t, sourceMap); + rmSync(join(directory, "shared/Paths.js")); + assert.notEqual(run().status, 0); +}); diff --git a/tests/dux-shell-nix-source.test.mjs b/tests/dux-shell-nix-source.test.mjs new file mode 100644 index 00000000..c78ef984 --- /dev/null +++ b/tests/dux-shell-nix-source.test.mjs @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const integration = join(root, "integrations/dux-shell"); + +test("the bounded Nix source selection assembles the same standalone payload", () => { + const recipe = readFileSync(join(integration, "package.nix"), "utf8"); + const selection = recipe.match(/fileset = lib\.fileset\.unions \[([^]*?)\];/); + assert.ok(selection, "review source coverage when changing the Nix fileset"); + const paths = selection[1].trim().split(/\s+/); + const work = mkdtempSync(join(tmpdir(), "syncshell-dux-shell-nix-source-")); + try { + const source = join(work, "source"); + for (const entry of paths) { + assert.match(entry, /^\.\.?\//); + const original = resolve(integration, entry); + const path = relative(root, original); + assert.ok(path && !path.startsWith("..")); + const destination = join(source, path); + mkdirSync(dirname(destination), { recursive: true }); + cpSync(original, destination, { recursive: true }); + } + for (const excluded of [".git", "TODO", "tests", "dist", "assets/01-folder-sync.mp4"]) + assert.equal(existsSync(join(source, excluded)), false); + const output = join(work, "package"); + execFileSync("bash", [join(source, "integrations/dux-shell/assemble.sh"), output]); + execFileSync("diff", ["-qr", output, join(root, "dist/dux-shell")]); + } finally { + rmSync(work, { recursive: true, force: true }); + } +}); diff --git a/tests/dux-shell-panel-model.test.mjs b/tests/dux-shell-panel-model.test.mjs new file mode 100644 index 00000000..ec198798 --- /dev/null +++ b/tests/dux-shell-panel-model.test.mjs @@ -0,0 +1,352 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const model = vm.createContext({}); +vm.runInContext(readFileSync(new URL( + "../hosts/dux-shell/models/PanelModel.js", import.meta.url), "utf8") + .replace(/^\.pragma library\n/, ""), model); +const folders = [ + { id: "z", label: "Documents", path: "/work/docs", status: { state: "idle" } }, + { id: "a", label: "Documents", path: "/home/docs", status: { state: "idle" } }, + { id: "busy", label: "Uploads", status: { state: "syncing" } }, + { id: "error", label: "Broken", status: { state: "idle", pullErrors: 1 } }, + { id: "paused", label: "Archive", paused: true, status: { state: "idle" } }, + { id: "unknown", label: "Starting", status: {} }, +]; + +test("fuzzy search preserves the Omarchy matcher and existing result order", () => { + const source = readFileSync(new URL( + "../hosts/omarchy/ui/SharedWidgetDropdown.qml", import.meta.url), "utf8"); + const reference = vm.createContext({}); + vm.runInContext(source.match(/^ function matchesSearch\([^]*?^ }/m)[0], reference); + for (const label of ["Documents", "Archive 2026", "Shared Photos", "", "aabb"]) { + for (const query of ["dcm", " DOC ", "ar26", "s p", "", "bbb", "nope"]) + assert.equal(model.matchesSearch(label, query), reference.matchesSearch(label, query)); + } + assert.deepEqual(Array.from(model.folderOptions(folders, true, null, "name") + .filter(row => model.matchesOption(row, "dcm")), + row => row.value), ["a", "z"]); + assert.deepEqual(Array.from(model.folderOptions(folders, true, null, "name") + .filter(row => model.matchesOption(row, "dcs")), row => row.label), ["docs", "docs"]); + assert.equal(model.matchesOption({ label: "Pictures", value: "photos", description: "/work/trip" }, "wk/t"), true); +}); + +test("duplicate labels retain distinct IDs and deterministic sorting", () => { + const rows = model.folderOptions(folders, true, null, "name") + .filter(row => model.matchesOption(row, "Documents")); + assert.deepEqual(Array.from(rows, row => row.value), ["a", "z"]); + assert.equal(model.retainedSelection(folders.slice().reverse(), "a"), "a"); +}); + +test("all five filter groups, search by path and priority sorting", () => { + for (const [group, ids] of Object.entries({ ready: ["a", "z"], active: ["busy"], + errors: ["error"], paused: ["paused"], unknown: ["unknown"] })) { + assert.deepEqual(Array.from(model.folderOptions(folders, true, [group], "name"), + row => row.value), ids); + } + assert.equal(model.folderOptions(folders, true, null, "name") + .filter(row => model.matchesOption(row, "/work"))[0].value, "z"); + for (const priority of ["active", "errors"]) + assert.equal(model.folderOptions(folders, true, null, priority)[0].group, priority); + assert.equal(model.folderOptions(folders, true, [], "name").length, 0); +}); + +test("stale folders never claim ready even with a retained snapshot", () => { + const rows = model.folderOptions(folders, false, null, "name"); + assert.ok(rows.every(row => row.group === "unknown" && row.status === "UNKNOWN")); + assert.equal(model.retainedSelection([], "vanished"), ""); +}); + +test("stale device options keep identity but do not claim a current connection", () => { + const devices = [{ id: "a", name: "Laptop", connected: true }, + { id: "b", name: "Laptop", paused: true }]; + const rows = model.deviceOptions(devices, false); + assert.deepEqual(Array.from(rows, row => row.value), ["a", "b"]); + assert.ok(rows.every(row => row.status === "UNKNOWN")); + assert.equal(model.deviceOptions(devices, true)[0].status, "CONNECTED"); +}); + +test("device search uses the same dropdown matcher for name, ID and address", () => { + const rows = model.deviceOptions([ + { id: "REMOTE-A", name: "Laptop", address: "tcp://192.0.2.1:22000", connected: true }, + { id: "REMOTE-B", name: "Phone", address: "dynamic", connected: false }, + ], true); + for (const query of ["ltp", "remote-a", "192.0.2.1"]) + assert.deepEqual(Array.from(rows.filter(row => model.matchesOption(row, query)), + row => row.value), ["REMOTE-A"]); + assert.equal(rows.filter(row => model.matchesOption(row, "missing")).length, 0); + assert.equal(rows.filter(row => model.matchesOption(row, "")).length, 2); +}); + +test("device cards and selectors share status rules including stale and missing data", () => { + assert.equal(model.deviceStatus(null, true), ""); + for (const [device, expected] of [ + [{ id: "a", paused: true, connected: true }, "PAUSED"], + [{ id: "a", connected: true }, "CONNECTED"], + [{ id: "a", connected: false }, "DISCONNECTED"], + ]) { + assert.equal(model.deviceStatus(device, true), expected); + assert.equal(model.deviceOptions([device], true)[0].status, expected); + assert.equal(model.deviceStatus(device, false), "UNKNOWN"); + assert.equal(model.deviceOptions([device], false)[0].status, "UNKNOWN"); + } +}); + +test("filtering never removes hidden multiselect IDs", () => { + const draft = ["visible", "hidden"]; + assert.deepEqual(Array.from(model.toggled(draft, "visible")), ["hidden"]); + assert.deepEqual(draft, ["visible", "hidden"]); + assert.deepEqual(Array.from(model.removedShares(["visible", "hidden"], ["hidden"])), + ["visible"]); +}); + +test("side forms flip at edges and stack only when neither side fits", () => { + assert.equal(model.sidePlacement(1920, 1400, 440, 360, 12, 16), "left"); + assert.equal(model.sidePlacement(1920, 16, 440, 360, 12, 16), "right"); + assert.equal(model.sidePlacement(700, 100, 440, 360, 12, 16), "stack"); +}); + +test("side form windows sit beside the popout at the trigger row", () => { + const popout = { x: 1100, y: 50, width: 400, height: 560 }; + assert.deepEqual({ ...model.sideWindowPlacement(1536, 864, popout, 360, 380, 200, 12, 16, 50) }, + { side: "left", x: 728, y: 250 }); + assert.deepEqual({ ...model.sideWindowPlacement(1536, 864, { ...popout, x: 16 }, 360, 380, 200, 12, 16, 50) }, + { side: "right", x: 428, y: 250 }); + const low = model.sideWindowPlacement(1536, 864, popout, 360, 700, 500, 12, 16, 50); + assert.equal(low.y, 864 - 16 - 700); + const high = model.sideWindowPlacement(1536, 864, { ...popout, y: 0 }, 360, 300, 0, 12, 16, 50); + assert.equal(high.y, 50); + const narrow = model.sideWindowPlacement(700, 864, { ...popout, x: 150 }, 360, 300, 100, 12, 16, 50); + assert.equal(narrow.side, "stack"); + assert.equal(narrow.x, 170); +}); + +const controllerSource = readFileSync(new URL( + "../hosts/dux-shell/controllers/PanelController.qml", import.meta.url), "utf8"); + +function controller(service) { + const context = vm.createContext({ + Model: model, service, busy: false, submitting: false, pendingAction: "", + fresh: true, form: "", draft: {}, originalShareIds: [], confirmation: null, error: "", + returnFocus: null, selectedFolderId: "a", selectedDeviceId: "REMOTE", + focusRequested() {}, + }); + context.root = context; + for (const match of controllerSource.matchAll(/^ function \w+\([^]*?^ }/gm)) + vm.runInContext(match[0], context); + Object.defineProperty(context, "busy", { + get: () => context.submitting || service.busy === true, + }); + return context; +} + +test("refresh preserves drafts and device sharing removes only original shares", () => { + let removed; + const service = { + folders, remoteDevices: () => [{ id: "REMOTE" }], device: () => ({ id: "REMOTE" }), + folderIdsForDevice: () => ["a", "z"], + removeDeviceFolderShares(id, ids) { removed = Array.from(ids); return true; }, + }; + const panel = controller(service); + panel.begin("device-folders", { id: "REMOTE", name: "Laptop" }); + panel.toggleDraft("a"); + service.folderIdsForDevice = () => ["a", "z", "newly-shared"]; + panel.reconcile(); + assert.deepEqual(Array.from(panel.draft.ids), ["z", "newly-shared"]); + panel.submit(); + assert.deepEqual(removed, ["a"]); + assert.equal(panel.submit(), false); +}); + +test("confirmation freezes its target and rejects a vanished target", () => { + let forgotten; + let exists = true; + const panel = controller({ folder: () => exists ? {} : null, + forgetFolder(id) { forgotten = id; return true; } }); + const target = { id: "a", label: "Documents" }; + panel.requestConfirmation("folder.forget", target); + target.id = "z"; + panel.selectedFolderId = "z"; + assert.equal(panel.confirm(), true); + assert.equal(forgotten, "a"); + assert.equal(panel.confirm(), false); + panel.settled("folder.forget", true, {}, null); + panel.requestConfirmation("folder.forget", { id: "a" }); + exists = false; + assert.equal(panel.confirm(), false); + assert.match(panel.error, /no longer exists/); +}); + +test("missing directory confirmation reuses submitted values, not later edits", () => { + let added; + const panel = controller({ requestFolderIdSuggestion() {}, + pendingFolderOffers: () => [{ folderId: "offer", deviceId: "REMOTE" }], + addFolder(values) { added = values; return true; } }); + panel.begin("add-folder", { folderId: "offer", deviceId: "REMOTE" }); + panel.setDraft("path", "/original"); + panel.submit(); + panel.setDraft("path", "/later-edit"); + panel.settled("folder.add-existing", false, null, + { code: "path_missing", message: "Directory missing" }); + assert.equal(panel.confirmation.target.path, "/original"); + panel.confirm(); + assert.equal(added.path, "/original"); + assert.equal(added.createDirectory, true); + assert.deepEqual(Array.from(added.deviceIds), ["REMOTE"]); +}); + +test("cancel and failure retain form drafts; suggestion cannot overwrite typed ID", () => { + const panel = controller({ requestFolderIdSuggestion() {}, addFolder() { return true; } }); + panel.begin("add-folder", {}); + panel.setDraft("folderId", "typed-id"); + panel.settled("folder.suggest-id", true, { folderId: "generated-id" }, null); + assert.equal(panel.draft.folderId, "typed-id"); + // DMS 2.0 fields echo programmatic text as an edit; an unchanged value is no edit. + const before = panel.draft; + panel.setDraft("folderId", "typed-id"); + panel.setDraft("label", ""); + assert.equal(panel.draft, before); + panel.setDraft("path", "/keep"); + panel.submit(); + panel.settled("folder.add-existing", false, null, { code: "offline", message: "Offline" }); + assert.equal(panel.form, "add-folder"); + assert.equal(panel.draft.path, "/keep"); + panel.requestConfirmation("folder.add-existing", panel.draft); + panel.cancelConfirmation(); + assert.equal(panel.confirmation, null); + assert.equal(panel.draft.path, "/keep"); +}); + +test("folder presentation preserves state precedence, local-only and remaining bytes", () => { + const folder = (status, extra = {}) => ({ id: "one", path: "/work/docs", label: "Archive", status, ...extra }); + const cases = [ + [folder({ state: "idle" }), false, "", false, false, "UNKNOWN"], + [folder({ state: "error" }, { paused: true }), true, "", false, false, "UNLINKED"], + [folder({ state: "idle", pullErrors: 1 }), true, "", false, false, "ERROR"], + [folder({ state: "scanning" }), true, "", false, false, "SCANNING"], + [folder({ state: "scanning", needTotalItems: 2 }), true, "", false, false, "SCAN+SYNC"], + [folder({ state: "idle" }), true, "", true, true, "SCAN+SYNC"], + [folder({ state: "syncing" }), true, "", false, false, "SYNCING"], + [folder({ state: "idle" }), true, "one", false, false, "LINKED"], + [folder({ state: "idle" }), true, "", false, false, "SYNCED"], + [folder({}), true, "", false, false, "UNKNOWN"], + ]; + for (const [f, fresh, linked, activity, scanning, expected] of cases) { + assert.equal(model.folderStatus(f, fresh, linked, activity, scanning), expected); + assert.ok(model.stateHelp(expected).startsWith(expected + " · ")); + } + assert.match(model.folderMeta(folder({ state: "syncing", needTotalItems: 2, needBytes: 2048 }), true, "local", false), /2 items remaining.*2.*KiB.*Archive/); + assert.match(model.folderMeta(folder({ state: "idle", globalFiles: 3 }, { devices: [{ id: "local" }] }), true, "local", false), /3 files.*local only/); + assert.match(model.folderMeta(folder({ state: "idle" }), false, "local", false), /^Last reported:/); +}); +test("activity is current and belongs to the displayed folder", () => { + const activity = { folderId: "one", action: "Uploading", detail: "photo.jpg" }; + assert.equal(model.folderActivity({ id: "one" }, true, activity), "Uploading photo.jpg"); + assert.equal(model.folderActivity({ id: "two" }, true, activity), ""); + assert.equal(model.folderActivity({ id: "one" }, false, activity), ""); + assert.equal(model.folderActivity(null, true, activity), ""); +}); +test("remote share confirmation requires fresh connected unpaused device state", () => { + for (const remoteState of ["valid", "paused", "unknown", "notSharing"]) { + const folder = { devices: [{ id: "peer", remoteState }] }; + assert.equal(model.remoteShare(folder, { id: "peer", connected: true }, true), remoteState); + assert.equal(model.remoteShare(folder, { id: "peer", connected: false }, true), "unknown"); + assert.equal(model.remoteShare(folder, { id: "peer", connected: true, paused: true }, true), "unknown"); + assert.equal(model.remoteShare(folder, { id: "peer", connected: true }, false), "unknown"); + } +}); + +test("error details group paths by reason and disclose bounded counts", () => { + const folder = { status: { pullErrors: 7, errors: [ + { path: "one", error: "denied" }, { path: "two", error: "denied" }, + { path: "three", error: "missing" } ] } }; + const detail = model.errorDetails(folder); + assert.match(detail, /denied\none\ntwo/); + assert.match(detail, /missing\nthree/); + assert.equal(detail.match(/denied/g).length, 1); + assert.match(detail, /Showing 3 of 7 current errors.*Open Web UI/s); + assert.equal(model.hasErrors({ status: { state: "error" } }), true); + assert.equal(model.hasErrors({ status: { errors: [{ error: "missing" }] } }), true); + assert.match(model.errorDetails({ status: { pullErrors: 4 } }), /no error details.*Showing 0 of 4/s); + assert.equal(model.errorDetails({ status: { state: "idle" } }), ""); +}); + +test("share descriptions preserve remote acceptance and pause explanations", () => { + for (const [state, expected] of Object.entries({ + valid: "Remote share confirmed", paused: "Remote folder paused", + notSharing: "Remote is not sharing back", unknown: "Remote acceptance unconfirmed", + })) { + const folder = { devices: [{ id: "peer", remoteState: state }] }; + assert.equal(model.remoteShareDescription(model.remoteShare(folder, + { id: "peer", connected: true }, true)), expected); + assert.equal(model.remoteShareDescription(model.remoteShare(folder, + { id: "peer", connected: true }, false)), "Remote acceptance unconfirmed"); + } +}); + +test("bar icon and tooltip follow Omarchy precedence without inventing success", () => { + const base = { phase: "ready", online: true, canControlService: false, lifecycle: {}, installation: { available: true }, + folderProblemCount: 0, syncingFolderCount: 0, refreshing: false, busy: false, currentActivity: {}, summaryText: "Up to date" }; + const s = over => Object.assign({}, base, over); + assert.equal(model.statusVariant(null), "notify"); + assert.equal(model.statusVariant(s({ canControlService: true, lifecycle: { active: false }, online: false })), "pause"); + assert.equal(model.statusVariant(s({ online: false, phase: "error" })), "notify"); + assert.equal(model.statusVariant(s({ refreshing: true })), "sync"); + assert.equal(model.statusVariant(s({})), "default"); + assert.equal(model.barTooltip(s({})), "Syncthing: Up to date"); + assert.equal(model.barTooltip(s({ refreshing: true })), "Syncthing: Up to date"); + assert.equal(model.barTooltip(s({ syncingFolderCount: 1 })), "Syncthing: Sync in progress..."); + assert.equal(model.barTooltip(s({ installation: { available: false } })), "Syncthing: Syncthing is not installed"); +}); + +test("counts and confirmations match the Omarchy panel", () => { + const omarchy = vm.createContext({}); + vm.runInContext(readFileSync(new URL("../hosts/omarchy/models/PanelModel.js", import.meta.url), "utf8") + .replace(/^\.(pragma|import) .*$/gm, ""), omarchy); + for (const n of [0, 999, 1500, 10000, 153000, 1250000]) + assert.equal(model.formatCount(n), omarchy.formatCount(n)); + const popup = readFileSync(new URL("../hosts/omarchy/ui/SyncshellPanelPopup.qml", import.meta.url), "utf8"); + const remove = model.confirmText("device.remove", { name: "optiplex" }); + assert.equal(remove.title, "Remove optiplex from this device?"); + for (const phrase of ["Folder sharing with it will be ", "removed locally. Local folders and files remain.", "The other device is unchanged."]) + assert.ok(popup.includes(phrase) && (remove.title + " " + remove.message).replace(/\s+/g, " ").includes(phrase.trim())); + const forget = model.confirmText("folder.forget", { id: "abc", label: "Docs", markerName: ".stfolder" }); + assert.equal(forget.title, "Forget Docs (abc)?"); + assert.match(forget.message, /directory and data files will not be deleted/); + assert.match(forget.message, /\.stfolder marker/); + assert.match(popup, /confirmText: root\.controller\.folderConfirmAction === "create" \? "Create and add" : "Yes"/); + assert.match(popup, /cancelText: root\.controller\.folderConfirmAction === "create" \? "Cancel" : "No"/); + assert.match(popup, /confirmText: "Yes"\n\s+cancelText: "No"/); + assert.deepEqual([remove.confirm, remove.destructive, forget.confirm, forget.destructive], ["Yes", true, "Yes", true]); + const create = model.confirmText("folder.add-existing", { path: "/srv/a" }); + assert.deepEqual([create.confirm, create.cancel, create.destructive], ["Create and add", "Cancel", false]); + assert.equal(remove.cancel, "No"); +}); + +test("folders are named by directory and the configured label joins the meta line", () => { + const omarchy = vm.createContext({}); + vm.runInContext(readFileSync(new URL("../hosts/omarchy/models/PanelModel.js", import.meta.url), "utf8") + .replace(/^\.(pragma|import) .*$/gm, ""), omarchy); + for (const path of ["/home/iz/Sync-Test", "/home/iz/Sync-Test/", "/"]) + assert.equal(model.folderName({ path, id: "x" }), omarchy.pathLabel(path)); + const folder = { id: "x", label: "Sync Test", path: "/home/iz/Sync-Test", + devices: [{ id: "remote" }], status: { state: "idle", globalFiles: 3, globalBytes: 138 } }; + assert.equal(model.folderMeta(folder, true, "local", false), "3 files · 138 B · Sync Test"); + assert.equal(model.folderMeta({ ...folder, label: "Sync-Test" }, true, "local", false), "3 files · 138 B"); +}); + +test("state colours follow Omarchy's green, yellow, red and muted rules", () => { + const panel = readFileSync(new URL("../hosts/omarchy/OmarchyPanel.qml", import.meta.url), "utf8"); + const omarchy = { warning: "warning", urgent: "error", success: "success", muted: "onSurfaceVariant" }; + const body = panel.match(/function folderStateColor\(folder\) \{([^]*?)\n \}/)[1]; + for (const [, state, colour] of body.matchAll(/state === "([^"]+)"\)\s*return ([\w.]+);/g)) + assert.equal(model.folderStateRole(state), omarchy[colour.split(".").pop()], state); + assert.equal(model.folderStateRole("SYNCED"), "success"); + assert.equal(model.folderStateRole("LINKED"), "success"); + assert.deepEqual(["CONNECTED", "PAUSED", "DISCONNECTED", "UNKNOWN"].map(model.deviceStateRole), + ["success", "warning", "onSurfaceVariant", "onSurfaceVariant"]); + assert.deepEqual(["removing", "upload", "sync", ""].map(model.activityRole), + ["error", "success", "info", "info"]); +}); diff --git a/tests/dux-shell-sdk-api.test.mjs b/tests/dux-shell-sdk-api.test.mjs new file mode 100644 index 00000000..d8bebc55 --- /dev/null +++ b/tests/dux-shell-sdk-api.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const host = join(root, "hosts/dux-shell"); + +function qmlFiles(directory) { + return readdirSync(directory, { withFileTypes: true }).flatMap(entry => { + const path = join(directory, entry.name); + if (entry.isDirectory()) + return qmlFiles(path); + return entry.name.endsWith(".qml") ? [path] : []; + }); +} + +const sources = qmlFiles(host).map(path => ({ + name: path.slice(host.length + 1), text: readFileSync(path, "utf8") +})); + +// DMS 2.0 keeps these 1.6 names only as deprecated shims that log errors. +const deprecated = /\b(Dank(Button|ActionButton|Icon|SVGIcon|Slider|Toggle|TextField|TabBar|Flickable|ListView|Scrollbar|Dropdown|Tooltip|Modal))\s*\{/; +// The 2.0 surface roles follow user overrides; the raw palette does not. +const rawSurface = /Theme\.(surfaceContainer\w*|surfaceVariant)\b|Theme\.(surfaceText|surfaceVariantText|primaryText)\b|Qt\.alpha\(/; + +test("DMS host uses the 2.0 control names", () => { + for (const { name, text } of sources) + assert.doesNotMatch(text, deprecated, name); +}); + +test("DMS controls come from qs.DCommon.Widgets", () => { + for (const { name, text } of sources) { + if (/^import qs\.Widgets$/m.test(text)) + assert.equal(name, "DuxShellPanel.qml", `${name} imports shell widgets`); + } + const panel = sources.find(source => source.name === "DuxShellPanel.qml").text; + assert.match(panel, /DTooltip \{/); +}); + +test("DMS UI uses surface roles instead of the raw palette", () => { + for (const { name, text } of sources) + assert.doesNotMatch(text, rawSurface, name); +}); + +test("DMS manifest requires the 2.0 SDK", () => { + const manifest = JSON.parse(readFileSync(join(root, + "integrations/dux-shell/plugin.json"), "utf8")); + assert.equal(manifest.requires_dms, ">=2.0.0"); +}); diff --git a/tests/dux-shell-service-lifecycle.test.mjs b/tests/dux-shell-service-lifecycle.test.mjs new file mode 100644 index 00000000..8b9c1b71 --- /dev/null +++ b/tests/dux-shell-service-lifecycle.test.mjs @@ -0,0 +1,143 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const daemon = readFileSync(new URL("../hosts/dux-shell/DuxShellService.qml", + import.meta.url), "utf8"); +const widget = readFileSync(new URL("../hosts/dux-shell/DuxShellPanel.qml", + import.meta.url), "utf8"); +function method(source, name) { + const match = source.match(new RegExp(`^([ \\t]*)function ${name}\\([^]*?^\\1}`, "m")); + assert.ok(match); + return match[0]; +} +function registry() { + const values = {}; + const listeners = []; + return { + getGlobalVar(id, name, fallback) { return values[name] ?? fallback; }, + setGlobalVar(id, name, value) { values[name] = value; listeners.forEach(fn => fn()); }, + listeners, + }; +} +function instance(source, name, data) { + const context = vm.createContext(data); + context.root = context; + vm.runInContext(method(source, name), context); + return context; +} + +for (const order of ["widget-first", "daemon-first"]) { + test(`${order} publishes one service to multiple widgets without polling`, () => { + const pluginService = registry(); + const core = { identity: "one worker" }; + const host = instance(daemon, "publish", { pluginId: "syncshell", pluginService, + service: core, ownsService: false }); + const views = [0, 1].map(() => instance(widget, "resolveService", { + pluginId: "syncshell", pluginService, service: null, host: null, + })); + if (order === "daemon-first") host.publish(); + for (const view of views) { + view.resolveService(); + pluginService.listeners.push(() => view.resolveService()); + } + if (order === "widget-first") host.publish(); + const publishedHost = pluginService.getGlobalVar("syncshell", "host"); + assert.equal(publishedHost.service, core); + assert.ok(views.every(view => view.service === core && view.host === publishedHost)); + pluginService.setGlobalVar("syncshell", "service", null); + pluginService.setGlobalVar("syncshell", "host", null); + assert.ok(views.every(view => view.service === null && view.host === null)); + assert.doesNotMatch(widget, /Timer\s*\{/); + assert.doesNotMatch(widget, /AdapterService\s*\{/); + }); +} + +test("foreign same-ID global service is not overwritten", () => { + const pluginService = registry(); + const foreign = {}; + pluginService.setGlobalVar("syncshell", "service", foreign); + const host = instance(daemon, "publish", { + pluginId: "syncshell", pluginService, service: null, ownsService: false, + }); + host.publish(); + assert.equal(host.ownsService, false); + assert.match(host.collisionError, /already owns/); + assert.equal(pluginService.getGlobalVar("syncshell", "service"), foreign); +}); + +test("outside close retains controller drafts and dismisses transient surfaces", () => { + const popup = readFileSync(new URL( + "../hosts/dux-shell/ui/SyncshellPanelPopup.qml", import.meta.url), "utf8"); + const closed = method(popup, "onPopoutClosed"); + assert.doesNotMatch(closed, /closeForm/); + assert.match(closed, /transientSurfaceTracker.closeAll/); +}); + +test("closing inactive selectors cannot steal focus from the active one", () => { + const dropdown = readFileSync(new URL( + "../hosts/dux-shell/ui/SharedWidgetDropdown.qml", import.meta.url), "utf8"); + let focused = 0; + const selector = instance(dropdown, "close", { + opened: false, trigger: { forceActiveFocus() { focused++; } }, + }); + selector.close(); + assert.equal(focused, 0); + selector.opened = true; + selector.close(); + assert.equal(selector.opened, false); + assert.equal(focused, 1); +}); + +test("returning to a retained confirmation restores Cancel selection", () => { + const popup = readFileSync(new URL( + "../hosts/dux-shell/ui/SyncshellPanelPopup.qml", import.meta.url), "utf8"); + let cancelled = 0; + let formFocused = 0; + // Without a form or confirmation, focus starts at the tab's selector. + let panelFocused = 0; + const root = instance(popup, "restoreFocus", { + parentPopout: { shouldBeVisible: true }, + confirming: true, sideOpen: true, + confirmLoader: { item: { selectCancel() { cancelled++; } } }, + sidePane: { focusContent() { formFocused++; return true; } }, + focusSelector() { panelFocused++; }, + }); + root.restoreFocus(); + assert.deepEqual([cancelled, formFocused, panelFocused], [1, 0, 0]); + root.confirming = false; + root.restoreFocus(); + assert.deepEqual([cancelled, formFocused, panelFocused], [1, 1, 0]); + root.sideOpen = false; + root.restoreFocus(); + assert.deepEqual([cancelled, formFocused, panelFocused], [1, 1, 1]); +}); + +test("connection edits retry even when startup never reached a handshake", () => { + assert.match(daemon, + /onConnectionKeyChanged:\s*if\s*\(service\)\s*restartTimer\.restart\(\)/); +}); + +for (const name of ["SharedWidgetBusyButton", "SharedWidgetSquareActionButton"]) { + test(`${name} rejects held activation keys even after a fast action settles`, () => { + const source = readFileSync(new URL( + `../hosts/dux-shell/ui/${name}.qml`, import.meta.url), "utf8"); + let clicks = 0; + const button = instance(source, "activateKey", { + Qt: { Key_Return: 13, Key_Enter: 10, Key_Space: 32 }, + enabled: true, busy: false, clicked() { clicks++; }, + }); + button.activateKey({ key: 13, isAutoRepeat: false }); + assert.equal(clicks, 1); + button.activateKey({ key: 13, isAutoRepeat: true }); + assert.equal(clicks, 1); + button.busy = true; + button.activateKey({ key: 32, isAutoRepeat: false }); + assert.equal(clicks, 1); + button.busy = false; + button.enabled = false; + button.activateKey({ key: 32, isAutoRepeat: false }); + assert.equal(clicks, 1); + }); +} diff --git a/tests/dux-shell-settings.test.mjs b/tests/dux-shell-settings.test.mjs new file mode 100644 index 00000000..50feabe8 --- /dev/null +++ b/tests/dux-shell-settings.test.mjs @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const source = readFileSync(new URL( + "../hosts/dux-shell/controllers/SettingsController.qml", import.meta.url), "utf8"); +const defaults = source.match(/readonly property var defaults:\s*(\(\{[^]*?^\s*\}\))/m); +assert.ok(defaults); + +function settings(data = {}) { + const writes = []; + const context = vm.createContext({ + owner: "omarchy-QOL/syncshell", pluginId: "syncshell", pluginData: data, + pluginService: { savePluginData: (...args) => writes.push(args) }, + }); + context.root = context; + context.defaults = vm.runInContext(defaults[1], context); + for (const match of source.matchAll(/^ function \w+\([^]*?^ }/gm)) + vm.runInContext(match[0], context); + Object.defineProperties(context, { + valid: { get: () => context.validate(context.pluginData) === "" }, + values: { get: () => ({ ...context.defaults, ...context.pluginData.syncshell }) }, + }); + return { context, writes }; +} + +test("new settings default to unprivileged service control", () => { + const { context } = settings(); + assert.equal(context.valid, true); + assert.equal(context.defaults.lifecycleAuthorized, false); + assert.equal(context.defaults.webUiTheme, "default"); +}); + +test("foreign or unsupported settings are rejected without writes", () => { + for (const data of [ + { refreshIntervalSec: 60 }, + { syncshell: { schema: 2, owner: "omarchy-QOL/syncshell" } }, + { syncshell: { schema: 1, owner: "another-port" } }, + { syncshell: { schema: 1, owner: "omarchy-QOL/syncshell", unexpected: true } }, + ]) { + const { context, writes } = settings(data); + assert.equal(context.valid, false); + assert.equal(context.save("iconStyle", "branded"), false); + assert.deepEqual(writes, []); + } +}); + +test("settings updates write one owned object and reject invalid values", () => { + const { context, writes } = settings({ enabled: true }); + for (const [key, value] of [ + ["probeIntervalSeconds", 0], ["probeIntervalSeconds", 1.5], + ["refreshIntervalSeconds", 1], ["refreshIntervalSeconds", 59], + ["refreshIntervalSeconds", 3601], ["webUiTheme", "unknown"], + ["iconStyle", "unknown"], ["desiredServiceState", "start"], + ]) { + assert.equal(context.save(key, value), false); + } + assert.equal(writes.length, 0); + assert.equal(context.save("iconStyle", "branded"), true); + assert.equal(writes.length, 1); + assert.equal(writes[0][0], "syncshell"); + assert.equal(writes[0][1], "syncshell"); + assert.equal(writes[0][2].schema, 1); + assert.equal(writes[0][2].owner, "omarchy-QOL/syncshell"); + assert.equal(writes[0][2].iconStyle, "branded"); +}); + +test("lifecycle authorization requires an exact safe unit", () => { + const { context } = settings(); + assert.notEqual(context.validate({ syncshell: { ...context.defaults, + lifecycleAuthorized: true, lifecycleUnit: "syncthing*" } }), ""); + assert.equal(context.validate({ syncshell: { ...context.defaults, + lifecycleAuthorized: true, lifecycleUnit: "syncthing.service" } }), ""); +}); + +test("interval boundaries match the shared core contract", () => { + const { context } = settings(); + for (const seconds of [1, 3600]) + assert.equal(context.save("probeIntervalSeconds", seconds), true); + for (const seconds of [60, 3600]) + assert.equal(context.save("refreshIntervalSeconds", seconds), true); +}); diff --git a/tests/dux-shell-shortcuts.test.mjs b/tests/dux-shell-shortcuts.test.mjs new file mode 100644 index 00000000..f6cb5023 --- /dev/null +++ b/tests/dux-shell-shortcuts.test.mjs @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; +const source = readFileSync(new URL("../hosts/dux-shell/ui/SyncshellPanelPopup.qml", import.meta.url), "utf8"); +const handler = source.match(/^ function handleKey\(event\) \{[^]*?^ \}/m)[0] + "\nhandleKey"; +const Qt = Object.fromEntries(["Escape", "Up", "Down", "Left", "Right", "R", "W", "P", "S", "Q"].map(k => ["Key_" + k, k])); +test("p requests the service toggle on either tab, even with no selection", () => { + for (const tab of ["folders", "devices"]) { + for (const selected of [null, { id: "retained", paused: false }]) { + let toggles = 0; + const controller = { tab, view: { tab }, folder: selected, device: selected, + requestServiceToggle() { toggles++; } }; + const root = { Window: { window: { activeFocusItem: null } } }; + const context = vm.createContext({ Qt, controller, root, hasForm: false }); + const run = vm.runInContext(handler, context); + const event = { key: "P", accepted: false }; + run(event); + assert.equal(toggles, 1); + assert.equal(event.accepted, true); + for (const guard of ["repeat", "busy", "form", "confirmation", "editor"]) { + toggles = 0; + controller.busy = guard === "busy"; + controller.form = guard === "form" ? "add-folder" : ""; + context.hasForm = guard === "form"; + controller.confirmation = controller.view.confirmation = guard === "confirmation" ? {} : null; + root.Window.window.activeFocusItem = guard === "editor" ? { cursorPosition: 1 } : null; + run({ key: "P", isAutoRepeat: guard === "repeat", accepted: false }); + assert.equal(toggles, 0, guard); + } + } + } +}); diff --git a/tests/dux-shell-theme.test.mjs b/tests/dux-shell-theme.test.mjs new file mode 100644 index 00000000..23a7c291 --- /dev/null +++ b/tests/dux-shell-theme.test.mjs @@ -0,0 +1,106 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const source = readFileSync(new URL( + "../hosts/dux-shell/controllers/ThemePaletteController.qml", + import.meta.url), "utf8"); + +function theme() { + const writes = []; + const context = vm.createContext({ + selection: "dms", palette: { accent: "#aabbcc" }, key: "current", + pendingKey: "", pendingSelection: "", error: "", dirty: false, paletteOnly: false, + initialized: true, debounce: { restart() {} }, + service: { + online: true, busy: false, refreshing: false, + webUi: { theme: "syncshell-dms-themed" }, + applyWebProfile(style, palette) { writes.push({ style, palette }); return true; }, + setWebUiTheme(style) { writes.push({ style }); return true; }, + }, + }); + context.root = context; + Object.defineProperty(context, "busy", { get: () => context.pendingKey !== "" }); + for (const match of source.matchAll(/^ function \w+\([^]*?^ }/gm)) + vm.runInContext(match[0], context); + vm.runInContext(source.match(/^ function onActionFinished\([^]*?^ }/m)[0], context); + const changed = source.match(/^ onPaletteChanged: (\{[^]*?^ \})/m)[1]; + const paletteChanged = vm.runInContext("(() => " + changed + ")", context); + return { context, writes, paletteChanged }; +} + +test("queued palette work cannot reselect a profile after ownership changes", () => { + for (const selected of ["default", "syncshell-dms-modern", "syncshell-caelestia-themed"]) { + const { context, writes, paletteChanged } = theme(); + paletteChanged(); + assert.equal(context.dirty, true); + context.service.webUi.theme = selected; + context.apply(); + assert.equal(writes.length, 0, selected); + assert.equal(context.dirty, false); + } +}); + +test("an explicit selection still applies when a palette change is also queued", () => { + const { context, writes, paletteChanged } = theme(); + context.schedule(); + paletteChanged(); + context.service.webUi.theme = "default"; + context.apply(); + assert.equal(writes.length, 1); + assert.equal(writes[0].style, "themed"); + assert.equal(writes[0].palette.accent, "#aabbcc"); +}); + +test("palette work waits for busy work and uses the newest palette", () => { + const { context, writes, paletteChanged } = theme(); + paletteChanged(); + context.service.busy = true; + context.apply(); + assert.equal(writes.length, 0); + assert.equal(context.dirty, true); + context.palette = { accent: "#123456" }; + context.service.busy = false; + context.apply(); + assert.equal(writes.length, 1); + assert.equal(writes[0].palette.accent, "#123456"); + assert.equal(context.dirty, false); +}); + +test("other profiles do not queue palette work", () => { + for (const selected of ["default", "syncshell-dms-modern", "syncshell-caelestia-themed"]) { + const { context, writes, paletteChanged } = theme(); + context.service.webUi.theme = selected; + paletteChanged(); + context.apply(); + assert.equal(context.dirty, false); + assert.equal(writes.length, 0); + } +}); + +test("a changed palette during profile application stays an automatic update", () => { + const { context, writes } = theme(); + context.schedule(); + context.apply(); + assert.equal(writes.length, 1); + context.key = "new palette"; + context.service.webUi.theme = "syncshell-caelestia-themed"; + context.onActionFinished("webui.apply-profile", true, {}, null); + context.apply(); + assert.equal(writes.length, 1); + assert.equal(context.dirty, false); +}); + +test("explicit selection changes during application still settle to the new choice", () => { + const { context, writes } = theme(); + context.schedule(); + context.apply(); + context.selection = "modern"; + context.key = "modern"; + context.schedule(); + context.onActionFinished("webui.apply-profile", true, {}, null); + context.apply(); + assert.equal(writes.length, 2); + assert.equal(writes[1].style, "modern"); +}); diff --git a/tests/dux-shell/tst_panel.qml b/tests/dux-shell/tst_panel.qml new file mode 100644 index 00000000..118b73c7 --- /dev/null +++ b/tests/dux-shell/tst_panel.qml @@ -0,0 +1,512 @@ +import QtQuick +import QtTest +import "../../hosts/dux-shell/controllers" + +TestCase { + id: test + name: "DmsPanelBehavior" + property var controller + QtObject { + id: backend + property var folders: [] + property var devices: [] + property var pendingDevices: [] + property var sharedFolders: ["a", "b"] + property QtObject core: QtObject { + property int generation: 1 + } + property bool online: true + property var connection: ({ + fresh: true + }) + property bool busy: false + property bool refreshing: false + property bool canControlService: true + property var lifecycle: ({ + active: false, + enabled: false + }) + property var sent: null + property string actionError: "" + property string _actionName: "" + property string _actionTargetId: "" + property var scanningIds: [] + function scanning(id) { + return scanningIds.includes(id); + } + function scanningFolderIds() { + return scanningIds; + } + property var offers: [] + function pendingFolderOffers() { + return offers; + } + function requestFolderIdSuggestion() { + return true; + } + function addFolder(args) { + return runAction("folder.add-existing", args); + } + function addDevice(id, name) { + return runAction("device.add", { + deviceId: id, + deviceName: name + }); + } + signal actionFinished(string action, bool ok, var data, var error) + function remoteDevices() { + return devices; + } + function shareableDevices() { + return devices; + } + function folder(id) { + return null; + } + function device(id) { + return devices.find(d => d.id === id) || null; + } + function folderIdsForDevice(id) { + return sharedFolders; + } + function removeDeviceFolderShares(id, ids) { + return runAction("device.remove-folder-shares", { + deviceId: id, + folderIds: ids + }); + } + function dismissPendingDevice(id, name) { + return runAction("device.dismiss-pending", { + deviceId: id + }); + } + function dismissPendingFolder(id, device) { + return runAction("folder.dismiss-pending", { + folderId: id, + pendingDeviceId: device + }); + } + function runAction(action, args) { + sent = { + action: action, + args: args + }; + busy = true; + return true; + } + } + Component { + id: factory + PanelController { + service: backend + } + } + function init() { + backend.connection = { + fresh: true + }; + backend.offers = []; + backend.devices = []; + backend.pendingDevices = []; + backend.sharedFolders = ["a", "b"]; + backend.busy = false; + backend.sent = null; + backend.canControlService = true; + backend.lifecycle = { + active: false, + enabled: false + }; + controller = factory.createObject(test); + } + function cleanup() { + controller.destroy(); + } + function test_vanished_device_invitation_preserves_accept_draft() { + backend.pendingDevices = [ + { + id: "peer", + name: "Invited" + } + ]; + controller.begin("accept-device", backend.pendingDevices[0], null); + controller.setDraft("name", "My name"); + backend.pendingDevices = [ + { + id: "another" + } + ]; + verify(!controller.submit()); + compare(backend.sent, null); + compare(controller.draft.deviceId, "peer"); + compare(controller.draft.name, "My name"); + verify(controller.error.includes("invitation")); + verify(!controller.submitting); + } + function test_vanished_invitation_cannot_be_dismissed() { + for (var folder of [false, true]) { + backend.pendingDevices = [ + { + id: "peer" + } + ]; + backend.offers = [ + { + folderId: "offered", + deviceId: "peer", + encrypted: true + } + ]; + var target = folder ? backend.offers[0] : backend.pendingDevices[0]; + controller.requestConfirmation(folder ? "folder.dismiss-pending" : "device.dismiss-pending", target, null); + backend.pendingDevices = [ + { + id: "another" + } + ]; + backend.offers = [ + { + folderId: "offered", + deviceId: "another" + } + ]; + verify(!controller.confirm()); + compare(backend.sent, null); + verify(controller.error.includes("invitation")); + controller.cancelConfirmation(); + } + } + function test_live_invitation_keeps_its_frozen_target() { + for (var folder of [false, true]) { + backend.pendingDevices = [ + { + id: "peer" + }, + { + id: "another" + } + ]; + backend.offers = [ + { + folderId: "offered", + deviceId: "peer", + encrypted: true + } + ]; + var target = folder ? { + folderId: "offered", + deviceId: "peer" + } : { + id: "peer" + }; + controller.requestConfirmation(folder ? "folder.dismiss-pending" : "device.dismiss-pending", target, null); + target.id = "another"; + target.deviceId = "another"; + verify(controller.confirm()); + compare(backend.sent.args[folder ? "pendingDeviceId" : "deviceId"], "peer"); + backend.busy = false; + backend.actionFinished(backend.sent.action, true, {}, null); + } + controller.begin("accept-device", backend.pendingDevices[0], null); + verify(controller.submit()); + compare(backend.sent.action, "device.add"); + compare(backend.sent.args.deviceId, "peer"); + } + function test_unchanged_shares_cannot_be_submitted() { + backend.devices = [ + { + id: "peer", + name: "Peer" + } + ]; + controller.begin("device-folders", backend.devices[0], null); + verify(!controller.submit()); + compare(backend.sent, null); + compare(controller.draft.ids.join(","), "a,b"); + verify(controller.error.includes("Uncheck")); + controller.toggleDraft("a"); + verify(controller.submit()); + compare(backend.sent.action, "device.remove-folder-shares"); + compare(backend.sent.args.folderIds.join(","), "a"); + } + function test_closed_form_cannot_submit() { + verify(!controller.submit()); + compare(backend.sent, null); + compare(controller.pendingAction, ""); + } + function test_runtime_toggle_preserves_autostart() { + for (var active of [false, true]) { + for (var enabled of [false, true]) { + backend.lifecycle = { + active: active, + enabled: enabled + }; + verify(controller.requestServiceToggle(null)); + compare(controller.confirmation.action, active ? "lifecycle.stop" : "lifecycle.start"); + verify(controller.confirm()); + compare(backend.sent.action, active ? "lifecycle.stop" : "lifecycle.start"); + compare(backend.lifecycle.enabled, enabled); + backend.busy = false; + backend.actionFinished(backend.sent.action, true, {}, null); + } + } + } + function test_unauthorized_busy_and_nested_actions_are_blocked() { + backend.canControlService = false; + verify(!controller.requestServiceToggle(null)); + backend.canControlService = true; + backend.busy = true; + verify(!controller.requestServiceToggle(null)); + backend.busy = false; + controller.begin("add-device", null, null); + verify(!controller.requestServiceToggle(null)); + controller.closeForm(); + controller.requestConfirmation("device.remove", { + id: "one" + }, null); + verify(!controller.requestServiceToggle(null)); + compare(controller.confirmation.action, "device.remove"); + compare(backend.sent, null); + } + function test_draft_and_confirmation_cannot_be_replaced() { + verify(controller.begin("add-device", null, null)); + controller.setDraft("name", "keep"); + verify(!controller.begin("add-folder", null, null)); + verify(!controller.requestConfirmation("device.remove", { + id: "one" + }, null)); + compare(controller.form, "add-device"); + compare(controller.draft.name, "keep"); + controller.closeForm(); + controller.requestConfirmation("device.remove", { + id: "one" + }, null); + verify(!controller.begin("add-folder", null, null)); + verify(!controller.requestConfirmation("folder.forget", { + id: "two" + }, null)); + compare(controller.confirmation.target.id, "one"); + } + function test_stale_submission_keeps_the_draft() { + controller.begin("add-device", null, null); + controller.setDraft("name", "keep"); + backend.connection = { + fresh: false + }; + verify(!controller.submit()); + compare(backend.sent, null); + compare(controller.draft.name, "keep"); + verify(controller.error.includes("stale")); + controller.closeForm(); + controller.requestConfirmation("device.remove", { + id: "one" + }, null); + verify(!controller.confirm()); + compare(backend.sent, null); + verify(controller.error.includes("stale")); + } + function test_vanished_offer_is_rechecked_before_directory_creation() { + backend.offers = [ + { + folderId: "offer", + deviceId: "peer" + } + ]; + controller.begin("add-folder", backend.offers[0], null); + controller.setDraft("path", "/original"); + verify(controller.submit()); + backend.busy = false; + backend.actionFinished("folder.add-existing", false, null, { + code: "path_missing" + }); + compare(controller.confirmation.target.folderId, "offer"); + backend.offers = []; + backend.sent = null; + verify(!controller.confirm()); + compare(backend.sent, null); + compare(controller.draft.path, "/original"); + verify(controller.error.includes("invitation")); + } + function test_late_results_cannot_clear_a_different_draft() { + controller.begin("add-device", null, null); + controller.setDraft("name", "original"); + controller.setDraft("deviceId", "peer"); + verify(controller.submit()); + verify(!controller.begin("add-folder", null, null)); + verify(!controller.closeForm()); + backend.busy = false; + backend.actionFinished("device.add", true, {}, null); + controller.begin("add-device", null, null); + controller.setDraft("name", "new draft"); + backend.actionFinished("device.add", true, {}, null); + compare(controller.draft.name, "new draft"); + compare(controller.form, "add-device"); + } + function test_rescan_feedback_tracks_the_operation_and_target() { + var folder = { + id: "a", + status: { + state: "idle" + } + }; + backend.busy = true; + backend._actionName = "webui.open"; + verify(!controller.rescanning(folder)); + backend._actionName = "folder.rescan"; + backend._actionTargetId = "other"; + verify(!controller.rescanning(folder)); + backend._actionTargetId = "a"; + verify(controller.rescanning(folder)); + compare(controller.folderStatus(folder), "SCANNING"); + backend.busy = false; + verify(!controller.rescanning(folder)); + backend.busy = true; + backend._actionName = "folder.rescan-all"; + backend.scanningIds = []; + verify(controller.rescanning(folder)); + backend.scanningIds = ["other"]; + verify(!controller.rescanning(folder)); + backend.scanningIds = ["a"]; + verify(controller.rescanning(folder)); + verify(!controller.rescanning({ + id: "a", + paused: true + })); + backend.busy = false; + verify(!controller.rescanning(folder)); + } + function test_service_replacement_unblocks_and_preserves_the_draft() { + controller.begin("add-device", null, null); + controller.setDraft("deviceId", "peer"); + controller.setDraft("name", "keep"); + verify(controller.submit()); + controller.service = null; + verify(!controller.submitting); + compare(controller.pendingAction, ""); + compare(controller.draft.name, "keep"); + verify(controller.error.includes("interrupted")); + backend.actionFinished("device.add", true, {}, null); + compare(controller.form, "add-device"); + backend.busy = false; + controller.service = backend; + compare(controller.draft.deviceId, "peer"); + verify(controller.submit()); + compare(backend.sent.args.deviceId, "peer"); + } + function test_restart_drops_the_old_confirmation_and_keeps_input() { + backend.offers = [ + { + folderId: "offer", + deviceId: "peer" + } + ]; + controller.begin("add-folder", backend.offers[0], null); + controller.setDraft("path", "/keep"); + verify(controller.submit()); + backend.busy = false; + backend.actionFinished("folder.add-existing", false, null, { + code: "path_missing" + }); + verify(!!controller.confirmation); + backend.core.generation++; + compare(controller.confirmation, null); + compare(controller.draft.path, "/keep"); + verify(!controller.confirm()); + verify(controller.error.includes("connection changed")); + } + function test_id_generation_preserves_existing_id_on_failure_or_typing() { + controller.begin("add-folder", null, null); + backend.actionFinished("folder.suggest-id", true, { + folderId: "first" + }, null); + compare(controller.draft.folderId, "first"); + verify(controller.suggestFolderId()); + backend.actionFinished("folder.suggest-id", false, null, { + message: "offline" + }); + compare(controller.draft.folderId, "first"); + verify(controller.suggestFolderId()); + controller.setDraft("folderId", "typed"); + backend.actionFinished("folder.suggest-id", true, { + folderId: "late" + }, null); + compare(controller.draft.folderId, "typed"); + verify(controller.suggestFolderId()); + backend.actionFinished("folder.suggest-id", true, { + folderId: "second" + }, null); + compare(controller.draft.folderId, "second"); + controller.closeForm(); + controller.begin("add-folder", { + folderId: "offer", + deviceId: "peer" + }, null); + verify(!controller.suggestFolderId()); + } + function test_required_fields_reject_whitespace_without_losing_input() { + controller.begin("add-folder", null, null); + controller.setDraft("folderId", "id"); + controller.setDraft("path", " "); + verify(!controller.submit()); + compare(backend.sent, null); + compare(controller.draft.path, " "); + verify(controller.error.includes("required")); + controller.closeForm(); + controller.begin("add-device", null, null); + controller.setDraft("deviceId", " "); + verify(!controller.submit()); + compare(backend.sent, null); + verify(controller.error.includes("required")); + } + function test_backend_rejections_preserve_input_and_do_not_confirm_creation() { + for (var failure of [ + { + code: "path_invalid", + message: "folder path must be a directory" + }, + { + code: "path_overlap", + message: "folder path overlaps a configured folder" + }, + { + code: "folder_exists", + message: "folder is already configured" + } + ]) { + controller.begin("add-folder", null, null); + controller.setDraft("folderId", "id"); + controller.setDraft("path", "/keep"); + verify(controller.submit()); + backend.busy = false; + backend.actionFinished("folder.add-existing", false, null, failure); + compare(controller.confirmation, null); + compare(controller.draft.path, "/keep"); + compare(controller.error, failure.message); + controller.closeForm(); + } + for (var failure of [ + { + code: "device_id_invalid", + message: "device ID is invalid" + }, + { + code: "device_self", + message: "this device cannot be added as a remote device" + }, + { + code: "device_exists", + message: "device is already configured" + } + ]) { + controller.begin("add-device", null, null); + controller.setDraft("deviceId", "input"); + controller.setDraft("name", "keep"); + verify(controller.submit()); + backend.busy = false; + backend.actionFinished("device.add", false, null, failure); + compare(controller.draft.deviceId, "input"); + compare(controller.draft.name, "keep"); + compare(controller.error, failure.message); + controller.closeForm(); + } + } +} diff --git a/tests/dux-shell/tst_settings.qml b/tests/dux-shell/tst_settings.qml new file mode 100644 index 00000000..60998d33 --- /dev/null +++ b/tests/dux-shell/tst_settings.qml @@ -0,0 +1,58 @@ +import QtQuick +import QtTest +import "../../hosts/dux-shell/controllers" + +TestCase { + id: test + name: "DmsSettingsReplacement" + property var settings + Component { + id: factory + SettingsController {} + } + function stored(path) { + return { + syncshell: { + schema: 1, + owner: "omarchy-QOL/syncshell", + configPath: path + } + }; + } + function init() { + settings = factory.createObject(test, { + pluginData: stored("/first/config.xml") + }); + } + function cleanup() { + settings.destroy(); + } + function test_replacing_plugin_data_rebinds_values() { + verify(settings.valid); + compare(settings.values.configPath, "/first/config.xml"); + var previous = settings.pluginData; + settings.pluginData = stored("/second/config.xml"); + compare(settings.values.configPath, "/second/config.xml"); + previous.syncshell.configPath = "/stale/config.xml"; + compare(settings.values.configPath, "/second/config.xml"); + settings.destroy(); + settings = factory.createObject(test, { + pluginData: stored("/second/config.xml") + }); + compare(settings.values.configPath, "/second/config.xml"); + } + function test_invalid_replacement_revokes_settings_validity() { + settings.pluginData = { + syncshell: { + schema: 99, + owner: "another/plugin" + } + }; + verify(!settings.valid); + verify(settings.validationError.length > 0); + compare(settings.values.lifecycleAuthorized, false); + settings.pluginData = stored("/recovered/config.xml"); + verify(settings.valid); + compare(settings.values.configPath, "/recovered/config.xml"); + } +} diff --git a/tests/folder-overview.qml b/tests/folder-overview.qml index 19cc41c0..baf61089 100644 --- a/tests/folder-overview.qml +++ b/tests/folder-overview.qml @@ -34,7 +34,7 @@ ShellRoot { when: false } - FolderOverview { + BodyTabFolders { id: overview width: parent.width cardAnchor: parent diff --git a/tests/plugin-ui.test.sh b/tests/plugin-ui.test.sh index 0ca96e40..d8797656 100755 --- a/tests/plugin-ui.test.sh +++ b/tests/plugin-ui.test.sh @@ -7,14 +7,14 @@ cd -- "$root" # Models run in Qt, not a JavaScript surrogate with different import semantics. QT_QPA_PLATFORM=offscreen QT_FORCE_STDERR_LOGGING=1 \ /usr/lib/qt6/bin/qml tests/run.qml -node --test tests/folder-creation.test.mjs tests/bar-click.test.mjs tests/device-sharing.test.mjs +node --test tests/folder-creation.test.mjs tests/bar-click.test.mjs tests/device-sharing.test.mjs tests/adapter-contract.test.mjs tests/caelestia-model.test.mjs tests/caelestia-ownership.test.mjs # Run serially: popup focus tests share the desktop and are timing sensitive. for name in architecture plugin-acceptance-lint \ dropdown-search folder-overview busy-button \ adapter-service core-process install-recovery refresh-recovery \ self-removal settings-migration theme-palette \ - caelestia-adapter dankmaterialshell-adapter illogical-impulse-adapter \ + caelestia-adapter dux-shell-adapter illogical-impulse-adapter \ waybar-adapter; do printf '\n==> %s\n' "$name" bash "tests/$name.test.sh" diff --git a/tests/run.qml b/tests/run.qml index 0d791422..efa9ff9b 100644 --- a/tests/run.qml +++ b/tests/run.qml @@ -148,15 +148,58 @@ QtObject { iconStyle: "themed", webUiTheme: "default", serviceState: "disabled", - probeIntervalSeconds: 27 + probeIntervalSeconds: 27, + folderSort: "name", + folderFilters: ["ready", "active", "errors", "paused", "unknown"] }; compare(SettingsModel.parse(current), expected, "current settings"); compare(SettingsModel.defaults(), { iconStyle: "themed", webUiTheme: "omarchy", serviceState: "enabled", - probeIntervalSeconds: 15 + probeIntervalSeconds: 15, + folderSort: "name", + folderFilters: ["ready", "active", "errors", "paused", "unknown"] }, "implicit defaults"); + var all = ["ready", "active", "errors", "paused", "unknown"]; + // "all" anywhere, or every group named, is all; one group works with or without a list. + [['"all"', all], ['["all"]', all], ["['all']", all], ['["all", "errors"]', all], + ['["ready", "active", "errors", "paused", "unknown"]', all], ['"ready"', ["ready"]], + ['["ready"]', ["ready"]], ['[ "errors" , \'ready\', ]', ["ready", "errors"]], ['[]', []]].forEach(function (pair) { + compare(SettingsModel.parse(current + '[view]\nfolder_filters = ' + pair[0] + '\n').folderFilters, pair[1], "filters " + pair[0]); + }); + ["name", "active-first", "errors-first"].forEach(function (sort) { + compare(SettingsModel.parse(current + "[view]\nfolder_sort = '" + sort + "'\n").folderSort, sort, "sort " + sort); + }); + [current + '[view]\nfolder_sort = "newest"\n', current + '[view]\nfolder_filters = ["ready", "stopped"]\n', + current + '[view]\nfolder_filters = [ready]\n', current + '[view]\nfolder_filters = ["ready",\n"active"]\n', + current + '[view]\nfolder_sort = "name"\n[view]\n', current + '[view]\nmore_open = "yes"\n', + current + '[view]\nfolder_sort = "name"\nfolder_sort = "name"\n'].forEach(function (raw, index) { + compare(!!SettingsModel.parse(raw).error, true, "invalid view " + index); + }); + compare([SettingsModel.formatFolderFilters(all), SettingsModel.formatFolderFilters(["errors", "ready"]), + SettingsModel.formatFolderFilters(["ready"]), SettingsModel.formatFolderFilters([])], + ['["all"]', '["ready", "errors"]', '["ready"]', '[]'], "the plugin writes lists"); + // The writer changes values only: comments, quotes elsewhere and line endings stay. + var template = 'version = 2\n\n[style]\nicon_style = "themed"\nweb_ui_theme = "omarchy"\n\n[service]\nservice_state = "enabled"\n\n[view]\n# sort note\nfolder_sort = "name"\n# filter note\nfolder_filters = ["all"]\n'; + var noted = current.replace('[service]', '[service] # owner') + '# trailing note\n'; + compare(SettingsModel.withView(noted, "active-first", ["errors", "ready"], template).text, + noted + '\n[view]\n# sort note\nfolder_sort = "active-first"\n# filter note\nfolder_filters = ["ready", "errors"]\n', "a missing view comes from the template"); + var viewed = current + "[view]\nfolder_sort = 'name' # mine\n"; + compare(SettingsModel.withView(viewed, "errors-first", [], template).text, + current + '[view]\nfolder_sort = "errors-first" # mine\nfolder_filters = []\n', "a missing key joins its section"); + var crlf = current.replace(/\n/g, "\r\n"); + compare(SettingsModel.withServiceState(crlf, "enabled", template).text, + crlf.replace('"disabled"', '"enabled"'), "line endings stay"); + compare(SettingsModel.withServiceState(current.replace(/\n$/, ""), "enabled", template).text, + current.replace('"disabled"', '"enabled"').replace(/\n$/, ""), "a missing final newline stays missing"); + compare(SettingsModel.withServiceState(current, "disabled", template).text, current, "an unchanged value leaves the text"); + [SettingsModel.withView(current + '[view]\n[view]\n', "name", all, template), + SettingsModel.withView(current, "newest", all, template), + SettingsModel.withServiceState(current, "stopped", template), + SettingsModel.withServiceState('icon_style = "themed"\nweb_ui_theme = "default"\n', "enabled", template)].forEach(function (result, index) { + compare(!!result.error && result.text === undefined, true, "refused write " + index); + }); ["default", "modern", "omarchy"].forEach(function (theme) { compare(SettingsModel.parse(current.replace('"default"', '"' + theme + '"')).webUiTheme, theme, "valid Web UI " + theme); }); @@ -181,7 +224,9 @@ QtObject { iconStyle: "branded", webUiTheme: "omarchy", serviceState: "enabled", - probeIntervalSeconds: 15 + probeIntervalSeconds: 15, + folderSort: "name", + folderFilters: ["ready", "active", "errors", "paused", "unknown"] }, "unversioned migration keeps old defaults"); compare(migrated.additions.length, 2, "missing defaults are listed"); compare(migrated.text.indexOf('# owner comment') >= 0, true, "legacy comment survives"); diff --git a/tests/scripts.test.sh b/tests/scripts.test.sh index ac39e3d7..73d88347 100755 --- a/tests/scripts.test.sh +++ b/tests/scripts.test.sh @@ -25,57 +25,6 @@ test_settings() { grep -Eq '^probe_interval_seconds[[:space:]]*=[[:space:]]*15$' "$target" \ || fail "service probe interval was not seeded" - printf '%s\n' '' '# retained owner comment' '[future]' \ - 'retained_value = "untouched"' >>"$target" - - bash "$root/hosts/omarchy/scripts/syncthing-settings.sh" set-service-state \ - "$root/hosts/omarchy/config/settings.toml" "$target" themed disabled \ - >/dev/null - grep -Eq '^service_state[[:space:]]*=[[:space:]]*"disabled"' "$target" \ - || fail "service state was not updated" - [[ $(grep -c '^service_state[[:space:]]*=' "$target") == 1 ]] \ - || fail "service state update created a duplicate" - grep -Eq '^icon_style[[:space:]]*=[[:space:]]*"themed"' "$target" \ - || fail "service state update changed icon style" - grep -Fxq '# retained owner comment' "$target" \ - || fail "service state update removed an owner comment" - grep -Fxq 'retained_value = "untouched"' "$target" \ - || fail "service state update removed an additive field" - - local legacy="$test_root/settings/config/legacy.toml" - printf '%s\n' \ - 'icon_style = "branded"' \ - 'web_ui_theme = "default"' \ - >"$legacy" - bash "$root/hosts/omarchy/scripts/syncthing-settings.sh" set-service-state \ - "$root/hosts/omarchy/config/settings.toml" "$legacy" branded disabled \ - >/dev/null - grep -Fxq '[service]' "$legacy" \ - || fail "legacy settings did not receive a service section" - grep -Eq '^service_state[[:space:]]*=[[:space:]]*"disabled"' "$legacy" \ - || fail "legacy settings did not receive the service state" - grep -Fxq 'web_ui_theme = "default"' "$legacy" \ - || fail "legacy settings were not preserved" - - local invalid="$test_root/settings/config/invalid.toml" - local invalid_before - printf '%s\n' \ - 'icon_style = "branded"' \ - 'web_ui_theme = "default"' \ - '[service]' \ - 'service_state = "enabled"' \ - 'service_state = "disabled"' \ - >"$invalid" - invalid_before=$(<"$invalid") - if bash "$root/hosts/omarchy/scripts/syncthing-settings.sh" \ - set-service-state "$root/hosts/omarchy/config/settings.toml" \ - "$invalid" branded enabled \ - >/dev/null 2>&1; then - fail "invalid service settings update succeeded" - fi - [[ $(<"$invalid") == "$invalid_before" ]] \ - || fail "failed service settings update changed the file" - printf '%s\n' '# user-owned' >"$target" bash "$root/hosts/omarchy/scripts/syncthing-settings.sh" ensure \ "$root/hosts/omarchy/config/settings.toml" "$target" branded >/dev/null @@ -83,6 +32,37 @@ test_settings() { || fail "existing settings were overwritten" } +# The panel computes the new text; replace only commits it unchanged-since-read. +test_replace_settings() { + local helper="$root/hosts/omarchy/scripts/syncthing-settings.sh" + local dir="$test_root/replace" target link before + target="$dir/owner.toml" + link="$dir/settings.toml" + mkdir -p -- "$dir" + printf '%s\n' 'old = 1' >"$target" + chmod 640 -- "$target" + ln -s owner.toml "$link" + + jq -nc '{original: "old = 1\n", replacement: "new = 2\n"}' \ + | bash "$helper" replace "$link" >/dev/null + [[ $(<"$target") == "new = 2" ]] || fail "replace did not commit the new text" + [[ -L $link ]] || fail "replace broke the settings symlink" + [[ $(stat -c %a "$target") == 640 ]] || fail "replace changed the file mode" + + before=$(<"$target") + local status=0 + jq -nc '{original: "old = 1\n", replacement: "lost = 3\n"}' \ + | bash "$helper" replace "$link" >/dev/null 2>&1 || status=$? + [[ $status == 3 ]] || fail "a stale replace did not exit 3 (got $status)" + [[ $(<"$target") == "$before" ]] || fail "a stale replace changed the file" + + if printf '%s\n' 'not json' | bash "$helper" replace "$link" >/dev/null 2>&1; then + fail "replace accepted a malformed request" + fi + [[ $(<"$target") == "$before" ]] || fail "a malformed request changed the file" + [[ -z $(find "$dir" -name '.settings*') ]] || fail "replace left temporary files" +} + test_installation_status() { local sandbox="$test_root/installation-status" local fake_bin="$sandbox/bin" @@ -133,6 +113,25 @@ test_installation_status() { PATH="$fake_bin" bash "$root/hosts/omarchy/scripts/syncthing-install.sh" status) jq -e '.state == "missing"' <<<"$output" >/dev/null \ || fail "failed Flatpak lookup reported an installation" + + # No sync databases yet: stop before omarchy runs pacman -S. + for tool in mkdir chmod unlink; do + ln -s -- "$(command -v "$tool")" "$fake_bin/$tool" + done + printf '%s\n' '#!/bin/bash' 'exit 1' >"$fake_bin/pacman" + printf '%s\n' '#!/bin/bash' 'touch "$HOME/omarchy-called"' \ + >"$fake_bin/omarchy" + chmod 700 -- "$fake_bin/pacman" "$fake_bin/omarchy" + if output=$(printf '\n' | HOME="$sandbox/home" \ + XDG_RUNTIME_DIR="$sandbox/runtime" PATH="$fake_bin" \ + bash "$root/hosts/omarchy/scripts/syncthing-install.sh" \ + run install-package 2>&1); then + fail "install succeeded without package lists" + fi + [[ $output == *"Run Omarchy's Update first"* ]] \ + || fail "missing package lists gave no update hint: $output" + [[ ! -e $sandbox/home/omarchy-called ]] \ + || fail "install ran omarchy without package lists" } test_modern_bundle() { @@ -465,6 +464,7 @@ if [[ ${1:-} == --webui-only ]]; then fi test_settings +test_replace_settings test_installation_status test_modern_bundle test_themes diff --git a/tests/self-removal.qml b/tests/self-removal.qml index cc321e36..044c89d2 100644 --- a/tests/self-removal.qml +++ b/tests/self-removal.qml @@ -13,7 +13,7 @@ ShellRoot { Item { width: 600 height: 600 - SelfRemovalDialog { + SettingsSelfRemovalDialog { id: dialog anchors.fill: parent opened: true diff --git a/tests/settings-migration.qml b/tests/settings-migration.qml index 010c107c..a1f7ccfe 100644 --- a/tests/settings-migration.qml +++ b/tests/settings-migration.qml @@ -8,6 +8,7 @@ ShellRoot { property int step: 0 property int ticks: 0 property string older: "" + property string hand: "" OmarchyService { id: service } @@ -85,10 +86,21 @@ ShellRoot { root.check(!!service.settingsError, "late completion preserves validation error"); source.setText(root.older.replace('version = 1', 'version = 2')); root.step = 6; - } else { + } else if (root.step === 6) { if (!service.settingsReady) return; root.check(!service.settingsError, "corrected save recovers automatically"); + // As if the file changed after the panel read it: the write is + // refused, the file reread and the write retried once, silently. + root.hand = settings._settingsRaw; + settings._settingsRaw += "# stale copy\n"; + service.setFolderView("errors-first", ["ready"]); + root.step = 7; + } else { + if (settings.settingsProcess.running || settings._awaitingReload || settings._settingsRaw.indexOf('folder_sort = "errors-first"') < 0) + return; + root.check(!service.settingsError, "a retried write reports no error"); + root.check(settings._settingsRaw === root.hand.replace('folder_sort = "name"', 'folder_sort = "errors-first"').replace('folder_filters = ["all"]', 'folder_filters = ["ready"]'), "the retry writes from the current file"); service.core.terminate(); console.log("settings migration controller tests passed"); Qt.quit(); diff --git a/tests/settings-migration.test.sh b/tests/settings-migration.test.sh index 34658f2f..9a2798d1 100644 --- a/tests/settings-migration.test.sh +++ b/tests/settings-migration.test.sh @@ -63,7 +63,9 @@ cmp "$test_root/before.toml" "$target" grep -q 'changed since the preview' "$test_root/error" [[ $(find "$test_root" -name '*.before-port.*' | wc -l) == 1 ]] # Ordinary preference writes also retain managed symlinks. -bash "$helper" set-service-state "$template" "$target" themed enabled >/dev/null +jq -nc --rawfile original "$target" \ + '{original: $original, replacement: ($original | sub("service_state = \"[a-z]+\""; "service_state = \"enabled\""))}' \ + | bash "$helper" replace "$target" >/dev/null [[ -L $target && $(stat -c %a "$test_root/owner.toml") == 640 ]] grep -q '^service_state = "enabled"$' "$target" printf 'settings writer tests passed\n'