diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 064c500d0..bec7e71b1 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -31,7 +31,7 @@ three. 1. `magpie` with no arguments, `magpie app` or `magpie tray` calls `runGUI`, which starts the app's log (`startLog`, above) and calls `gui.Run`. A `nogui` build runs the TUI instead. A second launch hands over to the instance already running. On Windows, before any window is made, `webView2Check` asks Wails whether the WebView2 runtime is there (`Env.Info().PlatformInfo["WebView2"]`, "" when its lookup fails; a key Wails doesn't set counts as there). Without it Wails would exit on the first window with nothing on screen, so magpie logs it, shows a Windows message box in the reader's language naming the runtime, Microsoft's download page (`webView2Page`) and `magpie web` / `magpie tui`, opens the page on Yes, and `Run` ends (#1806, `webview2.go`, `TestWebView2MissingFromWails` on Windows). The box can't come from `ErrorHandler`, which runs on the thread Wails makes its windows on. 2. `startBackend` brings up the gateway, or finds another magpie serving it. -3. The panel and the window load `index.html` from `Handler`. `boot.js` passes the saved language, theme, colorblind mode, text size and desktop font choices before the first paint. +3. The panel and the window load `index.html` from `Handler`. `boot.js` passes the saved language, theme, colorblind mode, text size and desktop font choices before the first paint. It also puts in the look of the reader's own (`appearance.go`, CHENGJIAHEGOXIS on X): Settings › General's Accent color (`accent`, `#rrggbb`; `accentVars` darkens it on the light theme and lightens it on the dark one until it reads as text at 4.5:1) and Background image (a PNG, JPEG, GIF or WebP of 16 MB at most, saved as `wallpaper` in magpie's folder by `POST /api/appearance/wallpaper` as base64 JSON, `{remove: true}` to take it away; `settings.Wallpaper` is its stamp), drawn behind the window's pages under a veil of the theme's background, never in the tray panel or under Omarchy. `bootPrefs.look` says which look was drawn; `applyPrefs` asks `/api/appearance/css` again only when the settings' look differs, and the rows are drawn by the lazy `appearance.js` (`appearance-look.test.cjs`, `appearance_test.go`). 4. The page reads `GET /api/state` and writes through `POST` routes. Each write answers with the new state, built under `held`. 5. Closing the window hides it. On the Mac a full-screen window first leaves full screen (`closeStep`). The system's close on the panel (a title bar's X, Alt+F4, a window manager's close key) hides it as Escape does, so the tray icon opens it again; a panel lightweight mode let go, no longer `h.panel`, closes (`makePanel`, `TestPanelCloseHidesIt`). A hidden macOS window keeps its WKWebView's page marked visible, so `hideWebview` tells the page it is out of sight before `orderOut`; that makes `document.hidden` and `visibilityState` true, stops the page's polling and frame loops, and pauses CSS animations. `showWebview` tells it it is visible again (#4293). Lightweight mode lets go only of a window closed this way: one covered by another app's window, minimised, or open as magpie was hidden is still open (`windowUp`, not Wails' `IsVisible`, which is the occlusion state), and so is it for the Dock while the window is open and for a restart (#1381, `TestCoveredWindowStaysUp`). On the Mac the tray icon and a usage cell close an open panel by the same test (`windowOpen` in `togglePanelNow` and `trayCellClick`, not Wails' `ToggleWindow`), so under a window over the whole screen, such as a remote-desktop server's privacy curtain, the icon still closes the panel instead of showing it again (#1661, `TestTrayCellClickReleasedPanel`). On Windows a hidden window's WebView2 is put on its low memory target (`lowWhileHidden`, [`memtarget_windows.go`](../../internal/gui/memtarget_windows.go): `ICoreWebView2_19::put_MemoryUsageTargetLevel`, on each hide, on a page that comes while hidden, and back to normal on each show), so the panel and the window kept loaded in the tray stop holding what they last drew; the page stays loaded and running, unlike lightweight mode. In the tray the WebView2 processes' private working set went from ~170 MB to 20 to 40 MB, while their commit charge stayed where it was (molamaker11 on X). WKWebView and WebKitGTK have nothing magpie can set for it. 6. The window opens as it was last left. Its settled size and whether it was maximised are kept in `settings.Window` and `settings.WindowMaximised` (`settle`; per machine, see `KeepOwn`). A maximised window keeps the size it restores to. `makeMain` opens it at that size (`openSize`). On its first show, `placeMain` maximises it again on the Mac and Windows (on Windows once the page has come). On Linux, `makeMain` makes it maximised with `StartState`. On Windows a size larger than the screen's work area is fitted and centred (`fitRoom`), and the larger size stays kept. Where it was left is kept too, in `settings.WindowAt` (its top left corner across every screen, in the system's coordinates), so after a restart or an update it opens there rather than in the middle (jorbenzhu on Discord). `keepAt` saves it once a move or resize has rested for half a second, unless the window is maximised, full screen, minimised or hidden; `settings.Save` writes through temp and rename, and a settings file that can't be read is left alone. On its first show `placeMain` puts it back (`putBack`): `openAt` takes the screen holding most of the window, moves the window fully onto that screen's work area, and leaves it centred when no screen holds any of it, such as a monitor that is gone, or when the screens or the file can't be read (`TestOpenAt`). Under Wayland a window can't place itself, so nothing is kept or put back there unless GDK_BACKEND is x11 (`keepsPlace`, `TestKeepsPlace`). The tray's panel isn't kept: on the Mac and Windows it opens under the tray icon, and on Linux where the click was. diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 8dd982c72..fd591d3a9 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -249,6 +249,9 @@ var notYet = map[string]string{ "GET /api/notices": W, // api.go "GET /api/feedback": W, // feedback.go: Settings › About's Report a problem, which opens a page "GET /api/omarchy": W, // api.go + "GET /api/appearance/css": W, // appearance.go: the stylesheet of the accent and the picture behind the pages; the accent is `magpie settings set accent` + "GET /api/appearance/wallpaper": W, // appearance.go + "POST /api/appearance/wallpaper": W, // appearance.go: the picture comes from the window's file picker "GET /api/quit": W, // api.go: the window's Quit question "GET /api/remote": W, // remote.go: another magpie opened in a window of the app "POST /api/remote": W, // remote.go diff --git a/internal/gui/api.go b/internal/gui/api.go index 99b2ce753..bf5d784ed 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1180,6 +1180,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { devRoutes(mux) pluginPageRoutes(mux, isWeb(w)) feedbackRoutes(mux) + appearanceRoutes(mux) // boot.js hands the page the saved language and theme before it paints: // they came only with the settings, so the tabs showed English first mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) { @@ -1266,10 +1267,19 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if th, ok := omarchyTheme(); ok { boot["omarchy"] = th } + // and the accent and wallpaper of the user's own (appearance.go), + // drawn before the first paint + boot["look"] = lookKey(s) b, _ := json.Marshal(boot) rw.Header().Set("Content-Type", "text/javascript; charset=utf-8") rw.Header().Set("Cache-Control", "no-store") - rw.Write(append(append([]byte("window.bootPrefs = "), b...), ";\n"...)) + out := append(append([]byte("window.bootPrefs = "), b...), ";\n"...) + if css := lookCSS(s); css != "" { + c, _ := json.Marshal(css) + out = append(out, `(function(){var e=document.createElement("style");e.id="lookCSS";e.textContent=`...) + out = append(append(out, c...), ";document.head.appendChild(e)})();\n"...) + } + rw.Write(out) }) // the Omarchy theme as it is now, asked again every few seconds so a // theme picked in Omarchy's menu reaches the page at once; null off Omarchy diff --git a/internal/gui/appearance.go b/internal/gui/appearance.go new file mode 100644 index 000000000..a2c0e62c2 --- /dev/null +++ b/internal/gui/appearance.go @@ -0,0 +1,237 @@ +package gui + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/settings" +) + +// Settings › General's Accent color and Background image +// (CHENGJIAHEGOXIS on X): a colour of the user's own for magpie's +// buttons, links and selection, and a picture of their own behind the +// window's pages. Both are drawn by lookCSS, a stylesheet boot.js puts in +// the page before it paints and /api/appearance/css hands a page whose +// settings changed (appearance.js). + +// maxWallpaper is the largest picture taken. +const maxWallpaper = 16 << 20 + +// wallpaperTypes are the pictures every webview magpie runs in draws. +var wallpaperTypes = []string{"image/png", "image/jpeg", "image/gif", "image/webp"} + +// wallpaperType is b's type when it is a picture magpie takes. +func wallpaperType(b []byte) (string, error) { + if len(b) == 0 || len(b) > maxWallpaper { + return "", fmt.Errorf("a background image is %d MB at most", maxWallpaper>>20) + } + ct := http.DetectContentType(b) + for _, t := range wallpaperTypes { + if ct == t { + return ct, nil + } + } + return "", errors.New("a background image is a PNG, JPEG, GIF or WebP picture") +} + +// lookKey is what the page compares to know its look is the saved one, +// as app.js's applyPrefs writes it: the accent and the wallpaper's stamp. +func lookKey(s settings.Settings) string { + w := "" + if s.Wallpaper != 0 { + w = strconv.FormatInt(s.Wallpaper, 10) + } + return s.Accent + "," + w +} + +// lookCSS is the stylesheet that draws s's accent and wallpaper, "" for +// magpie's own look. It never applies under Omarchy, whose theme is the +// look there. +func lookCSS(s settings.Settings) string { + var b strings.Builder + if c, ok := parseHex(s.Accent); ok { + light, dark := accentVars(c, false), accentVars(c, true) + fmt.Fprintf(&b, "html:not(.omarchy):root{%s}\n", light) + fmt.Fprintf(&b, "@media (prefers-color-scheme: dark){html:not(.omarchy):root:not([data-theme=\"light\"]){%s}}\n", dark) + fmt.Fprintf(&b, "html:not(.omarchy):root[data-theme=\"dark\"]{%s}\n", dark) + } + if s.Wallpaper != 0 { + if fi, err := os.Stat(settings.WallpaperPath()); err == nil && fi.Mode().IsRegular() { + // the picture fills the window behind the pages, under a veil of + // the theme's own background (one colour, the top layer), so text + // on it reads as on the plain page; the cards over it stay opaque. + // The background's colour is still the theme's, which Windows' + // title bar is painted from (tintTitleBar) + fmt.Fprintf(&b, "html:not(.omarchy) body:not(.panel){background:linear-gradient(%[1]s,%[1]s),url(\"/api/appearance/wallpaper?v=%[2]d\") center/cover no-repeat var(--bg)}\n", wallVeil, s.Wallpaper) + b.WriteString("html:not(.omarchy) body:not(.panel) .sidebar{background:transparent}\n") + } + } + return b.String() +} + +type rgb [3]float64 + +func parseHex(s string) (rgb, bool) { + if len(s) != 7 || s[0] != '#' { + return rgb{}, false + } + n, err := strconv.ParseUint(s[1:], 16, 32) + if err != nil { + return rgb{}, false + } + return rgb{float64(n >> 16 & 255), float64(n >> 8 & 255), float64(n & 255)}, true +} + +func (c rgb) hex() string { + return fmt.Sprintf("#%02x%02x%02x", int(math.Round(c[0])), int(math.Round(c[1])), int(math.Round(c[2]))) +} + +// mix is c moved p of the way to o. +func (c rgb) mix(o rgb, p float64) rgb { + return rgb{c[0] + (o[0]-c[0])*p, c[1] + (o[1]-c[1])*p, c[2] + (o[2]-c[2])*p} +} + +// luminance is WCAG's relative luminance. +func (c rgb) luminance() float64 { + ch := func(v float64) float64 { + v /= 255 + if v <= 0.03928 { + return v / 12.92 + } + return math.Pow((v+0.055)/1.055, 2.4) + } + return 0.2126*ch(c[0]) + 0.7152*ch(c[1]) + 0.0722*ch(c[2]) +} + +// contrast is WCAG's contrast ratio of a and b. +func contrast(a, b rgb) float64 { + la, lb := a.luminance(), b.luminance() + if la < lb { + la, lb = lb, la + } + return (la + 0.05) / (lb + 0.05) +} + +var ( + white = rgb{255, 255, 255} + black = rgb{0, 0, 0} + // the themes' backgrounds (app.css --bg and --card), what the accent + // is read against as text + lightBg = rgb{0xf4, 0xf4, 0xf6} + darkBg = rgb{0x1a, 0x1a, 0x1e} + darkCard = rgb{0x23, 0x23, 0x27} + accentInk = 4.5 // WCAG AA for text: the accent is a link's colour too + // how much of the theme's background lies over the picture + wallVeil = "color-mix(in srgb,var(--bg) 84%,transparent)" +) + +// accentOn is c, darkened (light theme) or lightened (dark theme) just +// enough to read as text on that theme's background and cards. +func accentOn(c rgb, dark bool) rgb { + toward, against := black, lightBg + if dark { + toward, against = white, darkCard + } + out := c + for p := 0.0; p <= 1 && contrast(out, against) < accentInk; p += 0.02 { + out = c.mix(toward, p) + } + return out +} + +// accentVars are the theme's --accent, its soft fill, the text on it and +// the selection, from c. +func accentVars(c rgb, dark bool) string { + a := accentOn(c, dark) + fg := white + if contrast(a, rgb{0x14, 0x14, 0x1a}) > contrast(a, white) { + fg = rgb{0x14, 0x14, 0x1a} + } + soft, sel := white.mix(a, 0.09), white.mix(a, 0.11) + if dark { + soft, sel = darkBg.mix(a, 0.14), darkBg.mix(a, 0.2) + } + return fmt.Sprintf("--accent:%s;--accent-soft:%s;--accent-fg:%s;--sel:%s", a.hex(), soft.hex(), fg.hex(), sel.hex()) +} + +// appearanceRoutes serve the look's stylesheet and the wallpaper, and take +// a picture chosen or removed. +func appearanceRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/appearance/css", func(rw http.ResponseWriter, r *http.Request) { + s := settings.Load() + writeJSON(rw, map[string]string{"css": lookCSS(s), "key": lookKey(s)}) + }) + mux.HandleFunc("GET /api/appearance/wallpaper", func(rw http.ResponseWriter, r *http.Request) { + b, err := os.ReadFile(settings.WallpaperPath()) + if err != nil { + http.NotFound(rw, r) + return + } + ct, err := wallpaperType(b) + if err != nil { + http.NotFound(rw, r) + return + } + rw.Header().Set("Content-Type", ct) + rw.Header().Set("Cache-Control", "private, max-age=31536000, immutable") // its address changes with it (?v=) + rw.Header().Set("X-Content-Type-Options", "nosniff") + rw.Write(b) + }) + // the picture comes as base64 in JSON, as the app's web view drops a + // File sent as the body; {"remove": true} takes it away + mux.HandleFunc("POST /api/appearance/wallpaper", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Data []byte `json:"data"` + Remove bool `json:"remove"` + } + if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, maxWallpaper*4/3+64<<10)).Decode(&in); err != nil { + fail(rw, fmt.Errorf("a background image is a PNG, JPEG, GIF or WebP picture of %d MB at most", maxWallpaper>>20)) + return + } + if err := setWallpaper(in.Data, in.Remove); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) +} + +// setWallpaper saves b as the picture behind the pages, or removes it. +func setWallpaper(b []byte, remove bool) error { + if !remove { + if _, err := wallpaperType(b); err != nil { + return err + } + } + s, err := settings.LoadChecked() + if err != nil { + return err + } + if remove { + s.Wallpaper = 0 + if err := settings.Save(s); err != nil { + return err + } + if err := os.Remove(settings.WallpaperPath()); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + return err + } + if err := edit.WriteAtomic(settings.WallpaperPath(), b); err != nil { + return err + } + // a new stamp, so the page asks for the new picture, not its cached one + s.Wallpaper = max(time.Now().UnixMilli(), s.Wallpaper+1) + return settings.Save(s) +} diff --git a/internal/gui/appearance_test.go b/internal/gui/appearance_test.go new file mode 100644 index 000000000..7b45763ef --- /dev/null +++ b/internal/gui/appearance_test.go @@ -0,0 +1,198 @@ +package gui + +import ( + "bytes" + "encoding/json" + "image" + "image/color" + "image/png" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +func appearanceHome(t *testing.T) http.Handler { + t.Helper() + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("APPDATA", filepath.Join(h, "AppData", "Roaming")) + t.Setenv("LOCALAPPDATA", filepath.Join(h, "AppData", "Local")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share")) + return Handler(&zoomWindows{}, nil) +} + +func lookServe(srv http.Handler, method, path, body string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body))) + return rec +} + +func tinyPNG(t *testing.T) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, 2, 2)) + img.Set(0, 0, color.RGBA{200, 30, 30, 255}) + var b bytes.Buffer + if err := png.Encode(&b, img); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +// An accent of the reader's own (CHENGJIAHEGOXIS on X) is saved from +// Settings, drawn by boot.js before the first paint, kept by a save that +// doesn't send it, and refused when it isn't a colour. +func TestAccentSetting(t *testing.T) { + srv := appearanceHome(t) + if rec := lookServe(srv, "POST", "/api/settings", `{"theme":"dark","lang":"en","accent":"#0d9488"}`); rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if got := settings.Load().Accent; got != "#0d9488" { + t.Fatalf("saved accent %q", got) + } + boot := lookServe(srv, "GET", "/boot.js", "").Body.String() + if !strings.Contains(boot, `"look":"#0d9488,"`) || !strings.Contains(boot, `e.id="lookCSS"`) || !strings.Contains(boot, "--accent:") { + t.Fatalf("boot.js draws no accent: %s", boot) + } + // a save from somewhere that doesn't know the accent keeps it + if rec := lookServe(srv, "POST", "/api/settings", `{"theme":"light","lang":"en"}`); rec.Code != http.StatusOK || settings.Load().Accent != "#0d9488" { + t.Fatalf("a save without the accent changed it: %d %q", rec.Code, settings.Load().Accent) + } + for _, bad := range []string{"teal", "#0d948", "#0d9488;}body{display:none", "red;--x:1"} { + b, _ := json.Marshal(map[string]string{"theme": "light", "lang": "en", "accent": bad}) + if rec := lookServe(srv, "POST", "/api/settings", string(b)); rec.Code == http.StatusOK || settings.Load().Accent != "#0d9488" { + t.Fatalf("accent %q was taken: %d", bad, rec.Code) + } + } + // and "" is magpie's own again, with nothing drawn over it + if rec := lookServe(srv, "POST", "/api/settings", `{"theme":"light","lang":"en","accent":""}`); rec.Code != http.StatusOK || settings.Load().Accent != "" { + t.Fatalf("accent not reset: %d %q", rec.Code, settings.Load().Accent) + } + if boot := lookServe(srv, "GET", "/boot.js", "").Body.String(); strings.Contains(boot, "lookCSS") || !strings.Contains(boot, `"look":","`) { + t.Fatalf("boot.js still draws a look: %s", boot) + } +} + +// Whatever colour is picked, the accent drawn reads as text on the +// theme's background and cards, and the text on it reads too. +func TestAccentReadable(t *testing.T) { + re := regexp.MustCompile(`--accent:(#[0-9a-f]{6});--accent-soft:(#[0-9a-f]{6});--accent-fg:(#[0-9a-f]{6})`) + for _, pick := range []string{"#ffffff", "#000000", "#ffff00", "#00ff00", "#0d9488", "#2563eb", "#ea580c", "#52525b", "#808080", "#1a1a1e", "#f4f4f6"} { + c, _ := parseHex(pick) + for _, dark := range []bool{false, true} { + m := re.FindStringSubmatch(accentVars(c, dark)) + if m == nil { + t.Fatalf("%s: %s", pick, accentVars(c, dark)) + } + a, _ := parseHex(m[1]) + fg, _ := parseHex(m[3]) + bgs := []rgb{lightBg, white} + if dark { + bgs = []rgb{darkBg, darkCard} + } + for _, bg := range bgs { + if r := contrast(a, bg); r < 4.4 { + t.Errorf("%s dark=%v: accent %s on %s is %.2f:1", pick, dark, m[1], bg.hex(), r) + } + } + if r := contrast(a, fg); r < 4.4 { + t.Errorf("%s dark=%v: text %s on accent %s is %.2f:1", pick, dark, m[3], m[1], r) + } + } + } + // a colour that reads already is drawn as picked + c, _ := parseHex("#2563eb") + if got := accentVars(c, false); !strings.HasPrefix(got, "--accent:#2563eb;") { + t.Fatalf("a readable blue was changed: %s", got) + } +} + +// A picture behind the pages is saved under magpie's folder, served back, +// drawn under a veil by boot.js, and removed with its file; what isn't a +// picture is refused. +func TestWallpaper(t *testing.T) { + srv := appearanceHome(t) + img := tinyPNG(t) + body, _ := json.Marshal(map[string][]byte{"data": img}) + rec := lookServe(srv, "POST", "/api/appearance/wallpaper", string(body)) + if rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + var got struct { + Wallpaper int64 `json:"wallpaper"` + } + if json.Unmarshal(rec.Body.Bytes(), &got); got.Wallpaper == 0 || settings.Load().Wallpaper != got.Wallpaper { + t.Fatalf("answered %d, saved %d", got.Wallpaper, settings.Load().Wallpaper) + } + if b, err := os.ReadFile(settings.WallpaperPath()); err != nil || !bytes.Equal(b, img) { + t.Fatalf("file: %v", err) + } + if !strings.HasPrefix(settings.WallpaperPath(), settings.Dir()) { + t.Fatalf("%s is not under %s", settings.WallpaperPath(), settings.Dir()) + } + if r := lookServe(srv, "GET", "/api/appearance/wallpaper", ""); r.Code != http.StatusOK || r.Header().Get("Content-Type") != "image/png" || !bytes.Equal(r.Body.Bytes(), img) { + t.Fatalf("served %d %s", r.Code, r.Header().Get("Content-Type")) + } + boot := lookServe(srv, "GET", "/boot.js", "").Body.String() + if !strings.Contains(boot, "/api/appearance/wallpaper?v=") || !strings.Contains(boot, "color-mix(in srgb,var(--bg) 84%") || !strings.Contains(boot, "body:not(.panel)") { + t.Fatalf("boot.js draws no picture: %s", boot) + } + // /api/appearance/css says the same, for a page whose settings changed + var css struct{ CSS, Key string } + if json.Unmarshal(lookServe(srv, "GET", "/api/appearance/css", "").Body.Bytes(), &css); !strings.Contains(css.CSS, "/api/appearance/wallpaper?v=") || css.Key != lookKey(settings.Load()) { + t.Fatalf("css: %+v", css) + } + // a save from Settings keeps it + if rec := lookServe(srv, "POST", "/api/settings", `{"theme":"dark","lang":"en"}`); rec.Code != http.StatusOK || settings.Load().Wallpaper != got.Wallpaper { + t.Fatalf("Settings' save dropped the picture: %d", rec.Code) + } + // not a picture, or nothing: refused, the picture kept + for _, bad := range [][]byte{[]byte(""), []byte("hi"), {}} { + b, _ := json.Marshal(map[string][]byte{"data": bad}) + if rec := lookServe(srv, "POST", "/api/appearance/wallpaper", string(b)); rec.Code == http.StatusOK { + t.Fatalf("%q was taken", bad) + } + } + if b, _ := os.ReadFile(settings.WallpaperPath()); !bytes.Equal(b, img) || settings.Load().Wallpaper != got.Wallpaper { + t.Fatal("a refused picture replaced the one saved") + } + // too big: refused before it is read whole + big := append(append([]byte{}, img...), make([]byte, maxWallpaper)...) + b, _ := json.Marshal(map[string][]byte{"data": big}) + if rec := lookServe(srv, "POST", "/api/appearance/wallpaper", string(b)); rec.Code == http.StatusOK { + t.Fatal("a picture over 16 MB was taken") + } + // removed: the file goes, nothing is drawn + if rec := lookServe(srv, "POST", "/api/appearance/wallpaper", `{"remove":true}`); rec.Code != http.StatusOK || settings.Load().Wallpaper != 0 { + t.Fatalf("remove: %d %s", rec.Code, rec.Body) + } + if _, err := os.Stat(settings.WallpaperPath()); !os.IsNotExist(err) { + t.Fatalf("the file stayed: %v", err) + } + if boot := lookServe(srv, "GET", "/boot.js", "").Body.String(); strings.Contains(boot, "wallpaper?v=") { + t.Fatalf("boot.js still draws a picture: %s", boot) + } + if r := lookServe(srv, "GET", "/api/appearance/wallpaper", ""); r.Code != http.StatusNotFound { + t.Fatalf("a removed picture is served: %d", r.Code) + } +} + +// A stamp whose file is gone (settings from another computer) draws no +// picture: the page would show its colour over nothing. +func TestWallpaperStampWithoutFile(t *testing.T) { + appearanceHome(t) + if css := lookCSS(settings.Settings{Wallpaper: 1}); css != "" { + t.Fatalf("drawn without a file: %s", css) + } + if css := lookCSS(settings.Settings{}); css != "" { + t.Fatalf("magpie's own look drew: %s", css) + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 2946c1df5..23e716f1e 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3211,6 +3211,19 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .row.pref .tray-windows { flex: 0 1 auto; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; min-width: 0; max-width: 55%; } .row.pref .tray-windows .proto.pick { max-width: 100%; margin-left: 0; } .row.pref .tray-windows .proto.pick > span { overflow: hidden; text-overflow: ellipsis; } +/* Accent color and Background image (appearance.js): a row of swatches, + the chosen one ringed; the last is a colour of the reader's own */ +.accent-pick { flex: 0 1 auto; display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; margin-left: auto; min-width: 0; } +.accent-pick .swatch { position: relative; flex: none; width: 18px; height: 18px; padding: 0; border: 0; border-radius: 50%; background: var(--sw); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .12); cursor: default; transition: box-shadow .15s ease, transform .12s var(--ease-out); } +.accent-pick .swatch.on { box-shadow: 0 0 0 2px var(--bg), 0 0 0 3.5px var(--sw); } +.accent-pick .swatch:active { transform: scale(.92); } +.accent-pick .swatch:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +/* not yet chosen, the own colour is an empty ring with a plus */ +.accent-pick .swatch.own:not(.on) { background: none; box-shadow: inset 0 0 0 1.5px var(--line); } +.accent-pick .swatch.own:not(.on)::after { content: "+"; position: absolute; inset: 0; display: grid; place-items: center; font-size: 13px; line-height: 1; color: var(--muted); } +.accent-pick .swatch.own input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; border: 0; padding: 0; cursor: default; } +.wall-pick { display: flex; align-items: center; gap: 8px; margin-left: auto; } +.wall-pick .wall-thumb { width: 40px; height: 26px; border-radius: 5px; object-fit: cover; box-shadow: inset 0 0 0 1px var(--line), 0 0 0 .5px var(--line); } .pop.proto-menu { width: 262px; max-height: min(360px, 70vh); overflow-y: auto; overscroll-behavior: contain; padding: 4px; border: 1px solid var(--line); display: grid; gap: 1px; } .proto-menu .pm-head { padding: 6px 8px 5px; font-size: 11px; color: var(--muted); } .proto-menu .pm-item { display: flex; align-items: flex-start; gap: 7px; width: 100%; padding: 6px 8px 7px; border: 0; border-radius: 7px; background: none; color: var(--fg); font: inherit; text-align: left; cursor: default; outline: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 667cf70e0..2c65aa169 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -19564,6 +19564,9 @@ function applyPrefs(s, rate) { // tooltip says which mode it was drawn in for (const b of document.querySelectorAll(".quota-curve:not(.balance-curve)")) b.title = quotaCurveTitle(); } + // an accent or picture of the user's own (appearance.go), when not the one drawn + const look = (s.accent || "") + "," + (s.wallpaper || ""); + if (look !== (applyPrefs.look ??= window.bootPrefs?.look ?? ",")) applyPrefs.look = look, import("./appearance.js").then(() => lookPaint(), () => {}); applyPrefs.ready = true; // accounts hidden while personal data is masked, until chosen otherwise window.hideAccounts?.follow(!!s.redactPersonal); @@ -20047,12 +20050,7 @@ function renderSettings() { prefsBase = keep; renderFonts(s); $("#themeSegs").replaceChildren(segs(THEMES.map(([id, name]) => [id, t(name)]), s.theme, (theme) => savePrefs({ ...keep, theme }))); - $("#colorblindSegs").title = t("Colorblind-safe chart colors, and each allowance window's line in a dash of its own"); - $("#colorblindSegs").replaceChildren(segsOO(s.colorblind, (v) => savePrefs({ ...keep, colorblind: v }))); - $("#reduceMotionSegs").title = t("Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy"); - $("#reduceMotionSegs").replaceChildren(segsOO(s.reduceMotion, (v) => savePrefs({ ...keep, reduceMotion: v }))); - $("#birdSegs").title = t("magpie's bird hops on what is still loading; Off keeps it away, and magpie stops looking for it"); - $("#birdSegs").replaceChildren(segsOO(!s.noBird, (v) => savePrefs({ ...keep, noBird: !v }))); + window.drawLook ? drawLook(s, keep) : import("./appearance.js").then(() => drawLook(s, keep), () => {}); renderLangPick(s, keep); renderGatewayMode(s); window.renderNavPages ? renderNavPages() : import("./navpages.js").then(() => renderNavPages(), () => {}); @@ -22834,7 +22832,7 @@ function dockChoice(s) { // prefsKeep is what the settings page sends of s, all of it each time. function prefsKeep(s) { - return { theme: s.theme, colorblind: !!s.colorblind, reduceMotion: !!s.reduceMotion, noBird: !!s.noBird, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, dockNever: !!s.dockNever, lightweight: s.lightweight, keepAwake: !!s.keepAwake, keepAwakeDisplay: !!s.keepAwakeDisplay, noWSLAgents: !!s.noWSLAgents, quitNoAsk: !!s.quitNoAsk, restoreOnQuit: !!s.restoreOnQuit, proxy: s.proxy || "", pluginProxy: s.pluginProxy || "", updateProxy: s.updateProxy || "", updateSource: s.updateSource || "", + return { theme: s.theme, accent: s.accent || "", colorblind: !!s.colorblind, reduceMotion: !!s.reduceMotion, noBird: !!s.noBird, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, dockNever: !!s.dockNever, lightweight: s.lightweight, keepAwake: !!s.keepAwake, keepAwakeDisplay: !!s.keepAwakeDisplay, noWSLAgents: !!s.noWSLAgents, quitNoAsk: !!s.quitNoAsk, restoreOnQuit: !!s.restoreOnQuit, proxy: s.proxy || "", pluginProxy: s.pluginProxy || "", updateProxy: s.updateProxy || "", updateSource: s.updateSource || "", sessionTerminal: s.sessionTerminal || "", uiFont: s.uiFont || null, codeFont: s.codeFont || null, otel: s.otel || {}, diff --git a/internal/gui/assets/appearance.js b/internal/gui/assets/appearance.js new file mode 100644 index 000000000..7fd0c30f0 --- /dev/null +++ b/internal/gui/assets/appearance.js @@ -0,0 +1,110 @@ +// Settings › General's look (CHENGJIAHEGOXIS on X): an accent colour of +// the reader's own and a picture behind the window's pages, beside the +// Colorblind, Reduce motion and Loading bird rows. The stylesheet that +// draws the look is the server's (appearance.go): boot.js puts it in +// before the first paint, and lookPaint takes it again once it changed. +// app.js imports this when Settings draws or the look changed, so it +// weighs nothing on the core. + +// the presets: magpie's own first, then a few quiet ones +const ACCENTS = () => [["", t("Default"), "#4f46e5"], ["#2563eb", t("Blue")], ["#0d9488", t("Teal")], ["#16a34a", t("Green")], ["#ea580c", t("Orange")], ["#db2777", t("Pink")], ["#52525b", t("Graphite")]]; + +window.lookPaint = async function () { + try { + const r = await (await fetch("/api/appearance/css")).json(); + let st = document.getElementById("lookCSS"); + if (!st) document.head.append((st = Object.assign(document.createElement("style"), { id: "lookCSS" }))); + st.textContent = r.css || ""; + // the accent is in the panel's tint and the title bar too + if (typeof tintPanel == "function") tintPanel(0); + } catch { /* the look stays as drawn */ } +}; + +window.drawLook = function (s, keep) { + $("#colorblindSegs").title = t("Colorblind-safe chart colors, and each allowance window's line in a dash of its own"); + $("#colorblindSegs").replaceChildren(segsOO(s.colorblind, (v) => savePrefs({ ...keep, colorblind: v }))); + $("#reduceMotionSegs").title = t("Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy"); + $("#reduceMotionSegs").replaceChildren(segsOO(s.reduceMotion, (v) => savePrefs({ ...keep, reduceMotion: v }))); + $("#birdSegs").title = t("magpie's bird hops on what is still loading; Off keeps it away, and magpie stops looking for it"); + $("#birdSegs").replaceChildren(segsOO(!s.noBird, (v) => savePrefs({ ...keep, noBird: !v }))); + drawAccent(s, keep); + drawWallpaper(s); +}; + +function drawAccent(s, keep) { + const box = $("#accentPick"); + if (!box) return; + const now = (s.accent || "").toLowerCase(); + const pick = (v) => savePrefs({ ...keep, accent: v }); + const swatch = (v, name, color) => { + const b = el("button", "swatch" + (v === now ? " on" : "")); + b.type = "button"; + b.setAttribute("role", "radio"); + b.setAttribute("aria-checked", String(v === now)); + b.title = name; + b.setAttribute("aria-label", name); + b.dataset.accent = v; + b.style.setProperty("--sw", color || v); + b.onclick = () => v !== now && pick(v); + return b; + }; + const presets = ACCENTS(); + const list = presets.map(([v, name, color]) => swatch(v, name, color)); + // a colour of the reader's own, from the system's colour picker + const mine = now && !presets.some(([v]) => v === now); + const own = el("label", "swatch own" + (mine ? " on" : "")); + own.title = t("Custom color"); + own.setAttribute("aria-label", own.title); + own.setAttribute("role", "radio"); + own.setAttribute("aria-checked", String(!!mine)); + if (mine) own.style.setProperty("--sw", now); + const input = el("input"); + input.type = "color"; + input.value = mine ? now : "#4f46e5"; + input.tabIndex = -1; + // the picker reports as the reader drags; the choice is saved when it closes + input.onchange = () => input.value.toLowerCase() !== now && pick(input.value.toLowerCase()); + own.tabIndex = 0; + own.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); input.click(); } }; + own.append(input); + box.replaceChildren(...list, own); +} + +function drawWallpaper(s) { + const box = $("#wallpaperPick"); + if (!box) return; + const file = el("input"); + file.type = "file"; + file.accept = "image/png,image/jpeg,image/gif,image/webp"; + file.hidden = true; + const send = async (body) => { + try { + prefs = await api("appearance/wallpaper", body); + if (state) state.settings = prefs; + applyPrefs(prefs); + renderSettings(); + } catch (e) { statusErr(e); } + }; + file.onchange = async () => { + const f = file.files[0]; + if (!f) return; + if (f.size > 16 << 20) { statusErr(new Error(t("A background image is 16 MB at most"))); return; } + // as base64 in JSON: the app's web view drops a File sent as the body + const bytes = new Uint8Array(await f.arrayBuffer()); + let bin = ""; + for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + send({ data: btoa(bin) }); + }; + const choose = el("button", "text", s.wallpaper ? t("Change") : t("Choose…")); + choose.type = "button"; + choose.onclick = () => file.click(); + if (!s.wallpaper) { box.replaceChildren(choose, file); return; } + const thumb = el("img", "wall-thumb"); + thumb.alt = ""; + thumb.src = "/api/appearance/wallpaper?v=" + s.wallpaper; + thumb.onerror = () => thumb.remove(); // a stamp whose file is gone (another computer's settings) + const remove = el("button", "text", t("Remove")); + remove.type = "button"; + remove.onclick = () => send({ remove: true }); + box.replaceChildren(thumb, choose, remove, file); +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d67bcd575..69fb123f5 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3929,6 +3929,16 @@ const I18N = { "Unavailable app ({id})": "应用不可用({id})", "Appearance": "外观", "Colorblind mode": "色盲模式", + "Accent color": "强调色", + "Background image": "背景图片", + "Custom color": "自定义颜色", + "Blue": "蓝色", + "Teal": "青色", + "Green": "绿色", + "Orange": "橙色", + "Pink": "粉色", + "Graphite": "石墨", + "A background image is 16 MB at most": "背景图片最大 16 MB", "Reduce motion": "减弱动态效果", "Loading bird": "加载时的喜鹊", "magpie's bird hops on what is still loading; Off keeps it away, and magpie stops looking for it": "magpie 的喜鹊会在还在加载的内容上跳来跳去;关闭后它不再出现,magpie 也不再为它盯着页面", @@ -9080,6 +9090,16 @@ const I18N = { "Unavailable app ({id})": "應用不可用({id})", "Appearance": "外觀", "Colorblind mode": "色盲模式", + "Accent color": "強調色", + "Background image": "背景圖片", + "Custom color": "自訂顏色", + "Blue": "藍色", + "Teal": "青色", + "Green": "綠色", + "Orange": "橙色", + "Pink": "粉紅色", + "Graphite": "石墨", + "A background image is 16 MB at most": "背景圖片最大 16 MB", "Reduce motion": "減少動態效果", "Loading bird": "載入時的喜鵲", "magpie's bird hops on what is still loading; Off keeps it away, and magpie stops looking for it": "magpie 的喜鵲會在還在載入的內容上跳來跳去;關閉後它不再出現,magpie 也不再為它盯著頁面", @@ -14246,6 +14266,16 @@ const I18N = { "Unavailable app ({id})": "利用できないアプリ({id})", "Appearance": "外観", "Colorblind mode": "色覚サポート", + "Accent color": "アクセントカラー", + "Background image": "背景画像", + "Custom color": "カスタムカラー", + "Blue": "ブルー", + "Teal": "ティール", + "Green": "グリーン", + "Orange": "オレンジ", + "Pink": "ピンク", + "Graphite": "グラファイト", + "A background image is 16 MB at most": "背景画像は 16 MB までです", "Reduce motion": "視差効果を減らす", "Loading bird": "読み込み中のカササギ", "magpie's bird hops on what is still loading; Off keeps it away, and magpie stops looking for it": "読み込み中の部分の上で magpie のカササギが跳ねます。オフにすると現れず、magpie もそのための監視をやめます", @@ -19421,6 +19451,16 @@ const I18N = { "Unavailable app ({id})": "Nicht verfügbare App ({id})", "Appearance": "Darstellung", "Colorblind mode": "Farbenblind-Modus", + "Accent color": "Akzentfarbe", + "Background image": "Hintergrundbild", + "Custom color": "Eigene Farbe", + "Blue": "Blau", + "Teal": "Petrol", + "Green": "Grün", + "Orange": "Orange", + "Pink": "Pink", + "Graphite": "Graphit", + "A background image is 16 MB at most": "Ein Hintergrundbild ist höchstens 16 MB groß", "Reduce motion": "Bewegung reduzieren", "Loading bird": "Elster beim Laden", "magpie's bird hops on what is still loading; Off keeps it away, and magpie stops looking for it": "magpies Elster hüpft über das, was noch lädt; Aus hält sie fern, und magpie hört auf, danach Ausschau zu halten", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 5aefe4fcd..eb4e767ad 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -173,6 +173,14 @@