diff --git a/design/icongen/Program.cs b/design/icongen/Program.cs index 18dd4c99..26f012cd 100644 --- a/design/icongen/Program.cs +++ b/design/icongen/Program.cs @@ -3,10 +3,11 @@ // // dotnet run --project design/icongen // -// Windows: windows/Flock.Tray/Assets/AppIcon.ico and Tray{,Stopped,Warning}.{Light,Dark}.ico, the -// notification area icon for a light or dark taskbar, plus large .png copies for inside the -// windows. macOS: macos/Resources/AppIcon.icns and MenuBar{,Stopped,Warning}{,@2x}.png, template -// images that macOS tints for the menu bar itself. +// Windows: windows/Flock.Tray/Assets/AppIcon.ico and Tray{,Warning,Stopped,Down}.{Light,Dark}.ico, +// the notification area icon for a light or dark taskbar, plus large .png copies for inside the +// windows. macOS: macos/Resources/AppIcon.icns, and MenuBar{,@2x}.png and LogoMark.png, template +// images that macOS tints for the menu bar itself; the app draws the dots on them (LogoMark.swift). +// Linux's tray icons are SVGs of their own (linux/data/icons). using SkiaSharp; using Svg.Skia; @@ -24,8 +25,11 @@ ["Light"] = File.ReadAllText(Path.Combine(root, "design", "logo", "flock-logomark-light.svg")), ["Dark"] = File.ReadAllText(Path.Combine(root, "design", "logo", "flock-logomark-dark.svg")), }; -// Ember, the brand's "notice this now" color, for the warning badge. +// The dot at the mark's lower right says what isn't as usual: ember, the brand's "notice this now" +// color, for a warning; grey while Flock is stopped; red when it should run and doesn't. var ember = SKColor.Parse("#E8792B"); +var grey = SKColor.Parse("#8E8E93"); +var red = SKColor.Parse("#E5484D"); var windowsAssets = Path.Combine(root, "windows", "Flock.Tray", "Assets"); var macResources = Path.Combine(root, "macos", "Resources"); Directory.CreateDirectory(macResources); @@ -35,20 +39,19 @@ size => Render(appIcon, size, size, 0)); // Notification area: the light (teal) or dark (mint) logomark for a light or dark taskbar, at -// every small-icon size from 100% to 300% scaling. Stopped is dimmed; a warning adds an ember -// badge. +// every small-icon size from 100% to 300% scaling, always the whole mark, with a dot by state. int[] traySizes = [16, 20, 24, 28, 32, 40, 48, 64]; +(string Name, SKColor? Dot)[] trayStates = [("Tray", null), ("TrayWarning", ember), ("TrayStopped", grey), ("TrayDown", red)]; foreach (var (theme, mark) in trayMarks) { - WriteIco(Path.Combine(windowsAssets, $"Tray.{theme}.ico"), traySizes, size => Mark(mark, size, 1)); - WriteIco(Path.Combine(windowsAssets, $"TrayStopped.{theme}.ico"), traySizes, size => Mark(mark, size, 0.45f)); - WriteIco(Path.Combine(windowsAssets, $"TrayWarning.{theme}.ico"), traySizes, size => Badge(Mark(mark, size, 1), ember)); - - // Inside the app's windows (the panel's header): WinUI's Image shows an .ico's first, smallest - // image scaled up, so the windows get large PNGs instead (128 px: 32 points at 400%). - File.WriteAllBytes(Path.Combine(windowsAssets, $"Tray.{theme}.png"), Png(Mark(mark, 128, 1))); - File.WriteAllBytes(Path.Combine(windowsAssets, $"TrayStopped.{theme}.png"), Png(Mark(mark, 128, 0.45f))); - File.WriteAllBytes(Path.Combine(windowsAssets, $"TrayWarning.{theme}.png"), Png(Badge(Mark(mark, 128, 1), ember))); + foreach (var (name, dot) in trayStates) + { + SKBitmap Icon(int size) => dot is { } color ? Badge(Mark(mark, size, 1), color) : Mark(mark, size, 1); + WriteIco(Path.Combine(windowsAssets, $"{name}.{theme}.ico"), traySizes, Icon); + // Inside the app's windows (the panel's header): WinUI's Image shows an .ico's first, smallest + // image scaled up, so the windows get large PNGs instead (128 px: 32 points at 400%). + File.WriteAllBytes(Path.Combine(windowsAssets, $"{name}.{theme}.png"), Png(Icon(128))); + } } // The app icon in the windows (title bar, Setup, About): up to 72 points at 300%. File.WriteAllBytes(Path.Combine(windowsAssets, "AppIcon.png"), Png(Render(appIcon, 256, 256, 0))); @@ -69,22 +72,14 @@ return bitmap; }); -// Menu bar: 18-point template images; macOS colors them for the menu bar's appearance. -foreach (var (name, alpha, badge) in new[] { ("MenuBar", 1f, false), ("MenuBarStopped", 0.45f, false), ("MenuBarWarning", 1f, true) }) +// Menu bar: an 18-point template image; macOS colors it for the menu bar's appearance. The app +// draws the state's dot on it. +foreach (var (suffix, size) in new[] { ("", 18), ("@2x", 36) }) { - foreach (var (suffix, size) in new[] { ("", 18), ("@2x", 36) }) - { - var image = Mark(logomark, size, alpha); - if (badge) - { - image = Badge(image, SKColors.Black); - } - File.WriteAllBytes(Path.Combine(macResources, $"{name}{suffix}.png"), Png(image)); - } - // Inside the app's windows (panel header, Settings): large enough for 64 points at 2x. - var large = Mark(logomark, 128, alpha); - File.WriteAllBytes(Path.Combine(macResources, name.Replace("MenuBar", "LogoMark") + ".png"), Png(badge ? Badge(large, SKColors.Black) : large)); + File.WriteAllBytes(Path.Combine(macResources, $"MenuBar{suffix}.png"), Png(Mark(logomark, size, 1))); } +// Inside the app's windows (panel header, Settings): large enough for 64 points at 2x. +File.WriteAllBytes(Path.Combine(macResources, "LogoMark.png"), Png(Mark(logomark, 128, 1))); Console.WriteLine("icons written"); @@ -98,23 +93,23 @@ var mark = trayMarks[theme]; foreach (var size in new[] { 16, 24, 32 }) { - rows.Add((SKColor.Parse(background), [Mark(mark, size, 1), Mark(mark, size, 0.45f), Badge(Mark(mark, size, 1), ember)])); + rows.Add((SKColor.Parse(background), [Mark(mark, size, 1), Badge(Mark(mark, size, 1), ember), Badge(Mark(mark, size, 1), grey), Badge(Mark(mark, size, 1), red)])); } } foreach (var (background, tint) in new[] { ("#ECECEC", "#000000"), ("#2A2A2A", "#FFFFFF") }) { var mark = logomark.Replace("#000000", tint); - rows.Add((SKColor.Parse(background), [Mark(mark, 18, 1), Mark(mark, 18, 0.45f), Badge(Mark(mark, 18, 1), SKColor.Parse(tint))])); + rows.Add((SKColor.Parse(background), [Mark(mark, 18, 1), Badge(Mark(mark, 18, 1), ember), Badge(Mark(mark, 18, 1), grey), Badge(Mark(mark, 18, 1), red)])); } rows.Add((SKColors.White, [Render(appIcon, 16, 16, 0), Render(appIcon, 32, 32, 0), Render(appIcon, 48, 48, 0)])); const int zoom = 4, cell = 48 * zoom + 16; - using var sheet = new SKBitmap(3 * cell, rows.Count * cell); + using var sheet = new SKBitmap(4 * cell, rows.Count * cell); using var canvas = new SKCanvas(sheet); for (var r = 0; r < rows.Count; r++) { using var fill = new SKPaint { Color = rows[r].Background }; - canvas.DrawRect(0, r * cell, 3 * cell, cell, fill); + canvas.DrawRect(0, r * cell, 4 * cell, cell, fill); for (var c = 0; c < rows[r].Icons.Length; c++) { var icon = rows[r].Icons[c]; diff --git a/docs/cli.md b/docs/cli.md index f74a363b..28a47661 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -16,8 +16,8 @@ This page lists the `flock` commands. The other pages show where to find each ac | `flock uninstall [--purge]` | Remove Flock. Keeps site settings and databases unless `--purge` is given | | `flock status` | Show the state of the daemon and its services | | `flock restart` | Restart the daemon and all services | -| `flock start` | Start the daemon and all services after `flock stop` | -| `flock stop` | Stop the daemon and all services until `flock start` | +| `flock start` | Start the daemon and all services after `flock stop` or after quitting the app | +| `flock stop` | Stop the daemon and all services until `flock start` or until the Flock app is opened | | `flock logs [name] [-n 50] [-f]` | Show service logs (daemon, web, php8.5-fpm on macOS and Linux or php8.5-cgi on Windows, postgres, …), or of what Flock runs for a site or proxy by its name (its FrankenPHP, dev server or command). Without a name, lists the logs | | `flock update` | Update Flock, CLI and daemon included: the app installs the new version (on Linux, apt or dnf) | | `flock version` | Print the Flock version | diff --git a/docs/installation.md b/docs/installation.md index 2e6a09d0..172fec61 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -62,7 +62,7 @@ The setup: - tells systemd-resolved to send `*.test` lookups to Flock's DNS server, - adds Flock's certificate authority to the system's trust store, to Firefox through a policy, and to the certificate databases of Chrome and other Chromium browsers. -Flock also puts an icon in the top bar with its status, your sites, mail, dumps and logs. KDE shows it on its own, and GNOME with the AppIndicator extension, which Ubuntu includes. On Fedora's GNOME, install **AppIndicator and KStatusNotifierItem Support** to get it. Without the icon, Flock is a regular window that quits when you close it, and the daemon keeps running. +Flock also puts an icon in the top bar with its status, your sites, mail, dumps and logs. KDE shows it on its own, and GNOME with the AppIndicator extension, which Ubuntu includes. On Fedora's GNOME, install **AppIndicator and KStatusNotifierItem Support** to get it. Without the icon, Flock is a regular window that quits when you close it, and Flock keeps running. ## Checking the installation @@ -98,7 +98,9 @@ Stop that program and run `flock restart`. ## Stopping Flock -Quitting the menu bar or tray app leaves Flock running, so your sites keep working. To stop Flock and everything it runs, for example to free memory, or ports 80 and 443 for another local environment: +Quitting Flock stops it: **Quit Flock** in the panel or in the icon's menu stops your sites, the databases and everything else Flock runs, and frees its ports, for example 80 and 443 for another local environment. Starting Flock again starts them, with the services that were on before. Logging out or shutting down the computer doesn't stop Flock that way: it is on again when you are back. + +To stop Flock without quitting it: :::app Switch off the switch at the top of the Flock panel, and switch it on to start Flock again. On Windows, **Stop Flock** and **Start Flock** are also in the tray icon's right-click menu. On Linux, the switch is at the top of the Flock window's sidebar, and **Stop Flock** and **Start Flock** are in the menu of Flock's icon in the top bar. @@ -108,4 +110,6 @@ Switch off the switch at the top of the Flock panel, and switch it on to start F Run `flock stop`, and `flock start` to start Flock again. ::: -Flock starts again at your next login on macOS and Windows, and when the computer starts on Linux. +A stopped Flock stays stopped until you start it again or open the Flock app. If the Flock app opens at login, that starts Flock too. Flock's icon shows its state with a dot: none while it runs, orange when something needs attention, grey while it is stopped, and red when it should run and doesn't. + +On Linux without Flock's icon in the top bar, closing the window quits the app only, and Flock keeps running. diff --git a/internal/api/api.go b/internal/api/api.go index 905ace79..41953e22 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -304,6 +304,8 @@ type Settings struct { type Backend interface { Status() Status Reload() error + // Shutdown makes the daemon stop everything it runs and exit, as on a termination signal. + Shutdown() Root() string // Mutate loads config.json, applies change, saves it and reloads the daemon. Mutate(change func(*config.Config) error) error @@ -367,6 +369,12 @@ func NewHandler(b Backend, token string) http.Handler { } writeJSON(w, http.StatusOK, b.Status()) }) + // The graceful stop where the service manager can only kill (Windows). Answered before the + // daemon stops: its exit is what the caller waits for. + mux.HandleFunc("POST /v1/shutdown", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, struct{}{}) + b.Shutdown() + }) mux.HandleFunc("POST /v1/settings", func(w http.ResponseWriter, r *http.Request) { var settings Settings if err := json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(&settings); err != nil { @@ -458,6 +466,12 @@ func (c *Client) Reload(ctx context.Context) (Status, error) { return status, err } +// Shutdown asks the daemon to stop everything it runs and exit. It answers before it has. +func (c *Client) Shutdown(ctx context.Context) error { + var out struct{} + return c.do(ctx, http.MethodPost, "/v1/shutdown", &out) +} + // UpdateSettings changes the given global settings and returns the resulting status. func (c *Client) UpdateSettings(ctx context.Context, s Settings) (Status, error) { var status Status diff --git a/internal/api/api_test.go b/internal/api/api_test.go index b20d4eba..1e0d4da0 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -30,7 +30,9 @@ type fakeBackend struct { catalog *catalog.Manager root string sites []SiteStatus - php *php.Manager + // shutdowns counts Shutdown calls. + shutdowns int + php *php.Manager pg *postgres.Manager frankenphp *frankenphp.Manager @@ -82,6 +84,7 @@ func (f *fakeBackend) RemoveWorktree(context.Context, string, bool) (string, err func (f *fakeBackend) Status() Status { return Status{Sites: f.sites} } func (f *fakeBackend) Reload() error { return nil } +func (f *fakeBackend) Shutdown() { f.shutdowns++ } func (f *fakeBackend) Root() string { return f.root } func (f *fakeBackend) ReleasePHP(string) {} func (f *fakeBackend) Services() []Service { return []Service{} } @@ -127,6 +130,18 @@ func call(t *testing.T, method, url, token, body string) (*http.Response, string return resp, string(data) } +func TestShutdownAnswersAndStopsTheDaemon(t *testing.T) { + backend := &fakeBackend{root: t.TempDir()} + srv := serve(t, backend, "") + + if resp, _ := call(t, "POST", srv.URL+"/v1/shutdown", "", ""); resp.StatusCode != http.StatusOK { + t.Fatalf("shutdown: %d", resp.StatusCode) + } + if backend.shutdowns != 1 { + t.Fatalf("want 1 shutdown, got %d", backend.shutdowns) + } +} + func TestTokenIsRequiredWhenConfigured(t *testing.T) { srv := serve(t, &fakeBackend{root: t.TempDir()}, "secret") diff --git a/internal/cli/daemon.go b/internal/cli/daemon.go index d5542817..5077e818 100644 --- a/internal/cli/daemon.go +++ b/internal/cli/daemon.go @@ -38,6 +38,13 @@ func newDaemonCommand() *cobra.Command { cmd.SetOut(f) cmd.SetErr(f) } + // The system starts the daemon at login or with the computer; while the user has Flock + // stopped, it doesn't run, and the service manager is told not to start it again. + if isStopped(root) { + cmd.Printf("flock daemon %s — Flock is stopped (`flock stop`), not starting; `flock start` starts it\n", Version) + stayStopped(root) + return nil + } if watchdog { return runWatchdog(cmd, logFile) } diff --git a/internal/cli/install.go b/internal/cli/install.go index d40824fd..89d60aca 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -40,6 +40,11 @@ func newInstallCommand() *cobra.Command { } } + // Until the first install gets through its privileged steps, Flock isn't set up: the apps + // take a registered daemon for a finished setup (Installation.isSetUp, IsSetUp). Read + // before those steps, which register the daemon on Linux. + firstInstall := !serviceInstalled() + // With privilegedFirst, the steps that need an administrator come before anything is // replaced: declining them leaves the installed version as it was. var ca *certs.CA @@ -93,13 +98,20 @@ func newInstallCommand() *cobra.Command { cmd.Printf("! could not update your shell profile: %v\n", err) } - // Until the first install gets through its privileged steps, Flock isn't set up: the apps - // take a registered daemon for a finished setup (Installation.isSetUp, IsSetUp). - firstInstall := !serviceInstalled() + if firstInstall { + // A setup turns Flock on; an update leaves a stopped Flock stopped. + if err := clearStopped(s.root); err != nil { + return err + } + } if err := installService(s.root, bin); err != nil { return fmt.Errorf("install background service: %w", err) } - cmd.Println("✓ daemon runs in the background and starts " + serviceStarts) + if isStopped(s.root) { + cmd.Println("✓ daemon is installed; Flock is stopped — `flock start` starts it") + } else { + cmd.Println("✓ daemon runs in the background and starts " + serviceStarts) + } if skipPrivileged || privilegedFirst { return nil diff --git a/internal/cli/install_darwin.go b/internal/cli/install_darwin.go index 27d950f7..25fb3cb8 100644 --- a/internal/cli/install_darwin.go +++ b/internal/cli/install_darwin.go @@ -166,6 +166,10 @@ func installService(root, bin string) error { domain := "gui/" + strconv.Itoa(os.Getuid()) stopService(domain) + // An update of a stopped Flock leaves it stopped: `flock start` loads the agent. + if isStopped(root) { + return nil + } return bootstrapService(domain, path) } @@ -491,8 +495,23 @@ func appDirs() []string { } } -// stopDaemon unloads the agent, which stops the daemon and everything it runs, until restartService -// or the next login loads it again. +// stayStopped unloads the agent a stopped Flock was started by (at login): launchd would start a +// daemon that only exits again and again (KeepAlive). Unloading ends this process. +func stayStopped(root string) { + // Not for a daemon run by hand, or when `flock start` came in between. + if os.Getenv("XPC_SERVICE_NAME") != launchLabel || !isStopped(root) { + return + } + _ = exec.Command("launchctl", "bootout", "gui/"+strconv.Itoa(os.Getuid())+"/"+launchLabel).Run() +} + +// serviceUnloaded reports whether launchd doesn't have the agent, so no daemon is starting. +func serviceUnloaded() bool { + return exec.Command("launchctl", "print", "gui/"+strconv.Itoa(os.Getuid())+"/"+launchLabel).Run() != nil +} + +// stopDaemon unloads the agent, which stops the daemon and everything it runs (launchd asks the +// daemon to end, and it stops its services), until restartService loads it again. func stopDaemon() error { target := "gui/" + strconv.Itoa(os.Getuid()) + "/" + launchLabel stopService("gui/" + strconv.Itoa(os.Getuid())) diff --git a/internal/cli/install_linux.go b/internal/cli/install_linux.go index 21cc1d37..e37b41c7 100644 --- a/internal/cli/install_linux.go +++ b/internal/cli/install_linux.go @@ -318,6 +318,10 @@ func installService(root, _ string) error { if !serviceInstalled() { return fmt.Errorf("%s isn't set up — run `flock install` without --skip-privileged", unitName(name)) } + // An update of a stopped Flock leaves it stopped: `flock start` starts the unit. + if isStopped(root) { + return nil + } return systemctl("restart", unitName(name)) } @@ -339,11 +343,34 @@ func uninstallService() error { return systemctl("stop", unitName(name)) } -// stopDaemon makes systemd stop the daemon until restartService or the next boot starts it. +// serviceUnloaded reports whether systemd doesn't run the unit (nor starts it), so no daemon is starting. +func serviceUnloaded() bool { + name, err := serviceUser() + if err != nil { + return false + } + out, _ := exec.Command("systemctl", "is-active", unitName(name)).Output() + state := strings.TrimSpace(string(out)) + return state == "inactive" || state == "failed" +} + +// stopDaemon makes systemd stop the daemon (it asks the daemon to end, which stops its services) +// until restartService starts it. func stopDaemon() error { return uninstallService() } +// stayStopped stops the unit a stopped Flock was started by (with the computer): systemd would +// start a daemon that only exits again and again (Restart=always). Stopping ends this process. +func stayStopped(root string) { + name, err := serviceUser() + // Not for a daemon run by hand, or when `flock start` came in between. + if err != nil || os.Getenv("INVOCATION_ID") == "" || !isStopped(root) { + return + } + _ = systemctl("stop", unitName(name)) +} + // restartService makes systemd stop and start the daemon. func restartService() error { name, err := serviceUser() diff --git a/internal/cli/install_windows.go b/internal/cli/install_windows.go index 07a2fab1..d1c32cb1 100644 --- a/internal/cli/install_windows.go +++ b/internal/cli/install_windows.go @@ -2,6 +2,7 @@ package cli import ( "bytes" + "context" "encoding/csv" "errors" "fmt" @@ -22,6 +23,7 @@ import ( "golang.org/x/sys/windows" "golang.org/x/sys/windows/registry" + "flock/internal/api" "flock/internal/certs" "flock/internal/dns" "flock/internal/hosts" @@ -202,6 +204,7 @@ func installService(root, bin string) error { } // Stop the running daemon first: it holds flockd.exe and the ports. + shutDownDaemon(root) _ = exec.Command("schtasks", "/End", "/TN", taskName).Run() waitDaemonGone(root) exe, args := daemonCommand(root) @@ -216,6 +219,10 @@ func installService(root, bin string) error { return installRunKey(exe, args) } removeRunKey() + // An update of a stopped Flock leaves it stopped: `flock start` runs the task. + if isStopped(root) { + return nil + } return runTask(root) } @@ -414,6 +421,10 @@ func serviceInstalled() bool { } func uninstallService() error { + // The databases stay unless the uninstall purges them: let them stop cleanly. + if root, err := paths.Root(); err == nil { + shutDownDaemon(root) + } if taskInstalled() { _ = exec.Command("schtasks", "/End", "/TN", taskName).Run() if out, err := exec.Command("schtasks", "/Delete", "/TN", taskName, "/F").CombinedOutput(); err != nil { @@ -492,12 +503,51 @@ func stopDaemonProcess() { _ = exec.Command("taskkill", "/F", "/IM", "flockd.exe").Run() } -// stopDaemon ends the scheduled task and the daemon, until restartService or the next login starts it. +// shutdownWait is how long the daemon gets to stop its services (PostgreSQL finishes its +// transactions, Valkey saves) before it is ended the hard way. +const shutdownWait = 30 * time.Second + +// shutDownDaemon asks the running daemon to stop its services and exit, and waits until it has. +// Ending the task or the process instead kills the daemon and everything it runs at once: Valkey +// loses what it hadn't saved, and PostgreSQL and MySQL recover as after a crash. The daemon's clean +// exit also ends its watchdog, and with it the task. It reports whether the daemon exited; the +// callers end the task and the process afterwards either way, for a daemon that didn't. +func shutDownDaemon(root string) bool { + client := api.NewClient(paths.Socket(root)) + ctx, cancel := context.WithTimeout(context.Background(), shutdownWait) + defer cancel() + status, err := client.Status(ctx) + if err != nil || status.PID <= 0 { + return false + } + // Opened before asking: afterwards the process may be gone, and its ID another program's. + process, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(status.PID)) + if err != nil { + return false + } + defer windows.CloseHandle(process) + if err := client.Shutdown(ctx); err != nil { + return false + } + event, err := windows.WaitForSingleObject(process, uint32(shutdownWait.Milliseconds())) + return err == nil && event == windows.WAIT_OBJECT_0 +} + +// serviceUnloaded: a stopped Flock's watchdog just ends, and restartService waits for a daemon of +// before to be gone, so there is nothing to start a second time. +func serviceUnloaded() bool { return false } + +// stayStopped: the watchdog ends when the daemon exits cleanly, and the task with it. +func stayStopped(string) {} + +// stopDaemon stops the daemon and everything it runs, until restartService starts it: it asks the +// daemon to stop, then ends the scheduled task and whatever is left. func stopDaemon() error { root, err := paths.Root() if err != nil { return err } + shutDownDaemon(root) _ = exec.Command("schtasks", "/End", "/TN", taskName).Run() stopDaemonProcess() if !waitDaemonGone(root) { @@ -506,12 +556,13 @@ func stopDaemon() error { return nil } -// restartService ends the scheduled task (killing the daemon and everything it runs) and starts it again. +// restartService stops the daemon and everything it runs (see shutDownDaemon) and starts it again. func restartService() error { root, err := paths.Root() if err != nil { return err } + shutDownDaemon(root) if taskInstalled() { _ = exec.Command("schtasks", "/End", "/TN", taskName).Run() // Also a daemon the task didn't start (`flock install` starts one directly). diff --git a/internal/cli/restart.go b/internal/cli/restart.go index 027a16ff..925489b8 100644 --- a/internal/cli/restart.go +++ b/internal/cli/restart.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "flock/internal/api" + "flock/internal/paths" ) func newRestartCommand() *cobra.Command { @@ -21,6 +22,11 @@ func newRestartCommand() *cobra.Command { return err } + // Flock is on again, also for the daemon the system starts at the next login. + if err := clearStopped(s.root); err != nil { + return err + } + before, err := s.client().Status(cmd.Context()) if cmd.Name() == "start" { // A daemon that is busy (a request timed out) runs: starting it again would restart it. @@ -37,7 +43,7 @@ func newRestartCommand() *cobra.Command { } // Wait for a new daemon (different PID) to answer. - deadline := time.Now().Add(15 * time.Second) + deadline, again := time.Now().Add(20*time.Second), time.Now().Add(2*time.Second) for time.Now().Before(deadline) { st, err := s.client().Status(cmd.Context()) if err == nil && st.PID != before.PID { @@ -50,15 +56,25 @@ func newRestartCommand() *cobra.Command { if err != nil && !errors.Is(err, api.ErrDaemonNotRunning) { return err } + // A daemon the system started just before (at login) may have seen Flock stopped and + // taken itself out of the service manager after this command started it: once more. + // Not while the service runs: a daemon answers only after its first reload, which can + // take a while. + if err != nil && !again.IsZero() && time.Now().After(again) && serviceUnloaded() { + again = time.Time{} + if err := restartService(); err != nil { + return err + } + } time.Sleep(200 * time.Millisecond) } - return fmt.Errorf("daemon did not come back within 15s — see `flock logs daemon`") + return fmt.Errorf("daemon did not come back within 20s — see `flock logs daemon`") }, } } // newStartCommand starts the daemon after `flock stop` (restartService also loads it again) and -// leaves a running one alone. +// leaves a running one alone. Like `flock restart`, it turns Flock on again for the next login too. func newStartCommand() *cobra.Command { cmd := newRestartCommand() cmd.Use, cmd.Short = "start", "Start the background daemon and all services after `flock stop`" @@ -71,7 +87,17 @@ func newStopCommand() *cobra.Command { Short: "Stop the background daemon and all services until `flock start`", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + root, err := paths.Root() + if err != nil { + return err + } + // First, so a daemon the service manager starts meanwhile doesn't run either. + if err := markStopped(root); err != nil { + return err + } if err := stopDaemon(); err != nil { + // Flock still runs: it must not count as stopped at its next start or update. + _ = clearStopped(root) return err } cmd.Println("stopped") diff --git a/internal/cli/status.go b/internal/cli/status.go index eba42d0a..3ba38a44 100644 --- a/internal/cli/status.go +++ b/internal/cli/status.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "io" "runtime" @@ -27,6 +28,9 @@ func newStatusCommand() *cobra.Command { } st, err := s.client().Status(cmd.Context()) + if errors.Is(err, api.ErrDaemonNotRunning) && isStopped(s.root) { + return errors.New("Flock is stopped — start it with `flock start`") + } if err != nil { return err } diff --git a/internal/cli/stopped.go b/internal/cli/stopped.go new file mode 100644 index 00000000..4bfb766d --- /dev/null +++ b/internal/cli/stopped.go @@ -0,0 +1,32 @@ +package cli + +import ( + "os" + + "flock/internal/paths" +) + +// Flock is off while paths.Stopped exists: the user stopped it (`flock stop`, the apps' switch +// or Quit), and it stays stopped over a login or a restart of the computer until `flock start`. + +// isStopped reports whether the user turned Flock off. +func isStopped(root string) bool { + _, err := os.Stat(paths.Stopped(root)) + return err == nil +} + +// markStopped records that the user turned Flock off. +func markStopped(root string) error { + if err := os.MkdirAll(root, 0o700); err != nil { + return err + } + return os.WriteFile(paths.Stopped(root), nil, 0o600) +} + +// clearStopped records that Flock is on again. +func clearStopped(root string) error { + if err := os.Remove(paths.Stopped(root)); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} diff --git a/internal/cli/stopped_test.go b/internal/cli/stopped_test.go new file mode 100644 index 00000000..cf8151ab --- /dev/null +++ b/internal/cli/stopped_test.go @@ -0,0 +1,62 @@ +package cli + +import ( + "bytes" + "os" + "strings" + "testing" + + "flock/internal/paths" +) + +func TestStoppedIsRememberedUntilCleared(t *testing.T) { + root := t.TempDir() + + if isStopped(root) { + t.Fatal("a new data dir must not be stopped") + } + if err := clearStopped(root); err != nil { + t.Fatalf("clearing when not stopped: %v", err) + } + if err := markStopped(root); err != nil { + t.Fatal(err) + } + if !isStopped(root) { + t.Fatal("want stopped after markStopped") + } + if err := clearStopped(root); err != nil { + t.Fatal(err) + } + if isStopped(root) { + t.Fatal("want not stopped after clearStopped") + } +} + +// The system starts the daemon at login; while Flock is stopped, it must not run (and so not +// take the socket or the ports). +func TestDaemonDoesNotRunWhileFlockIsStopped(t *testing.T) { + root := t.TempDir() + t.Setenv("FLOCK_HOME", root) + // As run by hand: nothing to tell the service manager. + t.Setenv("XPC_SERVICE_NAME", "") + t.Setenv("INVOCATION_ID", "") + if err := markStopped(root); err != nil { + t.Fatal(err) + } + + var out bytes.Buffer + cmd := NewRootCommand() + cmd.SetOut(&out) + cmd.SetErr(&out) + cmd.SetArgs([]string{"daemon"}) + if err := cmd.Execute(); err != nil { + t.Fatalf("daemon: %v", err) + } + + if !strings.Contains(out.String(), "Flock is stopped") { + t.Fatalf("want the reason printed, got %q", out.String()) + } + if _, err := os.Stat(paths.Socket(root)); err == nil { + t.Fatal("the daemon ran: its socket exists") + } +} diff --git a/internal/cli/uninstall.go b/internal/cli/uninstall.go index bac8b676..c77d6403 100644 --- a/internal/cli/uninstall.go +++ b/internal/cli/uninstall.go @@ -16,7 +16,7 @@ import ( var ( // rebuildable: programs, downloads, certificates, logs and runtime files. rebuildable = []string{"bin", "cache", "caddy", "certs", "log", "mail", "dumps", "tools", "php", "node", "node-global", "frankenphp", "cloudflared", "run", - "api.json", "flockd.sock", "hosts.txt", "hosts.txt.tmp", "hosts-helper-blocked", "config.json.tmp"} + "api.json", "flockd.sock", "hosts.txt", "hosts.txt.tmp", "hosts-helper-blocked", "config.json.tmp", "stopped"} // userData survives a plain uninstall: sites, parked folders and settings, and in services/ // each service's data/ (the PostgreSQL, Valkey, MySQL, Redis, ... databases; per version line). userData = []string{"config.json", "services"} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 022cd8f0..a5c42ce1 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -64,7 +64,9 @@ type daemon struct { root string version string startedAt time.Time - procs *supervisor.Supervisor + // stop ends Run, as a termination signal does (see Shutdown). + stop context.CancelFunc + procs *supervisor.Supervisor // reloadMu serialises reloads (API requests and the retry loop); mutateMu serialises config edits. reloadMu sync.Mutex @@ -287,7 +289,9 @@ func Run(ctx context.Context, cfg Config) error { return err } - d := &daemon{root: cfg.Root, version: cfg.Version, startedAt: time.Now(), procs: supervisor.New(), leaves: certs.NewLeaves(), restarts: map[string]int{}, + ctx, stop := context.WithCancel(ctx) + defer stop() + d := &daemon{root: cfg.Root, version: cfg.Version, startedAt: time.Now(), stop: stop, procs: supervisor.New(), leaves: certs.NewLeaves(), restarts: map[string]int{}, reverbRestarts: map[string]int{}} defer d.shutdown() @@ -350,7 +354,14 @@ func Run(ctx context.Context, cfg Config) error { } else { tcpServer := &http.Server{Handler: api.NewHandler(d, tcp.token), ReadHeaderTimeout: 5 * time.Second} go func() { _ = tcpServer.Serve(tcp.ln) }() - defer tcpServer.Close() + // Answers first: a shutdown asked for over this listener still gets its reply. + defer func() { + drain, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if tcpServer.Shutdown(drain) != nil { + _ = tcpServer.Close() + } + }() defer os.Remove(api.InfoFile(d.root)) } @@ -512,6 +523,9 @@ func (d *daemon) breakpointsChanged() bool { // Reload implements api.Backend. func (d *daemon) Reload() error { return d.reload() } +// Shutdown implements api.Backend: Run stops everything and returns, and the daemon exits cleanly. +func (d *daemon) Shutdown() { d.stop() } + // Root implements api.Backend. func (d *daemon) Root() string { return d.root } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 2a0a2a49..46ec076d 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -324,6 +324,46 @@ func TestRemovesStaleSocket(t *testing.T) { startDaemon(t, root) } +func TestShutdownRequestEndsTheDaemonCleanly(t *testing.T) { + root, _ := testRoot(t, nil) + ctx, cancel := context.WithCancel(context.Background()) + done, exited := make(chan error, 1), make(chan struct{}) + go func() { + done <- Run(ctx, Config{Root: root, Version: "dev"}) + close(exited) + }() + // Also when the test fails before the daemon has stopped. + t.Cleanup(func() { + cancel() + <-exited + }) + + client := api.NewClient(paths.Socket(root)) + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) { + if _, err := client.Status(context.Background()); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("daemon did not become ready") + } + } + + if err := client.Shutdown(context.Background()); err != nil { + t.Fatalf("shutdown: %v", err) + } + select { + case err := <-done: + if err != nil { + t.Fatalf("want a clean exit, got %v", err) + } + case <-time.After(15 * time.Second): + t.Fatal("daemon kept running after the shutdown request") + } + if _, err := client.Status(context.Background()); !errors.Is(err, api.ErrDaemonNotRunning) { + t.Fatalf("want ErrDaemonNotRunning after the shutdown, got %v", err) + } +} + func TestClientReportsDaemonNotRunning(t *testing.T) { client := api.NewClient(paths.Socket(shortTempDir(t))) diff --git a/internal/paths/paths.go b/internal/paths/paths.go index 52155336..85040b2b 100644 --- a/internal/paths/paths.go +++ b/internal/paths/paths.go @@ -46,6 +46,13 @@ func Socket(root string) string { return filepath.Join(root, "flockd.sock") } +// Stopped is the file that says the user turned Flock off (`flock stop`, the apps' switch and +// Quit). While it exists, a daemon the system starts (at login, with the computer) doesn't run; +// `flock start` and `flock restart` remove it. The apps read it to tell off from not responding. +func Stopped(root string) string { + return filepath.Join(root, "stopped") +} + // Run is the directory for the services' unix sockets (PHP-FPM, MySQL/MariaDB, Postgres). Kept // short: AF_UNIX paths are limited to ~104 bytes on macOS. func Run(root string) string { diff --git a/lang/cs/app.json b/lang/cs/app.json index 28ed4bd0..58f2f7a0 100644 --- a/lang/cs/app.json +++ b/lang/cs/app.json @@ -54,6 +54,7 @@ "app.conflict.quit": "Ukončete {app}", "app.conflict.uses": "používá {0}", "app.copy_database": "kopie", + "app.could_not_be_stopped": "Flock se nepodařilo zastavit", "app.could_not_open": "Tuto položku se nepodařilo otevřít.", "app.could_not_open_connection": "Toto databázové připojení se nepodařilo otevřít.", "app.could_not_open_link": "Tento odkaz se nepodařilo otevřít.", @@ -79,8 +80,11 @@ "app.not_running": "Flock neběží", "app.outcome_unknown": "Spojení selhalo. Změna se možná provedla; před dalším pokusem obnovte její stav.", "app.program_uses_ports": "{program} používá {ports}.", + "app.quit_anyway": "Přesto ukončit", + "app.quit_anyway_question": "{0}\n\nChcete aplikaci přesto ukončit? Flock poběží dál.", "app.running_version": "Běží · {version}", "app.shared_database": "sdílená", + "app.stopped": "Flock je zastavený", "app.timeout": "Flock na {0} {1} neodpověděl včas", "app.unexpected_answer": "Neočekávaná odpověď z {0}: {1}", "app.unexpected_answer_from_flock_error": "neočekávaná odpověď od Flocku: {error}", @@ -427,7 +431,6 @@ "menu.opens_settings_to_services": "Otevře Nastavení → Služby", "menu.own_db": "Vlastní DB", "menu.quit_flock": "Ukončit Flock", - "menu.quit_flock_bar": "Ukončit Flock Bar", "menu.restart": "Restartovat", "menu.restart_flock": "Restartovat Flock", "menu.restarted": "(restartováno {0}×)", @@ -443,6 +446,7 @@ "menu.status.not_running": "Neběží", "menu.status.not_set_up": "Nenastaveno", "menu.status.running": "Běží", + "menu.status.stopped": "Zastaveno", "menu.status.updating": "Aktualizuje se…", "menu.stop_flock": "Zastavit Flock", "menu.stopped": "zastaveno", @@ -752,7 +756,7 @@ "settings.pane.sites": "Weby", "settings.save_canceled": "Uložení předvoleb bylo zrušeno.", "settings.set_flock_up_to_run": "Nastavte Flock, abyste mohli provozovat své weby a měnit jeho nastavení.", - "settings.start_daemon_to_change": "Pro změnu nastavení spusťte démona.", + "settings.start_daemon_to_change": "Pro změnu nastavení spusťte Flock.", "settings.window_title": "Nastavení Flocku", "setup.admin_prompt": "Windows za chvíli požádá o oprávnění správce.", "setup.as_soon_as_flock_can": {"one": "Jakmile ho Flock bude moct stáhnout.", "few": "Jakmile je Flock bude moct stáhnout.", "other": "Jakmile je Flock bude moct stáhnout."}, diff --git a/lang/en/app.json b/lang/en/app.json index 8ffb03b5..8ddd573f 100644 --- a/lang/en/app.json +++ b/lang/en/app.json @@ -54,6 +54,7 @@ "app.conflict.quit": {"text": "Quit {app}", "note": "{app}: the program to quit"}, "app.conflict.uses": {"text": "uses {0}", "note": "{0}: the ports (\"port 80 (HTTP) and port 443 (HTTPS)\")"}, "app.copy_database": "copy", + "app.could_not_be_stopped": {"text": "Flock could not be stopped", "note": "Title of the question asked when quitting Flock couldn't stop it"}, "app.could_not_open": "Could not open this item.", "app.could_not_open_connection": "Could not open this database connection.", "app.could_not_open_link": "Could not open this link.", @@ -79,8 +80,11 @@ "app.not_running": "Flock is not running", "app.outcome_unknown": "The connection failed. The change may have completed; refresh its state before retrying.", "app.program_uses_ports": "{program} uses {ports}.", + "app.quit_anyway": {"text": "Quit Anyway", "note": "Button: quit the app although Flock keeps running"}, + "app.quit_anyway_question": {"text": "{0}\n\nQuit the app anyway? Flock keeps running.", "note": "{0}: why Flock could not be stopped"}, "app.running_version": "Running · {version}", "app.shared_database": "shared", + "app.stopped": {"text": "Flock is stopped", "note": "Title where a window can't show its content because the user turned Flock off"}, "app.timeout": {"text": "Flock did not answer {0} {1} in time", "note": "{0}: the HTTP method, {1}: the API path"}, "app.unexpected_answer": {"text": "Unexpected answer from {0}: {1}", "note": "{0}: the API path, {1}: the parser's error"}, "app.unexpected_answer_from_flock_error": "unexpected answer from Flock: {error}", @@ -450,7 +454,6 @@ "menu.opens_settings_to_services": "Opens Settings → Services", "menu.own_db": "Own DB", "menu.quit_flock": "Quit Flock", - "menu.quit_flock_bar": "Quit Flock Bar", "menu.restart": "Restart", "menu.restart_flock": {"text": "Restart Flock", "note": "Restarts the daemon and its services"}, "menu.restarted": {"text": "(restarted {0}×)", "note": "{0}: how often"}, @@ -466,6 +469,7 @@ "menu.status.not_running": "Not running", "menu.status.not_set_up": "Not set up", "menu.status.running": "Running", + "menu.status.stopped": {"text": "Stopped", "note": "Flock's state after the user turned it off (the switch, Quit or `flock stop`)"}, "menu.status.updating": "Updating…", "menu.stop_flock": {"text": "Stop Flock", "note": "Stops the daemon and its services until Flock is started again"}, "menu.stopped": "stopped", @@ -775,7 +779,7 @@ "settings.pane.sites": "Sites", "settings.save_canceled": "Preference save canceled.", "settings.set_flock_up_to_run": "Set Flock up to run your sites and change its settings.", - "settings.start_daemon_to_change": "Start the daemon to change its settings.", + "settings.start_daemon_to_change": "Start Flock to change its settings.", "settings.window_title": "Flock Settings", "setup.admin_prompt": "Windows asks for administrator permission in a moment.", "setup.as_soon_as_flock_can": {"one": "As soon as Flock can download it.", "other": "As soon as Flock can download them."}, diff --git a/lang/es/app.json b/lang/es/app.json index c25ce148..a72ef376 100644 --- a/lang/es/app.json +++ b/lang/es/app.json @@ -54,6 +54,7 @@ "app.conflict.quit": "Cierra {app}", "app.conflict.uses": "usa {0}", "app.copy_database": "copia", + "app.could_not_be_stopped": "No se pudo detener Flock", "app.could_not_open": "No se pudo abrir este elemento.", "app.could_not_open_connection": "No se pudo abrir esta conexión de base de datos.", "app.could_not_open_link": "No se pudo abrir este enlace.", @@ -79,8 +80,11 @@ "app.not_running": "Flock no está en ejecución", "app.outcome_unknown": "La conexión falló. Es posible que el cambio se haya completado; actualiza su estado antes de volver a intentarlo.", "app.program_uses_ports": "{program} usa {ports}.", + "app.quit_anyway": "Salir de todos modos", + "app.quit_anyway_question": "{0}\n\n¿Salir de la aplicación de todos modos? Flock seguirá en ejecución.", "app.running_version": "En ejecución · {version}", "app.shared_database": "compartida", + "app.stopped": "Flock está detenido", "app.timeout": "Flock no respondió a {0} {1} a tiempo", "app.unexpected_answer": "Respuesta inesperada de {0}: {1}", "app.unexpected_answer_from_flock_error": "respuesta inesperada de Flock: {error}", @@ -427,7 +431,6 @@ "menu.opens_settings_to_services": "Abre Ajustes → Servicios", "menu.own_db": "BD propia", "menu.quit_flock": "Salir de Flock", - "menu.quit_flock_bar": "Salir de Flock Bar", "menu.restart": "Reiniciar", "menu.restart_flock": "Reiniciar Flock", "menu.restarted": "(reiniciado {0}×)", @@ -443,6 +446,7 @@ "menu.status.not_running": "No está en ejecución", "menu.status.not_set_up": "Sin configurar", "menu.status.running": "En ejecución", + "menu.status.stopped": "Detenido", "menu.status.updating": "Actualizando…", "menu.stop_flock": "Detener Flock", "menu.stopped": "detenido", @@ -752,7 +756,7 @@ "settings.pane.sites": "Sitios", "settings.save_canceled": "Se canceló el guardado de las preferencias.", "settings.set_flock_up_to_run": "Configura Flock para ejecutar tus sitios y cambiar sus ajustes.", - "settings.start_daemon_to_change": {"default": "Inicia el demonio para cambiar su configuración.", "macos": "Inicia el demonio para cambiar sus ajustes."}, + "settings.start_daemon_to_change": {"default": "Inicia Flock para cambiar su configuración.", "macos": "Inicia Flock para cambiar sus ajustes."}, "settings.window_title": {"default": "Configuración de Flock", "macos": "Ajustes de Flock"}, "setup.admin_prompt": "Windows pedirá permiso de administrador en un momento.", "setup.as_soon_as_flock_can": {"one": "En cuanto Flock pueda descargarlo.", "other": "En cuanto Flock pueda descargarlos."}, diff --git a/linux/data/icons/README b/linux/data/icons/README index a5444665..1b9f001a 100644 --- a/linux/data/icons/README +++ b/linux/data/icons/README @@ -1,13 +1,15 @@ Flock's icons for Linux, installed into /usr/share/icons/hicolor by the packages: - scalable/apps/dev.flock.Flock.svg: the app icon (design/logo/flock-app-icon.svg). -- symbolic/apps/dev.flock.Flock{,-stopped,-warning}-symbolic.svg: the tray icon by state, the - logomark of design/logo/flock-logomark-black.svg; stopped is dimmed, a warning adds the ember - badge, as on Windows and macOS (design/icongen). GNOME recolors -symbolic icons for its top - bar, KDE through the ColorScheme-Text class. Each is one path with the logomark's cut-outs as - holes, traced from the logomark: a bar that recolors an icon through its alpha channel (the - Quickshell tray of Omarchy) draws an icon that uses an SVG mask as a solid square, and Qt - ignores clip paths, so neither can carry the cut-outs. +- symbolic/apps/dev.flock.Flock{,-warning,-stopped,-down}-symbolic.svg: the tray icon by state, the + logomark of design/logo/flock-logomark-black.svg, with a dot for what isn't as usual, as on + Windows and macOS (design/icongen): ember for a warning, grey while Flock is stopped, red when + it should run and doesn't. GNOME recolors -symbolic icons for its top bar (the dots by their + warning and error classes; the grey one is the text color at half strength), KDE through the + ColorScheme-Text class. Each is one path with the logomark's cut-outs as holes, traced + from the logomark: a bar that recolors an icon through its alpha channel (the Quickshell + tray of Omarchy) draws an icon that uses an SVG mask as a solid square, and Qt ignores clip + paths, so neither can carry the cut-outs. - symbolic/apps/dev.flock.Flock-sites-symbolic.svg: the globe for sites (Sites pane, Logs, setup). Themes draw web-browser-symbolic as different things or not at all (GTK then shows its red missing-image icon), so the app ships its own. diff --git a/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-down-symbolic.svg b/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-down-symbolic.svg new file mode 100644 index 00000000..f81dd686 --- /dev/null +++ b/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-down-symbolic.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-stopped-symbolic.svg b/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-stopped-symbolic.svg index f7641b9e..3ffdd408 100644 --- a/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-stopped-symbolic.svg +++ b/linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-stopped-symbolic.svg @@ -1,5 +1,6 @@ - + - + + diff --git a/linux/packaging/nfpm.yaml b/linux/packaging/nfpm.yaml index adb262bf..2bb5a400 100644 --- a/linux/packaging/nfpm.yaml +++ b/linux/packaging/nfpm.yaml @@ -47,6 +47,8 @@ contents: dst: /usr/share/icons/hicolor/symbolic/apps/dev.flock.Flock-stopped-symbolic.svg - src: linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-warning-symbolic.svg dst: /usr/share/icons/hicolor/symbolic/apps/dev.flock.Flock-warning-symbolic.svg + - src: linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-down-symbolic.svg + dst: /usr/share/icons/hicolor/symbolic/apps/dev.flock.Flock-down-symbolic.svg - src: linux/data/icons/hicolor/symbolic/apps/dev.flock.Flock-sites-symbolic.svg dst: /usr/share/icons/hicolor/symbolic/apps/dev.flock.Flock-sites-symbolic.svg # Each user's daemon is an instance of it, set up by `flk install` (per-user drop-in). diff --git a/linux/po/cs.po b/linux/po/cs.po index 79c8e4cf..12f66126 100644 --- a/linux/po/cs.po +++ b/linux/po/cs.po @@ -94,6 +94,9 @@ msgstr "Ukončete {app}" msgid "app.copy_database" msgstr "kopie" +msgid "app.could_not_be_stopped" +msgstr "Flock se nepodařilo zastavit" + msgid "app.could_not_relaunch" msgstr "Flock se nepodařilo znovu spustit: {error}" @@ -124,12 +127,18 @@ msgstr "Flock neběží" msgid "app.program_uses_ports" msgstr "{program} používá {ports}." +msgid "app.quit_anyway" +msgstr "Přesto ukončit" + msgid "app.running_version" msgstr "Běží · {version}" msgid "app.shared_database" msgstr "sdílená" +msgid "app.stopped" +msgstr "Flock je zastavený" + msgid "app.unexpected_answer_from_flock_error" msgstr "neočekávaná odpověď od Flocku: {error}" @@ -769,6 +778,9 @@ msgstr "Vyžaduje pozornost" msgid "menu.status.not_set_up" msgstr "Nenastaveno" +msgid "menu.status.stopped" +msgstr "Zastaveno" + msgid "menu.stop_flock" msgstr "Zastavit Flock" @@ -1151,7 +1163,7 @@ msgid "settings.pane.sites" msgstr "Weby" msgid "settings.start_daemon_to_change" -msgstr "Pro změnu nastavení spusťte démona." +msgstr "Pro změnu nastavení spusťte Flock." msgid "setup.as_soon_as_flock_can" msgid_plural "setup.as_soon_as_flock_can" diff --git a/linux/po/en.po b/linux/po/en.po index f7983b50..0082e41b 100644 --- a/linux/po/en.po +++ b/linux/po/en.po @@ -96,6 +96,10 @@ msgstr "Quit {app}" msgid "app.copy_database" msgstr "copy" +#. Title of the question asked when quitting Flock couldn't stop it +msgid "app.could_not_be_stopped" +msgstr "Flock could not be stopped" + #. {error}: why msgid "app.could_not_relaunch" msgstr "Could not relaunch Flock: {error}" @@ -127,12 +131,20 @@ msgstr "Flock is not running" msgid "app.program_uses_ports" msgstr "{program} uses {ports}." +#. Button: quit the app although Flock keeps running +msgid "app.quit_anyway" +msgstr "Quit Anyway" + msgid "app.running_version" msgstr "Running · {version}" msgid "app.shared_database" msgstr "shared" +#. Title where a window can't show its content because the user turned Flock off +msgid "app.stopped" +msgstr "Flock is stopped" + msgid "app.unexpected_answer_from_flock_error" msgstr "unexpected answer from Flock: {error}" @@ -795,6 +807,10 @@ msgstr "Needs attention" msgid "menu.status.not_set_up" msgstr "Not set up" +#. Flock's state after the user turned it off (the switch, Quit or `flock stop`) +msgid "menu.status.stopped" +msgstr "Stopped" + #. Stops the daemon and its services until Flock is started again msgid "menu.stop_flock" msgstr "Stop Flock" @@ -1198,7 +1214,7 @@ msgid "settings.pane.sites" msgstr "Sites" msgid "settings.start_daemon_to_change" -msgstr "Start the daemon to change its settings." +msgstr "Start Flock to change its settings." msgid "setup.as_soon_as_flock_can" msgid_plural "setup.as_soon_as_flock_can" diff --git a/linux/po/es.po b/linux/po/es.po index 5e28c329..5a5fbdbb 100644 --- a/linux/po/es.po +++ b/linux/po/es.po @@ -94,6 +94,9 @@ msgstr "Cierra {app}" msgid "app.copy_database" msgstr "copia" +msgid "app.could_not_be_stopped" +msgstr "No se pudo detener Flock" + msgid "app.could_not_relaunch" msgstr "No se pudo volver a abrir Flock: {error}" @@ -123,12 +126,18 @@ msgstr "Flock no está en ejecución" msgid "app.program_uses_ports" msgstr "{program} usa {ports}." +msgid "app.quit_anyway" +msgstr "Salir de todos modos" + msgid "app.running_version" msgstr "En ejecución · {version}" msgid "app.shared_database" msgstr "compartida" +msgid "app.stopped" +msgstr "Flock está detenido" + msgid "app.unexpected_answer_from_flock_error" msgstr "respuesta inesperada de Flock: {error}" @@ -762,6 +771,9 @@ msgstr "Requiere atención" msgid "menu.status.not_set_up" msgstr "Sin configurar" +msgid "menu.status.stopped" +msgstr "Detenido" + msgid "menu.stop_flock" msgstr "Detener Flock" @@ -1144,7 +1156,7 @@ msgid "settings.pane.sites" msgstr "Sitios" msgid "settings.start_daemon_to_change" -msgstr "Inicia el demonio para cambiar su configuración." +msgstr "Inicia Flock para cambiar su configuración." msgid "setup.as_soon_as_flock_can" msgid_plural "setup.as_soon_as_flock_can" diff --git a/linux/src/main.rs b/linux/src/main.rs index aa932918..fdeb33c3 100644 --- a/linux/src/main.rs +++ b/linux/src/main.rs @@ -186,6 +186,8 @@ fn main() -> glib::ExitCode { // --screenshot : renders that window (else the main one) once it shows the status, // saves it and quits (development and the docs' screenshots). let background = args.iter().any(|a| a == "--background"); + // A restart of the app only (app.relaunch): a stopped Flock stays stopped over it. + let relaunched = flag("--after").is_some(); let open = flag("--open"); let screenshot = flag("--screenshot").map(PathBuf::from); @@ -207,6 +209,9 @@ fn main() -> glib::ExitCode { } let main = window::MainWindow::new(app, m.clone()); m.start_polling(); + if screenshot.is_none() && !relaunched { + m.start_if_stopped(); + } w.main.replace(Some(main.clone())); // At login, the window only shows if there is no tray to stay in. let mut shown = (!background || screenshot.is_some()).then(|| w.main()).flatten(); @@ -240,7 +245,8 @@ fn main() -> glib::ExitCode { }); // app.settings opens General, app.open('settings/sites') a pane, app.open('mail') a window. - let quit = gio::ActionEntry::builder("quit").activate(|app: &adw::Application, _, _| app.quit()).build(); + let m = model.clone(); + let quit = gio::ActionEntry::builder("quit").activate(move |app: &adw::Application, _, _| quit_flock(app, &m)).build(); let (m, w) = (model.clone(), windows.clone()); let open_action = gio::ActionEntry::builder("open") .parameter_type(Some(glib::VariantTy::STRING)) @@ -313,11 +319,44 @@ fn start_tray(app: &adw::Application, model: &Rc, windows: &Rc< tray::Command::Restart => m.restart(), tray::Command::Start => m.start(), tray::Command::Stop => m.stop(), - tray::Command::Quit => app.quit(), + tray::Command::Quit => quit_flock(&app, &m), tray::Command::Available(_) => {} }); } +/// The user's Quit (the menus, Ctrl+Q): stops the daemon and everything it runs first, as quitting +/// other local environments does. Closing the window where there is no tray, logging out and +/// shutting down don't come here, so Flock is then still on. +fn quit_flock(app: &adw::Application, model: &Rc) { + if model.needs_setup() { + app.quit(); + return; + } + // The app stays until `flock stop` is done, also with every window closed. + let guard = app.hold(); + let app = app.clone(); + model.stop_then(move |error| { + let Some(error) = error else { + drop(guard); + app.quit(); + return; + }; + // Flock could not be stopped: ask before leaving it running. + let dialog = adw::AlertDialog::new(Some(tr!("app.could_not_be_stopped")), Some(&error)); + dialog.add_response("cancel", tr!("common.cancel")); + dialog.add_response("quit", tr!("app.quit_anyway")); + dialog.set_response_appearance("quit", adw::ResponseAppearance::Destructive); + let (quitting, guard) = (app.clone(), RefCell::new(Some(guard))); + dialog.connect_response(None, move |_, response| { + guard.take(); + if response == "quit" { + quitting.quit(); + } + }); + dialog.present(app.active_window().as_ref()); + }); +} + /// Starts this app again once this process has exited, at General, where the Language is. /// Through the display's launch context: the new window gets the activation token (Wayland /// focuses it), and the app the system's language back. diff --git a/linux/src/model.rs b/linux/src/model.rs index dd02a01a..47b0c492 100644 --- a/linux/src/model.rs +++ b/linux/src/model.rs @@ -4,7 +4,7 @@ use std::cell::{Cell, RefCell}; use std::collections::HashSet; use std::rc::Rc; -use std::time::Duration; +use std::time::{Duration, Instant}; use gtk::{gio, glib}; @@ -12,9 +12,12 @@ use crate::api::{Client, Error, SettingsChange, Status}; use crate::i18n::tr; use crate::installation; use crate::links::Link; +use crate::paths; /// How often the daemon is asked for its status. const POLL_INTERVAL: Duration = Duration::from_secs(2); +/// How long a daemon that should run may not answer before the app says so (is_down). +const DOWN_AFTER: Duration = Duration::from_secs(10); #[derive(Default)] pub struct AppModel { @@ -26,6 +29,12 @@ pub struct AppModel { action_error: RefCell>, needs_setup: Cell, restarting: Cell, + /// Since when a daemon that should run hasn't answered (see is_down). + unanswered_since: Cell>, + /// The user is quitting: nothing starts Flock any more. + quitting: Cell, + /// What to do once the command that runs is done: the user's Quit, which must stop Flock. + after_command: RefCell>>, polling: Cell, /// A flock:// link the pane it opened asks about once its data is loaded. link: RefCell>, @@ -67,6 +76,27 @@ impl AppModel { self.restarting.get() } + /// The daemon doesn't answer because the user stopped Flock, not because something is wrong. + pub fn is_off(&self) -> bool { + self.status.borrow().is_none() && paths::stopped().exists() + } + + /// Flock should run and doesn't: no answer for a while, though the user didn't stop it. Not at + /// once: a daemon that starts (with the computer, beside the app) answers only after its first reload. + pub fn is_down(&self) -> bool { + self.unanswered_since.get().is_some_and(|since| since.elapsed() >= DOWN_AFTER) + } + + /// Called with every poll that got no answer. + fn unanswered(&self) { + if self.needs_setup() || self.is_restarting() || paths::stopped().exists() { + // Nothing is expected to answer; the wait starts when one is. + self.unanswered_since.set(None); + } else if self.unanswered_since.get().is_none() { + self.unanswered_since.set(Some(Instant::now())); + } + } + pub fn link(&self) -> Option { self.link.borrow().clone() } @@ -123,6 +153,7 @@ impl AppModel { Err(e) => { this.status.replace(None); this.error.replace(Some(e.to_string())); + this.unanswered(); } } // `flock install` or `flock uninstall` in a terminal changes it while the app runs. @@ -134,6 +165,7 @@ impl AppModel { fn apply(&self, status: Status) { self.status.replace(Some(status)); self.error.replace(None); + self.unanswered_since.set(None); } /// Changes settings; on failure, report gets the error (the banner of the window that asked). @@ -162,22 +194,54 @@ impl AppModel { /// Runs `flock restart`, which also starts a stopped daemon. pub fn restart(self: &Rc) { - self.lifecycle("restart"); + self.lifecycle("restart", |_| {}); } /// Runs `flock start` after `stop`. pub fn start(self: &Rc) { - self.lifecycle("start"); + self.lifecycle("start", |_| {}); } - /// Runs `flock stop`: the daemon and everything it runs stop until `start` or the next login. + /// Runs `flock stop`: the daemon and everything it runs stop until `start` or until the app is + /// opened again (also at login, when it opens then). pub fn stop(self: &Rc) { - self.lifecycle("stop"); + self.lifecycle("stop", |_| {}); } - /// Runs one command at a time, like the Windows tray: one that comes while another runs is ignored. - fn lifecycle(self: &Rc, command: &'static str) { + /// Stops Flock for the user's Quit, then calls done with why it could not be stopped (None when + /// it was). A start or restart that runs finishes first: Quit must not leave Flock running. + pub fn stop_then(self: &Rc, done: impl FnOnce(Option) + 'static) { + if self.restarting.get() { + let this = self.clone(); + self.after_command.replace(Some(Box::new(move || this.stop_then(done)))); + return; + } + self.quitting.set(true); + let this = self.clone(); + self.lifecycle("stop", move |error| { + // The quit may be cancelled when Flock could not be stopped: it is used on. + this.quitting.set(error.is_none()); + done(error); + }); + } + + /// Starting the app starts Flock: quitting it stopped the daemon, and so did the switch. + pub fn start_if_stopped(self: &Rc) { + if !self.needs_setup() && paths::stopped().exists() { + self.start(); + } + } + + /// Runs one command at a time, like the Windows tray: one that comes while another runs is + /// ignored. done gets the command's error, None when it succeeded or was ignored. + fn lifecycle(self: &Rc, command: &'static str, done: impl FnOnce(Option) + 'static) { + // Once the user quits, only the stop runs: a start beside it would leave Flock running. + if self.quitting.get() && command != "stop" { + done(None); + return; + } if self.restarting.replace(true) { + done(None); return; } self.changed(); @@ -185,9 +249,14 @@ impl AppModel { glib::spawn_future_local(async move { let out = gio::spawn_blocking(move || installation::run(&[command])).await.expect("flock command"); this.restarting.set(false); - this.action_error.replace(if out.ok { None } else { Some(out.text) }); + let error = if out.ok { None } else { Some(out.text) }; + this.action_error.replace(error.clone()); this.changed(); this.refresh(); + done(error); + if let Some(next) = this.after_command.take() { + next(); + } }); } @@ -203,6 +272,7 @@ impl AppModel { (_, true) => tr!("menu.status.not_set_up").to_owned(), (Some(s), _) if s.is_degraded() => tr!("app.needs_attention_version", version = display_version(&s.version)), (Some(s), _) => tr!("app.running_version", version = display_version(&s.version)), + (None, _) if paths::stopped().exists() => tr!("menu.status.stopped").to_owned(), (None, _) => tr!("sites.proxy.not_running").to_owned(), } } diff --git a/linux/src/paths.rs b/linux/src/paths.rs index a43b2038..5176cc1b 100644 --- a/linux/src/paths.rs +++ b/linux/src/paths.rs @@ -23,6 +23,12 @@ pub fn api_json() -> PathBuf { root().join("api.json") } +/// Exists while the user has Flock stopped (`flock stop`, the switch, Quit): a daemon that +/// doesn't answer is then off, not broken. +pub fn stopped() -> PathBuf { + root().join("stopped") +} + /// The app's own binary. A package update that replaced it while it ran leaves /proc/self/exe /// naming it " (deleted)"; the new binary is at the path. pub fn app_exe() -> std::io::Result { diff --git a/linux/src/tray.rs b/linux/src/tray.rs index 27f5c622..1e57b43a 100644 --- a/linux/src/tray.rs +++ b/linux/src/tray.rs @@ -61,9 +61,12 @@ impl State { fn of(model: &AppModel) -> Self { let status = model.status(); let needs_setup = model.needs_setup(); + // A dot says what isn't as usual: ember for what needs attention, grey while Flock is stopped + // (or starting, or not set up), red when it should run and doesn't. let icon = match &status { Some(s) if !needs_setup && s.is_degraded() => "warning", Some(_) if !needs_setup => "", + None if model.is_down() => "down", _ => "stopped", }; let status = status.filter(|_| !needs_setup); diff --git a/linux/src/window.rs b/linux/src/window.rs index 4de89c4d..42d20ec0 100644 --- a/linux/src/window.rs +++ b/linux/src/window.rs @@ -43,6 +43,8 @@ pub struct MainWindow { split: adw::NavigationSplitView, sidebar: gtk::ListBox, banner: adw::Banner, + /// On About, which shows without the daemon: that Flock doesn't run, with the button that starts it. + start_banner: adw::Banner, unavailable: adw::StatusPage, unavailable_button: gtk::Button, /// The Language setting under it, which doesn't need the daemon. @@ -112,7 +114,9 @@ impl MainWindow { let unavailable = adw::StatusPage::builder().icon_name("network-server-symbolic").child(&unavailable_body).build(); stack.add_named(&unavailable, Some("unavailable")); + let start_banner = adw::Banner::builder().button_label(tr!("menu.start_flock")).use_markup(false).build(); let body = gtk::Box::new(gtk::Orientation::Vertical, 0); + body.append(&start_banner); body.append(&banner); body.append(&stack); let content_view = adw::ToolbarView::new(); @@ -153,6 +157,7 @@ impl MainWindow { split, sidebar, banner, + start_banner, unavailable, unavailable_button, unavailable_language, @@ -190,7 +195,9 @@ impl MainWindow { }); let model = self.model.clone(); - self.unavailable_button.connect_clicked(move |_| model.restart()); + self.unavailable_button.connect_clicked(move |_| if model.is_off() { model.start() } else { model.restart() }); + let model = self.model.clone(); + self.start_banner.connect_button_clicked(move |_| if model.is_off() { model.start() } else { model.restart() }); // Set from the status too (sync_power), which already matches it then. let model = self.model.clone(); @@ -315,10 +322,22 @@ impl MainWindow { self.top.set_visible_child_name("panes"); let status = self.model.status(); let id = self.selected(); + // What needs the daemon can't be opened while it doesn't run. + for (index, pane) in PANES.iter().enumerate() { + if let Some(row) = self.sidebar.row_at_index(index as i32) { + row.set_sensitive(status.is_some() || pane.0 == "about"); + } + } + self.start_banner.set_title(if self.model.is_off() { tr!("app.stopped") } else { tr!("settings.flock_is_not_running") }); + self.start_banner.set_revealed(status.is_none() && id == "about"); if status.is_none() && id != "about" { - self.unavailable.set_title(tr!("settings.flock_is_not_running")); - self.unavailable - .set_description(Some(&self.model.error().unwrap_or_else(|| tr!("settings.start_daemon_to_change").to_owned()))); + // Stopped by the user, nothing is wrong; else say why it doesn't answer. + let off = self.model.is_off(); + self.unavailable.set_title(if off { tr!("app.stopped") } else { tr!("settings.flock_is_not_running") }); + // Flock's logomark with the state's dot, as in the top bar. + self.unavailable.set_icon_name(Some(if off { "dev.flock.Flock-stopped-symbolic" } else { "dev.flock.Flock-down-symbolic" })); + let reason = self.model.error().filter(|_| !off); + self.unavailable.set_description(Some(&reason.unwrap_or_else(|| tr!("settings.start_daemon_to_change").to_owned()))); self.unavailable_button.set_label(tr!("menu.start_flock")); self.unavailable_button.set_sensitive(!self.model.is_restarting()); // Built again when the page shows, with the setting as it is now. diff --git a/macos/Resources/Localizable.xcstrings b/macos/Resources/Localizable.xcstrings index e55467a8..d67e3b67 100644 --- a/macos/Resources/Localizable.xcstrings +++ b/macos/Resources/Localizable.xcstrings @@ -730,6 +730,29 @@ } } }, + "app.could_not_be_stopped" : { + "comment" : "Title of the question asked when quitting Flock couldn't stop it", + "localizations" : { + "cs" : { + "stringUnit" : { + "state" : "translated", + "value" : "Flock se nepodařilo zastavit" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Flock could not be stopped" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "No se pudo detener Flock" + } + } + } + }, "app.could_not_run %@ %@" : { "comment" : "{0}: the program, {1}: the error", "localizations" : { @@ -956,6 +979,52 @@ } } }, + "app.quit_anyway" : { + "comment" : "Button: quit the app although Flock keeps running", + "localizations" : { + "cs" : { + "stringUnit" : { + "state" : "translated", + "value" : "Přesto ukončit" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Quit Anyway" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Salir de todos modos" + } + } + } + }, + "app.stopped" : { + "comment" : "Title where a window can't show its content because the user turned Flock off", + "localizations" : { + "cs" : { + "stringUnit" : { + "state" : "translated", + "value" : "Flock je zastavený" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Flock is stopped" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Flock está detenido" + } + } + } + }, "app.uses_and_answers_for %@ %@ %@" : { "localizations" : { "cs" : { @@ -6220,28 +6289,6 @@ } } }, - "menu.quit_flock_bar" : { - "localizations" : { - "cs" : { - "stringUnit" : { - "state" : "translated", - "value" : "Ukončit Flock Bar" - } - }, - "en" : { - "stringUnit" : { - "state" : "translated", - "value" : "Quit Flock Bar" - } - }, - "es" : { - "stringUnit" : { - "state" : "translated", - "value" : "Salir de Flock Bar" - } - } - } - }, "menu.restart" : { "localizations" : { "cs" : { @@ -6489,6 +6536,29 @@ } } }, + "menu.status.stopped" : { + "comment" : "Flock's state after the user turned it off (the switch, Quit or `flock stop`)", + "localizations" : { + "cs" : { + "stringUnit" : { + "state" : "translated", + "value" : "Zastaveno" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Stopped" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Detenido" + } + } + } + }, "menu.stopped" : { "localizations" : { "cs" : { @@ -10814,19 +10884,19 @@ "cs" : { "stringUnit" : { "state" : "translated", - "value" : "Pro změnu nastavení spusťte démona." + "value" : "Pro změnu nastavení spusťte Flock." } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "Start the daemon to change its settings." + "value" : "Start Flock to change its settings." } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "Inicia el demonio para cambiar sus ajustes." + "value" : "Inicia Flock para cambiar sus ajustes." } } } diff --git a/macos/Resources/LogoMarkStopped.png b/macos/Resources/LogoMarkStopped.png deleted file mode 100644 index a9612490..00000000 Binary files a/macos/Resources/LogoMarkStopped.png and /dev/null differ diff --git a/macos/Resources/LogoMarkWarning.png b/macos/Resources/LogoMarkWarning.png deleted file mode 100644 index c00bb618..00000000 Binary files a/macos/Resources/LogoMarkWarning.png and /dev/null differ diff --git a/macos/Resources/MenuBarStopped.png b/macos/Resources/MenuBarStopped.png deleted file mode 100644 index 9266c70e..00000000 Binary files a/macos/Resources/MenuBarStopped.png and /dev/null differ diff --git a/macos/Resources/MenuBarStopped@2x.png b/macos/Resources/MenuBarStopped@2x.png deleted file mode 100644 index ce876841..00000000 Binary files a/macos/Resources/MenuBarStopped@2x.png and /dev/null differ diff --git a/macos/Resources/MenuBarWarning.png b/macos/Resources/MenuBarWarning.png deleted file mode 100644 index e575b6cb..00000000 Binary files a/macos/Resources/MenuBarWarning.png and /dev/null differ diff --git a/macos/Resources/MenuBarWarning@2x.png b/macos/Resources/MenuBarWarning@2x.png deleted file mode 100644 index af8a26b8..00000000 Binary files a/macos/Resources/MenuBarWarning@2x.png and /dev/null differ diff --git a/macos/Sources/FlockKit/Client.swift b/macos/Sources/FlockKit/Client.swift index 666e7361..6c1c39c9 100644 --- a/macos/Sources/FlockKit/Client.swift +++ b/macos/Sources/FlockKit/Client.swift @@ -12,6 +12,9 @@ public enum FlockPaths { public static var apiJSON: URL { root.appendingPathComponent("api.json") } public static var flockBinary: URL { root.appendingPathComponent("bin/flock") } + /// Exists while the user has Flock stopped (`flock stop`, the panel's switch, Quit): a daemon + /// that doesn't answer is then off, not broken. + public static var stopped: URL { root.appendingPathComponent("stopped") } } /// Contents of api.json, written by the daemon. diff --git a/macos/Sources/FlockUI/AppLanguage.swift b/macos/Sources/FlockUI/AppLanguage.swift index b394a670..e85ccbc0 100644 --- a/macos/Sources/FlockUI/AppLanguage.swift +++ b/macos/Sources/FlockUI/AppLanguage.swift @@ -83,7 +83,7 @@ struct AppLanguage: Hashable, Identifiable { }() /// Starts Flock again once this process has quit, then quits; Flock keeps running when the - /// relaunch can't be started. The daemon keeps running either way. + /// relaunch can't be started. The daemon keeps running either way (keepsFlockRunning). @MainActor static func relaunch() throws { let bundle = Bundle.main.bundleURL @@ -94,6 +94,7 @@ struct AppLanguage: Hashable, Identifiable { process.arguments = ["-c", "while kill -0 \"$1\" 2>/dev/null; do sleep 0.2; done; if [ -d \"$2\" ]; then open \"$2\"; else \"$2\" & fi", "relaunch", String(ProcessInfo.processInfo.processIdentifier), target] try process.run() + AppDelegate.keepsFlockRunning = true NSApp.terminate(nil) } } diff --git a/macos/Sources/FlockUI/AppModel.swift b/macos/Sources/FlockUI/AppModel.swift index 36be84eb..0c9cb7eb 100644 --- a/macos/Sources/FlockUI/AppModel.swift +++ b/macos/Sources/FlockUI/AppModel.swift @@ -90,18 +90,45 @@ final class AppModel { startPolling() settings.onChange = { [weak self] in await self?.refresh() } - if !needsSetup, installation.needsUpdate(recorded: UserDefaults.standard.string(forKey: Self.installedFlockKey)) { - Task { await updateInstallation() } + isOff = Self.flockIsStopped + // A restart of the app only (another language, an update): a stopped Flock stays stopped over it. + let relaunched = AppDelegate.takeRelaunch() + let update = !needsSetup && installation.needsUpdate(recorded: UserDefaults.standard.string(forKey: Self.installedFlockKey)) + Task { + if update { + await updateInstallation() + } + // Starting the app starts Flock: quitting it stopped the daemon, and so did the switch. + // Not once the user quits (during the update): the stop that wrote the file is this run's. + if !needsSetup, !isQuitting, !relaunched, Self.flockIsStopped { + await start() + } } updater.start() + AppDelegate.stopFlock = { [weak self] in await self?.stopForQuit() ?? nil } } var isRunning: Bool { status != nil } var isDegraded: Bool { status?.isDegraded ?? false } - /// The logomark for the daemon's state: stopped is dimmed, a warning adds a badge. + /// The daemon doesn't answer because the user stopped Flock, not because something is wrong. + private(set) var isOff = false + + /// Flock should run and doesn't: no answer for a while, though the user didn't stop it. Not at + /// once: a daemon that starts (at login, beside the app) answers only after its first reload. + private(set) var isDown = false + + @ObservationIgnored private var unansweredSince: Date? + private static let downAfter: TimeInterval = 10 + + private static var flockIsStopped: Bool { FileManager.default.fileExists(atPath: FlockPaths.stopped.path) } + + /// The logomark for the daemon's state: a dot says what isn't as usual (see LogoMark.Mode). var logoMark: LogoMark.Mode { - guard isRunning, !needsSetup else { return .stopped } + if needsSetup || isRestarting || isUpdating { + return isRunning ? .running : .off + } + guard isRunning else { return isDown ? .down : .off } return isDegraded ? .warning : .running } @@ -117,7 +144,7 @@ final class AppModel { if let status { return "\(status.isDegraded ? String(localized: "menu.status.needs_attention") : String(localized: "sites.proxy.running")) · v\(status.version)" } - return String(localized: "sites.proxy.not_running") + return isOff ? String(localized: "menu.status.stopped") : String(localized: "sites.proxy.not_running") } private func startPolling() { @@ -135,6 +162,14 @@ final class AppModel { } catch { status = nil self.error = error.localizedDescription + isOff = Self.flockIsStopped + if isOff || needsSetup || isRestarting || isUpdating { + // Nothing is expected to answer; the wait starts when one is. + unansweredSince = nil + } else if unansweredSince == nil { + unansweredSince = Date() + } + isDown = unansweredSince.map { Date().timeIntervalSince($0) >= Self.downAfter } ?? false } } @@ -142,6 +177,9 @@ final class AppModel { let previous = status status = new error = nil + isOff = false + isDown = false + unansweredSince = nil worktreeNotifier.check(previous: previous, new: new) updater.channel = new.channel Task { await settings.refreshIfVisible() } @@ -209,22 +247,50 @@ final class AppModel { } } - /// Runs `flock restart` (which also starts a stopped daemon via launchd). + /// Runs `flock restart` (which also starts a stopped daemon via launchd). Not once the user + /// quits: a start beside the quit's stop would leave Flock running. func restart() async { + guard !isQuitting else { return } await run("restart") } /// Runs `flock start` after `stop`. func start() async { + guard !isQuitting else { return } await run("start") } - /// Runs `flock stop`: the daemon and everything it runs stop until `start`. + /// Runs `flock stop`: the daemon and everything it runs stop until `start` or until the app is + /// opened again (also at login, when it opens then). func stop() async { await run("stop") } - private func run(_ command: String) async { + /// The user is quitting: nothing starts Flock any more. + private var isQuitting = false + + /// Quitting Flock stops the daemon and everything it runs, as the switch does; the answer is why + /// it could not be stopped, nil when it was. Not before the setup, when there is nothing to stop, + /// but during it: `flock install` starts the daemon before its last steps. + func stopForQuit() async -> String? { + guard !needsSetup || isSettingUp, FileManager.default.fileExists(atPath: FlockPaths.flockBinary.path) else { return nil } + isQuitting = true + // A start or restart that runs finishes first, and the `flock install` of an update or the + // setup: stopping beside them could leave Flock running. + while isRestarting || isUpdating || isSettingUp { + try? await Task.sleep(for: .milliseconds(100)) + } + if await run("stop") { + return nil + } + // The quit may be cancelled: Flock is used on. + isQuitting = false + return actionError ?? String(localized: "app.not_running") + } + + /// Whether the command succeeded; actionError says why not. + @discardableResult + private func run(_ command: String) async -> Bool { isRestarting = true defer { isRestarting = false } @@ -233,11 +299,12 @@ final class AppModel { actionError = needsSetup ? String(localized: "app.flock_is_not_set_up") : String(localized: "app.flock_is_not_installed_for \(binary.path)") - return + return false } let result = await Installation.run(binary, [command]) actionError = result.ok ? nil : result.output await refresh() + return result.ok } /// Runs the bundled `flock install` after the app was updated. It restarts the daemon; macOS diff --git a/macos/Sources/FlockUI/FlockBarApp.swift b/macos/Sources/FlockUI/FlockBarApp.swift index d16c102c..cab6b8c8 100644 --- a/macos/Sources/FlockUI/FlockBarApp.swift +++ b/macos/Sources/FlockUI/FlockBarApp.swift @@ -78,6 +78,55 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// and kept, because the label can appear before or after the launch's Apple event arrives. private(set) static var pendingMain = false + /// Stops the daemon and everything it runs, and says why if it couldn't (AppModel.stopForQuit). + static var stopFlock: (@MainActor () async -> String?)? + + /// Set before the app quits only to start again (an update, another language): Flock keeps + /// running, and one that is stopped stays stopped when the app is back (takeRelaunch). + static var keepsFlockRunning = false { + didSet { + if keepsFlockRunning { + UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: relaunchKey) + } + } + } + + private static let relaunchKey = "relaunchingSince" + + /// Whether this start is the second half of such a restart: asked for in the last minutes, and + /// only once (a restart that never came must not keep a later start from starting Flock). + static func takeRelaunch() -> Bool { + let since = UserDefaults.standard.double(forKey: relaunchKey) + UserDefaults.standard.removeObject(forKey: relaunchKey) + return since > 0 && Date().timeIntervalSince1970 - since < 300 + } + + /// Quitting Flock stops it, as quitting other local environments does: the daemon, the sites + /// and the databases. Not when macOS ends the session (log out, restart, shut down): Flock is + /// then still on at the next login. The quit waits for the daemon to stop its services, and + /// asks before it leaves a Flock running that could not be stopped. + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + let sessionEnds = NSAppleEventManager.shared().currentAppleEvent?.attributeDescriptor(forKeyword: kAEQuitReason) != nil + guard !Self.keepsFlockRunning, !sessionEnds, let stop = Self.stopFlock else { + return .terminateNow + } + Task { + guard let problem = await stop() else { + sender.reply(toApplicationShouldTerminate: true) + return + } + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = String(localized: "app.could_not_be_stopped") + alert.informativeText = problem + alert.addButton(withTitle: String(localized: "app.quit_anyway")) + alert.addButton(withTitle: String(localized: "common.cancel")) + NSApp.activate() + sender.reply(toApplicationShouldTerminate: alert.runModal() == .alertFirstButtonReturn) + } + return .terminateLater + } + static func takePendingMain() -> Bool { defer { pendingMain = false } return pendingMain diff --git a/macos/Sources/FlockUI/LogoMark.swift b/macos/Sources/FlockUI/LogoMark.swift index bb0324c3..d6083151 100644 --- a/macos/Sources/FlockUI/LogoMark.swift +++ b/macos/Sources/FlockUI/LogoMark.swift @@ -2,39 +2,51 @@ import AppKit import SwiftUI /// Flock's logomark, from the template images that build-app.sh puts in the app bundle -/// (rendered by design/icongen). Template images take the foreground style, and in the menu bar -/// macOS colors them for its appearance. Without the bundle (`swift run`), an SF Symbol bird. +/// (rendered by design/icongen), always the whole mark. A dot at its lower right says what isn't +/// as usual: ember for what needs attention, grey while Flock is stopped, red when it should run +/// and doesn't. Without the bundle (`swift run`), an SF Symbol bird. struct LogoMark: View { enum Mode { - case running, stopped, warning + /// Running; needs attention; stopped by the user; not answering. + case running, warning, off, down - /// The menu bar's 18-point image, or a 128-pixel one to scale down inside windows. - func resource(large: Bool) -> String { - let suffix = switch self { - case .running: "" - case .stopped: "Stopped" - case .warning: "Warning" + var dot: Color? { + switch self { + case .running: nil + case .warning: .flockEmber + case .off: Color(nsColor: .systemGray) + case .down: Color(nsColor: .systemRed) } - return (large ? "LogoMark" : "MenuBar") + suffix } var fallback: String { switch self { - case .running: "bird.fill" - case .stopped: "bird" - case .warning: "exclamationmark.triangle.fill" + case .running, .warning: "bird.fill" + case .off, .down: "bird" } } } + /// Where the dot is in the mark's square, as fractions of its side (from the top left): its + /// center, its radius, and the radius of the gap that keeps it apart from the mark. + private static let dotCenter = 0.76, dotRadius = 0.2, gapRadius = 0.27 + var mode: Mode = .running - /// Points; nil keeps the image's own 18-point size (the menu bar's). + /// Points; nil is the menu bar's 18-point image. var size: CGFloat? = nil var body: some View { - if let size, let image = Self.image(mode.resource(large: true)) { + if let size, let image = Self.image("LogoMark") { Image(nsImage: image).resizable().frame(width: size, height: size) - } else if size == nil, let image = Self.image(mode.resource(large: false)) { + .mask { Self.gap(size, cut: mode.dot != nil) } + .overlay { + if let dot = mode.dot { + Circle().fill(dot) + .frame(width: size * Self.dotRadius * 2, height: size * Self.dotRadius * 2) + .position(x: size * Self.dotCenter, y: size * Self.dotCenter) + } + } + } else if size == nil, let image = Self.menuBarImage(mode) { Image(nsImage: image) } else { Image(systemName: mode.fallback) @@ -42,6 +54,18 @@ struct LogoMark: View { } } + /// Everything but a circle around the dot. + private static func gap(_ size: CGFloat, cut: Bool) -> some View { + Canvas { context, canvas in + context.fill(Path(CGRect(origin: .zero, size: canvas)), with: .color(.black)) + if cut { + context.blendMode = .destinationOut + let r = size * gapRadius + context.fill(Path(ellipseIn: CGRect(x: size * dotCenter - r, y: size * dotCenter - r, width: r * 2, height: r * 2)), with: .color(.black)) + } + } + } + @MainActor private static var cache: [String: NSImage] = [:] @MainActor private static func image(_ resource: String) -> NSImage? { @@ -55,6 +79,44 @@ struct LogoMark: View { cache[resource] = image return image } + + /// The menu bar's image. macOS colors a template image for the menu bar, all of it in one color, + /// so a mark with a dot draws itself: the mark in the menu bar's color (decided each time it is + /// drawn, from the appearance it is drawn for) and the dot in its own. + @MainActor private static func menuBarImage(_ mode: Mode) -> NSImage? { + guard let mark = image("MenuBar") else { + return nil + } + guard let dot = mode.dot else { + return mark + } + let key = "MenuBar.\(mode)" + if let image = cache[key] { + return image + } + let color = NSColor(dot) + let image = NSImage(size: mark.size, flipped: false) { rect in + let dark = NSAppearance.currentDrawing().bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + (dark ? NSColor.white : NSColor.black).setFill() + rect.fill() + mark.draw(in: rect, from: .zero, operation: .destinationIn, fraction: 1) + + // The image's origin is at the bottom left. + let side = rect.width + let center = CGPoint(x: side * dotCenter, y: side * (1 - dotCenter)) + func circle(_ radius: CGFloat) -> NSBezierPath { + NSBezierPath(ovalIn: NSRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2)) + } + NSGraphicsContext.current?.compositingOperation = .clear + circle(side * gapRadius).fill() + NSGraphicsContext.current?.compositingOperation = .sourceOver + color.setFill() + circle(side * dotRadius).fill() + return true + } + cache[key] = image + return image + } } extension Color { diff --git a/macos/Sources/FlockUI/PanelView.swift b/macos/Sources/FlockUI/PanelView.swift index 37ed0f5a..c9031597 100644 --- a/macos/Sources/FlockUI/PanelView.swift +++ b/macos/Sources/FlockUI/PanelView.swift @@ -41,6 +41,7 @@ struct PanelView: View { } .padding(14) .frame(width: 340) + .background(PanelShrinker()) .onAppear { model.refreshSetup() } } @@ -62,8 +63,7 @@ struct PanelView: View { private var header: some View { HStack(spacing: 8) { LogoMark(mode: model.logoMark, size: 24) - // The stopped image is already dimmed. - .foregroundStyle(model.isRunning && model.isDegraded ? Color.flockEmber : Color.flockMark) + .foregroundStyle(Color.flockMark) VStack(alignment: .leading, spacing: 1) { Text("common.flock").font(.headline) Text(model.headline).font(.caption).foregroundStyle(.secondary) @@ -244,6 +244,12 @@ struct PanelView: View { } .buttonStyle(.borderedProminent) } + } else if model.isDown { + // Not stopped by the user, and still no answer: say why. + Text(model.error ?? String(localized: "app.not_running")) + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } } @@ -261,15 +267,44 @@ struct PanelView: View { .keyboardShortcut(",") } Spacer() - Button("menu.quit_flock_bar") { + // Stops the daemon and everything it runs first (AppDelegate.applicationShouldTerminate). + Button("menu.quit_flock") { NSApp.terminate(nil) } + .disabled(model.isRestarting) } .buttonStyle(.borderless) .font(.callout) } } +/// Shrinks the panel's window to its content. MenuBarExtra grows an open window with its content +/// but doesn't shrink it: stopping Flock while the panel is open would leave the short panel in the +/// middle of the tall window. The window keeps its top edge, under the menu bar. +private struct PanelShrinker: NSViewRepresentable { + func makeNSView(context: Context) -> NSView { Sizer() } + func updateNSView(_ view: NSView, context: Context) {} + + /// As large as the panel's content, which it is the background of. + private final class Sizer: NSView { + override func setFrameSize(_ size: NSSize) { + super.setFrameSize(size) + // Not while the window lays its views out. + DispatchQueue.main.async { [weak self] in self?.shrink() } + } + + private func shrink() { + guard let window, frame.height > 0 else { return } + let height = window.frameRect(forContentRect: NSRect(origin: .zero, size: frame.size)).height + var target = window.frame + guard height < target.height - 0.5 else { return } + target.origin.y = target.maxY - height + target.size.height = height + window.setFrame(target, display: true) + } + } +} + private struct SectionTitle: View { let title: LocalizedStringKey diff --git a/macos/Sources/FlockUI/Settings/SettingsWindow.swift b/macos/Sources/FlockUI/Settings/SettingsWindow.swift index c772cf6e..72f912ad 100644 --- a/macos/Sources/FlockUI/Settings/SettingsWindow.swift +++ b/macos/Sources/FlockUI/Settings/SettingsWindow.swift @@ -77,6 +77,9 @@ struct SettingsWindow: View { } .tag(item) .padding(.vertical, 2) + // What needs the daemon can't be opened while it doesn't run. + .opacity(isAvailable(item) ? 1 : 0.4) + .selectionDisabled(!isAvailable(item)) } } .listStyle(.sidebar) @@ -86,6 +89,10 @@ struct SettingsWindow: View { Divider() VStack(spacing: 0) { + // General and About show without the daemon: the way to start it is here then. + if model.status == nil, !model.needsSetup, isAvailable(pane) { + startBar + } content .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) // The daemon's buttons here (Start, Restart) report through the model; "not running" @@ -106,27 +113,72 @@ struct SettingsWindow: View { .onDisappear { store.isVisible = false } } + /// About, and General once Flock is set up (its language, updates and login item don't need + /// the daemon), also show while the daemon isn't running. + private func isAvailable(_ item: SettingsPane) -> Bool { + model.status != nil || item == .about || item == .general && !model.needsSetup + } + + /// Above a pane that shows without the daemon: that Flock doesn't run, and the button that starts it. + private var startBar: some View { + HStack(spacing: 10) { + LogoMark(mode: model.logoMark, size: 22) + .foregroundStyle(Color.flockMark) + Text(model.isOff ? "app.stopped" : "app.not_running") + .font(.callout.weight(.medium)) + Spacer() + if model.isRestarting { + ProgressView().controlSize(.small) + } + Button("menu.start_flock") { + Task { model.isOff ? await model.start() : await model.restart() } + } + .buttonStyle(.borderedProminent) + .disabled(model.isRestarting || model.isUpdating) + } + .padding(.horizontal, 20) + .padding(.vertical, 10) + .padding(.top, 28) // clear the hidden title bar + .background(.quaternary.opacity(0.5)) + .overlay(alignment: .bottom) { Divider() } + } + + /// In place of a pane that needs the daemon: what is the matter, and the way on. + private func unavailable(_ title: LocalizedStringKey, _ description: String, _ action: LocalizedStringKey, perform: @escaping () -> Void) -> some View { + VStack(spacing: 10) { + LogoMark(mode: model.logoMark, size: 56) + .foregroundStyle(Color.flockMark) + .padding(.bottom, 6) + Text(title).font(.title2.weight(.semibold)) + Text(description) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .frame(maxWidth: 360) + Button(action, action: perform) + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(model.isRestarting || model.isUpdating) + .padding(.top, 8) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + @ViewBuilder private var content: some View { - // About, and General once Flock is set up (its language, updates and login item don't need - // the daemon), also show while the daemon isn't running. - if model.status == nil, pane != .about, pane != .general || model.needsSetup { + if !isAvailable(pane) { if model.needsSetup { - ContentUnavailableView { - Label { Text("settings.flock_isnt_set_up_yet") } icon: { LogoMark(size: 44) } - } description: { - Text("settings.set_flock_up_to_run") - } actions: { - Button("menu.set_up_flock") { openWindow.activating(WindowID.setup) } + unavailable("settings.flock_isnt_set_up_yet", String(localized: "settings.set_flock_up_to_run"), "menu.set_up_flock") { + openWindow.activating(WindowID.setup) + } + } else if model.isOff { + unavailable("app.stopped", String(localized: "settings.start_daemon_to_change"), "menu.start_flock") { + Task { await model.start() } } } else { - ContentUnavailableView { - Label { Text("app.not_running") } icon: { LogoMark(size: 44) } - } description: { - Text(model.error ?? String(localized: "settings.start_daemon_to_change")) - } actions: { - Button("menu.start_flock") { Task { await model.restart() } } - .disabled(model.isRestarting) + // Not stopped by the user: say why it doesn't answer, unless that is all there is to say. + let reason = model.error.flatMap { $0 == String(localized: "app.not_running") ? nil : $0 } + unavailable("app.not_running", reason ?? String(localized: "settings.start_daemon_to_change"), "menu.start_flock") { + Task { await model.restart() } } } } else { diff --git a/macos/Sources/FlockUI/Updater.swift b/macos/Sources/FlockUI/Updater.swift index 4090e308..1f39c5f0 100644 --- a/macos/Sources/FlockUI/Updater.swift +++ b/macos/Sources/FlockUI/Updater.swift @@ -92,6 +92,11 @@ extension Updater: SPUUpdaterDelegate { func updater(_ updater: SPUUpdater, didFinishUpdateCycleFor updateCheck: SPUUpdateCheck, error: (any Error)?) { isChecking = false } + + /// The app quits to start again as the new version: Flock keeps running meanwhile. + func updaterWillRelaunchApplication(_ updater: SPUUpdater) { + AppDelegate.keepsFlockRunning = true + } } extension Updater: @preconcurrency SPUStandardUserDriverDelegate { diff --git a/windows/Flock.Kit/FlockPaths.cs b/windows/Flock.Kit/FlockPaths.cs index 6bd1b2f2..49f8c03f 100644 --- a/windows/Flock.Kit/FlockPaths.cs +++ b/windows/Flock.Kit/FlockPaths.cs @@ -19,6 +19,12 @@ public static string Root public static string ApiJson => Path.Combine(Root, "api.json"); + /// + /// Exists while the user has Flock stopped (`flock stop`, the panel's switch, Quit): a daemon + /// that doesn't answer is then off, not broken. + /// + public static string Stopped => Path.Combine(Root, "stopped"); + public static string FlockBinary => Path.Combine(Root, "bin", OperatingSystem.IsWindows() ? "flock.exe" : "flock"); public static string LogFile(string name) => Path.Combine(Root, "log", name + ".log"); diff --git a/windows/Flock.Kit/Strings.cs.resx b/windows/Flock.Kit/Strings.cs.resx index 5e292ff6..fc00c535 100644 --- a/windows/Flock.Kit/Strings.cs.resx +++ b/windows/Flock.Kit/Strings.cs.resx @@ -154,6 +154,9 @@ používá {0} + + Flock se nepodařilo zastavit + Tuto položku se nepodařilo otevřít. @@ -204,6 +207,14 @@ Podrobnosti najdete v %LocalAppData%\Flock\tray.log. Spojení selhalo. Změna se možná provedla; před dalším pokusem obnovte její stav. + + {0} + +Chcete aplikaci přesto ukončit? Flock poběží dál. + + + Flock je zastavený + Flock na {0} {1} neodpověděl včas @@ -933,6 +944,9 @@ Podrobnosti najdete v %LocalAppData%\Flock\tray.log. Běží + + Zastaveno + Aktualizuje se… @@ -1414,7 +1428,7 @@ Podrobnosti najdete v %LocalAppData%\Flock\tray.log. Uložení předvoleb bylo zrušeno. - Pro změnu nastavení spusťte démona. + Pro změnu nastavení spusťte Flock. Nastavení Flocku diff --git a/windows/Flock.Kit/Strings.es.resx b/windows/Flock.Kit/Strings.es.resx index 2cfdba7d..4e8fdcc1 100644 --- a/windows/Flock.Kit/Strings.es.resx +++ b/windows/Flock.Kit/Strings.es.resx @@ -154,6 +154,9 @@ usa {0} + + No se pudo detener Flock + No se pudo abrir este elemento. @@ -204,6 +207,14 @@ Encontrarás los detalles en %LocalAppData%\Flock\tray.log. La conexión falló. Es posible que el cambio se haya completado; actualiza su estado antes de volver a intentarlo. + + {0} + +¿Salir de la aplicación de todos modos? Flock seguirá en ejecución. + + + Flock está detenido + Flock no respondió a {0} {1} a tiempo @@ -921,6 +932,9 @@ Encontrarás los detalles en %LocalAppData%\Flock\tray.log. En ejecución + + Detenido + Actualizando… @@ -1393,7 +1407,7 @@ Encontrarás los detalles en %LocalAppData%\Flock\tray.log. Se canceló el guardado de las preferencias. - Inicia el demonio para cambiar su configuración. + Inicia Flock para cambiar su configuración. Configuración de Flock diff --git a/windows/Flock.Kit/Strings.resx b/windows/Flock.Kit/Strings.resx index 2e943ee1..ac842779 100644 --- a/windows/Flock.Kit/Strings.resx +++ b/windows/Flock.Kit/Strings.resx @@ -161,6 +161,10 @@ uses {0} {0}: the ports ("port 80 (HTTP) and port 443 (HTTPS)") + + Flock could not be stopped + Title of the question asked when quitting Flock couldn't stop it + Could not open this item. @@ -218,6 +222,16 @@ Details are in %LocalAppData%\Flock\tray.log. The connection failed. The change may have completed; refresh its state before retrying. + + {0} + +Quit the app anyway? Flock keeps running. + {0}: why Flock could not be stopped + + + Flock is stopped + Title where a window can't show its content because the user turned Flock off + Flock did not answer {0} {1} in time {0}: the HTTP method, {1}: the API path @@ -1001,6 +1015,10 @@ Details are in %LocalAppData%\Flock\tray.log. Running + + Stopped + Flock's state after the user turned it off (the switch, Quit or `flock stop`) + Updating… @@ -1550,7 +1568,7 @@ Details are in %LocalAppData%\Flock\tray.log. Preference save canceled. - Start the daemon to change its settings. + Start Flock to change its settings. Flock Settings diff --git a/windows/Flock.Tray/App.xaml.cs b/windows/Flock.Tray/App.xaml.cs index ee340405..3f4f19ee 100644 --- a/windows/Flock.Tray/App.xaml.cs +++ b/windows/Flock.Tray/App.xaml.cs @@ -21,6 +21,9 @@ public sealed partial class App : Application /// Command line argument of the sign-in autostart. public const string BackgroundArgument = "--background"; + + /// Command line argument of the start after an update (windows/installer/Flock.iss). + public const string UpdatedArgument = "--updated"; private readonly AcceptedInstallTracker acceptedInstalls = new(Log); private DispatcherQueue? dispatcher; @@ -138,6 +141,11 @@ private async Task StartAsync(DispatcherQueue dispatcher) host.StartUpdateInstallation(); } var arguments = Environment.GetCommandLineArgs(); + // Not for a restart of the app only (another language, an update): a stopped Flock stays stopped over it. + if (!arguments.Contains(UpdatedArgument) && !arguments.Any(argument => argument.StartsWith(Program.RelaunchArgument, StringComparison.Ordinal))) + { + _ = State.StartIfStoppedAsync(); + } if (arguments.FirstOrDefault(SecureLink.IsFlockLink) is { } link) { OpenLink(link); @@ -169,7 +177,11 @@ private string IconPath() /// .ico for the notification area; .png inside windows (WinUI scales up an .ico's smallest image). public static string TrayIconPath(RuntimeService model, bool light, string extension = ".ico") { - var state = !model.IsRunning || model.NeedsSetup ? "TrayStopped" : model.IsDegraded ? "TrayWarning" : "Tray"; + // A dot says what isn't as usual: grey while Flock is stopped (or starting, updating, not set + // up), red when it should run and doesn't, ember for what needs attention. + var state = model.IsRunning && !model.NeedsSetup ? model.IsDegraded ? "TrayWarning" : "Tray" + : model.IsDown ? "TrayDown" + : "TrayStopped"; return Path.Combine(AppContext.BaseDirectory, "Assets", $"{state}.{(light ? "Light" : "Dark")}{extension}"); } @@ -332,7 +344,7 @@ private void ShowMenu() case 5: Open(WindowKind.Settings); break; case 7: _ = running ? State.RestartAsync() : State.StartAsync(); break; case 8 when running: _ = State.StopAsync(); break; - case 8 or 9: Quit(); break; + case 8 or 9: QuitFlock(); break; } } @@ -444,11 +456,45 @@ private async Task OpenLogsCoreAsync(LogsViewModel.Source? source = null) } } + /// Quits the app only: the daemon keeps running (a restart of the app, an update, an uninstall). public void Quit() { _ = QuitAsync(); } + /// + /// The user's Quit: stops the daemon and everything it runs first, as quitting other local + /// environments does. Signing out or shutting down doesn't come here, so Flock is still on at the + /// next sign-in. + /// + public void QuitFlock() + { + _ = QuitFlockAsync(); + } + + private async Task QuitFlockAsync() + { + if (!State.NeedsSetup) + { + string? problem; + try + { + problem = await State.StopForQuitAsync(); + } + catch (Exception error) + { + Log(error); + problem = error.Message; + } + // Flock could not be stopped: ask before leaving it running. + if (problem is not null && !Native.Confirm(Strings.App_CouldNotBeStopped, Localization.Format(Strings.App_QuitAnywayQuestion, problem))) + { + return; + } + } + await QuitAsync(); + } + /// /// Quits and starts again (a new language applies only to a new process), false when the new /// process couldn't start. The new process waits for this one to exit, however long quitting takes, diff --git a/windows/Flock.Tray/Assets/TrayDown.Dark.ico b/windows/Flock.Tray/Assets/TrayDown.Dark.ico new file mode 100644 index 00000000..506779e2 Binary files /dev/null and b/windows/Flock.Tray/Assets/TrayDown.Dark.ico differ diff --git a/windows/Flock.Tray/Assets/TrayDown.Dark.png b/windows/Flock.Tray/Assets/TrayDown.Dark.png new file mode 100644 index 00000000..486a23c4 Binary files /dev/null and b/windows/Flock.Tray/Assets/TrayDown.Dark.png differ diff --git a/windows/Flock.Tray/Assets/TrayDown.Light.ico b/windows/Flock.Tray/Assets/TrayDown.Light.ico new file mode 100644 index 00000000..80aaf823 Binary files /dev/null and b/windows/Flock.Tray/Assets/TrayDown.Light.ico differ diff --git a/windows/Flock.Tray/Assets/TrayDown.Light.png b/windows/Flock.Tray/Assets/TrayDown.Light.png new file mode 100644 index 00000000..e11e0a21 Binary files /dev/null and b/windows/Flock.Tray/Assets/TrayDown.Light.png differ diff --git a/windows/Flock.Tray/Assets/TrayStopped.Dark.ico b/windows/Flock.Tray/Assets/TrayStopped.Dark.ico index c6710ee3..092d04d2 100644 Binary files a/windows/Flock.Tray/Assets/TrayStopped.Dark.ico and b/windows/Flock.Tray/Assets/TrayStopped.Dark.ico differ diff --git a/windows/Flock.Tray/Assets/TrayStopped.Dark.png b/windows/Flock.Tray/Assets/TrayStopped.Dark.png index d8a978ae..02598b39 100644 Binary files a/windows/Flock.Tray/Assets/TrayStopped.Dark.png and b/windows/Flock.Tray/Assets/TrayStopped.Dark.png differ diff --git a/windows/Flock.Tray/Assets/TrayStopped.Light.ico b/windows/Flock.Tray/Assets/TrayStopped.Light.ico index 022a3a00..dde39216 100644 Binary files a/windows/Flock.Tray/Assets/TrayStopped.Light.ico and b/windows/Flock.Tray/Assets/TrayStopped.Light.ico differ diff --git a/windows/Flock.Tray/Assets/TrayStopped.Light.png b/windows/Flock.Tray/Assets/TrayStopped.Light.png index d83b5b33..df771de3 100644 Binary files a/windows/Flock.Tray/Assets/TrayStopped.Light.png and b/windows/Flock.Tray/Assets/TrayStopped.Light.png differ diff --git a/windows/Flock.Tray/Infrastructure/RuntimeService.cs b/windows/Flock.Tray/Infrastructure/RuntimeService.cs index cccc4c73..f3a23e2c 100644 --- a/windows/Flock.Tray/Infrastructure/RuntimeService.cs +++ b/windows/Flock.Tray/Infrastructure/RuntimeService.cs @@ -108,8 +108,20 @@ public SecureLink? PendingSecure public string Headline => IsUpdating ? Strings.Menu_Status_Updating : NeedsSetup ? Strings.Menu_Status_NotSetUp : Status is { } status ? $"{(status.IsDegraded ? Strings.Menu_Status_NeedsAttention : Strings.Menu_Status_Running)} · v{status.Version}" + : IsOff ? Strings.Menu_Status_Stopped : Strings.Menu_Status_NotRunning; public bool IsRunning => Status is not null; + /// The daemon doesn't answer because the user stopped Flock, not because something is wrong. + public bool IsOff => !IsRunning && File.Exists(FlockPaths.Stopped); + + /// + /// Flock should run and doesn't: no answer for a while, though the user didn't stop it. Not at once: + /// a daemon that starts (at sign-in, beside the app) answers only after its first reload. + /// + public bool IsDown { get; private set; } + + private static readonly TimeSpan DownAfter = TimeSpan.FromSeconds(10); + private DateTimeOffset? unansweredSince; public bool IsDegraded => Status?.IsDegraded ?? false; public UpdateService UpdateService { get; } public TimeProvider TimeProvider { get; } @@ -181,19 +193,62 @@ public void DismissError() NotifyChanged(); } - public Task RestartAsync() => RunLifecycleAsync("restart", Strings.App_CouldNotRestart); + // Once the user quits, only the stop runs: a start beside it would leave Flock running. + public Task RestartAsync() => quitting ? Task.CompletedTask : RunLifecycleAsync("restart", Strings.App_CouldNotRestart); /// Starts the daemon after . - public Task StartAsync() => RunLifecycleAsync("start", Strings.App_CouldNotStart); + public Task StartAsync() => quitting ? Task.CompletedTask : RunLifecycleAsync("start", Strings.App_CouldNotStart); - /// Stops the daemon and everything it runs until or the next sign-in. + /// Stops the daemon and everything it runs until or until the app is opened again (also at sign-in, when it opens then). public Task StopAsync() => RunLifecycleAsync("stop", Strings.App_CouldNotStop); - private async Task RunLifecycleAsync(string command, string error) + /// + /// Starting the app starts Flock: quitting it stopped the daemon, and so did the switch. An update's + /// `flock install` leaves a stopped Flock stopped, so this waits for it. + /// + public async Task StartIfStoppedAsync() + { + while (IsUpdating) + { + await Task.Delay(TimeSpan.FromMilliseconds(500)); + } + // Not once the user quits (during the update): the stop that wrote the file is this run's. + if (!NeedsSetup && !quitting && File.Exists(FlockPaths.Stopped)) + { + await StartAsync(); + } + } + + /// The user is quitting: nothing starts Flock any more. + private bool quitting; + + /// + /// Stops Flock for the user's Quit; the answer is why it could not be stopped, null when it was. + /// A start or restart that runs finishes first: stopping beside it would be ignored. + /// + public async Task StopForQuitAsync() + { + quitting = true; + // Also an update's `flock install`, which could start the daemon after the stop. + while (operations.IsRunning("lifecycle") || IsUpdating) + { + await Task.Delay(TimeSpan.FromMilliseconds(100)); + } + if (await RunLifecycleAsync("stop", Strings.App_CouldNotStop)) + { + return null; + } + // The quit may be cancelled: Flock is used on. + quitting = false; + return ActionError ?? Localization.Format(Strings.App_CouldNotStop, FlockPaths.FlockBinary); + } + + /// Whether the command ran and succeeded; one that comes while another runs is ignored. + private async Task RunLifecycleAsync(string command, string error) { if (operations.IsRunning("lifecycle")) { - return; + return false; } IsRestarting = true; NotifyChanged(); @@ -217,6 +272,7 @@ private async Task RunLifecycleAsync(string command, string error) { await RefreshAsync(); } + return outcome is OperationOutcome.Succeeded; } public ShellLaunchResult Open(string target) => ReportShellResult(shell.Open(target)); @@ -255,7 +311,19 @@ private void ApplyPublished(Status? status) { if (status is null) { - var changed = Error != statusPolling.LastError; + var now = TimeProvider.GetUtcNow(); + if (NeedsSetup || IsRestarting || IsUpdating || File.Exists(FlockPaths.Stopped)) + { + // Nothing is expected to answer; the wait starts when one is. + unansweredSince = null; + } + else + { + unansweredSince ??= now; + } + var down = unansweredSince is { } since && now - since >= DownAfter; + var changed = Error != statusPolling.LastError || down != IsDown; + IsDown = down; Error = statusPolling.LastError; Status = null; if (changed) @@ -287,6 +355,8 @@ private void Apply(Status fresh) var previous = Status; Status = fresh; Error = null; + unansweredSince = null; + IsDown = false; if (fresh.Channel != Preferences.Snapshot.Channel) { _ = Preferences.UpdateAsync(value => value with { Channel = fresh.Channel }); diff --git a/windows/Flock.Tray/Native.cs b/windows/Flock.Tray/Native.cs index 270e531f..ec386a69 100644 --- a/windows/Flock.Tray/Native.cs +++ b/windows/Flock.Tray/Native.cs @@ -109,6 +109,10 @@ public struct POINT /// A plain error dialog, for when WinUI itself could not start. public static void ShowError(string caption, string text) => MessageBox(IntPtr.Zero, text, caption, 0x10 /* MB_ICONERROR */); + /// Asks a yes/no question about something that went wrong; true for Yes. + public static bool Confirm(string caption, string text) => + MessageBox(IntPtr.Zero, text, caption, 0x4 /* MB_YESNO */ | 0x30 /* MB_ICONWARNING */ | 0x100 /* MB_DEFBUTTON2 */) == 6 /* IDYES */; + // Signatures [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] diff --git a/windows/Flock.Tray/PanelWindow.xaml b/windows/Flock.Tray/PanelWindow.xaml index acdea25e..51ef7f71 100644 --- a/windows/Flock.Tray/PanelWindow.xaml +++ b/windows/Flock.Tray/PanelWindow.xaml @@ -343,6 +343,7 @@ + diff --git a/windows/Flock.Tray/Settings/SettingsWindow.xaml b/windows/Flock.Tray/Settings/SettingsWindow.xaml index 8b37b6d0..558a2a63 100644 --- a/windows/Flock.Tray/Settings/SettingsWindow.xaml +++ b/windows/Flock.Tray/Settings/SettingsWindow.xaml @@ -79,22 +79,29 @@ + - + + + + + private bool IsAvailable(SettingsPane pane) => model.Status is not null || pane is SettingsPane.About or SettingsPane.General; + private void ShowPane() { + // What needs the daemon can't be opened while it doesn't run. + foreach (var item in Navigation.MenuItems.OfType()) + { + if (item.Tag is string tag && Enum.TryParse(tag, out var itemPane)) + { + item.IsEnabled = IsAvailable(itemPane); + } + } + // A pane that shows without the daemon says that Flock doesn't run, with the button that starts it. + StartBar.Title = model.IsOff ? Strings.App_Stopped : Strings.Common_FlockNotRunning; + StartBar.Severity = model.IsOff ? InfoBarSeverity.Informational : InfoBarSeverity.Warning; + StartBarButton.IsEnabled = !model.IsRestarting && !model.IsUpdating; + StartBar.IsOpen = model.Status is null && !model.NeedsSetup && IsAvailable(current); if (failedPane == current) { return; @@ -154,12 +176,22 @@ private void ShowPane() var fills = pane.ScrollsItself && model.Status is not null; Scroller.VerticalScrollMode = fills ? ScrollMode.Disabled : ScrollMode.Auto; Scroller.VerticalScrollBarVisibility = fills ? ScrollBarVisibility.Disabled : ScrollBarVisibility.Auto; - // About and General (the app's own settings, such as its language) work without the daemon. - if (model.Status is null && current is not (SettingsPane.About or SettingsPane.General)) + if (!IsAvailable(current)) { PaneHost.Children.Clear(); - PaneHost.Children.Add(Ui.EmptyState(Ui.GlyphWarning, Strings.Common_FlockNotRunning, model.Error ?? Strings.Settings_StartDaemonToChange, - Ui.Button(Strings.Menu_StartFlock, () => _ = model.RestartAsync(), true))); + // Say why it doesn't answer, unless the user stopped it or that is all there is to say. + var reason = !model.IsOff && model.Error is { } error && error != Strings.App_NotRunning && error != Strings.Common_FlockNotRunning ? error : null; + var state = Ui.EmptyState(Ui.GlyphInfo, model.IsOff ? Strings.App_Stopped : Strings.Common_FlockNotRunning, reason ?? Strings.Settings_StartDaemonToChange, + Ui.Button(Strings.Menu_StartFlock, () => _ = model.IsOff ? model.StartAsync() : model.RestartAsync(), true)); + // Flock's logomark with the state's dot, as in the panel and the notification area. + state.Children[0] = new Image + { + Source = new BitmapImage(new Uri(App.TrayIconPath(model, Scroller.ActualTheme == ElementTheme.Light, ".png"))), + Width = 56, + Height = 56, + HorizontalAlignment = HorizontalAlignment.Center, + }; + PaneHost.Children.Add(state); return; } if (PaneHost.Children.Count == 1 && ReferenceEquals(PaneHost.Children[0], pane.Root)) diff --git a/windows/Flock.Tray/ViewModels/PanelViewModel.cs b/windows/Flock.Tray/ViewModels/PanelViewModel.cs index a02fab1e..fc8b94aa 100644 --- a/windows/Flock.Tray/ViewModels/PanelViewModel.cs +++ b/windows/Flock.Tray/ViewModels/PanelViewModel.cs @@ -40,7 +40,7 @@ public PanelViewModel(RuntimeService model) OpenLogsCommand = new RelayCommand(() => App.Current.Open(WindowKind.Logs)); OpenSetupCommand = new RelayCommand(() => App.Current.Open(WindowKind.Setup)); OpenSettingsCommand = new RelayCommand(() => App.Current.Open(WindowKind.Settings)); - QuitCommand = new RelayCommand(() => App.Current.Quit()); + QuitCommand = new RelayCommand(() => App.Current.QuitFlock()); RefreshRows(); } @@ -115,6 +115,9 @@ public bool FlockOn public Visibility NotRunningVisibility => HasStatusContent ? Visibility.Collapsed : Visibility.Visible; public Visibility SetupVisibility => NeedsSetup ? Visibility.Visible : Visibility.Collapsed; public Visibility UpdatingVisibility => !NeedsSetup && IsUpdating ? Visibility.Visible : Visibility.Collapsed; + /// Not stopped by the user, and still no answer: the panel says why. + public Visibility DownVisibility => model.IsDown ? Visibility.Visible : Visibility.Collapsed; + public string DownMessage => model.Error ?? Strings.Common_FlockNotRunning; public Visibility FlockSwitchVisibility => NeedsSetup ? Visibility.Collapsed : Visibility.Visible; public Visibility FooterVisibility => HasStatusContent ? Visibility.Visible : Visibility.Collapsed; public Visibility MailCountVisibility => MailCount > 0 ? Visibility.Visible : Visibility.Collapsed; @@ -230,6 +233,8 @@ private void ModelChanged() OnPropertyChanged(nameof(NotRunningVisibility)); OnPropertyChanged(nameof(SetupVisibility)); OnPropertyChanged(nameof(UpdatingVisibility)); + OnPropertyChanged(nameof(DownVisibility)); + OnPropertyChanged(nameof(DownMessage)); OnPropertyChanged(nameof(FlockSwitchVisibility)); OnPropertyChanged(nameof(FooterVisibility)); OnPropertyChanged(nameof(MailCountVisibility)); diff --git a/windows/installer/Flock.iss b/windows/installer/Flock.iss index 04b1cf5e..bdc789f0 100644 --- a/windows/installer/Flock.iss +++ b/windows/installer/Flock.iss @@ -81,7 +81,7 @@ Root: HKCU; Subkey: "Software\Classes\flock\shell\open\command"; ValueType: stri [Run] Filename: "{app}\FlockTray.exe"; Description: "{cm:Installer_OpenFlock}"; Flags: postinstall nowait skipifsilent ; The app updates itself by running this installer silently with /RELAUNCH; it starts again quietly. -Filename: "{app}\FlockTray.exe"; Parameters: "--background"; Flags: nowait; Check: HasParam('/RELAUNCH') +Filename: "{app}\FlockTray.exe"; Parameters: "--background --updated"; Flags: nowait; Check: HasParam('/RELAUNCH') [Code] // /PURGE: the app's uninstall dialog, when the user also wants their data deleted.