diff --git a/.github/release-notes/v0.7.0-alpha.md b/.github/release-notes/v0.7.0-alpha.md new file mode 100644 index 0000000..f67530e --- /dev/null +++ b/.github/release-notes/v0.7.0-alpha.md @@ -0,0 +1,87 @@ +**FocusWShell 0.7.0-alpha: the deck on the network. Use the deck from a tablet or a phone, in its browser.** [Español más abajo](#español). + +> **It moves your windows.** If anything goes wrong, **Ctrl+Alt+Shift+Backspace** puts every window back where it was, at any time. + +## What's new + +### The deck on the network + +FocusWShell can now serve the deck as a web page on your local network. Open it in the browser of a tablet or a phone on the same Wi-Fi and tap: FocusWShell does the same as with the deck on the PC. You don't need Apollo, and there's nothing to install on the tablet. + +- **The whole deck, with every monitor at once:** the focus and the app in use, **Previous**, **To panel**, **Free all**, and the modes **Move…**, **Pin…**, **Minimize…**, **Fullscreen…** (an app in fullscreen on the monitor you choose) and **Close…**. +- **Each panel's presentation** (tiles, tabs, list, fill) and, in tabs, ◀ ▶. +- **The main screen layout** and **System**: keep the PC's screen on, the mouse to the focus app and **Rearrange all**. +- **🗂 Pages**, only if you turn on **Show the browser pages**. +- Two columns in landscape, one on a phone or a tablet in portrait. + +Turn it on in the main window, in **Deck on the network**, then tap **Pair** and scan the QR code with the tablet. How it works, step by step: **[Deck on the network](https://proteo5.github.io/FocusWShell/deck-network/)**. + +### Privacy and security + +- It's **off** until you turn it on. FocusWShell still doesn't connect to the internet. +- It only listens on networks that Windows marks as **private** (or domain), never on a public one. +- Each device is paired once with a one-time code (QR or 6 digits) and has its own key. **Remove** cuts it off at once. After 5 wrong codes, the code is cancelled. +- It only accepts requests from its own page: another website open on the tablet can't talk to your PC. + +**Before you use it:** + +- **The connection is not encrypted** (plain HTTP). Use it on a network you trust, such as your home Wi-Fi. +- **The Windows Firewall** must allow FocusWShell on **private** networks. If the tablet doesn't connect, see *If the tablet doesn't connect* in the manual. +- The page can't keep the tablet's screen on yet: raise the screen timeout in the tablet's settings. +- Tested on an Android tablet; not yet on an iPad. +- The power buttons and each app's long-press menu stay on the deck on the PC. + +## Install or update + +1. Download `FocusWShell-0.7.0-alpha-win-x64.zip` below. +2. Extract it to a **new** folder and double-click **install.cmd**. If an earlier version is open, the installer closes it first (putting your windows back) and keeps your settings. + +Windows 10 (2004) or 11, 64-bit. No administrator rights; .NET is included. The files are not signed: if Windows shows *"Windows protected your PC"*, choose **More info → Run anyway**. Check the download with the `.sha256` file. + +New to FocusWShell? Start with **[Getting started](https://proteo5.github.io/FocusWShell/first-steps/)**. Known limitations: see [Known limitations](https://proteo5.github.io/FocusWShell/limitations/). Please report problems and ideas in [Issues](https://github.com/proteo5/FocusWShell/issues). + +--- + +## Español + +**FocusWShell 0.7.0-alpha: el deck en la red. Usa el deck desde una tablet o un teléfono, en su navegador.** + +> **Mueve tus ventanas.** Si algo sale mal, **Ctrl+Alt+Mayús+Retroceso** devuelve todas las ventanas a su sitio, en cualquier momento. + +### Novedades + +#### El deck en la red + +FocusWShell ahora puede servir el deck como página web en tu red local. Ábrela en el navegador de una tablet o un teléfono en el mismo wifi y toca: FocusWShell hace lo mismo que con el deck del PC. No necesitas Apollo, y no hay que instalar nada en la tablet. + +- **Todo el deck, con todos los monitores a la vez:** el foco y la app en uso, **Anterior**, **Al panel**, **Liberar todas**, y los modos **Mover…**, **Anclar…**, **Minimizar…**, **Pantalla…** (una app en pantalla completa en el monitor que elijas) y **Cerrar…**. +- **La presentación de cada panel** (cuadrícula, pestañas, lista, llenar) y, en pestañas, ◀ ▶. +- **La disposición del principal** y **Sistema**: mantener encendida la pantalla del PC, el ratón a la app del foco y **Reordenar todas**. +- **🗂 Páginas**, sólo si prendes **Mostrar las páginas de los navegadores**. +- Dos columnas en horizontal, una en un teléfono o una tablet en vertical. + +Préndelo en la ventana principal, en **Deck en la red**; luego toca **Emparejar** y escanea el código QR con la tablet. Cómo funciona, paso a paso: **[Deck en la red](https://proteo5.github.io/FocusWShell/es/deck-red/)**. + +#### Privacidad y seguridad + +- Está **apagado** hasta que lo prendas. FocusWShell sigue sin conectarse a internet. +- Sólo escucha en redes que Windows marca como **privadas** (o de dominio), nunca en una pública. +- Cada dispositivo se empareja una vez con un código de un solo uso (QR o 6 cifras) y tiene su propia llave. **Quitar** lo corta al momento. Tras 5 códigos equivocados, el código se anula. +- Sólo acepta peticiones de su propia página: otra web abierta en la tablet no puede hablarle a tu PC. + +**Antes de usarlo:** + +- **La conexión no va cifrada** (HTTP). Úsalo en una red de confianza, como el wifi de tu casa. +- **El Firewall de Windows** tiene que permitir FocusWShell en redes **privadas**. Si la tablet no conecta, ve *Si la tablet no conecta* en el manual. +- La página todavía no puede mantener encendida la pantalla de la tablet: sube el tiempo de pantalla en los ajustes de la tablet. +- Probado en una tablet Android; todavía no en un iPad. +- Los botones de energía y el menú de cada app con pulsación larga se quedan en el deck del PC. + +### Instalar o actualizar + +1. Descarga `FocusWShell-0.7.0-alpha-win-x64.zip` más abajo. +2. Descomprímelo en una carpeta **nueva** y haz doble clic en **install.cmd**. Si hay una versión anterior abierta, el instalador la cierra antes (devolviendo tus ventanas) y conserva tu configuración. + +Windows 10 (2004) u 11, de 64 bits. Sin permisos de administrador; .NET va incluido. Los archivos no están firmados: si Windows muestra *«Windows protegió tu PC»*, elige **Más información → Ejecutar de todas formas**. Comprueba la descarga con el archivo `.sha256`. + +¿Nuevo en FocusWShell? Empieza por **[Primeros pasos](https://proteo5.github.io/FocusWShell/es/primeros-pasos/)**. Limitaciones conocidas: ver [Limitaciones conocidas](https://proteo5.github.io/FocusWShell/es/limitaciones/). Reporta problemas e ideas en [Issues](https://github.com/proteo5/FocusWShell/issues). diff --git a/CHANGELOG.md b/CHANGELOG.md index f8ef664..ae67eb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,14 @@ All notable changes to FocusWShell. Each release has its notes in [`.github/rele Todos los cambios importantes de FocusWShell. Cada versión tiene sus notas en [`.github/release-notes/`](.github/release-notes/). -## Unreleased / Sin publicar +## 0.7.0-alpha -- New: the deck on the network. FocusWShell can serve the deck as a web page on your local network, to use it from a tablet or a phone without Apollo (Android and iPad, nothing to install). Off by default; each device is paired once with a QR code and can be removed at any time. / Nuevo: el deck en la red. FocusWShell puede servir el deck como página web en tu red local, para usarlo desde una tablet o un teléfono sin Apollo (Android y iPad, sin instalar nada). Apagado por defecto; cada dispositivo se empareja una vez con un código QR y se puede quitar cuando quieras. +The deck on the network: use the deck from a tablet or a phone, in its browser. / El deck en la red: usa el deck desde una tablet o un teléfono, en su navegador. + +- New: the deck on the network. FocusWShell can serve the deck as a web page on your local network, to use it from a tablet or a phone without Apollo (nothing to install on the tablet). It does what the deck on the PC does, with every monitor at once: the focus and the app in use, Previous, To panel, Free all, the modes Move, Pin, Minimize, Fullscreen and Close, each panel's presentation, the main screen layout, System and the browser pages. / Nuevo: el deck en la red. FocusWShell puede servir el deck como página web en tu red local, para usarlo desde una tablet o un teléfono sin Apollo (sin instalar nada en la tablet). Hace lo mismo que el deck del PC, con todos los monitores a la vez: el foco y la app en uso, Anterior, Al panel, Liberar todas, los modos Mover, Anclar, Minimizar, Pantalla y Cerrar, la presentación de cada panel, la disposición del principal, Sistema y las páginas de los navegadores. +- It's off by default and only listens on networks Windows marks as private. Each device is paired once with a QR code and can be removed at any time. The connection is not encrypted (plain HTTP): use it on a network you trust, such as your home Wi-Fi. / Viene apagado y sólo escucha en redes que Windows marca como privadas. Cada dispositivo se empareja una vez con un código QR y se puede quitar cuando quieras. La conexión no va cifrada (HTTP): úsalo en una red de confianza, como el wifi de tu casa. + +Notes / Notas: [v0.7.0-alpha](.github/release-notes/v0.7.0-alpha.md) ## 0.6.0-alpha diff --git a/Directory.Build.props b/Directory.Build.props index 8394dfd..ada5f5e 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,7 +7,7 @@ latest-recommended true - 0.6.0-alpha + 0.7.0-alpha diff --git a/README.es.md b/README.es.md index 4ddca85..4ed30d7 100644 --- a/README.es.md +++ b/README.es.md @@ -32,7 +32,7 @@ Una ventana sólo cambia de lugar cuando tú lo decides. Hacer clic en el chat o ## Instalar -1. Descarga `FocusWShell-0.6.0-alpha-win-x64.zip` desde [Releases](https://github.com/proteo5/FocusWShell/releases). +1. Descarga `FocusWShell-0.7.0-alpha-win-x64.zip` desde [Releases](https://github.com/proteo5/FocusWShell/releases). 2. Descomprime todo el zip y haz doble clic en **install.cmd**. 3. FocusWShell se abre y aparece en la bandeja, junto al reloj. También está en el menú Inicio. @@ -53,9 +53,11 @@ El [manual](https://proteo5.github.io/FocusWShell/es/) explica cada parte, los a El deck funciona en cualquier pantalla, pero luce en una tablet junto al teclado. Lo probado es **[Apollo](https://github.com/ClassicOldSong/Apollo)** en el PC y **Artemis** en una tablet Android: Apollo crea un monitor virtual con la resolución de la tablet, así que Windows la ve como una pantalla más. Moonlight (iPad) y Sunshine con un controlador de pantalla virtual deberían funcionar también, pero no se han probado. +Sin nada de eso, el **[deck en la red](https://proteo5.github.io/FocusWShell/es/deck-red/)** sirve el deck como página web en tu red local: ábrelo en el navegador de la tablet, empareja una vez con un código QR, y toca. + ## Privacidad -FocusWShell funciona sólo en tu PC. No se conecta a la red ni envía telemetría. Los títulos de las pestañas se leen sólo mientras la lista de *Páginas* está a la vista y nunca se guardan. +FocusWShell funciona sólo en tu PC. No se conecta a internet ni envía telemetría. El deck en la red está apagado hasta que lo prendas, sólo escucha en redes privadas y sólo responde a los dispositivos que emparejes. Los títulos de las pestañas se leen sólo mientras la lista de *Páginas* está a la vista y nunca se guardan. ## Comentarios diff --git a/README.md b/README.md index 834e5af..e17523a 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ A window only changes place when you decide. Clicking the chat or getting a noti ## Install -1. Download `FocusWShell-0.6.0-alpha-win-x64.zip` from [Releases](https://github.com/proteo5/FocusWShell/releases). +1. Download `FocusWShell-0.7.0-alpha-win-x64.zip` from [Releases](https://github.com/proteo5/FocusWShell/releases). 2. Extract the whole zip and double-click **install.cmd**. 3. FocusWShell opens and shows up in the tray, next to the clock. It is also in the Start menu. @@ -53,9 +53,11 @@ The [manual](https://proteo5.github.io/FocusWShell/) explains each part, the sho The deck works on any screen, but it shines on a tablet next to your keyboard. The tested setup is **[Apollo](https://github.com/ClassicOldSong/Apollo)** on the PC and **Artemis** on an Android tablet: Apollo creates a virtual monitor at the tablet's resolution, so Windows sees it as one more screen. Moonlight (iPad) and Sunshine with a virtual display driver should work too, but have not been tested. +Without any of that, the **[deck on the network](https://proteo5.github.io/FocusWShell/deck-network/)** serves the deck as a web page on your local network: open it in the tablet's browser, pair it once with a QR code, and tap. + ## Privacy -FocusWShell runs on your PC only. It makes no network connections and sends no telemetry. Browser tab titles are read only while the *Pages* list is on screen and are never saved. +FocusWShell runs on your PC only. It doesn't connect to the internet and sends no telemetry. The deck on the network is off until you turn it on, only listens on private networks and only answers the devices you pair. Browser tab titles are read only while the *Pages* list is on screen and are never saved. ## Feedback diff --git a/docs/05-hoja-de-ruta.md b/docs/05-hoja-de-ruta.md index 3acabc9..c436e04 100644 --- a/docs/05-hoja-de-ruta.md +++ b/docs/05-hoja-de-ruta.md @@ -59,7 +59,7 @@ Objetivo: manejar el escritorio por paneles propios y vistas, con un deck opcion 8. **El foco con lugar propio en el deck**, el modo Minimizar y las apps que se cierran a la bandeja ([ADR 0013, enmienda](adr/0013-deck-superficie-de-control.md#enmienda-el-lugar-del-foco-y-el-modo-minimizar-2026-11-13), [ADR 0018](adr/0018-apps-en-la-bandeja.md)). **Hecho** (0.3.0-alpha). 9. **Actividad**: cuánto pasa cada app en el foco y en uso, y el tiempo en paralelo; en el deck, la app en uso junto a la del foco ([ADR 0019](adr/0019-actividad-foco-y-uso.md)). **Hecho** (0.4.0-alpha): la medición y el día; en 0.5.0-alpha, los sitios de los navegadores. Después: pares, línea del día, semana y exportar. 10. **El deck con todos los monitores a la vez**, uno arriba del otro, sin pestañas ([ADR 0020](adr/0020-deck-monitores-apilados.md)). **Hecho** (0.6.0-alpha). -11. **El deck por la red**: una app web que sirve FocusWShell, para Android e iPad sin Apollo (fase 3 del [ADR 0013](adr/0013-deck-superficie-de-control.md)). **Hecho** el MVP por HTTP ([ADR 0021](adr/0021-deck-por-la-red.md), spike S13). Después: los modos, la disposición, la energía y la pantalla encendida. +11. **El deck por la red**: una app web que sirve FocusWShell, para Android e iPad sin Apollo (fase 3 del [ADR 0013](adr/0013-deck-superficie-de-control.md)). **Hecho** (0.7.0-alpha) por HTTP ([ADR 0021](adr/0021-deck-por-la-red.md), spike S13), con todo el deck del PC salvo la energía y el menú de pulsación larga. Pendiente: el cifrado (para mantener encendida la pantalla de la tablet) y probar en un iPad. Criterio de salida: una semana de uso diario cambiando de vista y llevando apps al foco desde el deck, sin tocar los atajos. diff --git a/docs/adr/0021-deck-por-la-red.md b/docs/adr/0021-deck-por-la-red.md index 7213662..82ba3a8 100644 --- a/docs/adr/0021-deck-por-la-red.md +++ b/docs/adr/0021-deck-por-la-red.md @@ -1,6 +1,6 @@ # ADR 0021 — El deck por la red, como app web servida por FocusWShell -- **Estado:** Aceptada (2026-11-27): transporte por HTTP (opción A) tras el spike S13; MVP hecho. +- **Estado:** Aceptada (2026-11-27): transporte por HTTP (opción A) tras el spike S13. Publicado en 0.7.0-alpha. - **Fecha:** 2026-11-27 ## Contexto @@ -126,4 +126,19 @@ Hecho y probado en la tablet Android del usuario: - **Interfaz:** dos columnas en horizontal (incluida una tablet pequeña), una en vertical o en un teléfono; todos los monitores apilados (ADR 0020); ⛶ entra y sale de pantalla completa; las apps sin icono muestran su inicial. - **Privacidad:** el texto de General cambia cuando el deck en la red está prendido. -Pendiente: los modos Anclar, Minimizar y Cerrar, la disposición del principal, la energía (desactivada en remoto), la pantalla encendida (opción C), comprobar la categoría de red de Windows (hoy sólo se mira que la dirección sea privada) y probar en un iPad. +Agregado el 2026-11-28: Anclar, la app en uso junto al foco, la presentación de cada panel con ◀ ▶, la disposición del principal, Minimizar, Cerrar, Liberar todas con confirmación y Sistema (pantalla encendida, ratón al foco, reordenar). Después: el modo **Pantalla…** (una app en pantalla completa en el monitor que se elija; comando `fullscreen` con el `id` de uno de los `screens` del estado, que lista los monitores conectados aunque no tengan paneles), «de {panel}» bajo la app del foco, y Páginas sin desplazamiento horizontal. + +Decidido no llevar a la red: la energía, y el menú de cada app con pulsación larga (lo que hace ya está en los modos, y en un navegador táctil la pulsación larga choca con la selección de texto). Pendiente: mantener encendida la pantalla de la tablet (necesita el cifrado, opción C) y probar en un iPad. + +## Seguridad (2026-11-28) + +Antes de publicarlo en una alfa: + +1. **Emparejar con límite.** Cinco intentos fallidos anulan el código (`DeckWebDevices.MaxFailures`), y cada dirección que falla cinco veces espera 10 minutos; cada intento tarda 300 ms. +2. **Origen y host.** El `Host` tiene que ser una dirección del PC en la que escucha (contra el DNS rebinding), y lo que cambia algo (emparejar, el WebSocket) exige un `Origin` igual al de la página. Cabeceras `nosniff` y `X-Frame-Options: DENY`. +3. **Sólo redes privadas o de dominio de Windows** (`PrivateNetworks`, con el Network List Manager). Kestrel escucha sólo en las direcciones de esas redes, nunca en una pública ni en adaptadores que Windows no reconoce (Hyper-V, Docker). Se vuelve a elegir cuando cambian las direcciones y cada 20 s, porque marcar una red como privada no avisa. Si todas las redes son públicas, la sección lo explica y lleva a los ajustes de red de Windows. Hallazgo: el wifi del usuario estaba marcado como público, como hace Windows con las redes nuevas. +4. **Límites.** Tres conexiones por dispositivo, 32 en total, peticiones de 4 KB como mucho, y leer las páginas como mucho cada 2 s por conexión. + +Hallazgo del Firewall: la primera vez que FocusWShell escucha, Windows pregunta y crea la regla para el perfil de la red de ese momento. Con el wifi marcado como público, la regla quedó sólo para redes públicas; al marcarlo como privado, el Firewall bloqueaba la tablet y no volvía a preguntar. Se arregla a mano (con permisos de administrador); la sección y el manual lo explican. + +Sigue pendiente el cifrado (opción C): sin él, quien comparta la red puede ver el tráfico, incluido el token. diff --git a/site/deck-network.md b/site/deck-network.md index f51ed39..04e51b5 100644 --- a/site/deck-network.md +++ b/site/deck-network.md @@ -16,9 +16,10 @@ It's **off** until you turn it on, and it only answers the devices you pair. 1. In the main window, open **Deck on the network** and turn on **Serve the deck on the local network**. 2. The first time, Windows may ask for Firewall permission. Allow **private networks** only. -3. Tap **Pair**. A QR code and a 6-digit code appear; they work once and expire in 5 minutes. -4. On the tablet (on the same Wi-Fi), scan the QR code with the camera, or open the address shown and type the code. Give the device a name and tap **Pair**. -5. The deck opens. Add it to the home screen from the browser menu, so it opens straight into the deck next time. +3. It only listens on networks that Windows marks as **private** (or domain). If your home Wi-Fi is marked as public, the section says so and has a button to the Windows network settings: open your network and choose **Private network**. The deck starts listening by itself. +4. Tap **Pair**. A QR code and a 6-digit code appear; they work once and expire in 5 minutes. +5. On the tablet (on the same Wi-Fi), scan the QR code with the camera, or open the address shown and type the code. Give the device a name and tap **Pair**. +6. The deck opens. Add it to the home screen from the browser menu, so it opens straight into the deck next time. The tablet stays paired. To remove it, tap **Remove** next to it in **Deck on the network**: it is disconnected at once. @@ -26,15 +27,18 @@ The tablet stays paired. To remove it, tap **Remove** next to it in **Deck on th The same as the deck on the PC, with every monitor at once: -- **Left:** the app in focus, **Previous**, **To panel**, **Free all** and **Move…**. -- **Right:** each monitor with its panels, and below, **Free** and **🗂 Pages**. +- **Left:** the app in focus, with the panel it comes from (and, if you type in another one, that app next to it, with a white border), **Previous**, **To panel**, **Free all** (it asks for a second tap), and the modes **Move…**, **Pin…**, **Minimize…**, **Fullscreen…** and **Close…**. Below, the **main screen layout** (tap a column to turn it on or off; press and hold to reset the width) and **System**: keep the PC's screen on, the mouse to the focus app and, after a Free all, **Rearrange all**. +- **Right:** each monitor with its panels, and below, **Free** and **🗂 Pages**. Each panel header has its presentation (▦ ⧉ ☰, and ⛶ outside the main screen) and, in tabs, ◀ ▶. - **Tap an app** to bring it to the focus. In a panel in tabs, tapping a hidden tab shows it in its panel; a closed pinned app opens in its panel; a free one comes to the front. - **Move…:** tap the app, then the panel where it goes, the focus, or **Free** to free it. -- **⛶** enters and leaves fullscreen. +- **Pin…:** tap apps to pin or unpin them in their panel; tap **Pin…** again to finish. +- **Minimize…** and **Close…:** tap one app; the mode turns off by itself. A minimized app stays in its panel, and minimizing it again brings it back. Closing works like its ✕: if it has unsaved work, it asks on the PC. +- **Fullscreen…:** tap an app and, if you have more than one monitor, the monitor where it goes fullscreen. To take it out, tap it in the focus, or tap **To panel**. +- **⛶** (at the top) puts the page in fullscreen on the tablet, and takes it out. In landscape it uses two columns, like the deck on the PC; on a phone or a tablet in portrait, one. -Not in this version yet: the Pin, Minimize and Close modes, the main screen layout and the power buttons. Use the deck on the PC for those. +The power buttons (lock, sleep, restart, shut down) are not on the network: use the deck on the PC for those. Neither is each app's long-press menu; what it does is in the modes. ## Browser pages @@ -44,9 +48,21 @@ Not in this version yet: the Pin, Minimize and Close modes, the main screen layo For now the page can't keep the tablet's screen on (browsers only allow it over an encrypted connection). Raise the screen timeout in the tablet's settings. +## If the tablet doesn't connect + +- **Is the network private?** The section **Deck on the network** says so if Windows marks it as public. +- **The Windows Firewall** must allow FocusWShell on **private** networks. If you first turned it on while the network was marked as public, Windows allowed it for public networks only, and doesn't ask again. Fix it in **Control Panel → Windows Defender Firewall → Allow an app or feature…**: tap **Change settings**, find **focuswshell.exe** and check **Private** (uncheck **Public**). Or, in PowerShell as administrator: + + ```powershell + Get-NetFirewallRule -DisplayName 'focuswshell.exe' | Set-NetFirewallRule -Profile Private + ``` +- **Same Wi-Fi:** the tablet must be on the same network as the PC. + ## Privacy and security - FocusWShell doesn't connect to the internet. With the deck on the network on, it listens on your local network, on port 8765, and only for the devices you paired. -- It only answers addresses of the local network (such as 192.168.…), never from the internet. On a public Wi-Fi (a café, an airport) anyone on that network could see what travels: turn it off there. +- It only listens on networks that Windows marks as private or domain, never on a public one (a café, an airport), and only answers addresses of the local network. +- After 5 wrong pairing codes, the code is cancelled, and that address has to wait 10 minutes. +- It only accepts requests from its own page: another website open on the tablet can't talk to your PC. - Each device has its own key, which only the device keeps. Removing it cuts it off at once. - The connection is not encrypted (plain HTTP). Use it on a network you trust, such as your home Wi-Fi. diff --git a/site/es/comentarios.md b/site/es/comentarios.md index 5837591..2440303 100644 --- a/site/es/comentarios.md +++ b/site/es/comentarios.md @@ -12,7 +12,7 @@ permalink: /es/comentarios/ Abre un issue en [github.com/proteo5/FocusWShell/issues](https://github.com/proteo5/FocusWShell/issues). Ayuda mucho incluir: -- **La versión:** la primera línea del menú de la bandeja o General → Acerca de, por ejemplo *FocusWShell 0.6.0-alpha*. +- **La versión:** la primera línea del menú de la bandeja o General → Acerca de, por ejemplo *FocusWShell 0.7.0-alpha*. - **Tus monitores:** cuántos, cuál es el principal, su resolución y su escala (Configuración → Sistema → Pantalla). - **Qué hiciste y qué pasó,** paso a paso. - **`errors.log`,** si existe, en `%LOCALAPPDATA%\FocusWShell`. diff --git a/site/es/deck-red.md b/site/es/deck-red.md index 614958d..3cbefd0 100644 --- a/site/es/deck-red.md +++ b/site/es/deck-red.md @@ -16,9 +16,10 @@ Está **apagado** hasta que lo prendas, y sólo responde a los dispositivos que 1. En la ventana principal, abre **Deck en la red** y prende **Servir el deck en la red local**. 2. La primera vez, Windows puede pedir permiso en el Firewall. Acepta sólo **redes privadas**. -3. Toca **Emparejar**. Aparecen un código QR y un código de 6 cifras; sirven una vez y caducan en 5 minutos. -4. En la tablet (en el mismo wifi), escanea el QR con la cámara, o abre la dirección que aparece y escribe el código. Ponle un nombre al dispositivo y toca **Emparejar**. -5. Se abre el deck. Agrégalo a la pantalla de inicio desde el menú del navegador, para que la próxima vez entre directo. +3. Sólo escucha en redes que Windows marca como **privadas** (o de dominio). Si el wifi de tu casa está marcado como público, la sección lo dice y tiene un botón a los ajustes de red de Windows: abre tu red y elige **Red privada**. El deck empieza a escuchar solo. +4. Toca **Emparejar**. Aparecen un código QR y un código de 6 cifras; sirven una vez y caducan en 5 minutos. +5. En la tablet (en el mismo wifi), escanea el QR con la cámara, o abre la dirección que aparece y escribe el código. Ponle un nombre al dispositivo y toca **Emparejar**. +6. Se abre el deck. Agrégalo a la pantalla de inicio desde el menú del navegador, para que la próxima vez entre directo. La tablet queda emparejada. Para quitarla, toca **Quitar** junto a ella en **Deck en la red**: se desconecta al momento. @@ -26,15 +27,18 @@ La tablet queda emparejada. Para quitarla, toca **Quitar** junto a ella en **Dec Lo mismo que el deck del PC, con todos los monitores a la vez: -- **A la izquierda:** la app del foco, **Anterior**, **Al panel**, **Liberar todas** y **Mover…**. -- **A la derecha:** cada monitor con sus paneles y, abajo, **Libres** y **🗂 Páginas**. +- **A la izquierda:** la app del foco, con el panel de donde viene (y, si escribes en otra, esa app a su lado, con borde blanco), **Anterior**, **Al panel**, **Liberar todas** (pide un segundo toque), y los modos **Mover…**, **Anclar…**, **Minimizar…**, **Pantalla…** y **Cerrar…**. Debajo, la **disposición del principal** (toca una columna para prenderla o apagarla; déjala apretada para restablecer el ancho) y **Sistema**: mantener encendida la pantalla del PC, el ratón a la app del foco y, tras un Liberar todas, **Reordenar todas**. +- **A la derecha:** cada monitor con sus paneles y, abajo, **Libres** y **🗂 Páginas**. La cabecera de cada panel tiene su presentación (▦ ⧉ ☰, y ⛶ fuera del principal) y, en pestañas, ◀ ▶. - **Toca una app** para llevarla al foco. En un panel en pestañas, tocar una pestaña oculta la muestra en su panel; una app anclada y cerrada se abre en su panel; una libre se trae al frente. - **Mover…:** toca la app y luego el panel donde va, el foco, o **Libres** para liberarla. -- **⛶** entra y sale de pantalla completa. +- **Anclar…:** toca apps para anclarlas o desanclarlas en su panel; toca **Anclar…** otra vez para terminar. +- **Minimizar…** y **Cerrar…:** toca una app; el modo se apaga solo. Una minimizada se queda en su panel, y minimizarla otra vez la devuelve. Cerrar funciona como su ✕: si tiene algo sin guardar, pregunta en el PC. +- **Pantalla…:** toca una app y, si tienes más de un monitor, el monitor donde va en pantalla completa. Para sacarla, tócala en el foco, o toca **Al panel**. +- **⛶** (arriba) pone en pantalla completa la página en la tablet, y la saca. En horizontal usa dos columnas, como el deck del PC; en un teléfono o una tablet en vertical, una. -Todavía no tiene: los modos Anclar, Minimizar y Cerrar, la disposición del principal ni los botones de energía. Para eso, usa el deck del PC. +No están en la red los botones de energía (bloquear, suspender, reiniciar, apagar): para eso, usa el deck del PC. El menú de cada app con pulsación larga tampoco; lo que hace está en los modos. ## Páginas de los navegadores @@ -44,9 +48,21 @@ Todavía no tiene: los modos Anclar, Minimizar y Cerrar, la disposición del pri Por ahora la página no puede mantener encendida la pantalla de la tablet (los navegadores sólo lo permiten con una conexión cifrada). Sube el tiempo de pantalla en los ajustes de la tablet. +## Si la tablet no conecta + +- **¿La red es privada?** La sección **Deck en la red** lo dice si Windows la marca como pública. +- **El Firewall de Windows** tiene que permitir FocusWShell en redes **privadas**. Si lo prendiste por primera vez con la red marcada como pública, Windows lo permitió sólo para redes públicas, y no vuelve a preguntar. Arréglalo en **Panel de control → Firewall de Windows Defender → Permitir una aplicación o una característica…**: toca **Cambiar la configuración**, busca **focuswshell.exe** y marca **Privada** (desmarca **Pública**). O, en PowerShell como administrador: + + ```powershell + Get-NetFirewallRule -DisplayName 'focuswshell.exe' | Set-NetFirewallRule -Profile Private + ``` +- **El mismo wifi:** la tablet tiene que estar en la misma red que el PC. + ## Privacidad y seguridad - FocusWShell no se conecta a internet. Con el deck en la red prendido, escucha en tu red local, en el puerto 8765, y sólo para los dispositivos que emparejaste. -- Sólo responde a direcciones de la red local (como 192.168.…), nunca de internet. En un wifi público (un café, un aeropuerto) cualquiera en esa red podría ver lo que viaja: apágalo ahí. +- Sólo escucha en redes que Windows marca como privadas o de dominio, nunca en una pública (un café, un aeropuerto), y sólo responde a direcciones de la red local. +- Tras 5 códigos de emparejamiento equivocados, el código se anula, y esa dirección tiene que esperar 10 minutos. +- Sólo acepta peticiones de su propia página: otra web abierta en la tablet no puede hablarle a tu PC. - Cada dispositivo tiene su propia llave, que sólo guarda el dispositivo. Quitarlo lo corta al momento. - La conexión no va cifrada (HTTP). Úsalo en una red de confianza, como el wifi de tu casa. diff --git a/site/es/instalar.md b/site/es/instalar.md index 8b09b76..ac9d9db 100644 --- a/site/es/instalar.md +++ b/site/es/instalar.md @@ -30,7 +30,7 @@ El instalador copia FocusWShell a `%LOCALAPPDATA%\Programs\FocusWShell`, lo aña Los archivos todavía no están firmados, así que Windows puede avisarte la primera vez, porque vienen de internet. Elige **Más información → Ejecutar de todas formas**. Puedes comprobar la descarga con el archivo `.sha256` que se publica junto al zip: ```powershell -Get-FileHash .\FocusWShell-0.6.0-alpha-win-x64.zip -Algorithm SHA256 +Get-FileHash .\FocusWShell-0.7.0-alpha-win-x64.zip -Algorithm SHA256 ``` ## Iniciar con Windows diff --git a/site/feedback.md b/site/feedback.md index c93ca58..ff02e7b 100644 --- a/site/feedback.md +++ b/site/feedback.md @@ -12,7 +12,7 @@ permalink: /feedback/ Open an issue at [github.com/proteo5/FocusWShell/issues](https://github.com/proteo5/FocusWShell/issues). It helps a lot to include: -- **The version:** the first line of the tray menu or General → About, for example *FocusWShell 0.6.0-alpha*. +- **The version:** the first line of the tray menu or General → About, for example *FocusWShell 0.7.0-alpha*. - **Your monitors:** how many, which one is the main one, their resolution and scaling (Settings → System → Display). - **What you did and what happened,** step by step. - **`errors.log`,** if it exists, in `%LOCALAPPDATA%\FocusWShell`. diff --git a/site/install.md b/site/install.md index b0405f4..5c94ef9 100644 --- a/site/install.md +++ b/site/install.md @@ -30,7 +30,7 @@ The installer copies FocusWShell to `%LOCALAPPDATA%\Programs\FocusWShell`, adds The files are not signed yet, so Windows may warn you the first time, because they come from the internet. Choose **More info → Run anyway**. You can check the download against the `.sha256` file published next to the zip: ```powershell -Get-FileHash .\FocusWShell-0.6.0-alpha-win-x64.zip -Algorithm SHA256 +Get-FileHash .\FocusWShell-0.7.0-alpha-win-x64.zip -Algorithm SHA256 ``` ## Start with Windows diff --git a/src/FocusWShell.App/App.xaml.cs b/src/FocusWShell.App/App.xaml.cs index 44c6186..ad93957 100644 --- a/src/FocusWShell.App/App.xaml.cs +++ b/src/FocusWShell.App/App.xaml.cs @@ -537,7 +537,10 @@ public void ToggleDeck() Dispatcher.BeginInvoke(() => { _main?.Refresh(); - PresentDeck(); + if (_deck?.IsVisible == true) + { + PresentDeck(); + } }); return result; }), @@ -555,7 +558,10 @@ await Task.Run(() => WindowMover.Close(handle); }); await Task.Delay(1500); - PresentDeck(); + if (_deck?.IsVisible == true) + { + PresentDeck(); // desde la red, el deck del PC no se abre + } }, BringToFront: handle => Task.Run(() => { @@ -578,7 +584,7 @@ await Task.Run(() => SetPinned: (appKey, pinned) => { _controller.SetAppPinned(appKey, pinned); - PresentDeck(); + RefreshDeck(); // al día si está a la vista; desde la red, el deck del PC no se abre }, ReadPages: () => Task.Run(_controller.BrowserPages), SelectPage: (handle, tab) => Task.Run(() => ShellController.SelectPage(handle, tab)), diff --git a/src/FocusWShell.App/DeckWeb/DeckWebDevices.cs b/src/FocusWShell.App/DeckWeb/DeckWebDevices.cs index 983fadd..ff8e28a 100644 --- a/src/FocusWShell.App/DeckWeb/DeckWebDevices.cs +++ b/src/FocusWShell.App/DeckWeb/DeckWebDevices.cs @@ -55,10 +55,20 @@ public string NewCode() { var code = RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); _code = (code, DateTime.UtcNow + CodeLife); + _failures = 0; return code; } } + /// Intentos fallidos con el código de ahora: al llegar a , el código deja de valer. + private int _failures; + + /// Con 6 cifras, 5 intentos dan 1 entre 200 000 de acertar a ciegas antes de que el código se anule. + public const int MaxFailures = 5; + + /// Si el código se anuló por intentos fallidos (para decirlo en la ventana principal). + public event Action? CodeBurned; + /// Si el código vale (sin gastarlo). public bool IsValidCode(string? code) { @@ -73,6 +83,25 @@ public bool IsValidCode(string? code) public string? Pair(string? code, string name) { string token; + bool burned = false; + lock (_gate) + { + if (!IsValidCode(code)) + { + // Un intento fallido con un código vigente cuenta; a los cinco, se anula y hay que pedir otro. + if (_code is { } current && current.Until > DateTime.UtcNow && ++_failures >= MaxFailures) + { + _code = null; + burned = true; + } + } + } + + if (burned) + { + CodeBurned?.Invoke(); + } + lock (_gate) { if (!IsValidCode(code)) diff --git a/src/FocusWShell.App/DeckWeb/DeckWebServer.cs b/src/FocusWShell.App/DeckWeb/DeckWebServer.cs index 6ee6985..4dc9922 100644 --- a/src/FocusWShell.App/DeckWeb/DeckWebServer.cs +++ b/src/FocusWShell.App/DeckWeb/DeckWebServer.cs @@ -72,27 +72,81 @@ public DeckWebServer( /// Las direcciones del PC en la red local (una por red privada). public IReadOnlyList Urls { get; private set; } = []; + /// No escucha porque Windows marca como públicas todas las redes conectadas. + public bool PublicOnly { get; private set; } + /// Si no se pudo escuchar (puerto ocupado, sin permiso), por qué. public string? Error { get; private set; } + /// Conexiones abiertas a la vez por dispositivo (una tablet con dos pestañas, más una que reconecta). + private const int MaxSocketsPerDevice = 3; + + /// Las direcciones del PC en las que escucha: sólo las de redes que Windows marca como privadas o de dominio. + private IReadOnlyList _addresses = []; + + /// + /// Escucha sólo en las redes privadas o de dominio de Windows (no en una pública, ni en adaptadores virtuales + /// que Windows no reconoce como red), y vuelve a elegir cuando cambian las redes del PC. + /// public async Task StartAsync() { + NetworkChange.NetworkAddressChanged -= OnNetworkChanged; + NetworkChange.NetworkAddressChanged += OnNetworkChanged; + + // Marcar la red como privada (o pública) no cambia las direcciones ni avisa: se revisa cada 20 s. + _recheck?.Dispose(); + _recheck = new Timer(_ => OnNetworkChanged(null, EventArgs.Empty), null, TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(20)); + await ListenAsync(); + } + + private async Task ListenAsync() + { + await _listenGate.WaitAsync(); try { + if (_app is not null) + { + await _app.StopAsync(); + await _app.DisposeAsync(); + _app = null; + } + + Error = null; + var networks = PrivateNetworks.Read(); + _addresses = networks.Addresses; + PublicOnly = networks.PublicOnly; + Urls = [.. _addresses.Select(ip => $"http://{ip}:{Port}/")]; + if (_addresses.Count == 0) + { + ListeningChanged?.Invoke(); + return; // en una red pública (o sin red) no escucha + } + var builder = WebApplication.CreateSlimBuilder(); builder.Logging.ClearProviders(); - builder.WebHost.ConfigureKestrel(o => o.ListenAnyIP(Port)); + builder.WebHost.ConfigureKestrel(o => + { + foreach (var address in _addresses) + { + o.Listen(address, Port); + } + + o.Limits.MaxConcurrentConnections = 32; + o.Limits.MaxRequestBodySize = 4096; + }); var app = builder.Build(); app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(15) }); app.Use(async (context, next) => { - if (!IsPrivate(context.Connection.RemoteIpAddress)) + if (!IsPrivate(context.Connection.RemoteIpAddress) || !IsOwnHost(context) || !IsOwnOrigin(context)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; return; } context.Response.Headers.CacheControl = "no-store"; + context.Response.Headers.XContentTypeOptions = "nosniff"; + context.Response.Headers["X-Frame-Options"] = "DENY"; await next(context); }); app.MapGet("/", (Func)Home); @@ -103,12 +157,69 @@ public async Task StartAsync() app.Map("/ws", Socket); await app.StartAsync(); _app = app; - Urls = [.. LocalAddresses().Select(ip => $"http://{ip}:{Port}/")]; } catch (Exception ex) when (ex is IOException or SocketException or InvalidOperationException or UnauthorizedAccessException) { Error = ex.Message; } + finally + { + _listenGate.Release(); + } + + ListeningChanged?.Invoke(); + } + + private readonly SemaphoreSlim _listenGate = new(1); + private CancellationTokenSource? _networkDebounce; + private Timer? _recheck; + + /// Cambió dónde escucha (otra red, o dejó de haber una privada): para la ventana principal. + public event Action? ListeningChanged; + + /// Las redes cambian en ráfaga (wifi que se conecta, VPN): se espera un poco y se vuelve a elegir. + private void OnNetworkChanged(object? sender, EventArgs e) + { + _networkDebounce?.Cancel(); + var debounce = _networkDebounce = new CancellationTokenSource(); + _ = Task.Run(async () => + { + try + { + await Task.Delay(TimeSpan.FromSeconds(3), debounce.Token); + var now = PrivateNetworks.Read().Addresses; + if (!now.SequenceEqual(_addresses)) + { + await ListenAsync(); + } + } + catch (OperationCanceledException) + { + } + }); + } + + /// El Host es una dirección del PC en la que escucha: así no responde a un nombre ajeno (DNS rebinding). + private bool IsOwnHost(HttpContext context) + { + var host = context.Request.Host; + return host.Port is null or Port && IPAddress.TryParse(host.Host, out var ip) && _addresses.Contains(ip); + } + + /// + /// Lo que cambia algo (emparejar, el WebSocket) sólo desde la propia página: el navegador manda Origin + /// y tiene que ser el del deck. Así una web abierta en la tablet no puede hablarle al PC. + /// + private static bool IsOwnOrigin(HttpContext context) + { + bool changes = HttpMethods.IsPost(context.Request.Method) || context.WebSockets.IsWebSocketRequest; + if (!changes) + { + return true; + } + + var origin = context.Request.Headers.Origin.ToString(); + return origin.Length > 0 && string.Equals(origin, $"http://{context.Request.Host}", StringComparison.OrdinalIgnoreCase); } /// La dirección para emparejar con un código (la del QR). @@ -129,8 +240,20 @@ private IResult Home(HttpContext context) return Asset(Authorized(context) is null ? "pair.html" : "index.html", "text/html; charset=utf-8"); } + /// Intentos fallidos de emparejar por dirección, y hasta cuándo esa dirección no puede intentarlo. + private readonly ConcurrentDictionary _pairFailures = new(); + private async Task Pair(HttpContext context) { + // Además del límite por código (DeckWebDevices.MaxFailures), un freno por dirección: tras 5 fallos, + // 10 minutos sin poder intentarlo, y mientras tanto cada intento tarda un poco. + var ip = context.Connection.RemoteIpAddress ?? IPAddress.None; + if (_pairFailures.TryGetValue(ip, out var f) && f.Failures >= 5 && f.Until > DateTime.UtcNow) + { + return Results.StatusCode(StatusCodes.Status429TooManyRequests); + } + + await Task.Delay(300); try { using var doc = await JsonDocument.ParseAsync(context.Request.Body); @@ -138,9 +261,12 @@ private async Task Pair(HttpContext context) var name = doc.RootElement.TryGetProperty("name", out var n) ? n.GetString() ?? "" : ""; if (Devices.Pair(code, name) is not { } token) { + _pairFailures.AddOrUpdate(ip, (1, DateTime.UtcNow.AddMinutes(10)), (_, old) => (old.Until > DateTime.UtcNow ? old.Failures + 1 : 1, DateTime.UtcNow.AddMinutes(10))); return Results.Json(new { ok = false }); } + _pairFailures.TryRemove(ip, out _); + SetCookie(context, token); return Results.Json(new { ok = true, token }); } @@ -201,8 +327,16 @@ private async Task Socket(HttpContext context) return; } + // Pocas conexiones por dispositivo: uno emparejado no puede saturar el PC. + if (_sockets.Values.Count(id => id == device.Id) >= MaxSocketsPerDevice) + { + context.Response.StatusCode = StatusCodes.Status429TooManyRequests; + return; + } + using var socket = await context.WebSockets.AcceptWebSocketAsync(); _sockets[socket] = device.Id; + var lastPages = DateTime.MinValue; using var cancel = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); var send = new SemaphoreSlim(1); string? last = null; @@ -261,6 +395,17 @@ async Task PushIfChanged() using var doc = JsonDocument.Parse(buffer.AsMemory(0, received.Count)); var root = doc.RootElement; int seq = root.TryGetProperty("seq", out var s) ? s.GetInt32() : 0; + // Leer las páginas cuesta (UI Automation en cada navegador): como mucho cada 2 s por conexión. + if (root.TryGetProperty("cmd", out var c) && c.GetString() == "pages") + { + if (DateTime.UtcNow - lastPages < TimeSpan.FromSeconds(2)) + { + continue; + } + + lastPages = DateTime.UtcNow; + } + var reply = await Handle(root); await Send(reply ?? new { type = "ack", seq, ok = true }); await PushIfChanged(); @@ -307,6 +452,57 @@ async Task PushIfChanged() await Run(app.PanelId is null ? new Adopt(h, app.Name, panel) : new SendTo(h, panel)); } + break; + case "pin" when App() is { App: { } catalog, PanelId: not null, State: not ListItemState.Unmovable } app: + // Como el modo Anclar del deck: alterna; una anclada se queda en su panel aunque se cierre. + await _onUi(() => + { + _actions.SetPinned(app.AppKey, !catalog.Pinned); + return Task.CompletedTask; + }); + break; + case "presentation" when Panel(root) is { } target + && Enum.TryParse(root.GetProperty("template").GetString(), out var template) + && (template != PanelTemplate.Fill || target.Display is not null): + await Run(new SetPresentation(target.Id, template)); + break; + case "tabPrev" or "tabNext" when Panel(root) is { } target && Tabs(target) is { Count: > 1 } tabs: + // En pestañas, la visible es la primera: ▶ pone la segunda; ◀, la última (como el deck del PC). + await Run(new MakeActiveInPanel((cmd == "tabNext" ? tabs[1] : tabs[^1]).Handle!.Value)); + break; + case "view" when Layout(_state()).FirstOrDefault(b => b.Key == root.GetProperty("key").GetString()) is { } button: + await Run(new SetView(button.Next)); + break; + case "resetWidth": + await Run(new SetProportions(_state().View, null)); + break; + case "minimize" when App() is { Handle: { } h, PanelId: not null, State: not ListItemState.Unmovable } app: + await Run(app.State == ListItemState.Parked ? new Restore(h) : new Park(h)); + break; + case "fullscreen" when App() is { Handle: { } h, State: not (ListItemState.Unmovable or ListItemState.OtherDesktop) } app + && root.TryGetProperty("display", out var d) && d.GetString() is { } key + && _state() is { } now && now.Displays.Any(x => (x.Display ?? "") == key): + // Como «Pantalla completa en…» del menú del deck del PC; una libre entra antes al panel de trabajo. + var display = key.Length == 0 ? null : key; + await Run(app.PanelId is null + ? [new Adopt(h, app.Name, DefaultPanel(now)), new EnterFullscreen(h, display)] + : [new EnterFullscreen(h, display)]); + break; + case "close" when App() is { Handle: { } h, State: not ListItemState.Unmovable }: + await _onUi(() => _actions.CloseApp(h)); + break; + case "keepAwake": + await _onUi(() => + { + _actions.ToggleKeepAwake(); + return Task.CompletedTask; + }); + break; + case "mouseToFocus": + await _onUi(() => _actions.MouseToFocus()); + break; + case "rearrange" when _actions.CanRearrange(): + await _onUi(() => _actions.RearrangeAll()); break; case "previous": await Run(new SwapWithPrevious()); @@ -391,8 +587,50 @@ private async Task Tap(DeckApp app) await Run(new Promote(h)); } + private static string DefaultPanel(DeckState s) => + s.Panels.FirstOrDefault(p => p.Id == Workspace.WorkPanel)?.Id ?? s.Panels[0].Id; + private Task Run(params Command[] commands) => _onUi(() => _actions.Run(commands)); + /// El panel que nombra el comando, en el estado de ahora. + private DeckPanel? Panel(JsonElement root) => + root.TryGetProperty("panel", out var id) && id.GetString() is { } key ? _state().Panels.FirstOrDefault(p => p.Id == key) : null; + + /// Las pestañas de un panel en pestañas o Llenar: sus apps en el panel, la visible primero. + private static List Tabs(DeckPanel panel) => + panel.Template is PanelTemplate.Stack or PanelTemplate.Fill + ? [.. panel.Apps.Where(a => a.State == ListItemState.InPanel && a.Handle is not null)] + : []; + + /// Un botón de la disposición del principal: su clave, su texto, si está prendido y la vista a la que lleva. + private sealed record LayoutButton(string Key, string Label, bool On, FocusPosition Next); + + /// + /// La disposición del principal, como en el deck del PC (DeckWindow.ArrangementButtons): prender y + /// apagar cada columna y, en un ultrawide, traer una al otro lado. + /// + private static List Layout(DeckState s) + { + string Column(PanelSide side, string fallback) => + s.Panels.Where(p => p.Display is null && p.Side == side).OrderBy(p => p.Slot).FirstOrDefault()?.Name ?? fallback; + var view = s.View; + string left = Column(PanelSide.Left, Strings.Deck_LeftColumn), right = Column(PanelSide.Right, Strings.Deck_RightColumn); + var buttons = new List(); + if (MainArrangement.CanBorrowToLeft(view, s.Ultrawide)) + { + buttons.Add(new("borrowLeft", "⇠ " + right, MainArrangement.RightBorrowedLeft(view), MainArrangement.ToggleBorrowToLeft(view))); + } + + buttons.Add(new("left", "◧ " + left, MainArrangement.LeftOn(view), MainArrangement.ToggleLeft(view))); + buttons.Add(new("right", right + " ◨", MainArrangement.RightOn(view), MainArrangement.ToggleRight(view))); + if (MainArrangement.CanBorrowToRight(view, s.Ultrawide)) + { + buttons.Add(new("borrowRight", left + " ⇢", MainArrangement.LeftBorrowedRight(view), MainArrangement.ToggleBorrowToRight(view))); + } + + return buttons; + } + /// En un panel en pestañas (o Llenar) con varias: «visible» la que se ve, «hidden» las demás. private static string? TabOf(DeckApp app, DeckState state) { @@ -435,6 +673,7 @@ string Id(DeckApp a) state = a.State.ToString(), tab = TabOf(a, s), pinned = a.App?.Pinned == true, + canPin = a.App is not null && a.PanelId is not null && a.State != ListItemState.Unmovable, panel = a.PanelId, }; @@ -454,6 +693,8 @@ string Id(DeckApp a) name = p.Name, side = p.Side.ToString(), template = p.Template.ToString(), + canFill = p.Display is not null, + tabs = Tabs(p).Count, off = p.Off, apps = p.Apps.Select(App).ToList(), }).ToList(), @@ -471,8 +712,13 @@ string Id(DeckApp a) hasPrevious = s.HasPrevious, foreground = s.Foreground is { } fg ? apps.FirstOrDefault(x => x.Value.Handle == fg).Key : null, monitors, + // Los monitores conectados, también sin paneles: donde puede ir una app en pantalla completa. + screens = s.Displays.Select(d => new { id = d.Display ?? "", name = d.Name }).ToList(), free, pages = _pageTitles() && s.Browsers.Count > 0, + layout = Layout(s).Select(b => new { key = b.Key, label = b.Label, on = b.On }).ToList(), + keepAwake = _actions.KeepAwake(), + canRearrange = _actions.CanRearrange(), }; } } @@ -537,13 +783,7 @@ private void DropRevoked() } } - private static IEnumerable LocalAddresses() => - NetworkInterface.GetAllNetworkInterfaces() - .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback) - .SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(u => u.Address)) - .Where(a => a.AddressFamily == AddressFamily.InterNetwork && IsPrivate(a) && !IPAddress.IsLoopback(a)); - - private static bool IsPrivate(IPAddress? address) + internal static bool IsPrivate(IPAddress? address) { if (address is null) { @@ -568,6 +808,9 @@ private static bool IsPrivate(IPAddress? address) public async ValueTask DisposeAsync() { Devices.Changed -= DropRevoked; + NetworkChange.NetworkAddressChanged -= OnNetworkChanged; + _networkDebounce?.Cancel(); + _recheck?.Dispose(); foreach (var socket in _sockets.Keys) { socket.Abort(); diff --git a/src/FocusWShell.App/DeckWeb/PrivateNetworks.cs b/src/FocusWShell.App/DeckWeb/PrivateNetworks.cs new file mode 100644 index 0000000..a69ce91 --- /dev/null +++ b/src/FocusWShell.App/DeckWeb/PrivateNetworks.cs @@ -0,0 +1,173 @@ +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Runtime.InteropServices; + +namespace FocusWShell.App.DeckWeb; + +/// +/// Las direcciones del PC en las redes que Windows marca como **privadas o de dominio** (ADR 0021). Una red +/// pública (un café, un aeropuerto) no cuenta, aunque use direcciones 192.168.x; tampoco los adaptadores que +/// Windows no reconoce como red conectada (Hyper-V, Docker). Lo dice el Network List Manager de Windows. +/// +internal static class PrivateNetworks +{ + /// Categoría de red de Windows (NLM_NETWORK_CATEGORY). + private const int Public = 0; + + /// Lo que dice Windows de las redes conectadas. + /// Las IPv4 de las redes privadas o de dominio, ordenadas. + /// Hay redes conectadas, pero Windows las marca todas como públicas. + public sealed record Result(IReadOnlyList Addresses, bool PublicOnly); + + public static Result Read() + { + var (trusted, anyPublic) = Adapters(); + var addresses = NetworkInterface.GetAllNetworkInterfaces() + .Where(n => n.OperationalStatus == OperationalStatus.Up && Guid.TryParse(n.Id, out var id) && trusted.Contains(id)) + .SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(u => u.Address)) + .Where(a => a.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(a) && DeckWebServer.IsPrivate(a)) + .Distinct() + .OrderBy(a => a.ToString(), StringComparer.Ordinal) + .ToList(); + return new Result(addresses, addresses.Count == 0 && anyPublic); + } + + /// Los adaptadores de las conexiones que no son públicas. Si Windows no responde, ninguno: no se escucha. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031", Justification = "Sin respuesta de Windows, no se escucha: es lo seguro.")] + private static (HashSet Trusted, bool AnyPublic) Adapters() + { + var trusted = new HashSet(); + bool anyPublic = false; + INetworkListManager? manager = null; + try + { + manager = (INetworkListManager)new NetworkListManagerClass(); + var connections = manager.GetNetworkConnections(); + while (true) + { + connections.Next(1, out var connection, out var fetched); + if (fetched == 0 || connection is null) + { + break; + } + + if (connection.IsConnected() && connection.GetNetwork().GetCategory() is var category) + { + if (category == Public) + { + anyPublic = true; + } + else + { + trusted.Add(connection.GetAdapterId()); + } + } + + Marshal.ReleaseComObject(connection); + } + + Marshal.ReleaseComObject(connections); + } + catch (Exception) + { + trusted.Clear(); + } + finally + { + if (manager is not null) + { + Marshal.FinalReleaseComObject(manager); + } + } + + return (trusted, anyPublic); + } + + // --- Network List Manager (netlistmgr.h): sólo lo que se usa, en el orden de su vtable ------------- + + [ComImport] + [Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")] + private class NetworkListManagerClass + { + } + + [ComImport] + [Guid("DCB00000-570F-4A9B-8D69-199FDBA5723B")] + [InterfaceType(ComInterfaceType.InterfaceIsDual)] + private interface INetworkListManager + { + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetNetworks(int flags); + + INetwork GetNetwork(Guid networkId); + + IEnumNetworkConnections GetNetworkConnections(); + } + + [ComImport] + [Guid("DCB00006-570F-4A9B-8D69-199FDBA5723B")] + [InterfaceType(ComInterfaceType.InterfaceIsDual)] + private interface IEnumNetworkConnections + { + [return: MarshalAs(UnmanagedType.IUnknown)] + object NewEnum(); + + void Next(uint count, out INetworkConnection? element, out uint fetched); + } + + [ComImport] + [Guid("DCB00005-570F-4A9B-8D69-199FDBA5723B")] + [InterfaceType(ComInterfaceType.InterfaceIsDual)] + private interface INetworkConnection + { + INetwork GetNetwork(); + + [return: MarshalAs(UnmanagedType.VariantBool)] + bool IsConnectedToInternet(); + + [return: MarshalAs(UnmanagedType.VariantBool)] + bool IsConnected(); + + int GetConnectivity(); + + Guid GetConnectionId(); + + Guid GetAdapterId(); + } + + [ComImport] + [Guid("DCB00002-570F-4A9B-8D69-199FDBA5723B")] + [InterfaceType(ComInterfaceType.InterfaceIsDual)] + private interface INetwork + { + [return: MarshalAs(UnmanagedType.BStr)] + string GetName(); + + void SetName([MarshalAs(UnmanagedType.BStr)] string name); + + [return: MarshalAs(UnmanagedType.BStr)] + string GetDescription(); + + void SetDescription([MarshalAs(UnmanagedType.BStr)] string description); + + Guid GetNetworkId(); + + int GetDomainType(); + + [return: MarshalAs(UnmanagedType.IUnknown)] + object GetNetworkConnections(); + + void GetTimeCreatedAndConnected(out uint createdLow, out uint createdHigh, out uint connectedLow, out uint connectedHigh); + + [return: MarshalAs(UnmanagedType.VariantBool)] + bool IsConnectedToInternet(); + + [return: MarshalAs(UnmanagedType.VariantBool)] + bool IsConnected(); + + int GetConnectivity(); + + int GetCategory(); + } +} diff --git a/src/FocusWShell.App/DeckWeb/deck.css b/src/FocusWShell.App/DeckWeb/deck.css index 06041d8..b48e68d 100644 --- a/src/FocusWShell.App/DeckWeb/deck.css +++ b/src/FocusWShell.App/DeckWeb/deck.css @@ -5,8 +5,8 @@ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); button { font: inherit; color: var(--text); background: var(--card); border: 0; border-radius: 6px; min-height: var(--touch); cursor: pointer; } button:active { filter: brightness(1.25); } button:disabled { opacity: .4; } -#app { display: grid; grid-template-columns: clamp(210px, 27vw, 300px) 1fr; gap: 12px; height: 100%; padding: 10px 10px 10px max(10px, env(safe-area-inset-left)); } -#left { display: flex; flex-direction: column; gap: 10px; min-height: 0; } +#app { display: grid; grid-template-columns: clamp(210px, 27vw, 300px) minmax(0, 1fr); gap: 12px; height: 100%; padding: 10px 10px 10px max(10px, env(safe-area-inset-left)); } +#left { display: flex; flex-direction: column; gap: 10px; min-height: 0; overflow-y: auto; } .card { border: 1px solid #2c3240; border-radius: 8px; padding: 8px; } .head { display: flex; align-items: center; gap: 8px; } .head .title { flex: 1; display: flex; flex-direction: column; } @@ -25,7 +25,7 @@ small { color: var(--dim); font-size: 11px; } .mode.move.on { background: var(--blue); } .status { color: var(--dim); font-size: 12px; min-height: 16px; padding: 0 4px; } .status.bad { color: #f09595; } -#right { display: flex; flex-direction: column; gap: 8px; min-height: 0; } +#right { display: flex; flex-direction: column; gap: 8px; min-height: 0; min-width: 0; } #monitors, #pagesView { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; -webkit-overflow-scrolling: touch; } .monitor { display: flex; gap: 6px; } .mname { writing-mode: vertical-rl; transform: rotate(180deg); color: var(--dim); font-size: 13px; text-align: center; white-space: nowrap; width: 22px; } @@ -51,13 +51,18 @@ small { color: var(--dim); font-size: 11px; } .free { flex: 1; } .pages { width: 150px; } .pages.on { background: var(--blue); } -.sites { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 6px; } -.pageRow { display: flex; gap: 4px; } -.pageRow button.go { flex: 1; text-align: left; padding: 0 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sites { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); gap: 6px; } +/* Un nombre largo se recorta con «…» en vez de ensanchar la columna (y obligar a desplazarse a la derecha). */ +.sites button { min-width: 0; display: flex; align-items: center; gap: 6px; } +.sites b { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sites small { flex: none; } +#pagesView > * { min-width: 0; } +.pageRow { display: flex; gap: 4px; min-width: 0; } +.pageRow button.go { flex: 1; min-width: 0; text-align: left; padding: 0 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pageRow button.go.active { border-left: 4px solid var(--blue); } .pageRow button.x { width: var(--touch); color: #e57373; } .pagesHead { display: flex; gap: 8px; align-items: center; } -.pagesHead b { flex: 1; } +.pagesHead b { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .section { color: var(--dim); font-size: 11px; text-transform: uppercase; margin: 6px 2px 2px; } /* Estrecho (teléfono, o tablet en vertical): una sola columna. En horizontal, aunque la tablet sea pequeña, dos columnas. */ @@ -84,3 +89,68 @@ small { color: var(--dim); font-size: 11px; } .panel { min-height: 0; } .bottom { min-height: 0; height: 104px; } } + +/* Anclar (índigo, como en el deck del PC) y la app en uso junto al foco. */ +.row2 { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6px; } +.mode.pin { border-bottom: 3px solid #5a78c8; } +.mode.pin.on { background: #5a78c8; } +.app.pinnable { outline: 2px solid rgba(90, 120, 200, .55); outline-offset: -2px; } +.app.pinnable.pinnedOn { outline: 3px solid #5a78c8; outline-offset: -3px; } +.duo { display: flex; align-items: center; gap: 14px; } +.duo .main { display: flex; flex-direction: column; align-items: center; gap: 6px; } +.duo .sep { width: 1px; align-self: stretch; background: rgba(255, 255, 255, .45); } +.duo .use { display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 13px; font-weight: 400; } +.duo .use img, .duo .use .ph { width: 32px; height: 32px; border: 2px solid #fff; border-radius: 6px; } +.duo .use small { color: #dfe8f7; } + +/* Minimizar (verde azulado) y Cerrar (rojo), como en el deck del PC; la disposición y el sistema. */ +.mode.minimize { border-bottom: 3px solid #2aa198; } +.mode.minimize.on { background: #2aa198; } +.mode.close { border-bottom: 3px solid #c23b3b; } +.mode.close.on { background: #c23b3b; } +.app.minimizable { outline: 2px solid #2aa198; outline-offset: -2px; } +.app.minimizable.parked { outline-width: 3px; outline-offset: -3px; } +.app.closable { outline: 2px solid #c23b3b; outline-offset: -2px; } +#freeAll.armed { background: #c23b3b; } +.layoutRow { display: flex; gap: 6px; } +.layoutRow button { flex: 1; padding: 0 6px; font-size: 13px; } +.layoutRow button.on { background: var(--blue); } +#awake.on { background: #c88a1e; } +.row2 button { padding: 0 6px; font-size: 13px; } +.panel h3 { align-items: center; } +.panel h3 .title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tools { display: flex; gap: 3px; } +.tools button { width: 40px; min-height: 40px; height: 40px; font-size: 16px; padding: 0; } +.tools button.on { background: var(--blue); } +.tools .gap { width: 6px; } +@media (orientation: landscape) and (max-height: 700px) { + .tools button { width: 34px; min-height: 34px; height: 34px; font-size: 14px; } +} + +/* Columna izquierda compacta: los cuatro modos en una fila (icono arriba, nombre abajo) y el sistema en otra. */ +.row4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; } +.row4 button { padding: 2px; font-size: 12px; line-height: 1.25; display: flex; flex-direction: column; align-items: center; justify-content: center; } +.sys button { font-size: 12px; padding: 0 4px; line-height: 1.2; } +.focus { min-height: 120px; } +.focusTile { overflow: hidden; } +.duo { gap: 10px; font-size: 15px; } +@media (orientation: landscape) and (max-height: 700px) { + #left { gap: 6px; } + .card { padding: 6px; } + #left button { min-height: 42px; } + .row3 button, .row4 button { font-size: 12px; } + .label { margin-bottom: 4px; } + .duo .main img, .duo .main .ph { width: 36px; height: 36px; } + .duo .use img, .duo .use .ph { width: 26px; height: 26px; } +} + +/* Pantalla…: quinto modo; elegida la app, los monitores como botones. */ +.row5 { grid-template-columns: repeat(auto-fit, minmax(56px, 1fr)); gap: 4px; } /* si la columna es angosta, pasa a 3 + 2 */ +.row5 button { font-size: 11px; } +.mode.full { border-bottom: 3px solid #9b6bd6; } +.mode.full.on { background: #9b6bd6; } +.app.fullable { outline: 2px solid #9b6bd6; outline-offset: -2px; } +.app.fullable.chosen { outline-width: 3px; outline-offset: -3px; background: #3a2f4d; } +.screens { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 6px; } +.screens button { background: #9b6bd6; padding: 0 8px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.focusTile small.from { color: #dfe8f7; font-size: 12px; font-weight: 400; } diff --git a/src/FocusWShell.App/DeckWeb/deck.js b/src/FocusWShell.App/DeckWeb/deck.js index b0e18bf..f7aa3fb 100644 --- a/src/FocusWShell.App/DeckWeb/deck.js +++ b/src/FocusWShell.App/DeckWeb/deck.js @@ -3,7 +3,14 @@ const T = { es: { - focus: 'Foco', previous: 'Anterior', toPanel: 'Al panel', freeAll: 'Liberar todas', move: 'Mover…', moving: 'Moviendo…', + focus: 'Foco', previous: 'Anterior', toPanel: 'Al panel', freeAll: 'Liberar todas', move: 'Mover…', moving: 'Moviendo…', pin: 'Anclar…', pinning: 'Anclando…', inUse: 'en uso', + minimize: 'Minimizar…', minimizing: 'Minimizando…', close: 'Cerrar…', closing: 'Cerrando…', + pickMinimize: 'Toca una app de un panel para minimizarla (o devolverla).', + full: 'Pantalla…', fulling: 'Eligiendo…', pickFull: 'Toca la app que quieres en pantalla completa. Para salir, tócala en el foco.', pickScreen: n => `¿En qué monitor va ${n}?`, from: n => `de ${n}`, pickClose: 'Toca la app que quieres cerrar. Si tiene algo sin guardar, ella pregunta en el PC.', + freeAllSure: '¿Liberar? Toca otra vez', layout: 'Disposición del principal', system: 'Sistema', awakeOn: 'Pantalla encendida', awakeOff: 'Pantalla: normal', + mouse: 'Ratón al foco', rearrange: 'Reordenar todas', resetTip: 'Mantén apretado para restablecer el ancho', + tiles: 'Cuadrícula', stack: 'Pestañas', list: 'Lista', fill: 'Llenar', prevTab: 'Pestaña anterior', nextTab: 'Pestaña siguiente', + pickPin: 'Toca una app para anclarla o desanclarla en su panel. Toca Anclar otra vez para terminar.', pickApp: 'Toca la app que quieres mover.', pickPanel: 'Toca el panel donde va, o Libres para liberarla.', free: 'Libres', noFree: 'Sin ventanas libres.', pages: 'Páginas', nothingInFocus: 'Nada en el foco', monitors: n => `${n} ${n === 1 ? 'monitor' : 'monitores'}`, apps: n => `${n} apps`, @@ -12,7 +19,14 @@ const T = { loading: 'Leyendo las páginas…', noPages: 'No hay pestañas que leer en Chrome ni en Edge.', closeAll: 'Cerrar todas', }, en: { - focus: 'Focus', previous: 'Previous', toPanel: 'To panel', freeAll: 'Free all', move: 'Move…', moving: 'Moving…', + focus: 'Focus', previous: 'Previous', toPanel: 'To panel', freeAll: 'Free all', move: 'Move…', moving: 'Moving…', pin: 'Pin…', pinning: 'Pinning…', inUse: 'in use', + minimize: 'Minimize…', minimizing: 'Minimizing…', close: 'Close…', closing: 'Closing…', + pickMinimize: 'Tap an app in a panel to minimize it (or bring it back).', + full: 'Fullscreen…', fulling: 'Choosing…', pickFull: 'Tap the app you want in fullscreen. To leave, tap it in the focus.', pickScreen: n => `Which monitor for ${n}?`, from: n => `from ${n}`, pickClose: 'Tap the app you want to close. If it has unsaved work, it asks on the PC.', + freeAllSure: 'Free all? Tap again', layout: 'Main screen layout', system: 'System', awakeOn: 'Screen kept on', awakeOff: 'Screen: normal', + mouse: 'Mouse to focus', rearrange: 'Rearrange all', resetTip: 'Press and hold to reset the width', + tiles: 'Tiles', stack: 'Tabs', list: 'List', fill: 'Fill', prevTab: 'Previous tab', nextTab: 'Next tab', + pickPin: 'Tap an app to pin or unpin it in its panel. Tap Pin again to finish.', pickApp: 'Tap the app you want to move.', pickPanel: 'Tap the panel where it goes, or Free to free it.', free: 'Free', noFree: 'No free windows.', pages: 'Pages', nothingInFocus: 'Nothing in focus', monitors: n => `${n} ${n === 1 ? 'monitor' : 'monitors'}`, apps: n => `${n} apps`, @@ -34,6 +48,12 @@ function noIcon(el) { const s = document.createElement('span'); s.className = 'p let state = null, ws = null, seq = 0, retry = 500; let moving = null; // null | 'app' | 'panel' let chosen = null; // la app elegida para mover +let pinning = false; // modo Anclar: tocar alterna el ancla; sigue prendido hasta tocarlo otra vez +let minimizing = false, closing = false; // Minimizar y Cerrar: se apagan tras un toque, como en el deck del PC +let fulling = false, fullApp = null; // Pantalla…: la app y, si hay varios monitores, el monitor +let freeAllArmed = 0; // «Liberar todas» pide un segundo toque en 4 s +const anyMode = () => !!moving || pinning || minimizing || closing || fulling; +function clearModes() { moving = null; chosen = null; pinning = false; minimizing = false; closing = false; fulling = false; fullApp = null; status(''); } let pagesOpen = false, pages = null, site = null; function status(text, bad) { $('status').textContent = text || ''; $('status').className = 'status' + (bad ? ' bad' : ''); } @@ -58,23 +78,90 @@ function renderLeft() { $('summary').textContent = `${L.monitors(state.monitors.length)} · ${L.apps(apps)}`; const f = state.focus, tile = $('focusTile'); tile.className = 'focusTile' + (f ? '' : ' empty') + (moving === 'panel' && chosen && (!f || chosen.id !== f.id) ? ' pick' : ''); - tile.innerHTML = f ? `${img(f.key, f.name)}${esc(f.name)}` : esc(L.nothingInFocus); + // Como en el deck del PC: si el teclado está en otra app, se ve a su lado, más pequeña y con borde blanco. + const use = f && state.foreground && state.foreground !== f.id ? findApp(state.foreground) : null; + // Como en el deck del PC: debajo del nombre, de qué panel viene. + const home = f && f.panel ? state.monitors.flatMap(m => m.panels).find(p => p.id === f.panel) : null; + const from = home ? `${esc(L.from(home.name))}` : ''; + tile.innerHTML = !f ? esc(L.nothingInFocus) + : !use ? `${img(f.key, f.name)}${esc(f.name)}${from}` + : `
${img(f.key, f.name)}${esc(f.name)}${from}
` + + `
${img(use.key, use.name)}${esc(use.name)}${esc(L.inUse)}
`; $('previous').disabled = !state.hasPrevious; $('toPanel').disabled = !f; const move = $('move'); move.classList.toggle('on', !!moving); move.querySelector('span').textContent = moving ? L.moving : L.move; if (moving) status(moving === 'app' ? L.pickApp : L.pickPanel); + $('pin').classList.toggle('on', pinning); + $('pin').querySelector('span').textContent = pinning ? L.pinning : L.pin; + if (pinning) status(L.pickPin); + for (const [id, on, text, busy] of [['minimize', minimizing, L.minimize, L.minimizing], ['close', closing, L.close, L.closing]]) { + $(id).classList.toggle('on', on); + $(id).querySelector('span').textContent = on ? busy : text; + } + if (minimizing) status(L.pickMinimize); + $('fullMode').classList.toggle('on', fulling); + $('fullMode').querySelector('span').textContent = fulling ? L.fulling : L.full; + // Elegida la app, los monitores aparecen como botones debajo de los modos. + const screens = $('screens'); screens.innerHTML = ''; + screens.hidden = !(fulling && fullApp); + if (fulling && fullApp) { + status(L.pickScreen(fullApp.name)); + for (const sc of state.screens || []) { + const b = document.createElement('button'); b.textContent = sc.name; + b.onclick = () => { send('fullscreen', { id: fullApp.id, display: sc.id }); clearModes(); render(); }; + screens.appendChild(b); + } + } else if (fulling) status(L.pickFull); + if (closing) status(L.pickClose); + const armed = Date.now() - freeAllArmed < 4000; + $('freeAll').classList.toggle('armed', armed); + $('freeAll').querySelector('span').textContent = armed ? L.freeAllSure : L.freeAll; + + // La disposición del principal: azul, prendida. Mantener apretado restablece el ancho. + const lay = $('layout'); lay.innerHTML = ''; + for (const b of state.layout || []) { + const btn = document.createElement('button'); + btn.textContent = b.label; btn.title = L.resetTip; btn.className = b.on ? 'on' : ''; + btn.onclick = () => send('view', { key: b.key }); + holdToReset(btn); + lay.appendChild(btn); + } + + $('awake').classList.toggle('on', !!state.keepAwake); + $('awake').querySelector('span').textContent = state.keepAwake ? L.awakeOn : L.awakeOff; + $('rearrange').hidden = !state.canRearrange; } +function holdToReset(btn) { + let timer = null, held = false; + btn.addEventListener('pointerdown', () => { held = false; timer = setTimeout(() => { held = true; send('resetWidth'); }, 700); }); + ['pointerup', 'pointerleave', 'pointercancel'].forEach(e => btn.addEventListener(e, () => clearTimeout(timer))); + btn.addEventListener('click', e => { if (held) { e.stopImmediatePropagation(); held = false; } }, true); + btn.addEventListener('contextmenu', e => e.preventDefault()); +} + +const findApp = id => [...state.monitors.flatMap(m => m.panels.flatMap(p => p.apps)), ...state.free].find(a => a.id === id); + $('focusTile').onclick = () => { if (moving === 'panel' && chosen) { send('tap', { id: chosen.id }); endMove(); return; } // mover al foco if (state && state.focus) send('tap', { id: state.focus.id }); }; $('previous').onclick = () => send('previous'); $('toPanel').onclick = () => send('toPanel'); -$('freeAll').onclick = () => send('freeAll'); -$('move').onclick = () => { moving = moving ? null : 'app'; chosen = null; if (!moving) status(''); render(); }; +$('freeAll').onclick = () => { + if (Date.now() - freeAllArmed < 4000) { freeAllArmed = 0; send('freeAll'); render(); return; } + freeAllArmed = Date.now(); render(); setTimeout(render, 4100); +}; +$('awake').onclick = () => send('keepAwake'); +$('mouse').onclick = () => send('mouseToFocus'); +$('rearrange').onclick = () => send('rearrange'); +$('minimize').onclick = () => { const on = !minimizing; clearModes(); minimizing = on; render(); }; +$('close').onclick = () => { const on = !closing; clearModes(); closing = on; render(); }; +$('fullMode').onclick = () => { const on = !fulling; clearModes(); fulling = on; render(); }; +$('move').onclick = () => { const on = !moving; clearModes(); moving = on ? 'app' : null; render(); }; +$('pin').onclick = () => { const on = !pinning; clearModes(); pinning = on; render(); }; // ⛶ entra y sale de pantalla completa; el icono dice qué hará. const isFull = () => !!(document.fullscreenElement || document.webkitFullscreenElement); $('full').onclick = () => { @@ -95,12 +182,27 @@ function appButton(a) { const away = ['Closed', 'InTray', 'OtherDesktop', 'Unmovable'].includes(a.state); const mark = { InFocus: ' ↑', Parked: ' ⏸', Detached: ' ↗', OtherDesktop: ' ⧉', InTray: ' ▴', Unmovable: ' 🛡' }[a.state] || ''; b.className = 'app' + (away ? ' away' : '') + (a.state === 'InFocus' ? ' infocus' : '') - + (state.foreground === a.id && a.state !== 'InFocus' && !moving ? ' inuse' : '') + + (state.foreground === a.id && a.state !== 'InFocus' && !anyMode() ? ' inuse' : '') + (a.tab === 'visible' ? ' tabvisible' : '') - + (moving === 'app' && canMove(a) ? ' pick' : '') + (chosen && chosen.id === a.id ? ' chosen' : ''); + + (moving === 'app' && canMove(a) ? ' pick' : '') + (chosen && chosen.id === a.id ? ' chosen' : '') + + (pinning ? (a.canPin ? ' pinnable' + (a.pinned ? ' pinnedOn' : '') : ' away') : '') + + (minimizing ? (canMinimize(a) ? ' minimizable' + (a.state === 'Parked' ? ' parked' : '') : ' away') : '') + + (closing ? (canMove(a) ? ' closable' : ' away') : '') + + (fulling ? (canMove(a) ? ' fullable' + (fullApp && fullApp.id === a.id ? ' chosen' : '') : ' away') : ''); b.innerHTML = `${a.pinned ? '📌' : ''}${img(a.key, a.name)}${esc(a.name + mark)}`; b.onclick = e => { e.stopPropagation(); + if (pinning) { if (a.canPin) send('pin', { id: a.id }); return; } + if (minimizing) { if (canMinimize(a)) { send('minimize', { id: a.id }); clearModes(); render(); } return; } + if (closing) { if (canMove(a)) { send('close', { id: a.id }); clearModes(); render(); } return; } + if (fulling) { + if (!canMove(a)) return; + const screens = state.screens || []; + if (screens.length === 1) { send('fullscreen', { id: a.id, display: screens[0].id }); clearModes(); } + else fullApp = fullApp && fullApp.id === a.id ? null : a; + render(); + return; + } if (moving) { // Elegida la app, todo el panel destino es el destino, también sus iconos: un panel lleno no deja hueco // donde tocar. Lo mismo con Libres. Otra app del mismo panel (que no es destino) cambia la elegida. @@ -119,15 +221,53 @@ function appButton(a) { } const canMove = a => !['Closed', 'InTray', 'OtherDesktop', 'Unmovable'].includes(a.state); +const canMinimize = a => canMove(a) && !!a.panel; + +// Los iconos no cambian de lugar: el PC ordena las pestañas con la visible primero, y al tocar una oculta se +// movería bajo el dedo. Como en el deck del PC (StableOrder), cada panel recuerda el orden en que vio sus apps; +// las nuevas van al final. +const panelOrder = {}; +function stable(p) { + const known = panelOrder[p.id] || []; + const ordered = [...p.apps].sort((a, b) => { + const ia = known.indexOf(a.id), ib = known.indexOf(b.id); + return (ia < 0 ? Infinity : ia) - (ib < 0 ? Infinity : ib); + }); + panelOrder[p.id] = ordered.map(a => a.id); + return ordered; +} + +// La cabecera de un panel, como en el deck del PC: ◀ ▶ si está en pestañas, y su presentación (la activa en azul). +function panelTools(p) { + const tools = document.createElement('div'); tools.className = 'tools'; + const add = (text, title, on, click) => { + const b = document.createElement('button'); b.textContent = text; b.title = title; b.setAttribute('aria-label', title); + if (on) b.className = 'on'; + b.onclick = e => { e.stopPropagation(); if (!anyMode()) click(); }; + tools.appendChild(b); + }; + if (p.tabs > 1) { + add('◀', L.prevTab, false, () => send('tabPrev', { panel: p.id })); + add('▶', L.nextTab, false, () => send('tabNext', { panel: p.id })); + tools.insertAdjacentHTML('beforeend', ''); + } + const templates = [['Tiles', '▦', L.tiles], ['Stack', '⧉', L.stack], ['List', '☰', L.list]]; + if (p.canFill) templates.push(['Fill', '⛶', L.fill]); + for (const [t, icon, name] of templates) add(icon, name, p.template === t, () => send('presentation', { panel: p.id, template: t })); + return tools; +} function panelCard(p) { const card = document.createElement('section'); const target = moving === 'panel' && chosen && chosen.panel !== p.id; card.className = 'panel' + (p.off ? ' off' : '') + (target ? ' target' : ''); const side = { Left: { es: 'izquierda', en: 'left' }, Right: { es: 'derecha', en: 'right' } }[p.side]; - card.innerHTML = `

${esc(p.name.toUpperCase())}${side ? side[L === T.es ? 'es' : 'en'] : ''}

`; + const h3 = document.createElement('h3'); + h3.innerHTML = `${esc(p.name.toUpperCase())} ${side ? side[L === T.es ? 'es' : 'en'] : ''}`; + h3.appendChild(panelTools(p)); + card.appendChild(h3); const apps = document.createElement('div'); apps.className = 'apps'; - p.apps.forEach(a => apps.appendChild(appButton(a))); + stable(p).forEach(a => apps.appendChild(appButton(a))); card.appendChild(apps); if (target) card.onclick = () => { send('move', { id: chosen.id, panel: p.id }); endMove(); }; return card; diff --git a/src/FocusWShell.App/DeckWeb/index.html b/src/FocusWShell.App/DeckWeb/index.html index d781ead..b8e10d6 100644 --- a/src/FocusWShell.App/DeckWeb/index.html +++ b/src/FocusWShell.App/DeckWeb/index.html @@ -27,7 +27,26 @@ - +
+ + + + + +
+ + +
+ +
+
+
+ +
+ + + +
diff --git a/src/FocusWShell.App/MainWindow.DeckWeb.cs b/src/FocusWShell.App/MainWindow.DeckWeb.cs index fd9f66d..1308f2e 100644 --- a/src/FocusWShell.App/MainWindow.DeckWeb.cs +++ b/src/FocusWShell.App/MainWindow.DeckWeb.cs @@ -29,10 +29,12 @@ private void BuildDeckWeb() WebAddress.Text = !_settings.DeckWebEnabled ? "" : server is null ? Strings.Web_Starting : server.Error is { } error ? Core.Text.F(Strings.Web_Error, error) + : server.PublicOnly ? Strings.Web_PublicNetwork : server.Urls.Count == 0 ? Strings.Web_NoNetwork : string.Join(Environment.NewLine, server.Urls); + WebNetworkButton.Visibility = server is { PublicOnly: true } && _settings.DeckWebEnabled ? Visibility.Visible : Visibility.Collapsed; WebPairButton.IsEnabled = server is { Error: null, Urls.Count: > 0 }; - if (server is null) + if (server is null || server.Urls.Count == 0) { WebPairing.Visibility = Visibility.Collapsed; } @@ -40,15 +42,29 @@ private void BuildDeckWeb() if (!_webHooked && server is not null) { _webHooked = true; - server.Devices.Changed += () => Dispatcher.BeginInvoke(() => + void Rebuild() => Dispatcher.BeginInvoke(() => { - // Al emparejarse uno, el código ya se gastó: se esconde. - WebPairing.Visibility = Visibility.Collapsed; if (DeckWebSection.Visibility == Visibility.Visible) { BuildDeckWeb(); } }); + server.Devices.Changed += () => Dispatcher.BeginInvoke(() => + { + // Al emparejarse uno, el código ya se gastó: se esconde. + WebPairing.Visibility = Visibility.Collapsed; + Rebuild(); + }); + + // Otra red (o la misma, que pasó a privada o a pública): otras direcciones, o ninguna. + server.ListeningChanged += Rebuild; + + // Cinco intentos fallidos anulan el código: se esconde y se dice por qué. + server.Devices.CodeBurned += () => Dispatcher.BeginInvoke(() => + { + WebPairing.Visibility = Visibility.Collapsed; + SetStatus(Strings.Web_CodeBurned); + }); } WebDevices.Children.Clear(); @@ -95,6 +111,10 @@ private async void Web_Changed(object sender, RoutedEventArgs e) BuildDeckWeb(); } + /// Los ajustes de red de Windows, para marcar la red de casa como privada. + private void WebNetwork_Click(object sender, RoutedEventArgs e) => + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("ms-settings:network-status") { UseShellExecute = true })?.Dispose(); + private void WebPages_Changed(object sender, RoutedEventArgs e) { if (!_loadingGestures) diff --git a/src/FocusWShell.App/MainWindow.xaml b/src/FocusWShell.App/MainWindow.xaml index fef5ec7..5ea934c 100644 --- a/src/FocusWShell.App/MainWindow.xaml +++ b/src/FocusWShell.App/MainWindow.xaml @@ -338,6 +338,8 @@ + + diff --git a/src/FocusWShell.App/Strings.Designer.cs b/src/FocusWShell.App/Strings.Designer.cs index fd43c6a..8913fe3 100644 --- a/src/FocusWShell.App/Strings.Designer.cs +++ b/src/FocusWShell.App/Strings.Designer.cs @@ -1464,12 +1464,18 @@ public static class Strings /// no se puede mover public static string Unmanageable_Generic => ResourceManager.GetString("Unmanageable_Generic", Culture)!; + /// El código para emparejar se anuló tras 5 intentos fallidos. Toca Emparejar para + public static string Web_CodeBurned => ResourceManager.GetString("Web_CodeBurned", Culture)!; + /// Dispositivos public static string Web_Devices => ResourceManager.GetString("Web_Devices", Culture)!; /// No pudo escuchar en la red: {0} public static string Web_Error => ResourceManager.GetString("Web_Error", Culture)!; + /// ¿La tablet no conecta? Revisa que el Firewall de Windows permita FocusWShell en + public static string Web_FirewallTip => ResourceManager.GetString("Web_FirewallTip", Culture)!; + /// Usa el deck desde una tablet o un teléfono en tu red local, sin Apollo: FocusWSh public static string Web_Help => ResourceManager.GetString("Web_Help", Culture)!; @@ -1482,9 +1488,12 @@ public static class Strings /// Ningún dispositivo emparejado. public static string Web_NoDevices => ResourceManager.GetString("Web_NoDevices", Culture)!; - /// Escuchando, pero el PC no está en una red privada. + /// No escucha: el PC no está conectado a ninguna red. public static string Web_NoNetwork => ResourceManager.GetString("Web_NoNetwork", Culture)!; + /// Abrir los ajustes de red + public static string Web_OpenNetwork => ResourceManager.GetString("Web_OpenNetwork", Culture)!; + /// Mostrar las páginas de los navegadores public static string Web_Pages => ResourceManager.GetString("Web_Pages", Culture)!; @@ -1500,6 +1509,9 @@ public static class Strings /// Escanea el código con la cámara de la tablet, o abre la dirección y escribe el c public static string Web_PairScan => ResourceManager.GetString("Web_PairScan", Culture)!; + /// No escucha: Windows marca tu red como pública, y en una red pública cualquiera p + public static string Web_PublicNetwork => ResourceManager.GetString("Web_PublicNetwork", Culture)!; + /// Quitar public static string Web_Revoke => ResourceManager.GetString("Web_Revoke", Culture)!; diff --git a/src/FocusWShell.App/Strings.en.resx b/src/FocusWShell.App/Strings.en.resx index 060267a..7ca9198 100644 --- a/src/FocusWShell.App/Strings.en.resx +++ b/src/FocusWShell.App/Strings.en.resx @@ -489,9 +489,13 @@ Restore them now? Each device is paired once with a code that expires in 5 minutes. Scan the code with the tablet's camera, or open the address and type the code. Then add the page to the home screen. For now the page can't keep the tablet's screen on: raise the screen timeout in the tablet's settings. + Tablet not connecting? Check that the Windows Firewall allows FocusWShell on private networks: Control Panel → Windows Defender Firewall → Allow an app… → focuswshell.exe, with Private checked (and Public unchecked). If you first turned it on while the network was marked as public, Windows allowed it for public networks only. Opening… Couldn't listen on the network: {0} - Listening, but the PC is not on a private network. + Not listening: the PC is not connected to any network. + Not listening: Windows marks your network as public, and on a public network anyone could try to connect. If it is your home or office network, mark it as private in the Windows network settings (your network → Properties → Private network); the deck starts listening by itself. + Open network settings + The pairing code was cancelled after 5 failed attempts. Tap Pair to get a new one. No paired devices. Remove Last connected: {0} diff --git a/src/FocusWShell.App/Strings.resx b/src/FocusWShell.App/Strings.resx index e14746d..b9bc8fc 100644 --- a/src/FocusWShell.App/Strings.resx +++ b/src/FocusWShell.App/Strings.resx @@ -489,9 +489,13 @@ Cada dispositivo se empareja una vez con un código que caduca en 5 minutos. Escanea el código con la cámara de la tablet, o abre la dirección y escribe el código. Luego agrega la página a la pantalla de inicio. Por ahora la página no puede mantener encendida la pantalla de la tablet: sube el tiempo de pantalla en los ajustes de la tablet. + ¿La tablet no conecta? Revisa que el Firewall de Windows permita FocusWShell en redes privadas: Panel de control → Firewall de Windows Defender → Permitir una aplicación… → focuswshell.exe, con Privada marcada (y Pública desmarcada). Si lo prendiste por primera vez con la red marcada como pública, Windows lo permitió sólo para redes públicas. Abriendo… No pudo escuchar en la red: {0} - Escuchando, pero el PC no está en una red privada. + No escucha: el PC no está conectado a ninguna red. + No escucha: Windows marca tu red como pública, y en una red pública cualquiera podría intentar conectarse. Si es la red de tu casa o tu oficina, márcala como privada en los ajustes de red de Windows (tu red → Propiedades → Red privada); el deck empieza a escuchar solo. + Abrir los ajustes de red + El código para emparejar se anuló tras 5 intentos fallidos. Toca Emparejar para pedir otro. Ningún dispositivo emparejado. Quitar Última conexión: {0}