diff --git a/CHANGELOG.md b/CHANGELOG.md index d55176d..45dfdc5 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] + +### Changed +- **The settings window is the web-style one again** (the 1.2.x window, shown in an Edge app window; the native Win32 window from 1.3.0 is removed). It keeps the 1.3.0 improvements: Blur works on Windows 11, and the preview shows how Blur really looks there. + +### Added +- The settings window now has the TaskGlass icon (title bar and taskbar) through a favicon served by the local settings page. + ## [1.3.0] - 2026-11-20 ### Fixed diff --git a/cmd/taskglass/resource_windows_amd64.syso b/cmd/taskglass/resource_windows_amd64.syso index 78e6cec..956bde1 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 fa671a6..736ce3c 100644 --- a/cmd/taskglass/taskglass.manifest +++ b/cmd/taskglass/taskglass.manifest @@ -2,12 +2,6 @@ TaskGlass - - - - - - diff --git a/go.mod b/go.mod index 1430290..319678c 100644 --- a/go.mod +++ b/go.mod @@ -4,12 +4,7 @@ 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 - gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirect -) +require github.com/godbus/dbus/v5 v5.1.0 // indirect diff --git a/go.sum b/go.sum index 6b86fb3..ae0ebec 100644 --- a/go.sum +++ b/go.sum @@ -2,12 +2,5 @@ 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 10ba7d6..fd4d92d 100644 --- a/graphify-out/.graphify_labels.json +++ b/graphify-out/.graphify_labels.json @@ -12,7 +12,7 @@ "10": "tray_icon", "11": "PULL_REQUEST_TEMPLATE.md", "12": "definitions", - "13": "preview.go", + "13": "config.go", "14": "assets.go", "15": "bug_report.md", "16": "feature_request.md", @@ -40,12 +40,16 @@ "38": "Contributing", "39": "Security Policy", "40": "default", - "41": "apps", + "41": "fakeHost", "42": "enabled", "43": "hotkey", "44": "enum", "45": "theme", - "46": "window", + "46": "Server", + "47": "exe", "48": "autostart_windows.go", - "50": "language" + "49": "xaml_fix", + "50": "language", + "51": "main.go", + "52": "locale_other.go" } diff --git a/graphify-out/.graphify_labels.json.sig b/graphify-out/.graphify_labels.json.sig index e8b1c49..5823665 100644 --- a/graphify-out/.graphify_labels.json.sig +++ b/graphify-out/.graphify_labels.json.sig @@ -1 +1 @@ -{"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 +{"0": "5076d5ac64ef5c4a", "1": "b64346c57c2f1370", "2": "3e72afd85194fc6d", "3": "01646dff01d2eb7e", "4": "b366977a781f3394", "5": "347b8ad08160da2d", "6": "5f1178d3b76d5916", "7": "c3edf3c38080d85c", "8": "7c8d94ab6376b921", "9": "7e5fd0bf5677dec6", "10": "952491af3b1e9f78", "11": "e0f13635f45c650b", "12": "690ee408139029c9", "13": "17570957673a4fdd", "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": "029966ca5faa5a2a", "29": "2f07b244a1b1bebb", "30": "4cbef3533d917f67", "31": "39e69bcdefe2b0d2", "32": "804482094d693c22", "33": "077458ac008cc4d9", "34": "77bc2d977d7ff4cd", "35": "13af2a57728b14e4", "36": "bb6ec3da677724b3", "37": "4c1831b02af7bd53", "38": "268b36fafa333572", "39": "89111ec01d66aeef", "40": "a6d5a524b6f14c57", "41": "70a729a8c2ed65e6", "42": "629a30dc96674e1a", "43": "4249983e8612bb1d", "44": "0baabc23a0122bf6", "45": "568df988db03bae3", "46": "ed151e4065cb4366", "47": "ab47fb02a9b2717a", "48": "a5b30f9d71bf9f82", "49": "43b67b0ff2e57329", "50": "58627c65df2a80a1", "51": "9346c9771bed4f8d", "52": "7984419eb8b2f465"} \ No newline at end of file diff --git a/graphify-out/GRAPH_REPORT.md b/graphify-out/GRAPH_REPORT.md index c32fa10..a75200b 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 -- 49 files · ~99,000 words +- 50 files · ~98,812 words - Verdict: corpus is large enough that graph structure adds value. ## Summary -- 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) +- 622 nodes · 1081 edges · 53 communities (47 shown, 6 thin omitted) +- Extraction: 92% EXTRACTED · 8% INFERRED · 0% AMBIGUOUS · INFERRED: 91 edges (avg confidence: 0.8) - Token cost: 0 input · 0 output ## Graph Freshness -- Built from commit: `05ca89d4` +- Built from commit: `cc5eb08c` - Run `git rev-parse HEAD` and compare to check if the graph is stale. - Run `graphify update .` after code changes (no API cost). @@ -28,7 +28,7 @@ - tray_icon - PULL_REQUEST_TEMPLATE.md - definitions -- preview.go +- config.go - github.com/AnderCMD/TaskGlass - properties - Watcher @@ -50,26 +50,29 @@ - Contributing - Security Policy - default -- apps +- fakeHost - enabled - hotkey - enum - theme -- window +- Server +- exe - autostart_windows.go +- xaml_fix - language +- main.go ## God Nodes (most connected - your core abstractions) -1. `T()` - 41 edges +1. `T()` - 40 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 +3. `Config` - 35 edges +4. `Controller` - 21 edges +5. `Default()` - 20 edges +6. `Parse()` - 18 edges +7. `Server` - 17 edges +8. `main()` - 13 edges +9. `logf_()` - 12 edges +10. `host` - 11 edges ## Surprising Connections (you probably didn't know these) - `main()` --calls--> `Default()` [INFERRED] @@ -80,13 +83,13 @@ cmd/taskglass/main_windows.go → internal/config/config.go - `main()` --calls--> `Save()` [INFERRED] cmd/taskglass/main_windows.go → internal/config/config.go -- `watchForQuit()` --references--> `App` [EXTRACTED] - cmd/taskglass/main_windows.go → internal/app/app_windows.go +- `main()` --calls--> `Parse()` [INFERRED] + tools/genicon/main.go → internal/config/config.go ## Import Cycles - None detected. -## Communities (49 total, 5 thin omitted) +## Communities (53 total, 6 thin omitted) ### Community 0 - "main" Cohesion: 0.26 @@ -98,27 +101,27 @@ Nodes (10): Before you start, Contributing, Features, How it works, Install, Lic ### Community 2 - "winapi_windows.go" Cohesion: 0.11 -Nodes (31): blurPolicy(), TestToPolicy(), HWND, Logger, Time, lighten(), New(), toPolicy() (+23 more) +Nodes (30): blurPolicy(), TestToPolicy(), HWND, Logger, Time, lighten(), New(), toPolicy() (+22 more) ### Community 3 - "hotkey_enabled" Cohesion: 0.50 Nodes (4): default, description, type, hotkey_enabled ### Community 4 - "App" -Cohesion: 0.07 -Nodes (25): App, host, menuItems, Options, panicGuard, Int32, check(), Bool (+17 more) +Cohesion: 0.06 +Nodes (27): App, host, Options, panicGuard, Config, Int32, check(), Bool (+19 more) ### Community 5 - "Controller" -Cohesion: 0.07 -Nodes (28): Attr, GUID, Handler, Duration, TaskbarAnchor(), Duration, TrayProbe(), Unhook() (+20 more) +Cohesion: 0.06 +Nodes (29): Attr, Handler, GUID, Duration, TaskbarAnchor(), Duration, TrayProbe(), Handle (+21 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.19 -Nodes (14): $ref, properties, type, $ref, properties, appearance, rule, $ref (+6 more) +Cohesion: 0.25 +Nodes (11): $ref, properties, type, $ref, properties, appearance, properties, $ref (+3 more) ### Community 8 - "config.schema.json" Cohesion: 0.29 @@ -126,23 +129,23 @@ Nodes (6): additionalProperties, description, $id, $schema, title, type ### Community 9 - "Changelog" 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) +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, [1.3.0] - 2026-11-20, Added (+15 more) ### Community 10 - "tray_icon" Cohesion: 0.24 Nodes (10): tray_icon, enum, default, description, enum, type, auto, color (+2 more) ### Community 12 - "definitions" -Cohesion: 0.25 -Nodes (8): description, type, description, pattern, type, definitions, accent, color +Cohesion: 0.22 +Nodes (9): description, pattern, type, definitions, color, surface, additionalProperties, properties (+1 more) -### Community 13 - "preview.go" -Cohesion: 0.19 -Nodes (30): at(), blur(), boxH(), boxV(), clamp8(), Color(), drawFlyout(), drawTaskbarContents() (+22 more) +### Community 13 - "config.go" +Cohesion: 0.12 +Nodes (14): menuItems, Accent, Appearance, AppRule, Percent, Rule, Surface, Surfaces (+6 more) ### Community 18 - "properties" -Cohesion: 0.15 -Nodes (13): description, $ref, properties, maximized, $schema, version, xaml_fix, type (+5 more) +Cohesion: 0.22 +Nodes (9): description, $ref, properties, maximized, $schema, version, type, const (+1 more) ### Community 19 - "Watcher" Cohesion: 0.33 @@ -177,8 +180,8 @@ Cohesion: 0.40 Nodes (5): opacity, description, maximum, minimum, type ### Community 29 - "T" -Cohesion: 0.06 -Nodes (57): Accent, Appearance, AppRule, Config, Percent, Rule, Surface, Surfaces (+49 more) +Cohesion: 0.08 +Nodes (48): Lang, Default(), Load(), Parse(), ParseHotkey(), Save(), TestAppRuleMatching(), TestAutoColorFollowsTheme() (+40 more) ### Community 30 - "Architecture" Cohesion: 0.18 @@ -189,8 +192,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.18 -Nodes (11): items, description, minLength, pattern, type, additionalProperties, properties, required (+3 more) +Cohesion: 0.22 +Nodes (9): description, items, maxItems, type, additionalProperties, required, type, apps (+1 more) ### Community 37 - "Configuration" Cohesion: 0.22 @@ -208,57 +211,65 @@ Nodes (4): Reporting a vulnerability, Scope, Security Policy, Supported versions Cohesion: 0.50 Nodes (4): additionalProperties, description, type, default -### Community 41 - "apps" -Cohesion: 0.50 -Nodes (4): description, maxItems, type, apps - ### Community 42 - "enabled" Cohesion: 0.25 -Nodes (8): surface, default, description, type, enabled, additionalProperties, properties, type +Nodes (8): rule, default, description, type, enabled, additionalProperties, properties, type ### Community 43 - "hotkey" Cohesion: 0.50 Nodes (4): default, description, type, hotkey ### Community 44 - "enum" -Cohesion: 0.33 -Nodes (6): enum, acrylic, blur, clear, normal, opaque +Cohesion: 0.22 +Nodes (9): description, enum, type, accent, acrylic, blur, clear, normal (+1 more) ### Community 45 - "theme" Cohesion: 0.50 Nodes (4): theme, default, description, type -### Community 46 - "window" -Cohesion: 0.06 -Nodes (41): Bitmap, CheckBox, ComboBox, Composite, ImageView, Container, window, unsafeSizeofChooseColor() (+33 more) +### Community 46 - "Server" +Cohesion: 0.19 +Nodes (13): HandlerFunc, favicon(), Handler, loopbackHost(), New(), writeErr(), writeJSON(), Listener (+5 more) + +### Community 47 - "exe" +Cohesion: 0.40 +Nodes (5): description, minLength, pattern, type, exe ### Community 48 - "autostart_windows.go" Cohesion: 0.38 Nodes (8): clearDisabled(), command(), Enabled(), Repair(), sameCommand(), Set(), TestCommandIsPlainQuotedPath(), TestSameCommandRecognisesLegacyDoubledBackslashes() +### Community 49 - "xaml_fix" +Cohesion: 0.50 +Nodes (4): xaml_fix, default, description, type + ### Community 50 - "language" Cohesion: 0.29 Nodes (7): default, description, enum, type, language, en, es +### Community 51 - "main.go" +Cohesion: 0.83 +Nodes (3): entry, main(), writeICO() + ## Knowledge Gaps - **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. +- **6 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`, `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._ +- **Why does `App` connect `App` to `main`, `winapi_windows.go`, `Controller`, `config.go`, `Server`, `Watcher`?** + _High betweenness centrality (0.094) - this node is a cross-community bridge._ +- **Why does `Config` connect `App` to `winapi_windows.go`, `fakeHost`, `config.go`, `Server`, `T`?** + _High betweenness centrality (0.073) - this node is a cross-community bridge._ +- **Why does `properties` connect `properties` to `hotkey_enabled`, `items`, `config.schema.json`, `default`, `enabled`, `hotkey`, `tray_icon`, `theme`, `xaml_fix`, `language`, `enum`, `taskbars`, `debounce_ms`, `poll_ms`, `refresh_ms`, `surfaces`?** + _High betweenness centrality (0.048) - this node is a cross-community bridge._ +- **Are the 16 inferred relationships involving `Default()` (e.g. with `main()` and `TestDefaultIsValid()`) actually correct?** + _`Default()` has 16 INFERRED edges - model-reasoned connections that need verification._ - **What connects `$schema`, `$id`, `title` to the rest of the system?** _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.10810810810810811 - nodes in this community are weakly interconnected._ - **Should `App` be split into smaller, more focused modules?** - _Cohesion score 0.06779661016949153 - nodes in this community are weakly interconnected._ \ No newline at end of file + _Cohesion score 0.06448412698412699 - 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 125708e..aa45d30 100644 --- a/graphify-out/graph.html +++ b/graphify-out/graph.html @@ -63,12 +63,12 @@

Communities

-
679 nodes · 1289 edges · 49 communities
+
622 nodes · 1081 edges · 53 communities
+ + diff --git a/internal/settings/locale_other.go b/internal/settings/locale_other.go new file mode 100644 index 0000000..79666b2 --- /dev/null +++ b/internal/settings/locale_other.go @@ -0,0 +1,5 @@ +//go:build !windows + +package settings + +func systemLocale() string { return "" } diff --git a/internal/settings/locale_windows.go b/internal/settings/locale_windows.go new file mode 100644 index 0000000..f06b05a --- /dev/null +++ b/internal/settings/locale_windows.go @@ -0,0 +1,7 @@ +//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 new file mode 100644 index 0000000..3e75e58 --- /dev/null +++ b/internal/settings/server.go @@ -0,0 +1,245 @@ +// 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/assets" + "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 + // BlurNeedsAcrylic reports that Blur is drawn with the acrylic backdrop (Windows 11). + BlurNeedsAcrylic() 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 /favicon.ico", favicon) + 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 +} + +// favicon serves the TaskGlass icon, which the app-style browser window shows +// in its title bar and on the taskbar. +func favicon(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "image/x-icon") + w.Header().Set("Cache-Control", "public, max-age=86400") + _, _ = w.Write(assets.Color) +} + +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 'self' 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"` + BlurViaAcrylic bool `json:"blurViaAcrylic"` + 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(), + BlurViaAcrylic: s.host.BlurNeedsAcrylic(), + 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 new file mode 100644 index 0000000..a578ee5 --- /dev/null +++ b/internal/settings/server_test.go @@ -0,0 +1,119 @@ +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 (f *fakeHost) BlurNeedsAcrylic() 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) + } +} + +func TestFaviconIsServedWithoutToken(t *testing.T) { + s := New(&fakeHost{cfg: config.Default()}) + w := do(s.Handler(), "GET", "/favicon.ico", "127.0.0.1:1", "", "") + if w.Code != 200 || w.Header().Get("Content-Type") != "image/x-icon" || w.Body.Len() < 100 { + t.Fatalf("favicon: %d %s %d bytes", w.Code, w.Header().Get("Content-Type"), w.Body.Len()) + } +} diff --git a/internal/settings/window_windows.go b/internal/settings/window_windows.go new file mode 100644 index 0000000..02a9220 --- /dev/null +++ b/internal/settings/window_windows.go @@ -0,0 +1,66 @@ +//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/ui/tabs_windows.go b/internal/ui/tabs_windows.go deleted file mode 100644 index dae4ec1..0000000 --- a/internal/ui/tabs_windows.go +++ /dev/null @@ -1,491 +0,0 @@ -//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 deleted file mode 100644 index 5154a14..0000000 --- a/internal/ui/ui_windows.go +++ /dev/null @@ -1,497 +0,0 @@ -//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() -}