From 222af990de4e11df688609d4dd1a5a943e943ca6 Mon Sep 17 00:00:00 2001 From: AnderCMD Date: Fri, 20 Nov 2026 10:29:35 -0600 Subject: [PATCH] feat: settings window, English/Spanish UI, installer wizard, autostart fix - fix: "Start with Windows" wrote the Run-key path with doubled backslashes (Go %q), so Windows never launched it at sign-in. Write plain quotes, repair legacy values on start and clear the StartupApproved flag. - feat: settings window (loopback server + embedded page, token-protected) with live taskbar and tray-flyout preview; opened from the tray left click, menu, --settings or a second launch. - feat: i18n (en/es) for tray menu, settings window and a new `language` config key. - feat: installer asks for style, language and extras on first install and writes config.json; license shown per language (LICENSE.es.txt is an unofficial translation). - fix: Blur no longer renders opaque black with a 0 tint. - docs: changelog, README, configuration and schema updated. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 14 + LICENSE.es.txt | 227 + README.es.md | 2 + README.md | 2 + cmd/taskglass/main_windows.go | 32 +- docs/config.schema.json | 10 + docs/configuration.md | 1 + graphify-out/.graphify_labels.json | 17 +- graphify-out/.graphify_labels.json.sig | 2 +- graphify-out/GRAPH_REPORT.md | 140 +- graphify-out/graph.html | 8 +- graphify-out/graph.json | 12380 ++++++++++------- installer/taskglass.iss | 167 +- internal/app/app_windows.go | 195 +- internal/autostart/autostart_windows.go | 55 +- internal/autostart/autostart_windows_test.go | 23 + internal/config/config.go | 8 + internal/i18n/i18n.go | 325 + internal/i18n/i18n_test.go | 38 + internal/i18n/locale_windows.go | 21 + internal/settings/index.html | 482 + internal/settings/locale_other.go | 5 + internal/settings/locale_windows.go | 7 + internal/settings/server.go | 231 + internal/settings/server_test.go | 110 + internal/settings/window_windows.go | 66 + internal/taskbar/taskbar_windows.go | 3 + 27 files changed, 9769 insertions(+), 4802 deletions(-) create mode 100644 LICENSE.es.txt create mode 100644 internal/autostart/autostart_windows_test.go create mode 100644 internal/i18n/i18n.go create mode 100644 internal/i18n/i18n_test.go create mode 100644 internal/i18n/locale_windows.go create mode 100644 internal/settings/index.html create mode 100644 internal/settings/locale_other.go create mode 100644 internal/settings/locale_windows.go create mode 100644 internal/settings/server.go create mode 100644 internal/settings/server_test.go create mode 100644 internal/settings/window_windows.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ce5e28..214d6ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ Format based on [Keep a Changelog](https://keepachangelog.com/); versioning follows [SemVer](https://semver.org/). +## [Unreleased] + +### Fixed +- **Start with Windows did not start TaskGlass.** The Run-key value was written with Go's `%q`, which doubled every backslash (`"C:\Dir\taskglass.exe"`), and Windows could not launch it at sign-in. The path is now written in plain quotes. An entry written by an older version is repaired automatically the next time TaskGlass runs; turning "Start with Windows" on also clears a "disabled in Task Manager" mark. + +### Added +- **Settings window** with a live preview of the taskbar (default, maximized and per-app looks) and of the hidden-icons flyout. Edit everything there: style, tint colour and strength, theme, language, tray icon, hotkey, per-app rules, flyout opacity, start with Windows and advanced timings. Open it with a left click on the tray icon, "Settings…" in the menu, `taskglass --settings` or by launching TaskGlass again. It is a local page (loopback only, protected by a per-run token) shown in an Edge app window. +- **English and Spanish** everywhere: tray menu, settings window, installer and license. New `language` setting (`auto`, `en`, `es`). +- **Installer**: asks for the taskbar style, language and extras on a first install and writes the initial `config.json`; shows the license in the installer language (`LICENSE.es.txt`, an unofficial translation, alongside the binding English `LICENSE`); adds a "TaskGlass Settings" Start-menu entry. +- Quick presets (pure glass, frosted, acrylic tint, solid). + +### Changed +- Blur no longer renders opaque black when its tint is 0 (same floor Clear and Acrylic already had). + ## [1.1.1] - 2026-11-18 ### Changed diff --git a/LICENSE.es.txt b/LICENSE.es.txt new file mode 100644 index 0000000..fb4a3f0 --- /dev/null +++ b/LICENSE.es.txt @@ -0,0 +1,227 @@ +TRADUCCIÓN NO OFICIAL AL ESPAÑOL / UNOFFICIAL SPANISH TRANSLATION + +Esta traducción se ofrece solo por cortesía, para facilitar la lectura. No ha +sido publicada por la Apache Software Foundation ni por el titular de los +derechos de TaskGlass, y no tiene valor legal. El único texto jurídicamente +vinculante es el original en inglés, incluido en el archivo LICENSE. Si existe +cualquier diferencia entre ambos, prevalece el texto en inglés. + +------------------------------------------------------------------------------ + + Licencia Apache + Versión 2.0, enero de 2004 + http://www.apache.org/licenses/ + + TÉRMINOS Y CONDICIONES DE USO, REPRODUCCIÓN Y DISTRIBUCIÓN + + 1. Definiciones. + + «Licencia» significa los términos y condiciones de uso, reproducción + y distribución definidos en las Secciones 1 a 9 de este documento. + + «Licenciante» significa el titular de los derechos de autor o la + entidad autorizada por dicho titular que otorga la Licencia. + + «Entidad Legal» significa la unión de la entidad que actúa y de todas + las demás entidades que controlan, son controladas por, o están bajo + control común con esa entidad. A los efectos de esta definición, + «control» significa (i) el poder, directo o indirecto, de dirigir o + administrar dicha entidad, ya sea por contrato o de otro modo, o + (ii) la titularidad del cincuenta por ciento (50 %) o más de las + acciones en circulación, o (iii) la titularidad efectiva de dicha + entidad. + + «Usted» (o «Su») significa una persona física o Entidad Legal que + ejerce los permisos concedidos por esta Licencia. + + Forma «Fuente» significa la forma preferida para realizar + modificaciones, incluyendo, entre otros, el código fuente del + software, la fuente de la documentación y los archivos de + configuración. + + Forma «Objeto» significa cualquier forma resultante de la + transformación o traducción mecánica de una forma Fuente, incluyendo, + entre otros, el código objeto compilado, la documentación generada y + las conversiones a otros tipos de medios. + + «Obra» significa la obra de autoría, ya sea en forma Fuente o Objeto, + puesta a disposición bajo la Licencia, según se indique mediante un + aviso de derechos de autor incluido o adjunto a la obra (en el + Apéndice siguiente se proporciona un ejemplo). + + «Obras Derivadas» significa cualquier obra, ya sea en forma Fuente u + Objeto, que esté basada en (o derive de) la Obra y cuyas revisiones + editoriales, anotaciones, elaboraciones u otras modificaciones + representen, en su conjunto, una obra de autoría original. A los + efectos de esta Licencia, las Obras Derivadas no incluyen las obras + que permanezcan separables de las interfaces de la Obra y de sus + Obras Derivadas, o que simplemente se enlacen (o se vinculen por + nombre) a ellas. + + «Contribución» significa cualquier obra de autoría, incluida la + versión original de la Obra y cualquier modificación o adición a esa + Obra o a sus Obras Derivadas, que sea sometida intencionadamente al + Licenciante para su inclusión en la Obra por el titular de los + derechos de autor o por una persona física o Entidad Legal autorizada + para presentarla en nombre del titular. A los efectos de esta + definición, «sometida» significa cualquier forma de comunicación + electrónica, verbal o escrita enviada al Licenciante o a sus + representantes, incluyendo, entre otras, la comunicación en listas de + correo electrónico, sistemas de control de código fuente y sistemas de + seguimiento de incidencias gestionados por el Licenciante, o en su + nombre, con el fin de debatir y mejorar la Obra, pero excluyendo la + comunicación que el titular de los derechos de autor haya marcado de + forma visible o designado de otro modo por escrito como «No es una + Contribución». + + «Contribuyente» significa el Licenciante y toda persona física o + Entidad Legal en cuyo nombre el Licenciante haya recibido una + Contribución que se haya incorporado posteriormente a la Obra. + + 2. Concesión de la Licencia de Derechos de Autor. Sujeto a los términos + y condiciones de esta Licencia, cada Contribuyente le concede por la + presente una licencia de derechos de autor perpetua, mundial, no + exclusiva, gratuita, libre de regalías e irrevocable para reproducir, + preparar Obras Derivadas, exhibir públicamente, ejecutar + públicamente, sublicenciar y distribuir la Obra y dichas Obras + Derivadas, en forma Fuente u Objeto. + + 3. Concesión de la Licencia de Patentes. Sujeto a los términos y + condiciones de esta Licencia, cada Contribuyente le concede por la + presente una licencia de patentes perpetua, mundial, no exclusiva, + gratuita, libre de regalías e irrevocable (salvo lo indicado en esta + sección) para fabricar, hacer fabricar, usar, ofrecer a la venta, + vender, importar y transferir de otro modo la Obra, siempre que dicha + licencia se aplique únicamente a aquellas reivindicaciones de patente + susceptibles de ser licenciadas por dicho Contribuyente que resulten + necesariamente infringidas por su(s) Contribución(es) por sí solas o + por la combinación de su(s) Contribución(es) con la Obra a la que + dicha(s) Contribución(es) fue(ron) sometida(s). Si Usted inicia un + litigio sobre patentes contra cualquier entidad (incluida una + reconvención o contrademanda en un juicio) alegando que la Obra o una + Contribución incorporada a la Obra constituye una infracción directa + o contributiva de patente, entonces las licencias de patentes que se + le hayan concedido bajo esta Licencia para esa Obra terminarán en la + fecha en que se presente dicho litigio. + + 4. Redistribución. Usted puede reproducir y distribuir copias de la + Obra o de Obras Derivadas de la misma en cualquier medio, con o sin + modificaciones, y en forma Fuente u Objeto, siempre que cumpla las + siguientes condiciones: + + (a) Debe entregar a cualquier otro receptor de la Obra o de Obras + Derivadas una copia de esta Licencia; y + + (b) Debe hacer que los archivos modificados incluyan avisos + destacados que indiquen que Usted modificó los archivos; y + + (c) Debe conservar, en la forma Fuente de cualquier Obra Derivada que + distribuya, todos los avisos de derechos de autor, patentes, + marcas y atribución de la forma Fuente de la Obra, excluyendo + aquellos avisos que no correspondan a ninguna parte de las Obras + Derivadas; y + + (d) Si la Obra incluye un archivo de texto «NOTICE» como parte de su + distribución, entonces cualquier Obra Derivada que Usted + distribuya debe incluir una copia legible de los avisos de + atribución contenidos en dicho archivo NOTICE, excluyendo + aquellos avisos que no correspondan a ninguna parte de las Obras + Derivadas, en al menos uno de los siguientes lugares: dentro de + un archivo de texto NOTICE distribuido como parte de las Obras + Derivadas; dentro de la forma Fuente o de la documentación, si + se proporciona junto con las Obras Derivadas; o dentro de una + pantalla generada por las Obras Derivadas, si y donde suelan + aparecer normalmente dichos avisos de terceros. El contenido del + archivo NOTICE es solo informativo y no modifica la Licencia. + Usted puede añadir sus propios avisos de atribución en las Obras + Derivadas que distribuya, junto al texto del NOTICE de la Obra o + como anexo al mismo, siempre que dichos avisos de atribución + adicionales no puedan interpretarse como una modificación de la + Licencia. + + Usted puede añadir su propia declaración de derechos de autor a sus + modificaciones y puede ofrecer términos y condiciones de licencia + adicionales o diferentes para el uso, la reproducción o la + distribución de sus modificaciones, o de cualquier Obra Derivada de + ese tipo en su conjunto, siempre que su uso, reproducción y + distribución de la Obra cumpla, por lo demás, las condiciones + establecidas en esta Licencia. + + 5. Presentación de Contribuciones. Salvo que Usted indique + expresamente lo contrario, cualquier Contribución sometida + intencionadamente por Usted al Licenciante para su inclusión en la + Obra se regirá por los términos y condiciones de esta Licencia, sin + términos ni condiciones adicionales. No obstante lo anterior, nada de + lo aquí dispuesto sustituirá ni modificará los términos de cualquier + acuerdo de licencia independiente que Usted haya firmado con el + Licenciante en relación con dichas Contribuciones. + + 6. Marcas. Esta Licencia no concede permiso para usar los nombres + comerciales, marcas, marcas de servicio o nombres de producto del + Licenciante, salvo en la medida necesaria para un uso razonable y + habitual al describir el origen de la Obra y al reproducir el + contenido del archivo NOTICE. + + 7. Exclusión de Garantía. Salvo que lo exija la ley aplicable o se + acuerde por escrito, el Licenciante proporciona la Obra (y cada + Contribuyente proporciona sus Contribuciones) «TAL CUAL», SIN + GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ya sean expresas o + implícitas, incluyendo, sin limitación, cualquier garantía o + condición de TITULARIDAD, NO INFRACCIÓN, COMERCIABILIDAD o IDONEIDAD + PARA UN FIN PARTICULAR. Usted es el único responsable de determinar + la idoneidad de usar o redistribuir la Obra y asume los riesgos + asociados con el ejercicio de los permisos otorgados por esta + Licencia. + + 8. Limitación de Responsabilidad. En ningún caso y bajo ninguna teoría + legal, ya sea por responsabilidad extracontractual (incluida la + negligencia), contractual o de otro tipo, salvo que lo exija la ley + aplicable (como en los actos deliberados y de negligencia grave) o se + acuerde por escrito, ningún Contribuyente será responsable ante + Usted por daños, incluidos los daños directos, indirectos, + especiales, incidentales o consecuentes de cualquier carácter que + surjan como resultado de esta Licencia o del uso o la imposibilidad + de usar la Obra (incluyendo, entre otros, los daños por pérdida de + fondo de comercio, paralización del trabajo, fallo o mal + funcionamiento informático, o cualquier otro daño o pérdida + comercial), incluso si dicho Contribuyente hubiera sido advertido de + la posibilidad de tales daños. + + 9. Aceptación de Garantía o Responsabilidad Adicional. Al redistribuir + la Obra o Obras Derivadas de la misma, Usted puede optar por ofrecer, + y cobrar una tarifa por, la aceptación de obligaciones y/o derechos + de soporte, garantía, indemnización u otra responsabilidad + compatibles con esta Licencia. Sin embargo, al aceptar dichas + obligaciones, Usted solo puede actuar en su propio nombre y bajo su + exclusiva responsabilidad, no en nombre de ningún otro Contribuyente, + y solo si se compromete a indemnizar, defender y mantener indemne a + cada Contribuyente frente a cualquier responsabilidad en que incurra, + o reclamación que se formule contra dicho Contribuyente, por razón de + que Usted acepte tal garantía o responsabilidad adicional. + + FIN DE LOS TÉRMINOS Y CONDICIONES + + APÉNDICE: Cómo aplicar la Licencia Apache a su obra. + + Para aplicar la Licencia Apache a su obra, adjunte el siguiente + aviso modelo, sustituyendo los campos entre corchetes «[]» por su + propia información de identificación. (¡No incluya los corchetes!) + El texto debe incluirse con la sintaxis de comentarios adecuada al + formato del archivo. También recomendamos que se incluyan el nombre + del archivo o de la clase y una descripción de su propósito en la + misma «página impresa» que el aviso de derechos de autor, para + facilitar su identificación en archivos de terceros. + + Copyright [aaaa] [nombre del titular de los derechos de autor] + + Licenciado bajo la Licencia Apache, Versión 2.0 (la «Licencia»); + no puede usar este archivo excepto de conformidad con la Licencia. + Puede obtener una copia de la Licencia en + + http://www.apache.org/licenses/LICENSE-2.0 + + Salvo que lo exija la ley aplicable o se acuerde por escrito, el + software distribuido bajo la Licencia se distribuye «TAL CUAL», SIN + GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ya sean expresas o implícitas. + Consulte la Licencia para conocer el texto específico que rige los + permisos y las limitaciones bajo la Licencia. diff --git a/README.es.md b/README.es.md index 5ebc522..9c990b4 100644 --- a/README.es.md +++ b/README.es.md @@ -39,6 +39,8 @@ powershell -File scripts/build-tap.ps1 # genera dist/taskglass_tap.dll ## Uso +Clic izquierdo en el icono de bandeja (o `taskglass --settings`) abre la **ventana de configuración**: todas las opciones, en español o inglés, con vista previa en vivo de tu barra de tareas y del desplegable de iconos ocultos. + Clic derecho en el icono de bandeja para activar o desactivar TaskGlass, elegir estilo o tema, alternar las reglas, iniciar con Windows, o abrir la configuración y el log. Una configuración mínima: barra transparente, opaca si algo está maximizado, y desenfoque teñido en tu editor: diff --git a/README.md b/README.md index d68b090..43fa46c 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,8 @@ powershell -File scripts/build-tap.ps1 # builds dist/taskglass_tap.dll ## Usage +Left-click the tray icon (or run `taskglass --settings`) to open the **settings window**: every option, in English or Spanish, with a live preview of your taskbar and the hidden-icons flyout. + Right-click the tray icon to enable or disable TaskGlass, pick a style or a theme, toggle the rules and the tray flyout, start with Windows, or open the config and the log. A minimal config that makes the bar clear, opaque when something is maximized, and a tinted blur in your editor: diff --git a/cmd/taskglass/main_windows.go b/cmd/taskglass/main_windows.go index f109de1..09239db 100644 --- a/cmd/taskglass/main_windows.go +++ b/cmd/taskglass/main_windows.go @@ -28,6 +28,9 @@ var version = "dev" const ( mutexName = `Local\TaskGlass.Singleton` quitName = `Local\TaskGlass.Quit` + // settingsName is signalled to make the running instance show its settings + // window (a second launch, or --settings). + settingsName = `Local\TaskGlass.Settings` ) func main() { @@ -38,6 +41,7 @@ func main() { validate = flag.Bool("validate", false, "check the config file and exit (non-zero on errors)") quit = flag.Bool("quit", false, "ask a running TaskGlass to exit") verbose = flag.Bool("verbose", false, "log to stderr as well as the log file") + openUI = flag.Bool("settings", false, "open the settings window (starts TaskGlass if it is not running)") restore = flag.Bool("restore", false, "put the taskbar back to the stock look and exit (use after a crash)") ) flag.Usage = func() { @@ -94,6 +98,7 @@ func main() { // Single instance. if _, err := windows.CreateMutex(nil, false, windows.StringToUTF16Ptr(mutexName)); err != nil { if err == windows.ERROR_ALREADY_EXISTS { + signalEvent(settingsName) // already running: just bring up its settings return } fatal("mutex: %v", err) @@ -110,8 +115,9 @@ func main() { log.Error("config invalid, using defaults until it is fixed", "path", cfgPath, "err", cfgErr) } - a := app.New(app.Options{Log: log, CfgPath: cfgPath, LogPath: logPath, Version: version, Config: cfg}) + a := app.New(app.Options{Log: log, CfgPath: cfgPath, LogPath: logPath, Version: version, Config: cfg, ShowSettings: *openUI}) watchForQuit(a) + watchForSettings(a) a.Run() } @@ -140,6 +146,30 @@ func watchForQuit(a *app.App) { }() } +// watchForSettings shows the settings window whenever another launch asks. +func watchForSettings(a *app.App) { + ev, err := windows.CreateEvent(nil, 0, 0, windows.StringToUTF16Ptr(settingsName)) // auto-reset + if err != nil { + return + } + go func() { + for { + if r, _ := windows.WaitForSingleObject(ev, windows.INFINITE); r == windows.WAIT_OBJECT_0 { + a.OpenSettings() + } + } + }() +} + +func signalEvent(name string) { + ev, err := windows.OpenEvent(windows.EVENT_MODIFY_STATE, false, windows.StringToUTF16Ptr(name)) + if err != nil { + return + } + defer windows.CloseHandle(ev) + _ = windows.SetEvent(ev) +} + func signalQuit() error { ev, err := windows.OpenEvent(windows.EVENT_MODIFY_STATE, false, windows.StringToUTF16Ptr(quitName)) if err != nil { diff --git a/docs/config.schema.json b/docs/config.schema.json index a4b8cfd..a04ce4d 100644 --- a/docs/config.schema.json +++ b/docs/config.schema.json @@ -87,6 +87,16 @@ "default": true, "description": "Master switch. When false the stock taskbar is shown." }, + "language": { + "type": "string", + "enum": [ + "auto", + "en", + "es" + ], + "default": "auto", + "description": "Language of the tray menu and settings window. auto follows the Windows display language." + }, "theme": { "type": "string", "enum": [ diff --git a/docs/configuration.md b/docs/configuration.md index 3502d51..f2814b2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -41,6 +41,7 @@ Changes made from the tray menu are saved to this same file. | Key | Values | Meaning | |-----|--------|---------| | `enabled` | bool | Master switch. `false` shows the stock taskbar. | +| `language` | `auto`, `en`, `es` | Language of the tray menu and settings window. `auto` follows the Windows display language. | | `theme` | `auto`, `light`, `dark` | Which colour mode drives `"auto"` colours, the tray icon and the tray menu (the menu follows the Windows *apps* mode when `auto`). `auto` follows the Windows *system* theme (the one the taskbar uses). | | `taskbars` | `all`, `primary` | Style every monitor's taskbar or only the primary one. | | `default` | appearance | Used when no other rule matches. | diff --git a/graphify-out/.graphify_labels.json b/graphify-out/.graphify_labels.json index ab7d2c5..53b26d9 100644 --- a/graphify-out/.graphify_labels.json +++ b/graphify-out/.graphify_labels.json @@ -8,11 +8,11 @@ "6": "tap.c", "7": "opacity", "8": "config.schema.json", - "9": "[1.0.0] - 2026-11-17", - "10": "enum", + "9": "Changelog", + "10": "theme", "11": "PULL_REQUEST_TEMPLATE.md", "12": "definitions", - "13": "TaskGlassHookProc", + "13": "Config", "14": "assets.go", "15": "bug_report.md", "16": "feature_request.md", @@ -28,7 +28,7 @@ "26": "refresh_ms", "27": "surfaces", "28": "xaml_fix", - "29": "Config", + "29": "T", "30": "Architecture", "31": "render-assets.ps1", "32": "gen-resources.ps1", @@ -45,8 +45,11 @@ "43": "hotkey", "44": "enum", "45": "anchor_windows.go", - "46": "opacity", + "46": "Server", "47": "exe", - "48": "theme", - "49": "tray_icon" + "48": "autostart_windows.go", + "49": "tray_icon", + "50": "language", + "51": "properties", + "52": "locale_other.go" } diff --git a/graphify-out/.graphify_labels.json.sig b/graphify-out/.graphify_labels.json.sig index 27b1ce4..12534e9 100644 --- a/graphify-out/.graphify_labels.json.sig +++ b/graphify-out/.graphify_labels.json.sig @@ -1 +1 @@ -{"0": "728159539e20b361", "1": "b64346c57c2f1370", "2": "b6ac6698294942ec", "3": "01646dff01d2eb7e", "4": "b19e1a547b61804c", "5": "9e6a96d967526383", "6": "c695d786a99347c0", "7": "4ce5c000616c77f0", "8": "7c8d94ab6376b921", "9": "0b1ed92623ee9a06", "10": "35a0d3fed002e1eb", "11": "e0f13635f45c650b", "12": "c2f6f3578481b87d", "13": "85b922fa4acc6a6c", "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": "15f42d8ec19f621f", "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": "4c1a85cc953cf600", "45": "44ec9eeee4b329e7", "46": "029966ca5faa5a2a", "47": "ab47fb02a9b2717a", "48": "568df988db03bae3", "49": "d041a87ea2070ac4"} \ No newline at end of file +{"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 diff --git a/graphify-out/GRAPH_REPORT.md b/graphify-out/GRAPH_REPORT.md index d2464b8..1ac082b 100644 --- a/graphify-out/GRAPH_REPORT.md +++ b/graphify-out/GRAPH_REPORT.md @@ -1,16 +1,16 @@ -# Graph Report - TaskGlass (2026-11-18) +# Graph Report - TaskGlass (2026-11-20) ## Corpus Check -- 41 files · ~88,379 words +- 50 files · ~97,994 words - Verdict: corpus is large enough that graph structure adds value. ## Summary -- 523 nodes · 874 edges · 50 communities (45 shown, 5 thin omitted) -- Extraction: 93% EXTRACTED · 7% INFERRED · 0% AMBIGUOUS · INFERRED: 65 edges (avg confidence: 0.8) +- 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) - Token cost: 0 input · 0 output ## Graph Freshness -- Built from commit: `4a191fda` +- Built from commit: `c8f79e7d` - Run `git rev-parse HEAD` and compare to check if the graph is stale. - Run `graphify update .` after code changes (no API cost). @@ -24,11 +24,11 @@ - tap.c - opacity - config.schema.json -- [1.0.0] - 2026-11-17 -- enum +- Changelog +- theme - PULL_REQUEST_TEMPLATE.md - definitions -- TaskGlassHookProc +- Config - github.com/AnderCMD/TaskGlass - properties - Watcher @@ -40,7 +40,7 @@ - refresh_ms - surfaces - xaml_fix -- Config +- T - Architecture - render-assets.ps1 - apply-baseline.sh @@ -55,22 +55,24 @@ - hotkey - enum - anchor_windows.go -- opacity +- Server - exe -- theme +- autostart_windows.go - tray_icon +- language +- properties ## God Nodes (most connected - your core abstractions) -1. `App` - 32 edges -2. `Config` - 25 edges -3. `Controller` - 21 edges -4. `Parse()` - 16 edges -5. `Default()` - 15 edges -6. `logf_()` - 12 edges -7. `main()` - 11 edges -8. `Context` - 11 edges -9. `Appearance` - 10 edges -10. `Resolve()` - 10 edges +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 ## Surprising Connections (you probably didn't know these) - `main()` --calls--> `Default()` [INFERRED] @@ -87,59 +89,59 @@ ## Import Cycles - None detected. -## Communities (50 total, 5 thin omitted) +## Communities (53 total, 5 thin omitted) ### Community 0 - "main" -Cohesion: 0.31 -Nodes (8): attachConsole(), fatal(), Logger, main(), newLogger(), signalQuit(), versionString(), watchForQuit() +Cohesion: 0.26 +Nodes (10): attachConsole(), fatal(), Logger, main(), newLogger(), signalEvent(), signalQuit(), versionString() (+2 more) ### Community 1 - "README.md" 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.11 -Nodes (29): T, TestToPolicy(), HWND, Logger, Time, New(), toPolicy(), className() (+21 more) +Cohesion: 0.12 +Nodes (28): TestToPolicy(), HWND, Logger, Time, New(), toPolicy(), className(), cloaked() (+20 more) ### Community 3 - "hotkey_enabled" Cohesion: 0.50 Nodes (4): default, description, type, hotkey_enabled ### Community 4 - "App" -Cohesion: 0.08 -Nodes (26): App, menuItems, Options, panicGuard, Int32, check(), Bool, CancelFunc (+18 more) +Cohesion: 0.06 +Nodes (27): App, host, menuItems, Options, panicGuard, Int32, check(), Bool (+19 more) ### Community 5 - "Controller" Cohesion: 0.07 -Nodes (26): Attr, GUID, Handler, Duration, TrayProbe(), Handle, SetCallWndProcHook(), Available() (+18 more) +Nodes (25): Attr, Handler, GUID, Duration, TrayProbe(), Handle, SetCallWndProcHook(), Available() (+17 more) ### Community 6 - "tap.c" Cohesion: 0.07 -Nodes (68): DWORD, HINSTANCE, HRESULT, HSTRING, IClassFactory, IDispatchedHandler_, Inst, InstanceHandle (+60 more) +Nodes (72): DWORD, HINSTANCE, HRESULT, HSTRING, IClassFactory, IDispatchedHandler_, Inst, InstanceHandle (+64 more) ### Community 7 - "opacity" -Cohesion: 0.19 -Nodes (15): $ref, properties, type, $ref, properties, appearance, rule, properties (+7 more) +Cohesion: 0.25 +Nodes (11): $ref, properties, type, $ref, properties, appearance, properties, $ref (+3 more) ### Community 8 - "config.schema.json" Cohesion: 0.29 Nodes (6): additionalProperties, description, $id, $schema, title, type -### Community 9 - "[1.0.0] - 2026-11-17" -Cohesion: 0.13 -Nodes (14): [1.0.0] - 2026-11-17, [1.0.1] - 2026-11-17, [1.1.0] - 2026-11-18, Added, Added, Changed, Changed, Changed (+6 more) +### 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) -### Community 10 - "enum" -Cohesion: 0.47 -Nodes (6): enum, enum, auto, color, dark, light +### Community 10 - "theme" +Cohesion: 0.24 +Nodes (10): theme, default, description, enum, type, enum, auto, color (+2 more) ### Community 12 - "definitions" -Cohesion: 0.25 -Nodes (8): description, type, description, pattern, type, definitions, accent, color +Cohesion: 0.20 +Nodes (10): description, pattern, type, definitions, color, opacity, description, maximum (+2 more) -### Community 13 - "TaskGlassHookProc" -Cohesion: 0.50 -Nodes (4): LPARAM, LRESULT, TaskGlassHookProc(), WPARAM +### Community 13 - "Config" +Cohesion: 0.09 +Nodes (16): Accent, Appearance, AppRule, Config, Percent, Rule, Surface, Surfaces (+8 more) ### Community 18 - "properties" Cohesion: 0.22 @@ -177,9 +179,9 @@ Nodes (8): surfaces, tray_overflow, additionalProperties, description, propertie Cohesion: 0.50 Nodes (4): xaml_fix, default, description, type -### Community 29 - "Config" -Cohesion: 0.08 -Nodes (47): Accent, Appearance, AppRule, Config, Percent, Rule, Surface, Surfaces (+39 more) +### Community 29 - "T" +Cohesion: 0.09 +Nodes (44): Lang, Default(), Load(), Parse(), TestAppRuleMatching(), TestAutoColorFollowsTheme(), TestDefaultIsValid(), TestExplicitFalseSticks() (+36 more) ### Community 30 - "Architecture" Cohesion: 0.18 @@ -222,48 +224,56 @@ 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 - "anchor_windows.go" Cohesion: 0.40 Nodes (5): Duration, TaskbarAnchor(), msg, point, wndClassEx -### Community 46 - "opacity" -Cohesion: 0.40 -Nodes (5): opacity, description, maximum, minimum, type +### Community 46 - "Server" +Cohesion: 0.20 +Nodes (12): HandlerFunc, Handler, loopbackHost(), New(), writeErr(), writeJSON(), Listener, Mutex (+4 more) ### Community 47 - "exe" Cohesion: 0.40 Nodes (5): description, minLength, pattern, type, exe -### Community 48 - "theme" -Cohesion: 0.50 -Nodes (4): theme, default, description, type +### 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 -- **154 isolated node(s):** `$schema`, `$id`, `title`, `description`, `type` (+149 more) +- **162 isolated node(s):** `$schema`, `$id`, `title`, `description`, `type` (+157 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`, `Watcher`, `Config`?** - _High betweenness centrality (0.068) - 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`, `enum`, `taskbars`, `debounce_ms`, `poll_ms`, `refresh_ms`, `surfaces`, `xaml_fix`?** - _High betweenness centrality (0.060) - this node is a cross-community bridge._ -- **Why does `Config` connect `Config` to `winapi_windows.go`, `App`?** - _High betweenness centrality (0.059) - this node is a cross-community bridge._ +- **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._ - **What connects `$schema`, `$id`, `title` to the rest of the system?** - _154 weakly-connected nodes found - possible documentation gaps or missing edges._ + _162 weakly-connected nodes found - possible documentation gaps or missing edges._ - **Should `winapi_windows.go` be split into smaller, more focused modules?** - _Cohesion score 0.11260504201680673 - nodes in this community are weakly interconnected._ + _Cohesion score 0.11764705882352941 - nodes in this community are weakly interconnected._ - **Should `App` be split into smaller, more focused modules?** - _Cohesion score 0.08326530612244898 - nodes in this community are weakly interconnected._ + _Cohesion score 0.061955965181771634 - nodes in this community are weakly interconnected._ - **Should `Controller` be split into smaller, more focused modules?** - _Cohesion score 0.07123034227567067 - nodes in this community are weakly interconnected._ \ No newline at end of file + _Cohesion score 0.07342995169082125 - 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 526787e..58c52f1 100644 --- a/graphify-out/graph.html +++ b/graphify-out/graph.html @@ -63,12 +63,12 @@

Communities

-
523 nodes · 874 edges · 50 communities
+
609 nodes · 1055 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..2e46c40 --- /dev/null +++ b/internal/settings/server.go @@ -0,0 +1,231 @@ +// 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 new file mode 100644 index 0000000..e9e0741 --- /dev/null +++ b/internal/settings/server_test.go @@ -0,0 +1,110 @@ +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 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/taskbar/taskbar_windows.go b/internal/taskbar/taskbar_windows.go index 889c894..eea50c4 100644 --- a/internal/taskbar/taskbar_windows.go +++ b/internal/taskbar/taskbar_windows.go @@ -137,6 +137,9 @@ func toPolicy(ap config.Appearance, light bool) policy { } case config.AccentBlur: st = winapi.AccentEnableBlurBehind + if alpha == 0 { + alpha = 1 // same quirk as clear: a fully zero tint can render opaque black + } case config.AccentAcrylic: st = winapi.AccentEnableAcrylicBlurBG if alpha == 0 {