diff --git a/CHANGELOG.md b/CHANGELOG.md index bdb62ac..832eedb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ Format based on [Keep a Changelog](https://keepachangelog.com/); versioning follows [SemVer](https://semver.org/). +## [Unreleased] + +### Fixed +- **Blur rendered solid black on Windows 11.** The classic blur-behind accent is drawn black by Windows 11 (measured on build 26300), whatever the tint. On Windows 11 Blur now uses the acrylic backdrop, and its strength lightens or darkens the glass (that backdrop takes its brightness from the tint colour and ignores the alpha). Windows 10 keeps the classic blur. + +### Changed +- **The settings window is now native Windows** (real Win32 controls with the TaskGlass icon) instead of a web page, so there is no Edge window or local server any more. The live preview is drawn in-app with real blur, and shows the maximized and per-app looks and the hidden-icons flyout. The maximized rule has its own tab. + ## [1.2.1] - 2026-11-20 ### Fixed diff --git a/cmd/taskglass/resource_windows_amd64.syso b/cmd/taskglass/resource_windows_amd64.syso index da7e458..7e125a7 100644 Binary files a/cmd/taskglass/resource_windows_amd64.syso and b/cmd/taskglass/resource_windows_amd64.syso differ diff --git a/cmd/taskglass/taskglass.manifest b/cmd/taskglass/taskglass.manifest index ab28287..b7d9882 100644 --- a/cmd/taskglass/taskglass.manifest +++ b/cmd/taskglass/taskglass.manifest @@ -2,6 +2,12 @@ TaskGlass + + + + + + diff --git a/go.mod b/go.mod index 319678c..1430290 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,12 @@ go 1.26.7 require ( fyne.io/systray v1.12.2 + github.com/lxn/walk v0.0.0-20210112085537-c389da54e794 + github.com/lxn/win v0.0.0-20210218163916-a377121e959e golang.org/x/sys v0.50.0 ) -require github.com/godbus/dbus/v5 v5.1.0 // indirect +require ( + github.com/godbus/dbus/v5 v5.1.0 // indirect + gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirect +) diff --git a/go.sum b/go.sum index ae0ebec..6b86fb3 100644 --- a/go.sum +++ b/go.sum @@ -2,5 +2,12 @@ fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA= fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/lxn/walk v0.0.0-20210112085537-c389da54e794 h1:NVRJ0Uy0SOFcXSKLsS65OmI1sgCCfiDUPj+cwnH7GZw= +github.com/lxn/walk v0.0.0-20210112085537-c389da54e794/go.mod h1:E23UucZGqpuUANJooIbHWCufXvOcT6E7Stq81gU+CSQ= +github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc= +github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk= +golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +gopkg.in/Knetic/govaluate.v3 v3.0.0 h1:18mUyIt4ZlRlFZAAfVetz4/rzlJs9yhN+U02F4u1AOc= +gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E= diff --git a/graphify-out/.graphify_labels.json b/graphify-out/.graphify_labels.json index 53b26d9..10ba7d6 100644 --- a/graphify-out/.graphify_labels.json +++ b/graphify-out/.graphify_labels.json @@ -9,10 +9,10 @@ "7": "opacity", "8": "config.schema.json", "9": "Changelog", - "10": "theme", + "10": "tray_icon", "11": "PULL_REQUEST_TEMPLATE.md", "12": "definitions", - "13": "Config", + "13": "preview.go", "14": "assets.go", "15": "bug_report.md", "16": "feature_request.md", @@ -27,7 +27,7 @@ "25": "poll_ms", "26": "refresh_ms", "27": "surfaces", - "28": "xaml_fix", + "28": "opacity", "29": "T", "30": "Architecture", "31": "render-assets.ps1", @@ -40,16 +40,12 @@ "38": "Contributing", "39": "Security Policy", "40": "default", - "41": "main.go", + "41": "apps", "42": "enabled", "43": "hotkey", "44": "enum", - "45": "anchor_windows.go", - "46": "Server", - "47": "exe", + "45": "theme", + "46": "window", "48": "autostart_windows.go", - "49": "tray_icon", - "50": "language", - "51": "properties", - "52": "locale_other.go" + "50": "language" } diff --git a/graphify-out/.graphify_labels.json.sig b/graphify-out/.graphify_labels.json.sig index 12534e9..e8b1c49 100644 --- a/graphify-out/.graphify_labels.json.sig +++ b/graphify-out/.graphify_labels.json.sig @@ -1 +1 @@ -{"0": "5076d5ac64ef5c4a", "1": "b64346c57c2f1370", "2": "33ff8415b4a61bba", "3": "01646dff01d2eb7e", "4": "8eda15899afbea06", "5": "d91d8c7e6614d2e4", "6": "5f1178d3b76d5916", "7": "c3edf3c38080d85c", "8": "7c8d94ab6376b921", "9": "7fe8c816be42994d", "10": "43dd470eba70e8b2", "11": "e0f13635f45c650b", "12": "277e559f4d0e1ba6", "13": "89b36edeac3661ed", "14": "6c7a71fed0eb24b5", "15": "ec76c5b024eab860", "16": "37bcee490d34fb1d", "17": "5c97800323607746", "18": "136e8401d4dcd739", "19": "5dbe09da18834400", "20": "b8b416d32d64abd5", "21": "6e7b82d0387bf16d", "22": "a0e1e2546c3370b0", "23": "a309b6ae1fe8f288", "24": "420dd9e70a20e9ac", "25": "c36fef69ae3bd6c5", "26": "e9dfc248ad6fcedc", "27": "b8e36120f4e5b47a", "28": "43b67b0ff2e57329", "29": "3c5c92f0728e499a", "30": "4cbef3533d917f67", "31": "39e69bcdefe2b0d2", "32": "804482094d693c22", "33": "077458ac008cc4d9", "34": "77bc2d977d7ff4cd", "35": "13af2a57728b14e4", "36": "bb6ec3da677724b3", "37": "4c1831b02af7bd53", "38": "268b36fafa333572", "39": "89111ec01d66aeef", "40": "a6d5a524b6f14c57", "41": "9346c9771bed4f8d", "42": "25b2731804072e95", "43": "4249983e8612bb1d", "44": "0baabc23a0122bf6", "45": "44ec9eeee4b329e7", "46": "751cd197468d3622", "47": "ab47fb02a9b2717a", "48": "a5b30f9d71bf9f82", "49": "d041a87ea2070ac4", "50": "58627c65df2a80a1", "51": "5259f23670b0c110", "52": "7984419eb8b2f465"} \ No newline at end of file +{"0": "5076d5ac64ef5c4a", "1": "b64346c57c2f1370", "2": "6bef3ac583d4f42c", "3": "01646dff01d2eb7e", "4": "df681840d16ff3d5", "5": "6bda37dc8cb09c04", "6": "5f1178d3b76d5916", "7": "a38ebed4de8f78eb", "8": "7c8d94ab6376b921", "9": "0ea3b56aede6e75a", "10": "952491af3b1e9f78", "11": "e0f13635f45c650b", "12": "c2f6f3578481b87d", "13": "f920c17e32bfb614", "14": "6c7a71fed0eb24b5", "15": "ec76c5b024eab860", "16": "37bcee490d34fb1d", "17": "5c97800323607746", "18": "4974e3d5715a769b", "19": "5dbe09da18834400", "20": "b8b416d32d64abd5", "21": "6e7b82d0387bf16d", "22": "a0e1e2546c3370b0", "23": "a309b6ae1fe8f288", "24": "420dd9e70a20e9ac", "25": "c36fef69ae3bd6c5", "26": "e9dfc248ad6fcedc", "27": "b8e36120f4e5b47a", "28": "029966ca5faa5a2a", "29": "6f1828727aec4f13", "30": "4cbef3533d917f67", "31": "39e69bcdefe2b0d2", "32": "804482094d693c22", "33": "077458ac008cc4d9", "34": "77bc2d977d7ff4cd", "35": "13af2a57728b14e4", "36": "f88db8f9d07d6c49", "37": "4c1831b02af7bd53", "38": "268b36fafa333572", "39": "89111ec01d66aeef", "40": "a6d5a524b6f14c57", "41": "99012460fbf55554", "42": "25b2731804072e95", "43": "4249983e8612bb1d", "44": "4c1a85cc953cf600", "45": "568df988db03bae3", "46": "e93ca5dce766a4ee", "48": "a5b30f9d71bf9f82", "50": "58627c65df2a80a1"} \ No newline at end of file diff --git a/graphify-out/GRAPH_REPORT.md b/graphify-out/GRAPH_REPORT.md index 1ac082b..c32fa10 100644 --- a/graphify-out/GRAPH_REPORT.md +++ b/graphify-out/GRAPH_REPORT.md @@ -1,16 +1,16 @@ # Graph Report - TaskGlass (2026-11-20) ## Corpus Check -- 50 files · ~97,994 words +- 49 files · ~99,000 words - Verdict: corpus is large enough that graph structure adds value. ## Summary -- 609 nodes · 1055 edges · 53 communities (48 shown, 5 thin omitted) -- Extraction: 92% EXTRACTED · 8% INFERRED · 0% AMBIGUOUS · INFERRED: 87 edges (avg confidence: 0.8) +- 679 nodes · 1289 edges · 49 communities (44 shown, 5 thin omitted) +- Extraction: 91% EXTRACTED · 9% INFERRED · 0% AMBIGUOUS · INFERRED: 112 edges (avg confidence: 0.8) - Token cost: 0 input · 0 output ## Graph Freshness -- Built from commit: `c8f79e7d` +- Built from commit: `05ca89d4` - Run `git rev-parse HEAD` and compare to check if the graph is stale. - Run `graphify update .` after code changes (no API cost). @@ -25,10 +25,10 @@ - opacity - config.schema.json - Changelog -- theme +- tray_icon - PULL_REQUEST_TEMPLATE.md - definitions -- Config +- preview.go - github.com/AnderCMD/TaskGlass - properties - Watcher @@ -39,7 +39,7 @@ - poll_ms - refresh_ms - surfaces -- xaml_fix +- opacity - T - Architecture - render-assets.ps1 @@ -50,29 +50,26 @@ - Contributing - Security Policy - default -- main.go +- apps - enabled - hotkey - enum -- anchor_windows.go -- Server -- exe +- theme +- window - autostart_windows.go -- tray_icon - language -- properties ## God Nodes (most connected - your core abstractions) -1. `App` - 38 edges -2. `T()` - 38 edges -3. `Config` - 35 edges -4. `Controller` - 21 edges -5. `Default()` - 19 edges -6. `Parse()` - 17 edges -7. `Server` - 17 edges -8. `main()` - 13 edges -9. `logf_()` - 12 edges -10. `Context` - 11 edges +1. `T()` - 41 edges +2. `App` - 38 edges +3. `window` - 35 edges +4. `Config` - 33 edges +5. `Controller` - 21 edges +6. `Render()` - 18 edges +7. `Parse()` - 17 edges +8. `Default()` - 16 edges +9. `Appearance` - 15 edges +10. `window` - 15 edges ## Surprising Connections (you probably didn't know these) - `main()` --calls--> `Default()` [INFERRED] @@ -83,13 +80,13 @@ cmd/taskglass/main_windows.go → internal/config/config.go - `main()` --calls--> `Save()` [INFERRED] cmd/taskglass/main_windows.go → internal/config/config.go -- `main()` --calls--> `Parse()` [INFERRED] - tools/genicon/main.go → internal/config/config.go +- `watchForQuit()` --references--> `App` [EXTRACTED] + cmd/taskglass/main_windows.go → internal/app/app_windows.go ## Import Cycles - None detected. -## Communities (53 total, 5 thin omitted) +## Communities (49 total, 5 thin omitted) ### Community 0 - "main" Cohesion: 0.26 @@ -100,52 +97,52 @@ Cohesion: 0.18 Nodes (10): Before you start, Contributing, Features, How it works, Install, License, Limitations and safety, Roadmap (+2 more) ### Community 2 - "winapi_windows.go" -Cohesion: 0.12 -Nodes (28): TestToPolicy(), HWND, Logger, Time, New(), toPolicy(), className(), cloaked() (+20 more) +Cohesion: 0.11 +Nodes (31): blurPolicy(), TestToPolicy(), HWND, Logger, Time, lighten(), New(), toPolicy() (+23 more) ### Community 3 - "hotkey_enabled" Cohesion: 0.50 Nodes (4): default, description, type, hotkey_enabled ### Community 4 - "App" -Cohesion: 0.06 -Nodes (27): App, host, menuItems, Options, panicGuard, Int32, check(), Bool (+19 more) +Cohesion: 0.07 +Nodes (25): App, host, menuItems, Options, panicGuard, Int32, check(), Bool (+17 more) ### Community 5 - "Controller" Cohesion: 0.07 -Nodes (25): Attr, Handler, GUID, Duration, TrayProbe(), Handle, SetCallWndProcHook(), Available() (+17 more) +Nodes (28): Attr, GUID, Handler, Duration, TaskbarAnchor(), Duration, TrayProbe(), Unhook() (+20 more) ### Community 6 - "tap.c" Cohesion: 0.07 Nodes (72): DWORD, HINSTANCE, HRESULT, HSTRING, IClassFactory, IDispatchedHandler_, Inst, InstanceHandle (+64 more) ### Community 7 - "opacity" -Cohesion: 0.25 -Nodes (11): $ref, properties, type, $ref, properties, appearance, properties, $ref (+3 more) +Cohesion: 0.19 +Nodes (14): $ref, properties, type, $ref, properties, appearance, rule, $ref (+6 more) ### Community 8 - "config.schema.json" Cohesion: 0.29 Nodes (6): additionalProperties, description, $id, $schema, title, type ### Community 9 - "Changelog" -Cohesion: 0.11 -Nodes (18): [1.0.0] - 2026-11-17, [1.0.1] - 2026-11-17, [1.1.0] - 2026-11-18, [1.1.1] - 2026-11-18, Added, Added, Added, Changed (+10 more) +Cohesion: 0.08 +Nodes (23): [1.0.0] - 2026-11-17, [1.0.1] - 2026-11-17, [1.1.0] - 2026-11-18, [1.1.1] - 2026-11-18, [1.2.0] - 2026-11-20, [1.2.1] - 2026-11-20, Added, Added (+15 more) -### Community 10 - "theme" +### Community 10 - "tray_icon" Cohesion: 0.24 -Nodes (10): theme, default, description, enum, type, enum, auto, color (+2 more) +Nodes (10): tray_icon, enum, default, description, enum, type, auto, color (+2 more) ### Community 12 - "definitions" -Cohesion: 0.20 -Nodes (10): description, pattern, type, definitions, color, opacity, description, maximum (+2 more) +Cohesion: 0.25 +Nodes (8): description, type, description, pattern, type, definitions, accent, color -### Community 13 - "Config" -Cohesion: 0.09 -Nodes (16): Accent, Appearance, AppRule, Config, Percent, Rule, Surface, Surfaces (+8 more) +### Community 13 - "preview.go" +Cohesion: 0.19 +Nodes (30): at(), blur(), boxH(), boxV(), clamp8(), Color(), drawFlyout(), drawTaskbarContents() (+22 more) ### Community 18 - "properties" -Cohesion: 0.22 -Nodes (9): description, $ref, properties, maximized, $schema, version, type, const (+1 more) +Cohesion: 0.15 +Nodes (13): description, $ref, properties, maximized, $schema, version, xaml_fix, type (+5 more) ### Community 19 - "Watcher" Cohesion: 0.33 @@ -175,13 +172,13 @@ Nodes (6): refresh_ms, default, description, maximum, minimum, type Cohesion: 0.25 Nodes (8): surfaces, tray_overflow, additionalProperties, description, properties, type, description, $ref -### Community 28 - "xaml_fix" -Cohesion: 0.50 -Nodes (4): xaml_fix, default, description, type +### Community 28 - "opacity" +Cohesion: 0.40 +Nodes (5): opacity, description, maximum, minimum, type ### Community 29 - "T" -Cohesion: 0.09 -Nodes (44): Lang, Default(), Load(), Parse(), TestAppRuleMatching(), TestAutoColorFollowsTheme(), TestDefaultIsValid(), TestExplicitFalseSticks() (+36 more) +Cohesion: 0.06 +Nodes (57): Accent, Appearance, AppRule, Config, Percent, Rule, Surface, Surfaces (+49 more) ### Community 30 - "Architecture" Cohesion: 0.18 @@ -192,8 +189,8 @@ Cohesion: 0.18 Nodes (10): Antes de empezar, Características, Contribuir, Cómo funciona, Hoja de ruta, Instalación, Licencia, Limitaciones y seguridad (+2 more) ### Community 36 - "items" -Cohesion: 0.22 -Nodes (9): description, items, maxItems, type, additionalProperties, required, type, apps (+1 more) +Cohesion: 0.18 +Nodes (11): items, description, minLength, pattern, type, additionalProperties, properties, required (+3 more) ### Community 37 - "Configuration" Cohesion: 0.22 @@ -211,9 +208,9 @@ Nodes (4): Reporting a vulnerability, Scope, Security Policy, Supported versions Cohesion: 0.50 Nodes (4): additionalProperties, description, type, default -### Community 41 - "main.go" -Cohesion: 0.83 -Nodes (3): entry, main(), writeICO() +### Community 41 - "apps" +Cohesion: 0.50 +Nodes (4): description, maxItems, type, apps ### Community 42 - "enabled" Cohesion: 0.25 @@ -224,56 +221,44 @@ Cohesion: 0.50 Nodes (4): default, description, type, hotkey ### Community 44 - "enum" -Cohesion: 0.22 -Nodes (9): description, enum, type, accent, acrylic, blur, clear, normal (+1 more) - -### Community 45 - "anchor_windows.go" -Cohesion: 0.40 -Nodes (5): Duration, TaskbarAnchor(), msg, point, wndClassEx +Cohesion: 0.33 +Nodes (6): enum, acrylic, blur, clear, normal, opaque -### Community 46 - "Server" -Cohesion: 0.20 -Nodes (12): HandlerFunc, Handler, loopbackHost(), New(), writeErr(), writeJSON(), Listener, Mutex (+4 more) +### Community 45 - "theme" +Cohesion: 0.50 +Nodes (4): theme, default, description, type -### Community 47 - "exe" -Cohesion: 0.40 -Nodes (5): description, minLength, pattern, type, exe +### Community 46 - "window" +Cohesion: 0.06 +Nodes (41): Bitmap, CheckBox, ComboBox, Composite, ImageView, Container, window, unsafeSizeofChooseColor() (+33 more) ### Community 48 - "autostart_windows.go" Cohesion: 0.38 Nodes (8): clearDisabled(), command(), Enabled(), Repair(), sameCommand(), Set(), TestCommandIsPlainQuotedPath(), TestSameCommandRecognisesLegacyDoubledBackslashes() -### Community 49 - "tray_icon" -Cohesion: 0.50 -Nodes (4): tray_icon, default, description, type - ### Community 50 - "language" Cohesion: 0.29 Nodes (7): default, description, enum, type, language, en, es -### Community 51 - "properties" -Cohesion: 0.50 -Nodes (4): rule, additionalProperties, properties, type - ## Knowledge Gaps -- **162 isolated node(s):** `$schema`, `$id`, `title`, `description`, `type` (+157 more) +- **165 isolated node(s):** `$schema`, `$id`, `title`, `description`, `type` (+160 more) These have ≤1 connection - possible missing edges or undocumented components. - **5 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes. ## Suggested Questions _Questions this graph is uniquely positioned to answer:_ -- **Why does `App` connect `App` to `main`, `winapi_windows.go`, `Controller`, `Config`, `Server`, `Watcher`?** - _High betweenness centrality (0.095) - this node is a cross-community bridge._ -- **Why does `Config` connect `Config` to `winapi_windows.go`, `App`, `T`, `Server`?** - _High betweenness centrality (0.072) - this node is a cross-community bridge._ -- **Why does `properties` connect `properties` to `hotkey_enabled`, `items`, `config.schema.json`, `default`, `enabled`, `hotkey`, `theme`, `tray_icon`, `language`, `enum`, `taskbars`, `debounce_ms`, `poll_ms`, `refresh_ms`, `surfaces`, `xaml_fix`?** - _High betweenness centrality (0.050) - this node is a cross-community bridge._ +- **Why does `App` connect `App` to `main`, `winapi_windows.go`, `Controller`, `window`, `Watcher`, `T`?** + _High betweenness centrality (0.082) - this node is a cross-community bridge._ +- **Why does `Config` connect `T` to `winapi_windows.go`, `App`, `window`?** + _High betweenness centrality (0.077) - this node is a cross-community bridge._ +- **Why does `T()` connect `T` to `winapi_windows.go`, `App`, `Controller`, `preview.go`, `window`, `autostart_windows.go`?** + _High betweenness centrality (0.052) - this node is a cross-community bridge._ +- **Are the 2 inferred relationships involving `T()` (e.g. with `.syncMenu()` and `.t()`) actually correct?** + _`T()` has 2 INFERRED edges - model-reasoned connections that need verification._ - **What connects `$schema`, `$id`, `title` to the rest of the system?** - _162 weakly-connected nodes found - possible documentation gaps or missing edges._ + _165 weakly-connected nodes found - possible documentation gaps or missing edges._ - **Should `winapi_windows.go` be split into smaller, more focused modules?** - _Cohesion score 0.11764705882352941 - nodes in this community are weakly interconnected._ + _Cohesion score 0.10810810810810811 - nodes in this community are weakly interconnected._ - **Should `App` be split into smaller, more focused modules?** - _Cohesion score 0.061955965181771634 - nodes in this community are weakly interconnected._ -- **Should `Controller` be split into smaller, more focused modules?** - _Cohesion score 0.07342995169082125 - nodes in this community are weakly interconnected._ \ No newline at end of file + _Cohesion score 0.06779661016949153 - nodes in this community are weakly interconnected._ \ No newline at end of file diff --git a/graphify-out/graph.html b/graphify-out/graph.html index 58c52f1..125708e 100644 --- a/graphify-out/graph.html +++ b/graphify-out/graph.html @@ -63,12 +63,12 @@

Communities

-
609 nodes · 1055 edges · 53 communities
+
679 nodes · 1289 edges · 49 communities
- - diff --git a/internal/settings/locale_other.go b/internal/settings/locale_other.go deleted file mode 100644 index 79666b2..0000000 --- a/internal/settings/locale_other.go +++ /dev/null @@ -1,5 +0,0 @@ -//go:build !windows - -package settings - -func systemLocale() string { return "" } diff --git a/internal/settings/locale_windows.go b/internal/settings/locale_windows.go deleted file mode 100644 index f06b05a..0000000 --- a/internal/settings/locale_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build windows - -package settings - -import "github.com/AnderCMD/TaskGlass/internal/i18n" - -func systemLocale() string { return i18n.SystemLocale() } diff --git a/internal/settings/server.go b/internal/settings/server.go deleted file mode 100644 index 2e46c40..0000000 --- a/internal/settings/server.go +++ /dev/null @@ -1,231 +0,0 @@ -// Package settings serves TaskGlass' graphical settings window. -// -// The window is a small web page (embedded in the executable) served on a -// loopback-only port and shown in an app-style browser window, so it needs no -// GUI toolkit, no extra DLLs and no CGO. Every request must carry a random -// per-run token and a loopback Host header, so neither other local programs -// nor web pages (DNS rebinding) can change the settings. -package settings - -import ( - "crypto/rand" - "crypto/subtle" - _ "embed" - "encoding/hex" - "encoding/json" - "errors" - "io" - "net" - "net/http" - "strings" - "sync" - "time" - - "github.com/AnderCMD/TaskGlass/internal/config" - "github.com/AnderCMD/TaskGlass/internal/i18n" -) - -//go:embed index.html -var indexHTML string - -// Host is what the settings window needs from the running application. -type Host interface { - Config() config.Config - // Apply validates, saves and applies a whole configuration. - Apply(config.Config) error - AutostartEnabled() bool - SetAutostart(on bool) error - OpenFile(which string) error // "config" or "log" - Version() string - ConfigPath() string - XamlAvailable() bool -} - -// Server is the loopback HTTP server behind the settings window. -type Server struct { - host Host - token string - - mu sync.Mutex - ln net.Listener - hs *http.Server -} - -// New creates a Server. It does not listen until URL is first called. -func New(h Host) *Server { - var b [16]byte - _, _ = rand.Read(b[:]) - return &Server{host: h, token: hex.EncodeToString(b[:])} -} - -// URL starts the server if needed and returns the address of the settings page. -func (s *Server) URL() (string, error) { - s.mu.Lock() - defer s.mu.Unlock() - if s.ln == nil { - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return "", err - } - s.ln = ln - s.hs = &http.Server{Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second} - go s.hs.Serve(ln) - } - return "http://" + s.ln.Addr().String() + "/?t=" + s.token, nil -} - -// Close stops the server. -func (s *Server) Close() { - s.mu.Lock() - defer s.mu.Unlock() - if s.hs != nil { - _ = s.hs.Close() - s.hs, s.ln = nil, nil - } -} - -// Handler returns the HTTP handler (exported for tests). -func (s *Server) Handler() http.Handler { - mux := http.NewServeMux() - mux.HandleFunc("GET /{$}", s.index) - mux.HandleFunc("GET /api/state", s.guard(s.state)) - mux.HandleFunc("POST /api/config", s.guard(s.saveConfig)) - mux.HandleFunc("POST /api/defaults", s.guard(s.defaults)) - mux.HandleFunc("POST /api/autostart", s.guard(s.autostart)) - mux.HandleFunc("POST /api/open", s.guard(s.open)) - return mux -} - -func loopbackHost(h string) bool { - host, _, err := net.SplitHostPort(h) - if err != nil { - host = h - } - return host == "127.0.0.1" || host == "localhost" || host == "[::1]" || host == "::1" -} - -func (s *Server) tokenOK(t string) bool { - return subtle.ConstantTimeCompare([]byte(t), []byte(s.token)) == 1 -} - -func (s *Server) index(w http.ResponseWriter, r *http.Request) { - if !loopbackHost(r.Host) || !s.tokenOK(r.URL.Query().Get("t")) { - http.Error(w, "forbidden", http.StatusForbidden) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; img-src data:") - w.Header().Set("X-Content-Type-Options", "nosniff") - _, _ = io.WriteString(w, strings.Replace(indexHTML, "__TOKEN__", s.token, 1)) -} - -func (s *Server) guard(next http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if !loopbackHost(r.Host) || !s.tokenOK(r.Header.Get("X-TaskGlass-Token")) { - http.Error(w, "forbidden", http.StatusForbidden) - return - } - if r.Method == http.MethodPost { - if o := r.Header.Get("Origin"); o != "" && !loopbackHost(strings.TrimPrefix(strings.TrimPrefix(o, "http://"), "https://")) { - http.Error(w, "forbidden", http.StatusForbidden) - return - } - r.Body = http.MaxBytesReader(w, r.Body, 1<<20) - } - w.Header().Set("Cache-Control", "no-store") - next(w, r) - } -} - -type stateResp struct { - Config config.Config `json:"config"` - Defaults config.Config `json:"defaults"` - Autostart bool `json:"autostart"` - Version string `json:"version"` - ConfigPath string `json:"configPath"` - XamlAvailable bool `json:"xamlAvailable"` - SystemLang i18n.Lang `json:"systemLang"` - I18n map[i18n.Lang]map[string]string `json:"i18n"` - MaxApps int `json:"maxApps"` -} - -func (s *Server) state(w http.ResponseWriter, _ *http.Request) { - tbl := map[i18n.Lang]map[string]string{} - for _, l := range i18n.Langs { - tbl[l] = i18n.Table(l) - } - writeJSON(w, http.StatusOK, stateResp{ - Config: s.host.Config(), - Defaults: config.Default(), - Autostart: s.host.AutostartEnabled(), - Version: s.host.Version(), - ConfigPath: s.host.ConfigPath(), - XamlAvailable: s.host.XamlAvailable(), - SystemLang: i18n.Resolve(i18n.Auto, systemLocale()), - I18n: tbl, - MaxApps: config.MaxAppRules, - }) -} - -func (s *Server) saveConfig(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - if err != nil { - writeErr(w, http.StatusBadRequest, err) - return - } - c, err := config.Parse(body) // strict: unknown fields and bad values are rejected - if err != nil { - writeErr(w, http.StatusUnprocessableEntity, err) - return - } - if err := s.host.Apply(c); err != nil { - writeErr(w, http.StatusInternalServerError, err) - return - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "config": s.host.Config()}) -} - -func (s *Server) defaults(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, config.Default()) -} - -func (s *Server) autostart(w http.ResponseWriter, r *http.Request) { - var req struct { - On bool `json:"on"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeErr(w, http.StatusBadRequest, err) - return - } - if err := s.host.SetAutostart(req.On); err != nil { - writeErr(w, http.StatusInternalServerError, err) - return - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "autostart": s.host.AutostartEnabled()}) -} - -func (s *Server) open(w http.ResponseWriter, r *http.Request) { - var req struct { - What string `json:"what"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil || (req.What != "config" && req.What != "log") { - writeErr(w, http.StatusBadRequest, errors.New("what must be config or log")) - return - } - if err := s.host.OpenFile(req.What); err != nil { - writeErr(w, http.StatusInternalServerError, err) - return - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func writeJSON(w http.ResponseWriter, code int, v any) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(code) - _ = json.NewEncoder(w).Encode(v) -} - -func writeErr(w http.ResponseWriter, code int, err error) { - writeJSON(w, code, map[string]any{"ok": false, "error": err.Error()}) -} diff --git a/internal/settings/server_test.go b/internal/settings/server_test.go deleted file mode 100644 index e9e0741..0000000 --- a/internal/settings/server_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package settings - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/AnderCMD/TaskGlass/internal/config" -) - -type fakeHost struct { - cfg config.Config - auto bool -} - -func (f *fakeHost) Config() config.Config { return f.cfg } -func (f *fakeHost) Apply(c config.Config) error { - f.cfg = c - return nil -} -func (f *fakeHost) AutostartEnabled() bool { return f.auto } -func (f *fakeHost) SetAutostart(on bool) error { f.auto = on; return nil } -func (f *fakeHost) OpenFile(string) error { return nil } -func (f *fakeHost) Version() string { return "test" } -func (f *fakeHost) ConfigPath() string { return "cfg.json" } -func (f *fakeHost) XamlAvailable() bool { return true } - -func do(h http.Handler, method, path, host, token, body string) *httptest.ResponseRecorder { - r := httptest.NewRequest(method, path, strings.NewReader(body)) - r.Host = host - if token != "" { - r.Header.Set("X-TaskGlass-Token", token) - } - w := httptest.NewRecorder() - h.ServeHTTP(w, r) - return w -} - -func TestAuthAndHostChecks(t *testing.T) { - f := &fakeHost{cfg: config.Default()} - s := New(f) - h := s.Handler() - - if w := do(h, "GET", "/api/state", "127.0.0.1:1", "", ""); w.Code != 403 { - t.Errorf("no token: %d", w.Code) - } - if w := do(h, "GET", "/api/state", "127.0.0.1:1", "wrong", ""); w.Code != 403 { - t.Errorf("bad token: %d", w.Code) - } - if w := do(h, "GET", "/api/state", "evil.example.com", s.token, ""); w.Code != 403 { - t.Errorf("rebinding host: %d", w.Code) - } - if w := do(h, "GET", "/?t=wrong", "127.0.0.1:1", "", ""); w.Code != 403 { - t.Errorf("page with bad token: %d", w.Code) - } - w := do(h, "GET", "/?t="+s.token, "127.0.0.1:1", "", "") - if w.Code != 200 || !strings.Contains(w.Body.String(), s.token) || strings.Contains(w.Body.String(), "__TOKEN__") { - t.Errorf("page not served with token: %d", w.Code) - } -} - -func TestStateAndSave(t *testing.T) { - f := &fakeHost{cfg: config.Default()} - s := New(f) - h := s.Handler() - - w := do(h, "GET", "/api/state", "127.0.0.1:1", s.token, "") - if w.Code != 200 { - t.Fatalf("state: %d %s", w.Code, w.Body) - } - var st struct { - I18n map[string]map[string]string `json:"i18n"` - } - if err := json.Unmarshal(w.Body.Bytes(), &st); err != nil || st.I18n["es"]["ui.save"] != "Guardar" || st.I18n["en"]["ui.save"] != "Save" { - t.Fatalf("i18n tables missing: %v", err) - } - - c := config.Default() - c.Default.Accent = config.AccentAcrylic - c.Default.Opacity = 55 - c.Language = "es" - body, _ := json.Marshal(c) - if w := do(h, "POST", "/api/config", "127.0.0.1:1", s.token, string(body)); w.Code != 200 { - t.Fatalf("save: %d %s", w.Code, w.Body) - } - if f.cfg.Default.Accent != config.AccentAcrylic || f.cfg.Language != "es" { - t.Errorf("config not applied: %+v", f.cfg.Default) - } - - // Invalid values and unknown keys are rejected without touching the config. - bad := strings.Replace(string(body), `"acrylic"`, `"rainbow"`, 1) - if w := do(h, "POST", "/api/config", "127.0.0.1:1", s.token, bad); w.Code != 422 { - t.Errorf("invalid accent accepted: %d", w.Code) - } - if w := do(h, "POST", "/api/config", "127.0.0.1:1", s.token, `{"bogus":1}`); w.Code != 422 { - t.Errorf("unknown key accepted: %d", w.Code) - } - if f.cfg.Default.Accent != config.AccentAcrylic { - t.Error("rejected save changed the config") - } - - if w := do(h, "POST", "/api/autostart", "127.0.0.1:1", s.token, `{"on":true}`); w.Code != 200 || !f.auto { - t.Errorf("autostart: %d", w.Code) - } - if w := do(h, "POST", "/api/open", "127.0.0.1:1", s.token, `{"what":"/etc/passwd"}`); w.Code != 400 { - t.Errorf("open accepted arbitrary path: %d", w.Code) - } -} diff --git a/internal/settings/window_windows.go b/internal/settings/window_windows.go deleted file mode 100644 index 02a9220..0000000 --- a/internal/settings/window_windows.go +++ /dev/null @@ -1,66 +0,0 @@ -//go:build windows - -package settings - -import ( - "os" - "os/exec" - "path/filepath" - "syscall" - - "golang.org/x/sys/windows/registry" -) - -// edgePath finds Microsoft Edge (shipped with Windows 10/11). -func edgePath() string { - for _, root := range []registry.Key{registry.LOCAL_MACHINE, registry.CURRENT_USER} { - k, err := registry.OpenKey(root, `SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe`, registry.QUERY_VALUE) - if err != nil { - continue - } - v, _, err := k.GetStringValue("") - k.Close() - if err == nil { - if _, err := os.Stat(v); err == nil { - return v - } - } - } - for _, env := range []string{"ProgramFiles(x86)", "ProgramFiles"} { - if base := os.Getenv(env); base != "" { - p := filepath.Join(base, `Microsoft\Edge\Application\msedge.exe`) - if _, err := os.Stat(p); err == nil { - return p - } - } - } - return "" -} - -// Show opens url in a standalone app-style window (no tabs or address bar). -// It uses Edge with a private profile so it neither joins the user's browser -// session nor shows first-run prompts; if Edge is missing it falls back to the -// default browser. -func Show(url, profileDir string) error { - if edge := edgePath(); edge != "" { - cmd := exec.Command(edge, - "--app="+url, - "--user-data-dir="+profileDir, - "--window-size=1240,820", - "--no-first-run", - "--no-default-browser-check", - "--disable-extensions", - ) - cmd.SysProcAttr = &syscall.SysProcAttr{} - if err := cmd.Start(); err == nil { - go cmd.Wait() - return nil - } - } - cmd := exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", url) - if err := cmd.Start(); err != nil { - return err - } - go cmd.Wait() - return nil -} diff --git a/internal/taskbar/policy_windows_test.go b/internal/taskbar/policy_windows_test.go index 5f6cbbd..c65b1a5 100644 --- a/internal/taskbar/policy_windows_test.go +++ b/internal/taskbar/policy_windows_test.go @@ -19,7 +19,7 @@ func TestToPolicy(t *testing.T) { {"normal disables", config.Appearance{Accent: config.AccentNormal, Color: "#112233"}, false, policy{winapi.AccentDisabled, 0}}, {"clear never alpha 0", config.Appearance{Accent: config.AccentClear, Color: "#000000", Opacity: 0}, false, policy{winapi.AccentEnableTransparent, 0x01000000}}, {"opaque full", config.Appearance{Accent: config.AccentOpaque, Color: "#112233", Opacity: 100}, false, policy{winapi.AccentEnableGradient, 0xFF332211}}, - {"blur half, BGR order", config.Appearance{Accent: config.AccentBlur, Color: "#FF0000", Opacity: 50}, false, policy{winapi.AccentEnableBlurBehind, 0x7F0000FF}}, + {"blur half, BGR order", config.Appearance{Accent: config.AccentBlur, Color: "#FF0000", Opacity: 50}, false, blurPolicy(0x7F0000FF)}, {"acrylic", config.Appearance{Accent: config.AccentAcrylic, Color: "#202020", Opacity: 60}, false, policy{winapi.AccentEnableAcrylicBlurBG, 0x99202020}}, {"auto colour, dark", config.Appearance{Accent: config.AccentOpaque, Color: "auto", Opacity: 100}, false, policy{winapi.AccentEnableGradient, 0xFF1C1C1C}}, {"auto colour, light", config.Appearance{Accent: config.AccentOpaque, Color: "auto", Opacity: 100}, true, policy{winapi.AccentEnableGradient, 0xFFF3F3F3}}, @@ -32,3 +32,11 @@ func TestToPolicy(t *testing.T) { }) } } + +// blurPolicy is what blur resolves to on this machine. +func blurPolicy(classic uint32) policy { + if blurViaAcrylic { + return policy{winapi.AccentEnableAcrylicBlurBG, 0x014040FF} // #FF0000 mixed 25% to white, BGR + } + return policy{winapi.AccentEnableBlurBehind, classic} +} diff --git a/internal/taskbar/taskbar_windows.go b/internal/taskbar/taskbar_windows.go index eea50c4..152e062 100644 --- a/internal/taskbar/taskbar_windows.go +++ b/internal/taskbar/taskbar_windows.go @@ -121,6 +121,16 @@ func (m *Manager) restoreOne(h winapi.HWND) { winapi.Redraw(h) } +// blurViaAcrylic is true where the classic blur-behind accent is unusable +// (Windows 11, build 22000 and later). +var blurViaAcrylic = winapi.BlurNeedsAcrylic() + +// lighten mixes a colour towards white by t (0..1). +func lighten(r, g, b uint8, t float64) (uint8, uint8, uint8) { + f := func(c uint8) uint8 { return uint8(float64(c) + (255-float64(c))*t + 0.5) } + return f(r), f(g), f(b) +} + // toPolicy converts an Appearance to an accent state and 0xAABBGGRR colour. func toPolicy(ap config.Appearance, light bool) policy { if ap.Accent == config.AccentNormal { @@ -136,6 +146,18 @@ func toPolicy(ap config.Appearance, light bool) policy { alpha = 1 // alpha 0 renders opaque black on some builds } case config.AccentBlur: + if blurViaAcrylic { + // Windows 11 draws the classic blur-behind accent as solid black, so + // blur is produced by the acrylic backdrop. That backdrop takes its + // brightness from the tint colour and ignores the alpha, so the + // strength is applied by mixing the tint towards white: 0 is a light + // frosted glass, 100 the full tint colour. + st = winapi.AccentEnableAcrylicBlurBG + mix := 0.5 * (1 - float64(ap.Opacity)/100) + r, g, b = lighten(r, g, b, mix) + alpha = 1 + break + } st = winapi.AccentEnableBlurBehind if alpha == 0 { alpha = 1 // same quirk as clear: a fully zero tint can render opaque black diff --git a/internal/ui/tabs_windows.go b/internal/ui/tabs_windows.go new file mode 100644 index 0000000..dae4ec1 --- /dev/null +++ b/internal/ui/tabs_windows.go @@ -0,0 +1,491 @@ +//go:build windows + +package ui + +import ( + "fmt" + "os/exec" + "time" + "unsafe" + + "github.com/lxn/walk" + "github.com/lxn/win" + + "github.com/AnderCMD/TaskGlass/internal/config" + "github.com/AnderCMD/TaskGlass/internal/i18n" + "github.com/AnderCMD/TaskGlass/internal/preview" + "github.com/AnderCMD/TaskGlass/internal/winapi" +) + +var ( + languageChoices = []choice{{"auto", "language.auto"}, {"en", "language.en"}, {"es", "language.es"}} + themeChoices = []choice{{"auto", "theme.auto"}, {"light", "theme.light"}, {"dark", "theme.dark"}} + taskbarChoices = []choice{{"all", "general.taskbars.all"}, {"primary", "general.taskbars.primary"}} + trayChoices = []choice{{"auto", "general.trayIcon.auto"}, {"color", "general.trayIcon.color"}, {"light", "general.trayIcon.light"}, {"dark", "general.trayIcon.dark"}} + logChoices = []choice{{"debug", ""}, {"info", ""}, {"warn", ""}, {"error", ""}} +) + +func unsafeSizeofChooseColor() uintptr { return unsafe.Sizeof(win.CHOOSECOLOR{}) } + +// page adds a scrolling tab page and returns the container to fill. +func (w *window) page(key string) walk.Container { + tp, _ := walk.NewTabPage() + tp.SetLayout(walk.NewVBoxLayout()) + if l, ok := tp.Layout().(*walk.BoxLayout); ok { + l.SetMargins(walk.Margins{}) + } + w.text(func(s string) { tp.SetTitle(s) }, key) + _ = w.tabs.Pages().Add(tp) + body, _ := walk.NewComposite(tp) + l := walk.NewVBoxLayout() + l.SetMargins(walk.Margins{HNear: 14, VNear: 12, HFar: 14, VFar: 12}) + l.SetSpacing(6) + body.SetLayout(l) + return body +} + +func (w *window) buildTabs(parent walk.Container) { + w.tabs, _ = walk.NewTabWidget(parent) + w.tabs.SetAlignment(walk.AlignHFarVNear) + + // --- General + g := w.page("ui.tab.general") + w.enabled = w.check(g, "general.enabled", func() bool { return w.cfg.Enabled }, func(v bool) { w.cfg.Enabled = v }) + w.help(g, "general.enabled.help") + w.autostart = w.check(g, "general.autostart", func() bool { return w.auto }, func(v bool) { w.auto = v }) + w.help(g, "general.autostart.help") + w.caption(g, "general.language") + w.language = w.combo(g, languageChoices, func() string { return string(w.cfg.Language) }, func(id string) { w.cfg.Language = i18n.Lang(id) }) + w.caption(g, "general.theme") + w.themeC = w.combo(g, themeChoices, func() string { return string(w.cfg.Theme) }, func(id string) { w.cfg.Theme = config.Theme(id) }) + w.help(g, "general.theme.help") + w.caption(g, "general.taskbars") + w.taskbars = w.combo(g, taskbarChoices, func() string { return string(w.cfg.Taskbars) }, func(id string) { w.cfg.Taskbars = config.Taskbars(id) }) + w.caption(g, "general.trayIcon") + w.trayIcon = w.combo(g, trayChoices, func() string { return string(w.cfg.TrayIcon) }, func(id string) { w.cfg.TrayIcon = config.TrayIcon(id) }) + w.caption(g, "general.hotkey") + w.hotkeyOn = w.check(g, "general.hotkey.enable", func() bool { return w.cfg.HotkeyEnabled }, func(v bool) { w.cfg.HotkeyEnabled = v }) + w.hotkey, _ = walk.NewLineEdit(g) + w.hotkey.TextChanged().Attach(func() { + if w.syncing { + return + } + w.cfg.Hotkey = w.hotkey.Text() + w.changed() + }) + w.hotkeyWarn, _ = walk.NewLabel(g) + w.help(g, "general.hotkey.help") + walk.NewVSpacer(g) + + // --- Appearance + a := w.page("ui.tab.appearance") + w.def = w.newAppEditor(a, func() *config.Appearance { return &w.cfg.Default }) + w.caption(a, "appear.preset") + pr := hbox(a, 6) + for _, p := range []struct { + key string + accent config.Accent + op config.Percent + }{ + {"appear.preset.glass", config.AccentClear, 0}, + {"appear.preset.frosted", config.AccentBlur, 35}, + {"appear.preset.acrylic", config.AccentAcrylic, 55}, + {"appear.preset.solid", config.AccentOpaque, 100}, + } { + p := p + w.button(pr, p.key, func() { + w.cfg.Default.Accent, w.cfg.Default.Opacity = p.accent, p.op + w.pull() + w.changed() + }) + } + walk.NewHSpacer(pr) + w.xaml = w.check(a, "appear.xaml", func() bool { return w.cfg.XamlFix }, func(v bool) { w.cfg.XamlFix = v }) + w.help(a, "appear.xaml.help") + if !w.host.XamlAvailable() { + l, _ := walk.NewTextLabel(a) + w.text(func(s string) { l.SetText(s) }, "appear.xaml.missing") + } + w.help(a, "appear.accentNote") + walk.NewVSpacer(a) + + // --- Maximized window + m := w.page("ui.tab.maximized") + w.max = w.check(m, "appear.maxRule", func() bool { return w.cfg.Maximized.Enabled }, func(v bool) { w.cfg.Maximized.Enabled = v }) + w.help(m, "appear.maxRule.help") + w.maxGroup = vbox(m, walk.Margins{VNear: 6}, 6) + w.maxEd = w.newAppEditor(w.maxGroup, func() *config.Appearance { return &w.cfg.Maximized.Appearance }) + walk.NewVSpacer(m) + + // --- Hidden icons + t := w.page("ui.tab.tray") + w.flyOn = w.check(t, "tray.surface", func() bool { return w.cfg.Surfaces.TrayOverflow.Enabled }, func(v bool) { w.cfg.Surfaces.TrayOverflow.Enabled = v }) + w.help(t, "tray.surface.help") + w.caption(t, "tray.opacity") + w.flyOp, w.flyOpVal = w.slider(t, func() int { return int(w.cfg.Surfaces.TrayOverflow.Opacity) }, func(v int) { w.cfg.Surfaces.TrayOverflow.Opacity = config.Percent(v) }) + w.help(t, "tray.opacity.help") + walk.NewVSpacer(t) + + // --- Per app + p := w.page("ui.tab.apps") + w.help(p, "apps.help") + split := hbox(p, 14) + left := vbox(split, walk.Margins{}, 6) + w.appList, _ = walk.NewListBox(left) + w.appList.SetMinMaxSize(walk.Size{Width: 190, Height: 220}, walk.Size{Width: 240}) + w.appList.CurrentIndexChanged().Attach(func() { + if w.syncing { + return + } + w.pullApp() + }) + br := hbox(left, 6) + w.appAdd = w.button(br, "apps.add", func() { + w.cfg.Apps = append(w.cfg.Apps, config.AppRule{Appearance: config.Appearance{Accent: config.AccentOpaque, Color: config.ColorAuto, Opacity: 100}}) + w.rebuildApps(len(w.cfg.Apps) - 1) + w.changed() + w.appExe.SetFocus() + }) + w.appRemove = w.button(br, "apps.remove", func() { + if i := w.appList.CurrentIndex(); i >= 0 && i < len(w.cfg.Apps) { + w.cfg.Apps = append(w.cfg.Apps[:i], w.cfg.Apps[i+1:]...) + w.rebuildApps(i) + w.changed() + } + }) + w.appLimit, _ = walk.NewLabel(left) + w.appEditorBox = vbox(split, walk.Margins{}, 6) + w.appPick, _ = walk.NewLabel(w.appEditorBox) + w.text(func(s string) { w.appPick.SetText(s) }, "apps.pick") + w.caption(w.appEditorBox, "apps.exe") + w.appExe, _ = walk.NewLineEdit(w.appEditorBox) + w.appExe.TextChanged().Attach(func() { + if w.syncing { + return + } + if i := w.appList.CurrentIndex(); i >= 0 && i < len(w.cfg.Apps) { + w.cfg.Apps[i].Exe = w.appExe.Text() + w.refreshAppNames(i) + w.changed() + } + }) + w.appEd = w.newAppEditor(w.appEditorBox, func() *config.Appearance { + if i := w.appList.CurrentIndex(); i >= 0 && i < len(w.cfg.Apps) { + return &w.cfg.Apps[i].Appearance + } + return nil + }) + walk.NewVSpacer(w.appEditorBox) + split.Layout().(*walk.BoxLayout).SetStretchFactor(w.appEditorBox, 2) + + // --- Advanced + d := w.page("ui.tab.advanced") + w.help(d, "adv.help") + num := func(key string, min, max float64, get func() int, set func(int)) *walk.NumberEdit { + w.caption(d, key) + n, _ := walk.NewNumberEdit(d) + _ = n.SetRange(min, max) + _ = n.SetDecimals(0) + n.ValueChanged().Attach(func() { + if w.syncing { + return + } + set(int(n.Value())) + w.changed() + }) + return n + } + w.poll = num("adv.poll", 50, 10000, func() int { return w.cfg.PollMs }, func(v int) { w.cfg.PollMs = v }) + w.debounce = num("adv.debounce", 0, 1000, func() int { return w.cfg.DebounceMs }, func(v int) { w.cfg.DebounceMs = v }) + w.refresh = num("adv.refresh", 100, 60000, func() int { return w.cfg.RefreshMs }, func(v int) { w.cfg.RefreshMs = v }) + w.caption(d, "adv.log") + w.logLevel = w.combo(d, logChoices, func() string { return w.cfg.LogLevel }, func(id string) { w.cfg.LogLevel = id }) + ob := hbox(d, 8) + w.button(ob, "adv.openConfig", func() { _ = w.host.OpenFile("config") }) + w.button(ob, "adv.openLog", func() { _ = w.host.OpenFile("log") }) + walk.NewHSpacer(ob) + walk.NewVSpacer(d) + + // --- About + ab := w.page("ui.tab.about") + w.caption(ab, "about.version") + w.ver, _ = walk.NewLabel(ab) + w.ver.SetText("TaskGlass " + w.host.Version()) + w.help(ab, "about.license") + ll, _ := walk.NewLinkLabel(ab) + ll.SetText(`github.com/AnderCMD/TaskGlass`) + ll.LinkActivated().Attach(func(l *walk.LinkLabelLink) { + _ = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", l.URL()).Start() + }) + w.cfgPath, _ = walk.NewLabel(ab) + w.cfgPath.SetText(w.host.ConfigPath()) + walk.NewVSpacer(ab) +} + +func (w *window) buildPreview(parent walk.Container) { + col := vbox(parent, walk.Margins{}, 8) + col.SetAlignment(walk.AlignHNearVNear) + col.SetMinMaxSize(walk.Size{Width: previewW + 10}, walk.Size{Width: previewW + 40}) + w.caption(col, "ui.preview") + row := hbox(col, 8) + w.caption(row, "ui.scenario") + w.scenCombo, _ = walk.NewComboBox(row) + w.scenCombo.CurrentIndexChanged().Attach(func() { + if w.syncing { + return + } + if i := w.scenCombo.CurrentIndex(); i >= 0 { + w.scenarioIdx = i + w.render() + } + }) + w.view, _ = walk.NewImageView(col) + w.view.SetMode(walk.ImageViewModeIdeal) + w.view.SetMinMaxSize(walk.Size{Width: previewW, Height: previewH}, walk.Size{Width: previewW, Height: previewH}) + w.help(col, "ui.previewNote") + walk.NewVSpacer(col) +} + +func (w *window) buildFooter(parent walk.Container) { + f := hbox(parent, 8) + w.save = w.button(f, "ui.save", func() { w.saveNow() }) + w.revert = w.button(f, "ui.revert", func() { + w.cfg, w.auto = clone(w.saved), w.savedAuto + w.lang = i18n.Resolve(w.cfg.Language, i18n.SystemLocale()) + w.pull() + w.applyText() + w.afterChange() + }) + w.status, _ = walk.NewLabel(f) + walk.NewHSpacer(f) + w.reset = w.button(f, "ui.reset", func() { + if walk.MsgBox(w.mw, w.t("ui.title"), w.t("ui.resetConfirm"), walk.MsgBoxYesNo|walk.MsgBoxIconQuestion) != walk.DlgCmdYes { + return + } + w.cfg = norm(config.Default()) + w.lang = i18n.Resolve(w.cfg.Language, i18n.SystemLocale()) + w.pull() + w.applyText() + w.afterChange() + }) +} + +// ---- state ------------------------------------------------------------------ + +func (w *window) applyText() { + for _, f := range w.retext { + f() + } + title := w.t("ui.title") + if w.dirty() { + title += " *" + } + w.mw.SetTitle(title) + w.def.refresh() + w.maxEd.refresh() + w.appEd.refresh() + w.appLimit.SetText(fmt.Sprintf(w.t("apps.limit"), config.MaxAppRules)) +} + +// pull copies the whole draft config into the controls. +func (w *window) pull() { + w.syncing = true + c := w.cfg + w.enabled.SetChecked(c.Enabled) + w.autostart.SetChecked(w.auto) + selectID(w.language, languageChoices, string(c.Language)) + selectID(w.themeC, themeChoices, string(c.Theme)) + selectID(w.taskbars, taskbarChoices, string(c.Taskbars)) + selectID(w.trayIcon, trayChoices, string(c.TrayIcon)) + w.hotkeyOn.SetChecked(c.HotkeyEnabled) + _ = w.hotkey.SetText(c.Hotkey) + w.xaml.SetChecked(c.XamlFix) + w.xaml.SetEnabled(w.host.XamlAvailable()) + w.max.SetChecked(c.Maximized.Enabled) + w.flyOn.SetChecked(c.Surfaces.TrayOverflow.Enabled) + w.flyOp.SetValue(int(c.Surfaces.TrayOverflow.Opacity)) + w.flyOpVal.SetText(fmt.Sprintf("%d %%", c.Surfaces.TrayOverflow.Opacity)) + _ = w.poll.SetValue(float64(c.PollMs)) + _ = w.debounce.SetValue(float64(c.DebounceMs)) + _ = w.refresh.SetValue(float64(c.RefreshMs)) + selectID(w.logLevel, logChoices, c.LogLevel) + w.syncing = false + w.def.pull() + w.maxEd.pull() + w.rebuildApps(0) + w.afterChange() +} + +func (w *window) appNames() []string { + names := make([]string, len(w.cfg.Apps)) + for i, r := range w.cfg.Apps { + names[i] = r.Exe + if names[i] == "" { + names[i] = "…" + } + } + return names +} + +func (w *window) rebuildApps(sel int) { + w.syncing = true + _ = w.appList.SetModel(w.appNames()) + if sel >= len(w.cfg.Apps) { + sel = len(w.cfg.Apps) - 1 + } + w.appList.SetCurrentIndex(sel) + w.syncing = false + w.pullApp() + w.appAdd.SetEnabled(len(w.cfg.Apps) < config.MaxAppRules) +} + +// refreshAppNames updates the list captions while keeping the selection. +func (w *window) refreshAppNames(sel int) { + w.syncing = true + _ = w.appList.SetModel(w.appNames()) + w.appList.SetCurrentIndex(sel) + w.syncing = false +} + +func (w *window) pullApp() { + i := w.appList.CurrentIndex() + has := i >= 0 && i < len(w.cfg.Apps) + w.syncing = true + if has { + _ = w.appExe.SetText(w.cfg.Apps[i].Exe) + } else { + _ = w.appExe.SetText("") + } + w.syncing = false + w.appExe.SetEnabled(has) + w.appRemove.SetEnabled(has) + w.appPick.SetVisible(!has) + w.appEd.root.SetEnabled(has) + w.appEd.pull() + w.rebuildScenarios() + w.render() +} + +// changed runs after every edit made by the user. +func (w *window) changed() { + if l := i18n.Resolve(w.cfg.Language, i18n.SystemLocale()); l != w.lang { + w.lang = l + w.applyText() + } + w.afterChange() +} + +func (w *window) afterChange() { + w.maxGroup.SetEnabled(w.cfg.Maximized.Enabled) + w.def.refresh() + w.maxEd.refresh() + w.appEd.refresh() + valid := true + if _, _, err := config.ParseHotkey(w.cfg.Hotkey); err != nil { + valid = false + w.hotkeyWarn.SetText("⚠ " + w.t("ui.hotkeyInvalid")) + } else { + w.hotkeyWarn.SetText("") + } + d := w.dirty() + w.save.SetEnabled(d && valid) + w.revert.SetEnabled(d) + title := w.t("ui.title") + if d { + title += " *" + w.status.SetText("") + } + w.mw.SetTitle(title) + w.rebuildScenarios() + w.render() +} + +func (w *window) rebuildScenarios() { + var sc []scenario + sc = append(sc, scenario{label: w.t("ui.previewTaskbar"), ap: &w.cfg.Default}) + if w.cfg.Maximized.Enabled { + sc = append(sc, scenario{label: w.t("ui.previewMax"), maximized: true, ap: &w.cfg.Maximized.Appearance}) + } + for i := range w.cfg.Apps { + if w.cfg.Apps[i].Exe != "" { + sc = append(sc, scenario{label: fmt.Sprintf(w.t("ui.previewApp"), w.cfg.Apps[i].Exe), ap: &w.cfg.Apps[i].Appearance}) + } + } + w.scenarios = sc + if w.scenarioIdx >= len(sc) { + w.scenarioIdx = 0 + } + names := make([]string, len(sc)) + for i, s := range sc { + names[i] = s.label + } + w.syncing = true + _ = w.scenCombo.SetModel(names) + w.scenCombo.SetCurrentIndex(w.scenarioIdx) + w.syncing = false +} + +func (w *window) render() { + if len(w.scenarios) == 0 || w.view == nil { + return + } + sc := w.scenarios[w.scenarioIdx] + avail := w.host.XamlAvailable() + img := preview.Render(preview.Input{ + Scenario: preview.Scenario{Maximized: sc.maximized, Appearance: *sc.ap}, + Disabled: !w.cfg.Enabled, + Light: w.light(), + XamlFix: w.cfg.XamlFix && avail, + BlurViaAcrylic: winapi.BlurNeedsAcrylic(), + Flyout: w.cfg.Surfaces.TrayOverflow, + FlyoutActive: w.cfg.Enabled && w.cfg.XamlFix && w.cfg.Surfaces.TrayOverflow.Enabled && avail, + }, previewW, previewH) + bmp, err := walk.NewBitmapFromImage(img) + if err != nil { + return + } + _ = w.view.SetImage(bmp) + if w.bmp != nil { + w.bmp.Dispose() + } + w.bmp = bmp +} + +// saveNow applies the draft; it reports whether it succeeded. +func (w *window) saveNow() bool { + c := clone(w.cfg) + kept := c.Apps[:0] + for _, r := range c.Apps { + if r.Exe != "" { + kept = append(kept, r) + } + } + c.Apps = kept + if err := w.host.Apply(c); err != nil { + walk.MsgBox(w.mw, w.t("ui.title"), fmt.Sprintf(w.t("ui.saveFailed"), err.Error()), walk.MsgBoxOK|walk.MsgBoxIconError) + return false + } + if w.auto != w.savedAuto { + if err := w.host.SetAutostart(w.auto); err != nil { + walk.MsgBox(w.mw, w.t("ui.title"), fmt.Sprintf(w.t("ui.saveFailed"), err.Error()), walk.MsgBoxOK|walk.MsgBoxIconError) + return false + } + } + w.cfg = norm(w.host.Config()) + w.saved = clone(w.cfg) + w.auto = w.host.AutostartEnabled() + w.savedAuto = w.auto + w.pull() + w.status.SetText("✓ " + w.t("ui.saved")) + if w.toastTimer != nil { + w.toastTimer.Stop() + } + w.toastTimer = time.AfterFunc(2500*time.Millisecond, func() { + w.mw.Synchronize(func() { + if !w.dirty() { + w.status.SetText("") + } + }) + }) + return true +} diff --git a/internal/ui/ui_windows.go b/internal/ui/ui_windows.go new file mode 100644 index 0000000..5154a14 --- /dev/null +++ b/internal/ui/ui_windows.go @@ -0,0 +1,497 @@ +//go:build windows + +// Package ui is TaskGlass' native settings window: real Win32 controls (via +// walk) next to a live preview of the taskbar and the hidden-icons flyout. +// +// All windows live on one dedicated OS thread, as Win32 requires; Show may be +// called from any goroutine. +package ui + +import ( + "encoding/json" + "fmt" + "runtime" + "strings" + "sync" + "time" + + "github.com/lxn/walk" + "github.com/lxn/win" + + "github.com/AnderCMD/TaskGlass/internal/config" + "github.com/AnderCMD/TaskGlass/internal/i18n" + "github.com/AnderCMD/TaskGlass/internal/theme" + "github.com/AnderCMD/TaskGlass/internal/winapi" +) + +// Host is what the settings window needs from the running application. +type Host interface { + Config() config.Config + // Apply validates, saves and applies a whole configuration. + Apply(config.Config) error + AutostartEnabled() bool + SetAutostart(on bool) error + OpenFile(which string) error // "config" or "log" + Version() string + ConfigPath() string + XamlAvailable() bool +} + +// UI owns the settings window. +type UI struct { + host Host + + once sync.Once + req chan struct{} + + mu sync.Mutex + cur *window +} + +// New creates the UI; nothing is shown until Show. +func New(h Host) *UI { return &UI{host: h, req: make(chan struct{}, 1)} } + +// Show opens the settings window, or brings the open one to the front. +func (u *UI) Show() { + u.once.Do(func() { go u.loop() }) + u.mu.Lock() + cur := u.cur + u.mu.Unlock() + if cur != nil { + cur.mw.Synchronize(func() { + h := cur.mw.Handle() + win.ShowWindow(h, win.SW_RESTORE) + win.SetForegroundWindow(h) + }) + return + } + select { + case u.req <- struct{}{}: + default: + } +} + +func (u *UI) loop() { + runtime.LockOSThread() + for range u.req { + w, err := newWindow(u.host) + if err != nil { + continue + } + u.mu.Lock() + u.cur = w + u.mu.Unlock() + w.center() + w.mw.Show() + w.mw.Run() + w.dispose() + u.mu.Lock() + u.cur = nil + u.mu.Unlock() + } +} + +// ---- window --------------------------------------------------------------- + +const ( + previewW, previewH = 560, 300 + resIconID = 1 // the icon linked into taskglass.exe +) + +type scenario struct { + label string + maximized bool + ap *config.Appearance +} + +type window struct { + host Host + mw *walk.MainWindow + + cfg, saved config.Config + auto, savedAuto bool + lang i18n.Lang + systemLight bool + syncing bool + retext []func() + scenarios []scenario + scenarioIdx int + bmp *walk.Bitmap + toastTimer *time.Timer + closeConfirmed bool + + tabs *walk.TabWidget + pages []*walk.TabPage + enabled, autostart, hotkeyOn, xaml, max *walk.CheckBox + language, themeC, taskbars, trayIcon *walk.ComboBox + hotkey *walk.LineEdit + hotkeyWarn *walk.Label + def, maxEd *appEditor + maxGroup *walk.Composite + flyOn *walk.CheckBox + flyOp *walk.Slider + flyOpVal *walk.Label + appList *walk.ListBox + appExe *walk.LineEdit + appEd *appEditor + appEditorBox *walk.Composite + appAdd, appRemove *walk.PushButton + appLimit, appPick *walk.Label + poll, debounce, refresh *walk.NumberEdit + logLevel *walk.ComboBox + scenCombo *walk.ComboBox + view *walk.ImageView + save, revert, reset *walk.PushButton + status *walk.Label + ver, cfgPath *walk.Label +} + +func newWindow(h Host) (*window, error) { + w := &window{host: h, systemLight: theme.SystemIsLight()} + w.cfg = norm(h.Config()) + w.saved = clone(w.cfg) + w.auto = h.AutostartEnabled() + w.savedAuto = w.auto + w.lang = i18n.Resolve(w.cfg.Language, i18n.SystemLocale()) + + mw, err := walk.NewMainWindow() + if err != nil { + return nil, err + } + w.mw = mw + if ic, err := walk.NewIconFromResourceId(resIconID); err == nil { + mw.SetIcon(ic) + } + mw.SetMinMaxSize(walk.Size{Width: 1000, Height: 560}, walk.Size{}) + mw.SetSize(walk.Size{Width: 1080, Height: 580}) + root := walk.NewVBoxLayout() + root.SetMargins(walk.Margins{HNear: 12, VNear: 12, HFar: 12, VFar: 10}) + root.SetSpacing(10) + mw.SetLayout(root) + + body, _ := walk.NewComposite(mw) + bl := walk.NewHBoxLayout() + bl.SetMargins(walk.Margins{}) + bl.SetSpacing(14) + body.SetLayout(bl) + + w.buildTabs(body) + w.buildPreview(body) + bl.SetStretchFactor(w.tabs, 11) + + walk.NewVSpacer(mw) // keeps the footer at the bottom when the window grows + w.buildFooter(mw) + + mw.Closing().Attach(func(canceled *bool, _ walk.CloseReason) { + if w.dirty() && !w.closeConfirmed { + switch walk.MsgBox(mw, w.t("ui.title"), w.t("ui.closeUnsaved"), walk.MsgBoxYesNoCancel|walk.MsgBoxIconQuestion) { + case walk.DlgCmdYes: + if !w.saveNow() { + *canceled = true + } + case walk.DlgCmdCancel: + *canceled = true + } + } + }) + + w.pull() + w.applyText() + return w, nil +} + +func (w *window) center() { + sw := int(win.GetSystemMetrics(win.SM_CXSCREEN)) + sh := int(win.GetSystemMetrics(win.SM_CYSCREEN)) + b := w.mw.BoundsPixels() + w.mw.SetBoundsPixels(walk.Rectangle{X: (sw - b.Width) / 2, Y: (sh - b.Height) / 2, Width: b.Width, Height: b.Height}) +} + +func (w *window) dispose() { + if w.toastTimer != nil { + w.toastTimer.Stop() + } + if w.bmp != nil { + w.bmp.Dispose() + } + w.mw.Dispose() +} + +// ---- helpers -------------------------------------------------------------- + +func norm(c config.Config) config.Config { + if c.Apps == nil { + c.Apps = []config.AppRule{} + } + return c +} + +func clone(c config.Config) config.Config { + c.Apps = append([]config.AppRule{}, c.Apps...) + return c +} + +func (w *window) t(key string) string { return i18n.T(w.lang, key) } + +// text registers a setter that is re-run whenever the language changes. +func (w *window) text(set func(string), key string) { + f := func() { set(w.t(key)) } + w.retext = append(w.retext, f) + f() +} + +func (w *window) light() bool { return w.cfg.Theme.Light(w.systemLight) } + +func (w *window) dirty() bool { + a, _ := json.Marshal(w.cfg) + b, _ := json.Marshal(w.saved) + return string(a) != string(b) || w.auto != w.savedAuto +} + +func hexOf(r, g, b uint8) string { return fmt.Sprintf("#%02X%02X%02X", r, g, b) } + +func label(parent walk.Container, wrap bool) *walk.TextLabel { + l, _ := walk.NewTextLabel(parent) + _ = wrap + return l +} + +func vbox(parent walk.Container, m walk.Margins, spacing int) *walk.Composite { + c, _ := walk.NewComposite(parent) + l := walk.NewVBoxLayout() + l.SetMargins(m) + l.SetSpacing(spacing) + c.SetLayout(l) + return c +} + +func hbox(parent walk.Container, spacing int) *walk.Composite { + c, _ := walk.NewComposite(parent) + l := walk.NewHBoxLayout() + l.SetMargins(walk.Margins{}) + l.SetSpacing(spacing) + c.SetLayout(l) + return c +} + +// row adds "label ........ control" style rows; help is an optional dim line. +func (w *window) caption(parent walk.Container, key string) { + l, _ := walk.NewTextLabel(parent) + w.text(func(s string) { l.SetText(s) }, key) +} + +func (w *window) check(parent walk.Container, key string, get func() bool, set func(bool)) *walk.CheckBox { + cb, _ := walk.NewCheckBox(parent) + cb.SetAlignment(walk.AlignHNearVNear) + w.text(func(s string) { cb.SetText(s) }, key) + cb.CheckedChanged().Attach(func() { + if w.syncing { + return + } + set(cb.Checked()) + w.changed() + }) + return cb +} + +func (w *window) help(parent walk.Container, key string) *walk.TextLabel { + l, _ := walk.NewTextLabel(parent) + w.text(func(s string) { l.SetText(s) }, key) + return l +} + +type choice struct { + id string + key string +} + +// combo builds a ComboBox whose items are translated and re-translated on language change. +func (w *window) combo(parent walk.Container, items []choice, get func() string, set func(string)) *walk.ComboBox { + cb, _ := walk.NewComboBox(parent) + fill := func() { + w.syncing = true + names := make([]string, len(items)) + sel := -1 + for i, it := range items { + names[i] = it.id // raw label unless it has a translation key + if it.key != "" { + names[i] = w.t(it.key) + } + if it.id == get() { + sel = i + } + } + _ = cb.SetModel(names) + cb.SetCurrentIndex(sel) + w.syncing = false + } + w.retext = append(w.retext, fill) + cb.CurrentIndexChanged().Attach(func() { + if w.syncing { + return + } + if i := cb.CurrentIndex(); i >= 0 && i < len(items) { + set(items[i].id) + w.changed() + } + }) + return cb +} + +func selectID(cb *walk.ComboBox, items []choice, id string) { + for i, it := range items { + if it.id == id { + cb.SetCurrentIndex(i) + return + } + } +} + +func (w *window) slider(parent walk.Container, get func() int, set func(int)) (*walk.Slider, *walk.Label) { + row := hbox(parent, 8) + s, _ := walk.NewSlider(row) + s.SetRange(0, 100) + s.SetTracking(true) + val, _ := walk.NewLabel(row) + val.SetMinMaxSize(walk.Size{Width: 40}, walk.Size{Width: 40}) + s.ValueChanged().Attach(func() { + val.SetText(fmt.Sprintf("%d %%", s.Value())) + if w.syncing { + return + } + set(s.Value()) + w.changed() + }) + return s, val +} + +func (w *window) button(parent walk.Container, key string, click func()) *walk.PushButton { + b, _ := walk.NewPushButton(parent) + w.text(func(s string) { b.SetText(s) }, key) + b.Clicked().Attach(click) + return b +} + +// ---- appearance editor (accent, colour, strength) ------------------------- + +var accentChoices = func() []choice { + var out []choice + for _, a := range config.Accents { + out = append(out, choice{string(a), "accent." + string(a)}) + } + return out +}() + +type appEditor struct { + w *window + get func() *config.Appearance + root *walk.Composite + accent *walk.ComboBox + desc *walk.TextLabel + auto *walk.CheckBox + swatch *walk.Composite + hexLbl *walk.Label + pick *walk.PushButton + slider *walk.Slider + value *walk.Label + note *walk.TextLabel + sw *walk.SolidColorBrush +} + +func (w *window) newAppEditor(parent walk.Container, get func() *config.Appearance) *appEditor { + orig := get + get = func() *config.Appearance { // never nil: an unselected rule edits a throw-away copy + if ap := orig(); ap != nil { + return ap + } + return &config.Appearance{Accent: config.AccentClear, Color: config.ColorAuto} + } + e := &appEditor{w: w, get: get} + e.root = vbox(parent, walk.Margins{}, 6) + + w.caption(e.root, "appear.style") + e.accent = w.combo(e.root, accentChoices, func() string { return string(get().Accent) }, func(id string) { get().Accent = config.Accent(id) }) + e.desc, _ = walk.NewTextLabel(e.root) + e.accent.CurrentIndexChanged().Attach(func() { e.refresh() }) + + w.caption(e.root, "appear.color") + crow := hbox(e.root, 8) + e.auto = w.check(crow, "appear.colorAuto", func() bool { return strings.EqualFold(get().Color, config.ColorAuto) }, func(on bool) { + if on { + get().Color = config.ColorAuto + } else { + r, g, b := get().RGB(w.light()) + get().Color = hexOf(r, g, b) + } + }) + e.swatch, _ = walk.NewComposite(crow) + e.swatch.SetLayout(walk.NewHBoxLayout()) + e.swatch.SetMinMaxSize(walk.Size{Width: 28, Height: 22}, walk.Size{Width: 28, Height: 22}) + e.hexLbl, _ = walk.NewLabel(crow) + e.pick = w.button(crow, "appear.pickColor", func() { e.chooseColor() }) + walk.NewHSpacer(crow) + + w.caption(e.root, "appear.opacity") + e.slider, e.value = w.slider(e.root, func() int { return int(get().Opacity) }, func(v int) { get().Opacity = config.Percent(v) }) + e.note, _ = walk.NewTextLabel(e.root) + w.text(func(s string) { e.note.SetText(s) }, "appear.blurNote") + w.text(func(string) { e.refresh() }, "appear.opacity.help") + return e +} + +func (e *appEditor) chooseColor() { + ap := e.get() + r, g, b := ap.RGB(e.w.light()) + var custom [16]win.COLORREF + cc := win.CHOOSECOLOR{ + LStructSize: uint32(unsafeSizeofChooseColor()), + HwndOwner: e.w.mw.Handle(), + RgbResult: win.COLORREF(uint32(r) | uint32(g)<<8 | uint32(b)<<16), + LpCustColors: &custom, + Flags: win.CC_RGBINIT | win.CC_FULLOPEN, + } + if !win.ChooseColor(&cc) { + return + } + v := uint32(cc.RgbResult) + ap.Color = hexOf(uint8(v), uint8(v>>8), uint8(v>>16)) + e.w.changed() +} + +// refresh updates the controls that depend on the current appearance. +func (e *appEditor) refresh() { + ap := e.get() + if ap == nil { + return + } + e.desc.SetText(e.w.t("style." + string(ap.Accent) + ".desc")) + auto := strings.EqualFold(ap.Color, config.ColorAuto) + r, g, b := ap.RGB(e.w.light()) + e.hexLbl.SetText(hexOf(r, g, b)) + e.pick.SetEnabled(!auto && ap.Accent != config.AccentNormal) + e.slider.SetEnabled(ap.Accent != config.AccentNormal) + e.auto.SetEnabled(ap.Accent != config.AccentNormal) + e.note.SetVisible(ap.Accent == config.AccentBlur && winapi.BlurNeedsAcrylic()) + if br, err := walk.NewSolidColorBrush(walk.RGB(r, g, b)); err == nil { + e.swatch.SetBackground(br) + if e.sw != nil { + e.sw.Dispose() + } + e.sw = br + } +} + +// pull copies the config into the controls. +func (e *appEditor) pull() { + ap := e.get() + if ap == nil { + return + } + e.w.syncing = true + selectID(e.accent, accentChoices, string(ap.Accent)) + e.auto.SetChecked(strings.EqualFold(ap.Color, config.ColorAuto)) + e.slider.SetValue(int(ap.Opacity)) + e.value.SetText(fmt.Sprintf("%d %%", ap.Opacity)) + e.w.syncing = false + e.refresh() +} diff --git a/internal/winapi/winapi_windows.go b/internal/winapi/winapi_windows.go index f82fe6a..ade837c 100644 --- a/internal/winapi/winapi_windows.go +++ b/internal/winapi/winapi_windows.go @@ -266,3 +266,8 @@ func Foreground() (exe string, monitor uintptr) { procGetWindowPID.Call(h, uintptr(unsafe.Pointer(&pid))) return processExe(pid), Monitor(h) } + +// BlurNeedsAcrylic reports whether the classic blur-behind accent is unusable. +// Windows 11 (build 22000 and later) draws it as solid black, so "blur" has to +// be produced with the acrylic backdrop there. +func BlurNeedsAcrylic() bool { return windows.RtlGetVersion().BuildNumber >= 22000 }