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