diff --git a/.github/release-notes/v0.5.0-alpha.md b/.github/release-notes/v0.5.0-alpha.md new file mode 100644 index 0000000..cef47e6 --- /dev/null +++ b/.github/release-notes/v0.5.0-alpha.md @@ -0,0 +1,77 @@ +**FocusWShell 0.5.0-alpha: sites in Activity, private windows kept private, and apps that go back to their panel.** [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 + +### Apps go back to their panel, however you open them + +After restarting Windows, the apps you opened yourself a few minutes later stayed **free**, even the pinned ones. Now: + +- **A pinned app always fills its place.** Open it from the deck, the taskbar, Start or a shortcut: it goes to its panel, unless one of its windows is already in a panel. +- **The apps of your last session go back to their panel the first time they appear** after restarting, even hours later. After that, another window of the same app stays free. +- **A window you free yourself is not moved,** and an app FocusWShell is opening (from the deck or a scene) goes to the panel you chose. + +### Sites in Activity + +- **Also measure sites** is a new switch in **Activity**, off by default. Under Chrome and Edge you see how long you spent on each site (github.com), with the same blue (in focus) and green (in use) bars. +- **Only the site is saved,** never the page, its address or its title. Pages inside the browser (settings, the new tab) and local files count for the browser, with no site. +- **The sites are folded** under their browser: tap **▸ 3 sites** to show or hide them. + +### Private windows stay private + +- In **Activity**, incognito (Chrome) and InPrivate (Edge) windows count as **Private browsing**, with no site. +- What you type in the address bar is not read. +- In the deck, **🗂 Pages** no longer lists the tabs of private windows: each one shows as **Private window · N tabs**, without titles. Tap it to bring that window to the front. + +Private windows are recognized by the browser's own "Incognito" or "InPrivate" button. If your browser uses a language that names them differently, let us know in [Issues](https://github.com/proteo5/FocusWShell/issues). + +## Install or update + +1. Download `FocusWShell-0.5.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.5.0-alpha: sitios en Actividad, ventanas privadas que se quedan privadas, y apps que vuelven a su panel.** + +> **Mueve tus ventanas.** Si algo sale mal, **Ctrl+Alt+Mayús+Retroceso** devuelve todas las ventanas a su sitio, en cualquier momento. + +### Novedades + +#### Las apps vuelven a su panel, las abras como las abras + +Después de reiniciar Windows, las apps que abrías tú unos minutos más tarde quedaban **libres**, aunque estuvieran ancladas. Ahora: + +- **Una app anclada siempre ocupa su lugar.** Ábrela desde el deck, la barra de tareas, Inicio o un acceso directo: va a su panel, salvo que alguna de sus ventanas ya esté en un panel. +- **Las apps de tu última sesión vuelven a su panel la primera vez que aparecen** tras reiniciar, aunque sea horas después. Después, otra ventana de la misma app queda libre. +- **Una ventana que tú liberas no se mueve,** y una app que FocusWShell está abriendo (desde el deck o una escena) va al panel que elegiste. + +#### Sitios en Actividad + +- **Medir también los sitios** es un interruptor nuevo en **Actividad**, apagado por defecto. Debajo de Chrome y Edge ves cuánto tiempo pasaste en cada sitio (github.com), con las mismas barras azul (en el foco) y verde (en uso). +- **Sólo se guarda el sitio,** nunca la página, su dirección ni su título. Las páginas del navegador (la configuración, la pestaña nueva) y los archivos locales cuentan para el navegador, sin sitio. +- **Los sitios van plegados** bajo su navegador: toca **▸ 3 sitios** para mostrarlos u ocultarlos. + +#### Las ventanas privadas se quedan privadas + +- En **Actividad**, las ventanas de incógnito (Chrome) e InPrivate (Edge) cuentan como **Navegación privada**, sin sitio. +- Lo que escribes en la barra de direcciones no se lee. +- En el deck, **🗂 Páginas** ya no lista las pestañas de las ventanas privadas: cada una sale como **Ventana privada · N pestañas**, sin títulos. Tócala para traer esa ventana al frente. + +Las ventanas privadas se reconocen por el botón «Incógnito» o «InPrivate» del propio navegador. Si tu navegador está en un idioma que los nombra distinto, avísanos en [Issues](https://github.com/proteo5/FocusWShell/issues). + +### Instalar o actualizar + +1. Descarga `FocusWShell-0.5.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 99f6a32..bb3aacd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ 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/). +## 0.5.0-alpha + +Sites in Activity, private windows kept private, and apps that go back to their panel however you open them. / Sitios en Actividad, ventanas privadas que se quedan privadas, y apps que vuelven a su panel las abras como las abras. + +- Fixed: after restarting, apps you opened yourself more than 3 minutes later stayed free, even pinned ones. Now a pinned app goes to its panel however you open it, and the apps of the last session go back to their panel the first time they appear. A window you free yourself is not moved. / Corregido: tras reiniciar, las apps que abrías tú más de 3 minutos después quedaban libres, aunque estuvieran ancladas. Ahora una app anclada va a su panel la abras como la abras, y las apps de la última sesión vuelven a su panel la primera vez que aparecen. Una ventana que tú liberas no se mueve. +- Activity can also measure sites: under Chrome and Edge, the time of each site (github.com). It is a separate switch, off by default; only the site is saved, never the page or its title. / La actividad puede medir también los sitios: debajo de Chrome y Edge, el tiempo de cada sitio (github.com). Es un interruptor aparte, apagado por defecto; sólo se guarda el sitio, nunca la página ni su título. +- Private windows (incognito, InPrivate) count as "Private browsing", with no site, and 🗂 Pages no longer lists their tabs: it shows "Private window · N tabs". / Las ventanas privadas (incógnito, InPrivate) cuentan como «Navegación privada», sin sitio, y 🗂 Páginas ya no lista sus pestañas: muestra «Ventana privada · N pestañas». + +Notes / Notas: [v0.5.0-alpha](.github/release-notes/v0.5.0-alpha.md) + ## 0.4.0-alpha Activity: how long each app spends in focus and in use, and the deck shows the app you type in. / Actividad: cuánto pasa cada app en el foco y en uso, y el deck muestra la app en la que escribes. diff --git a/Directory.Build.props b/Directory.Build.props index c374921..73385b8 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,7 +7,7 @@ latest-recommended true - 0.4.0-alpha + 0.5.0-alpha diff --git a/README.es.md b/README.es.md index 10f8d94..ebcd9b2 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.4.0-alpha-win-x64.zip` desde [Releases](https://github.com/proteo5/FocusWShell/releases). +1. Descarga `FocusWShell-0.5.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. diff --git a/README.md b/README.md index c7c73cc..8bdecca 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.4.0-alpha-win-x64.zip` from [Releases](https://github.com/proteo5/FocusWShell/releases). +1. Download `FocusWShell-0.5.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. diff --git a/docs/05-hoja-de-ruta.md b/docs/05-hoja-de-ruta.md index a5f79f7..327c340 100644 --- a/docs/05-hoja-de-ruta.md +++ b/docs/05-hoja-de-ruta.md @@ -1,4 +1,4 @@ -# 05 — Hoja de ruta +# 05 — Hoja de ruta Los hitos son incrementales: cada uno se usa a diario antes de pasar al siguiente. Las referencias **CA1–CA7** son los criterios de aceptación de [01 — Visión y alcance](01-vision.md#cómo-sabremos-si-funciona). @@ -57,7 +57,7 @@ Objetivo: manejar el escritorio por paneles propios y vistas, con un deck opcion 6. **La disposición del principal como columnas que se prenden y apagan**, para monitores normales y ultrawide, con Solo foco ([ADR 0012, enmienda](adr/0012-vistas-posicion-del-foco.md#enmienda-2026-11-12-la-disposición-del-principal-son-columnas-que-se-prenden-y-apagan)). **Hecho**, sin los anchos fijos. 7. **La ventana principal, moderna**, con WPF-UI: navegación lateral, Inicio con el mapa de monitores, panel aplicado al momento, tema claro u oscuro y «Acerca de» ([ADR 0017](adr/0017-ventana-principal-wpf-ui.md)). **Hecho** (0.2.0-alpha). 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. Después: pares, línea del día, semana y exportar. +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. 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/0019-actividad-foco-y-uso.md b/docs/adr/0019-actividad-foco-y-uso.md index 096597d..3757a5a 100644 --- a/docs/adr/0019-actividad-foco-y-uso.md +++ b/docs/adr/0019-actividad-foco-y-uso.md @@ -1,6 +1,6 @@ # ADR 0019 — Actividad: tiempo en el foco y en uso -- **Estado:** Aceptada (fase 1 en 0.4.0-alpha) +- **Estado:** Aceptada (fase 1 en 0.4.0-alpha; sitios, enmienda del 2026-11-17) - **Fecha:** 2026-11-17 ## Contexto @@ -59,7 +59,7 @@ Las gráficas se dibujan con formas de WPF, sin librería. ### Lo que no hace - Metas, límites ni avisos («llevas 2 h en X»): eso es otro producto y convertiría la actividad en vigilancia. -- Contar por página dentro de los navegadores. Si se agrega, será una opción aparte y apagada. +- Contar por página dentro de los navegadores, ni guardar sus títulos. Sí se cuentan los sitios, como opción aparte (ver la enmienda). ## Consecuencias @@ -67,3 +67,36 @@ Las gráficas se dibujan con formas de WPF, sin librería. - La app en uso puede ser una ventana que FocusWShell no organiza (libre, excluida o del sistema). Cuenta con su nombre, sin panel. - Con apps elevadas, el nombre puede no leerse; cuentan como «Elevada». - El cambio de app en uso se detecta con `EVENT_SYSTEM_FOREGROUND` (`SetWinEventHook`), sin sondeo. + +## Enmienda: los sitios de los navegadores (2026-11-17) + +### Contexto + +En un navegador, «Microsoft Edge 3 h» dice poco: el tiempo se reparte entre sitios muy distintos. La lista de 🗂 Páginas del deck ya agrupa por sitio, pero adivinando con los títulos (`PageSites`), y eso no sirve para medir: un mismo sitio cambia de título, y los títulos son lo más personal de la página. + +Además, Páginas listaba también las pestañas de las ventanas de incógnito y de InPrivate. + +### Spike + +Una sonda con UI Automation en Chrome y Edge (los dos en Windows 11, interfaz en inglés): + +- **La barra de direcciones se lee.** Es una caja de texto (`Edit`, «Address and search bar») fuera del contenido web, con `ValuePattern`. Tarda entre 15 y 130 ms por ventana. Edge muestra el `https://`; Chrome lo oculta. +- **Una ventana privada se reconoce por un botón** de la barra de herramientas: «Incognito» en Chrome, «InPrivate browsing» en Edge. Edge lo dice también en el título; Chrome no. En las ventanas normales no hubo falsos positivos. +- **Lo escrito sin Enter no queda.** Al salir del navegador, la barra vuelve a la dirección de la página. La pestaña nueva tiene la barra vacía. + +### Decisión + +- **Segundo interruptor, «Medir también los sitios»,** apagado por defecto. Solo se puede prender si la actividad está prendida. +- **Solo el host** (`github.com`), sin `www.`, en minúsculas. Nunca la ruta, la consulta, el puerto ni el título. `localhost` y las IP cuentan como sitio. Las páginas internas del navegador (`edge://`, `chrome://`), los archivos locales y la pestaña nueva no tienen sitio: cuentan solo para el navegador. La normalización está en Core (`SiteHost`) y se prueba con xUnit. +- **El sitio va en la app del tramo** (`ActivityApp.Site`). Otro sitio corta el tramo, pero no cuenta como otra llegada al foco ni corta la racha: sigue siendo el mismo navegador. +- **Ventana privada:** se guarda `(private)` y se muestra «Navegación privada». Se cuenta el tiempo, nunca qué se vio. +- **Mientras se escribe en la barra** (la barra tiene el teclado) no se lee: se conserva el sitio anterior. +- **Cuándo se lee:** al cambiar la app en el foco o en uso, y cada 5 s mientras se mide, porque cambiar de pestaña no avisa. Solo se leen los navegadores en el foco o en uso, en un hilo de fondo. +- **En la sección Actividad,** los sitios con al menos un minuto van debajo de su navegador, sangrados y con las mismas barras. Están plegados al principio («▸ 7 sitios»), para que un navegador con muchos sitios no tape las demás apps. +- **En 🗂 Páginas,** las ventanas privadas no se listan ni se agrupan por sitio: hay una fila por ventana, «Ventana privada · N pestañas», que la lleva al frente. + +### Consecuencias + +- El nombre del botón privado depende del idioma del navegador. Se reconoce `incogn`, `inkogn` e `InPrivate`, que cubre los idiomas comunes. En un idioma que no los use, una ventana privada contaría como normal y guardaría su sitio: es el límite conocido. +- La estructura de la interfaz de los navegadores no es un contrato. Si la barra no se encuentra, no hay sitio y la actividad sigue por app. +- Un cambio de pestaña se nota con hasta 5 s de retraso. diff --git a/site/_config.yml b/site/_config.yml index 6c457d4..4241812 100644 --- a/site/_config.yml +++ b/site/_config.yml @@ -5,7 +5,7 @@ description: A visual attention manager for Windows. One app in focus, the rest url: https://proteo5.github.io baseurl: /FocusWShell repository: proteo5/FocusWShell -version: 0.4.0-alpha +version: 0.5.0-alpha markdown: kramdown kramdown: input: GFM diff --git a/site/browser-pages.md b/site/browser-pages.md index 85429b1..06c9d9f 100644 --- a/site/browser-pages.md +++ b/site/browser-pages.md @@ -41,3 +41,5 @@ When it cannot tell, the page is shown as a single page, with its own title. It ## Privacy Titles are read only while the list is on screen, and are never saved or sent anywhere. + +Private windows (incognito in Chrome, InPrivate in Edge) are not listed: each one shows as **Private window · N tabs**, without titles. Tap it to bring that window to the front. diff --git a/site/es/comentarios.md b/site/es/comentarios.md index a823f49..7721a01 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.4.0-alpha*. +- **La versión:** la primera línea del menú de la bandeja o General → Acerca de, por ejemplo *FocusWShell 0.5.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/guias.md b/site/es/guias.md index 28745a1..3708258 100644 --- a/site/es/guias.md +++ b/site/es/guias.md @@ -84,7 +84,7 @@ Tiles para paneles con dos o tres apps que quieres ver a la vez; pestañas para ## Dejar una app en su panel aunque esté cerrada {#anclar} -Ánclala, y su lugar en el panel se queda aunque la cierres: atenuada, y un toque la abre ahí. +Ánclala, y su lugar en el panel se queda aunque la cierres: atenuada, y un toque la abre ahí. Si la abres de otra forma (la barra de tareas, Inicio, un acceso directo), también va a su panel, salvo que alguna de sus ventanas ya esté en un panel. 1. En el deck, toca **Anclar…** (índigo). 2. Toca la app. diff --git a/site/es/instalar.md b/site/es/instalar.md index b4efc6d..30b34da 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.4.0-alpha-win-x64.zip -Algorithm SHA256 +Get-FileHash .\FocusWShell-0.5.0-alpha-win-x64.zip -Algorithm SHA256 ``` ## Iniciar con Windows diff --git a/site/es/limitaciones.md b/site/es/limitaciones.md index c74167a..9a7c4ad 100644 --- a/site/es/limitaciones.md +++ b/site/es/limitaciones.md @@ -31,6 +31,7 @@ El soporte completo (un foco y unas apps por escritorio, y pestañas de escritor - Sólo **Chrome y Edge**. Firefox y los demás no. - El sitio de cada página se deduce de su título, así que algunas pueden salir como sueltas. - Probado con pestañas verticales. Las pestañas horizontales y los grupos plegados, todavía poco. +- Las ventanas privadas (incógnito, InPrivate) se reconocen por el botón del propio navegador. Si tu navegador está en un idioma que lo nombra distinto, una ventana privada puede contar como normal en Actividad y en Páginas. ## Otras diff --git a/site/es/paginas.md b/site/es/paginas.md index b70bb94..17b983b 100644 --- a/site/es/paginas.md +++ b/site/es/paginas.md @@ -41,3 +41,5 @@ Cuando no lo sabe, la página sale como suelta, con su propio título. Nunca mez ## Privacidad Los títulos se leen sólo mientras la lista está a la vista, y nunca se guardan ni se envían a ningún lado. + +Las ventanas privadas (incógnito en Chrome, InPrivate en Edge) no se listan: cada una sale como **Ventana privada · N pestañas**, sin títulos. Tócala para traer esa ventana al frente. diff --git a/site/es/ventana-principal.md b/site/es/ventana-principal.md index ea9b922..46a51a2 100644 --- a/site/es/ventana-principal.md +++ b/site/es/ventana-principal.md @@ -69,6 +69,8 @@ Está apagada hasta que prendas **Medir la actividad**. Se guarda sólo en este Para cada día: el tiempo activo, el tiempo en paralelo, cuántas veces llevaste una app al foco y la racha más larga con la misma app en el foco. Debajo, cada app con una barra azul (en el foco) y una verde (en uso). +**Medir también los sitios** agrega, debajo de Chrome y Edge, el tiempo de cada sitio (github.com); toca **▸ N sitios** para mostrarlos u ocultarlos. Sólo se guarda el sitio, nunca la página ni su título. Las ventanas privadas (incógnito, InPrivate) cuentan como **Navegación privada**, sin sitio, y lo que escribes en la barra de direcciones no se lee. + ## Excluidas Apps que FocusWShell nunca debe tocar, por ejecutable, AUMID o clase de ventana. Ver [Dejar una app fuera de FocusWShell]({{ '/es/guias/#excluir' | relative_url }}). diff --git a/site/feedback.md b/site/feedback.md index 6dcbdd2..c528503 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.4.0-alpha*. +- **The version:** the first line of the tray menu or General → About, for example *FocusWShell 0.5.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/guides.md b/site/guides.md index 030f773..49e76f1 100644 --- a/site/guides.md +++ b/site/guides.md @@ -84,7 +84,7 @@ Tiles for panels with two or three apps you want to see at once; tabs for a pane ## Keep an app in its panel, even when closed {#pin} -Pin it, and its place in the panel stays when you close it: dimmed, and one tap opens it there. +Pin it, and its place in the panel stays when you close it: dimmed, and one tap opens it there. If you open it another way (the taskbar, Start, a shortcut), it also goes to its panel, unless one of its windows is already in a panel. 1. In the deck, tap **Pin…** (indigo). 2. Tap the app. diff --git a/site/install.md b/site/install.md index b3b24ba..59f0199 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.4.0-alpha-win-x64.zip -Algorithm SHA256 +Get-FileHash .\FocusWShell-0.5.0-alpha-win-x64.zip -Algorithm SHA256 ``` ## Start with Windows diff --git a/site/limitations.md b/site/limitations.md index 24eb4ba..c8f459a 100644 --- a/site/limitations.md +++ b/site/limitations.md @@ -31,6 +31,7 @@ Full support (a focus and apps per desktop, and desktop tabs in the deck) is pla - Only **Chrome and Edge**. Firefox and others are not supported. - The site of each page is guessed from its title, so some pages may appear as single pages. - Tested with vertical tabs. Horizontal tabs and collapsed tab groups have not been tested much. +- Private windows (incognito, InPrivate) are recognized by the browser's own button. If your browser uses a language that names it differently, a private window may count as a normal one in Activity and in Pages. ## Other diff --git a/site/main-window.md b/site/main-window.md index 511ca97..7e7a985 100644 --- a/site/main-window.md +++ b/site/main-window.md @@ -69,6 +69,8 @@ It is off until you turn on **Measure activity**. It is kept only on this PC, wi For each day: the active time, the time side by side, how many times you brought an app to the focus, and the longest stretch with the same app in focus. Below, each app with a blue bar (in focus) and a green one (in use). +**Also measure sites** adds, under Chrome and Edge, the time of each site (github.com); tap **▸ N sites** to show or hide them. Only the site is saved, never the page or its title. Private windows (incognito, InPrivate) count as **Private browsing**, with no site, and what you type in the address bar is not read. + ## Excluded Apps FocusWShell should never touch, by executable, AUMID or window class. See [Keep an app out of FocusWShell]({{ '/guides/#keep-an-app-out-of-focuswshell' | relative_url }}). diff --git a/src/FocusWShell.App/ActivityRecorder.cs b/src/FocusWShell.App/ActivityRecorder.cs index 7fd3de6..89e3d08 100644 --- a/src/FocusWShell.App/ActivityRecorder.cs +++ b/src/FocusWShell.App/ActivityRecorder.cs @@ -1,11 +1,16 @@ using System.Windows.Threading; using FocusWShell.Core.Activity; +using FocusWShell.Core.Browsers; using FocusWShell.Win32; using FocusWShell.Win32.Persistence; using Microsoft.Win32; namespace FocusWShell.App; +/// Una app para la actividad con la ventana de la que salió. +/// Si es Chrome o Edge: con los sitios prendidos, se lee su barra de direcciones. +public sealed record ActivityWindow(ActivityApp App, nint Handle, bool Browser); + /// /// Lleva la cuenta de la actividad (ADR 0019): le pasa al los cambios de la app /// en el foco y en uso, y cuándo se deja de tocar el equipo; escribe los tramos en el . @@ -19,9 +24,15 @@ public sealed class ActivityRecorder : IDisposable private static readonly TimeSpan Tick = TimeSpan.FromSeconds(15); private static readonly TimeSpan FlushEvery = TimeSpan.FromMinutes(5); + /// Cada cuánto se mira el sitio del navegador (cambiar de pestaña no avisa). + private static readonly TimeSpan SitesEvery = TimeSpan.FromSeconds(5); + private readonly ShellController _controller; private readonly ActivityTracker _tracker = new(); private readonly DispatcherTimer _timer; + private readonly DispatcherTimer _sitesTimer; + private readonly Dictionary _sites = []; // el último sitio leído de cada navegador + private bool _readingSites; private DateTime _lastFlush = DateTime.Now; private bool _paused; // bloqueado o suspendido @@ -31,6 +42,8 @@ public ActivityRecorder(ShellController controller, ActivityStore store) Store = store; _timer = new DispatcherTimer { Interval = Tick }; _timer.Tick += (_, _) => OnTick(); + _sitesTimer = new DispatcherTimer { Interval = SitesEvery }; + _sitesTimer.Tick += (_, _) => Observe(); SystemEvents.SessionSwitch += OnSessionSwitch; SystemEvents.PowerModeChanged += OnPowerModeChanged; } @@ -67,14 +80,105 @@ public void Stop() _timer.Stop(); } + /// + /// Medir también los sitios de los navegadores (ADR 0019, sitios). Se lee la barra de direcciones del + /// navegador en el foco o en uso, en un hilo de fondo, y se guarda sólo su host. + /// + public bool Sites + { + get => _sitesTimer.IsEnabled; + set + { + if (value) + { + _sitesTimer.Start(); + } + else + { + _sitesTimer.Stop(); + _sites.Clear(); + } + + Observe(); // el tramo abierto se corta: con o sin sitio a partir de ahora + } + } + /// Cambió la app en uso o lo que hay en el foco. - public void Observe() + public void Observe() => Observe(readSites: true); + + private void Observe(bool readSites) + { + if (!_timer.IsEnabled || _paused) + { + return; + } + + var (focus, inUse) = _controller.ActivityNow(); + Write(_tracker.Observe(DateTime.Now, WithSite(focus), WithSite(inUse))); + if (readSites && Sites && _tracker.Running) + { + ReadSites(focus, inUse); + } + } + + /// La app, con el último sitio leído de su ventana si es un navegador. + private ActivityApp? WithSite(ActivityWindow? window) => + window is null ? null + : Sites && window.Browser && _sites.TryGetValue(window.Handle, out var site) ? window.App with { Site = site } + : window.App; + + /// + /// Lee en el fondo la barra de los navegadores en el foco y en uso. Si el sitio cambió, el tramo se corta. + /// Mientras se escribe en la barra se conserva el sitio anterior: lo escrito no es una página. + /// + private void ReadSites(ActivityWindow? focus, ActivityWindow? inUse) { - if (_timer.IsEnabled && !_paused) + nint[] handles = [.. new[] { focus, inUse }.Where(w => w is { Browser: true }).Select(w => w!.Handle).Distinct()]; + if (_readingSites || handles.Length == 0) { - var (focus, inUse) = _controller.ActivityNow(); - Write(_tracker.Observe(DateTime.Now, focus, inUse)); + return; } + + _readingSites = true; + Task.Run(() => handles.Select(h => (Handle: h, Address: BrowserAddressReader.Read(h))).ToList()) + .ContinueWith( + t => + { + _readingSites = false; + if (!Sites || t.IsFaulted) + { + return; + } + + bool changed = false; + var known = new Dictionary(); + foreach (var (handle, address) in t.Result) + { + _sites.TryGetValue(handle, out var before); + var site = address switch + { + null => null, + { Private: true } => SiteHost.Private, + { Editing: true } => before, + _ => SiteHost.From(address.Value), + }; + known[handle] = site; + changed |= !_sites.ContainsKey(handle) || !string.Equals(before, site, StringComparison.OrdinalIgnoreCase); + } + + // Sólo se recuerdan las ventanas leídas: otra que vuelva se lee otra vez. + _sites.Clear(); + foreach (var (handle, site) in known) + { + _sites[handle] = site; + } + + if (changed) + { + Observe(readSites: false); + } + }, + TaskScheduler.FromCurrentSynchronizationContext()); } /// Guarda el tramo abierto (al apagar o reiniciar, o para ver el día al momento). @@ -186,6 +290,7 @@ private void Write(IReadOnlyList segments) public void Dispose() { Stop(); + _sitesTimer.Stop(); SystemEvents.SessionSwitch -= OnSessionSwitch; SystemEvents.PowerModeChanged -= OnPowerModeChanged; } diff --git a/src/FocusWShell.App/App.xaml.cs b/src/FocusWShell.App/App.xaml.cs index e8e0ff9..72e4736 100644 --- a/src/FocusWShell.App/App.xaml.cs +++ b/src/FocusWShell.App/App.xaml.cs @@ -307,6 +307,10 @@ protected override void OnStartup(StartupEventArgs e) _lists?.OnForeground(hwnd); _deck?.UpdateForeground(hwnd); // el indicador de «al frente», sin esperar al siguiente repaso _activity?.Observe(); + if (_lateAdoption) + { + AdoptReturning(); // una app recién abierta pasa al frente: que vuelva a su panel ya + } }); _controller.PauseChanged += _ => Dispatcher.BeginInvoke(FollowPause); _controller.FocusGestureEnabled = g => g switch @@ -374,7 +378,7 @@ protected override void OnStartup(StartupEventArgs e) ShowMain(); // La última sesión: cada ventana a su panel, como estaba. Las apps que se abran después (al iniciar - // Windows suelen tardar) se adoptan durante unos minutos. + // Windows suelen tardar, o se abren a mano horas después) vuelven a su panel al aparecer. Task.Run(() => { var restored = _controller.RestoreSession(); @@ -1022,6 +1026,7 @@ private void StartActivity() if (!_settings.ActivityEnabled) { _activity.Stop(); + _activity.Sites = false; return; } @@ -1034,6 +1039,7 @@ private void StartActivity() } _activity.Start(); + _activity.Sites = _settings.ActivitySites; } /// La actividad, para la sección Actividad de la ventana principal. @@ -1047,6 +1053,14 @@ internal void SetActivity(bool enabled) StartActivity(); } + /// Prender o apagar la medición de los sitios de los navegadores (sección Actividad). + internal void SetActivitySites(bool enabled) + { + _settings.ActivitySites = enabled; + _settings.Save(); + StartActivity(); + } + /// Guarda la sesión unos segundos después del último cambio. private void ScheduleSessionSave() { @@ -1068,28 +1082,61 @@ private void SaveSessionTick(object? sender, EventArgs e) Task.Run(_controller.SaveSession); } - /// Cada 10 s durante 3 min, adopta las ventanas de la última sesión que aparezcan. + /// Si ya se restauró la sesión y las apps que aparecen pueden volver a su panel. + private bool _lateAdoption; + + /// + /// Vuelve a poner en su panel las apps que aparecen después de arrancar + /// (): cada 10 s durante el arranque, luego cada 30 s, y + /// en cuanto cambia la ventana en uso (una app recién abierta casi siempre pasa al frente). + /// private void StartLateAdoption() { - var until = DateTime.Now + ShellController.SessionAdoption; + _lateAdoption = true; + var fastUntil = DateTime.Now + ShellController.SessionAdoption; var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(10) }; timer.Tick += (_, _) => { - if (DateTime.Now > until || IsExiting) + if (IsExiting) { timer.Stop(); return; } - Task.Run(() => + if (DateTime.Now > fastUntil) { - if (_controller.AdoptLateSessionWindows() is { } result) + timer.Interval = TimeSpan.FromSeconds(30); + } + + AdoptReturning(); + }; + timer.Start(); + } + + private int _adopting; + + /// Una pasada en el fondo; si ya hay una en curso, no se encima otra. + private void AdoptReturning() + { + if (Interlocked.Exchange(ref _adopting, 1) == 1) + { + return; + } + + Task.Run(() => + { + try + { + if (_controller.AdoptReturningWindows() is { } result) { Dispatcher.BeginInvoke(() => RefreshAfter(result)); } - }); - }; - timer.Start(); + } + finally + { + Interlocked.Exchange(ref _adopting, 0); + } + }); } /// Reinicia FocusWShell (p. ej. para cambiar de idioma): sale como «Salir» y abre otra instancia. diff --git a/src/FocusWShell.App/AppSettings.cs b/src/FocusWShell.App/AppSettings.cs index 0aae1b4..3a94aaa 100644 --- a/src/FocusWShell.App/AppSettings.cs +++ b/src/FocusWShell.App/AppSettings.cs @@ -36,6 +36,9 @@ public sealed class AppSettings /// Cuántos días se guarda la actividad. public int ActivityKeepDays { get; set; } = 90; + /// Medir también los sitios de Chrome y Edge, sólo su host (ADR 0019, sitios). Apagado por defecto. + public bool ActivitySites { get; set; } + /// Alt+Tab a una ventana de un panel la lleva al foco (ADR 0003, enmienda). public bool FocusOnAltTab { get; set; } = true; diff --git a/src/FocusWShell.App/DeckState.cs b/src/FocusWShell.App/DeckState.cs index 8a8d494..3d94338 100644 --- a/src/FocusWShell.App/DeckState.cs +++ b/src/FocusWShell.App/DeckState.cs @@ -59,4 +59,5 @@ public sealed record DeckState( /// Nombre del navegador («Microsoft Edge»). /// Dónde está, para la UI: en el foco, su panel, libre u otro escritorio. /// Si está en un panel (tocar una página la lleva al foco) o es libre (sólo al frente). -public sealed record PageWindow(nint Handle, string Browser, string Where, bool InFocus, bool Managed, bool OtherDesktop, CatalogApp? App, IReadOnlyList Tabs); +/// Ventana de incógnito o InPrivate: el deck no muestra sus páginas, sólo cuántas son. +public sealed record PageWindow(nint Handle, string Browser, string Where, bool InFocus, bool Managed, bool OtherDesktop, CatalogApp? App, IReadOnlyList Tabs, bool Private = false); diff --git a/src/FocusWShell.App/DeckWindow.cs b/src/FocusWShell.App/DeckWindow.cs index f917cf3..23f5e2d 100644 --- a/src/FocusWShell.App/DeckWindow.cs +++ b/src/FocusWShell.App/DeckWindow.cs @@ -614,7 +614,8 @@ private sealed record PageEntry(PageWindow Window, BrowserTab Tab, string? Site) private List PageEntries() { - var all = (_pages ?? []).SelectMany(w => w.Tabs.Select(t => (Window: w, Tab: t))).ToList(); + // Las ventanas privadas no se listan ni se agrupan por sitio: van aparte, una fila cada una. + var all = (_pages ?? []).Where(w => !w.Private).SelectMany(w => w.Tabs.Select(t => (Window: w, Tab: t))).ToList(); var sites = PageSites.Assign([.. all.Select(x => x.Tab.Title)]); return [.. all.Select((x, i) => new PageEntry(x.Window, x.Tab, sites[i]))]; } @@ -635,7 +636,7 @@ private Border PagesView() Margin = new Thickness(0, 0, 8, 8), }; var entries = PageEntries(); - if (entries.Count == 0) + if (entries.Count == 0 && !(_pages ?? []).Any(w => w.Private)) { card.Child = new TextBlock { @@ -720,6 +721,43 @@ private void SitesAndLoose(StackPanel list, List entries) list.Children.Add(grid); } + + var hidden = (_pages ?? []).Where(w => w.Private).ToList(); + if (hidden.Count > 0) + { + list.Children.Add(Label(Strings.Deck_PagesPrivate)); + var grid = new UniformGrid { Columns = IsWide ? 3 : 2 }; + foreach (var window in hidden) + { + grid.Children.Add(PrivateTile(window)); + } + + list.Children.Add(grid); + } + } + + /// + /// Una ventana privada: cuántas pestañas tiene y dónde está, sin sus títulos. Tocarla la lleva al frente + /// (al foco, si es de un panel) en la pestaña que tenía. + /// + private Button PrivateTile(PageWindow window) + { + var content = new DockPanel(); + var where = new TextBlock { Text = Core.Text.F(Strings.Deck_PageWhere, window.Browser, window.Where), Foreground = DimBrush, FontSize = 11, Margin = new Thickness(6, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center }; + DockPanel.SetDock(where, Dock.Right); + content.Children.Add(where); + var text = Core.Text.F(Strings.Deck_PagesPrivateWindow, window.Tabs.Count); + content.Children.Add(new TextBlock { Text = "🕶 " + text, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center }); + var tile = PageButton(content); + if (window.OtherDesktop) + { + tile.Foreground = DimBrush; + } + + System.Windows.Automation.AutomationProperties.SetName(tile, text); + var tab = window.Tabs.FirstOrDefault(t => t.Active) ?? window.Tabs[0]; + tile.Click += async (_, _) => await ChoosePage(window, tab); + return tile; } /// Un sitio: su nombre y cuántas páginas tiene. Tocarlo muestra sus páginas. diff --git a/src/FocusWShell.App/MainWindow.Activity.cs b/src/FocusWShell.App/MainWindow.Activity.cs index f8b96ea..7835ed5 100644 --- a/src/FocusWShell.App/MainWindow.Activity.cs +++ b/src/FocusWShell.App/MainWindow.Activity.cs @@ -15,6 +15,9 @@ public partial class MainWindow private DateOnly _activityDay = DateOnly.FromDateTime(DateTime.Now); private bool _activityHooked; + /// Los navegadores con sus sitios desplegados. + private readonly HashSet _activityOpenSites = new(StringComparer.OrdinalIgnoreCase); + private static App Host => (App)Application.Current; /// Muestra la sección: el interruptor, el día elegido y sus cifras. @@ -34,6 +37,8 @@ private void BuildActivity() _loadingGestures = true; ActivitySwitch.IsChecked = _settings.ActivityEnabled; + ActivitySitesSwitch.IsChecked = _settings.ActivitySites; + ActivitySitesCard.IsEnabled = _settings.ActivityEnabled; _loadingGestures = false; ActivityPrivacy.Text = Core.Text.F(Strings.Activity_MeasureHelp, _settings.ActivityKeepDays); @@ -74,12 +79,80 @@ private void BuildActivity() foreach (var app in day.Apps.Where(a => a.InFocus + a.InUse >= TimeSpan.FromMinutes(1))) { var panel = app.PanelId is { } id && panels.TryGetValue(id, out var name) ? name : Strings.Activity_NoPanel; - rows.Children.Add(AppRow(app, panel, max)); + var row = AppRow(app.Name, panel, app.InFocus, app.InUse, max, site: false); + rows.Children.Add(row); + + // Los sitios del navegador, debajo, con las mismas barras (ADR 0019, sitios). Plegados al + // principio, para que un navegador con muchos sitios no tape las demás apps. + var sites = app.Sites.Where(s => s.InFocus + s.InUse >= TimeSpan.FromMinutes(1)).ToList(); + if (sites.Count == 0) + { + continue; + } + + var list = new WC.StackPanel { Visibility = _activityOpenSites.Contains(app.Key) ? Visibility.Visible : Visibility.Collapsed }; + foreach (var site in sites) + { + var siteName = site.Site == Core.Browsers.SiteHost.Private ? Strings.Activity_PrivateSite : site.Site; + list.Children.Add(AppRow(siteName, null, site.InFocus, site.InUse, max, site: true)); + } + + // En la línea del panel, a su derecha: no agrega altura a la fila. + var nameStack = (WC.StackPanel)row.Children[0]; + var panelText = (WC.TextBlock)nameStack.Children[1]; + nameStack.Children.Remove(panelText); + var line = new WC.StackPanel { Orientation = WC.Orientation.Horizontal }; + panelText.VerticalAlignment = VerticalAlignment.Center; + line.Children.Add(panelText); + line.Children.Add(SitesToggle(app.Key, sites.Count, list)); + nameStack.Children.Add(line); + rows.Children.Add(list); } ActivityContent.Children.Add(CardRow(rows)); } + /// + /// «▸ 7 sitios»: despliega o pliega los sitios de un navegador sin redibujar la sección. Se recuerda + /// mientras la ventana está abierta, también al cambiar de día. + /// + private Wpf.Ui.Controls.Button SitesToggle(string key, int count, WC.StackPanel list) + { + // Un botón pequeño del tema (relleno, borde y estado al pasar el ratón), con contraste en claro y oscuro; + // el chevron dice si está abierto. + var text = count == 1 ? Strings.Activity_SitesOne : Core.Text.F(Strings.Activity_SitesCount, count); + Wpf.Ui.Controls.SymbolIcon Chevron() => new(list.Visibility == Visibility.Visible ? Wpf.Ui.Controls.SymbolRegular.ChevronDown16 : Wpf.Ui.Controls.SymbolRegular.ChevronRight16) { FontSize = 12 }; + var button = new Wpf.Ui.Controls.Button + { + Content = text, + Icon = Chevron(), + Padding = new Thickness(6, 1, 8, 1), + MinHeight = 0, + Margin = new Thickness(8, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center, + HorizontalAlignment = HorizontalAlignment.Left, + FontSize = 12, + Cursor = System.Windows.Input.Cursors.Hand, + }; + System.Windows.Automation.AutomationProperties.SetName(button, text); + button.Click += (_, _) => + { + bool open = list.Visibility != Visibility.Visible; + list.Visibility = open ? Visibility.Visible : Visibility.Collapsed; + if (open) + { + _activityOpenSites.Add(key); + } + else + { + _activityOpenSites.Remove(key); + } + + button.Icon = Chevron(); + }; + return button; + } + /// Una cifra del día: su nombre arriba, el valor grande y, si hay, un detalle. private static WC.Border Figure(string label, string value, string? detail) { @@ -106,37 +179,48 @@ private static WC.StackPanel Swatch(Brush color, string label) return panel; } - /// Una app: su nombre y panel, una barra azul (en el foco) sobre una verde (en uso) y los dos tiempos. - private static WC.Grid AppRow(ActivityAppTotal app, string panel, long max) + /// + /// Una app (o un sitio de un navegador, sangrado y más pequeño, debajo de su navegador): su nombre y + /// panel, una barra azul (en el foco) sobre una verde (en uso) y los dos tiempos. + /// + private static WC.Grid AppRow(string title, string? panel, TimeSpan inFocus, TimeSpan inUse, long max, bool site) { - var row = new WC.Grid { Margin = new Thickness(0, 4, 0, 4) }; + var row = new WC.Grid { Margin = new Thickness(0, site ? 1 : 4, 0, site ? 1 : 4) }; row.ColumnDefinitions.Add(new WC.ColumnDefinition { Width = new GridLength(170) }); row.ColumnDefinitions.Add(new WC.ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); row.ColumnDefinitions.Add(new WC.ColumnDefinition { Width = new GridLength(150) }); - var name = new WC.StackPanel { VerticalAlignment = VerticalAlignment.Center }; - name.Children.Add(Text(app.Name)); - name.Children.Add(Text(panel, "TextFillColorSecondaryBrush", 12)); + var name = new WC.StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(site ? 16 : 0, 0, 0, 0) }; + var label = site ? Text(title, "TextFillColorSecondaryBrush", 12) : Text(title); + label.TextTrimming = TextTrimming.CharacterEllipsis; + label.ToolTip = title; + name.Children.Add(label); + if (panel is not null) + { + name.Children.Add(Text(panel, "TextFillColorSecondaryBrush", 12)); + } + row.Children.Add(name); - var bars = new WC.StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 8, 0) }; - bars.Children.Add(Bar(app.InFocus.Ticks, max, FocusBlue)); - bars.Children.Add(Bar(app.InUse.Ticks, max, InUseGreen)); + var bars = new WC.StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 8, 0), Opacity = site ? 0.75 : 1 }; + bars.Children.Add(Bar(inFocus.Ticks, max, FocusBlue, site ? 6 : 10)); + bars.Children.Add(Bar(inUse.Ticks, max, InUseGreen, site ? 6 : 10)); WC.Grid.SetColumn(bars, 1); row.Children.Add(bars); - var times = Text($"{Duration(app.InFocus)} · {Duration(app.InUse)}", "TextFillColorSecondaryBrush", 13); + var times = Text($"{Duration(inFocus)} · {Duration(inUse)}", "TextFillColorSecondaryBrush", site ? 12 : 13); times.HorizontalAlignment = HorizontalAlignment.Right; - times.ToolTip = $"{Strings.Activity_InFocus}: {Duration(app.InFocus)} · {Strings.Activity_InUse}: {Duration(app.InUse)}"; + times.VerticalAlignment = VerticalAlignment.Center; + times.ToolTip = $"{Strings.Activity_InFocus}: {Duration(inFocus)} · {Strings.Activity_InUse}: {Duration(inUse)}"; WC.Grid.SetColumn(times, 2); row.Children.Add(times); return row; } /// Una barra proporcional al máximo del día. - private static WC.Grid Bar(long value, long max, Brush color) + private static WC.Grid Bar(long value, long max, Brush color, double height) { - var bar = new WC.Grid { Height = 10, Margin = new Thickness(0, 1, 0, 1) }; + var bar = new WC.Grid { Height = height, Margin = new Thickness(0, 1, 0, 1) }; bar.ColumnDefinitions.Add(new WC.ColumnDefinition { Width = new GridLength(Math.Max(value, 0), GridUnitType.Star) }); bar.ColumnDefinitions.Add(new WC.ColumnDefinition { Width = new GridLength(Math.Max(max - value, 0), GridUnitType.Star) }); bar.Children.Add(new WC.Border { Background = color, CornerRadius = new CornerRadius(2) }); @@ -158,6 +242,15 @@ private void Activity_Changed(object sender, RoutedEventArgs e) } } + private void ActivitySites_Changed(object sender, RoutedEventArgs e) + { + if (!_loadingGestures) + { + Host.SetActivitySites(ActivitySitesSwitch.IsChecked == true); + BuildActivity(); + } + } + private void ActivityPrev_Click(object sender, RoutedEventArgs e) { _activityDay = _activityDay.AddDays(-1); diff --git a/src/FocusWShell.App/MainWindow.xaml b/src/FocusWShell.App/MainWindow.xaml index 36f1c97..375e333 100644 --- a/src/FocusWShell.App/MainWindow.xaml +++ b/src/FocusWShell.App/MainWindow.xaml @@ -301,6 +301,16 @@ + + + + + + + + + diff --git a/src/FocusWShell.App/ShellController.cs b/src/FocusWShell.App/ShellController.cs index 8c2c4a4..ea66e82 100644 --- a/src/FocusWShell.App/ShellController.cs +++ b/src/FocusWShell.App/ShellController.cs @@ -326,12 +326,12 @@ string Where(Panel p) => p.Display is null /// Qué app está en el foco y cuál en uso ahora, para contar la actividad. La app en uso puede no ser de /// FocusWShell (libre, excluida, del sistema): cuenta con su nombre, sin panel. /// - public (Core.Activity.ActivityApp? Focus, Core.Activity.ActivityApp? InUse) ActivityNow() + public (ActivityWindow? Focus, ActivityWindow? InUse) ActivityNow() { var foreground = WindowMover.Foreground(); lock (_gate) { - Core.Activity.ActivityApp? Of(WindowSnapshot s) + ActivityWindow? Of(WindowSnapshot s) { if (s.IsOwnProcess) { @@ -341,7 +341,9 @@ string Where(Panel p) => p.Display is null var key = MinSizeCatalog.KeyFor(s); var name = _catalog.Find(key)?.Name ?? Path.GetFileNameWithoutExtension(s.ProcessName); var panel = _workspace.Find(s.Handle) is { } w ? _workspace.EffectivePanel(w).Id : null; - return string.IsNullOrEmpty(key) ? null : new(key, string.IsNullOrEmpty(name) ? key : name, panel); + return string.IsNullOrEmpty(key) + ? null + : new(new(key, string.IsNullOrEmpty(name) ? key : name, panel), s.Handle, BrowserTabs.IsBrowser(s.ProcessName, s.ClassName)); } var focus = _workspace.Focused is { } f && !_elsewhere.ContainsKey(f.Handle) && _snapshots.TryGetValue(f.Handle, out var fs) ? Of(fs) : null; @@ -391,7 +393,7 @@ public IReadOnlyList BrowserPages() { if (BrowserTabs.Read(w.Handle) is { Count: > 0 } tabs) { - pages.Add(new PageWindow(w.Handle, w.Browser, w.Where, w.InFocus, w.Managed, w.Elsewhere, w.App, tabs)); + pages.Add(new PageWindow(w.Handle, w.Browser, w.Where, w.InFocus, w.Managed, w.Elsewhere, w.App, tabs, BrowserAddressReader.IsPrivate(w.Handle))); } } @@ -955,6 +957,20 @@ private void RememberAppPanels() /// Devuelve un mensaje para el usuario. /// public string OpenApp(string appKey, string panelId) + { + // Mientras tanto, su ventana nueva no vuelve sola a su último panel: la acomoda esto, en el pedido. + Launching([appKey], start: true); + try + { + return OpenAppCore(appKey, panelId); + } + finally + { + Launching([appKey], start: false); + } + } + + private string OpenAppCore(string appKey, string panelId) { CatalogApp? app; HashSet before; @@ -1236,7 +1252,7 @@ private void SessionWindowGoneLocked(nint handle) /// /// Al arrancar: vuelve a poner en sus paneles las ventanas de la última sesión que estén abiertas, con /// la vista de entonces. No toca los paneles (ya se guardan aparte) ni abre apps. Las que falten se - /// adoptan si aparecen en los próximos minutos (). + /// adoptan si aparecen en los próximos minutos (). /// public ControllerResult? RestoreSession() { @@ -1249,6 +1265,8 @@ private void SessionWindowGoneLocked(nint handle) var match = SceneMatcher.Match(scene, open, strict: true); lock (_gate) { + _seen.UnionWith(open.Select(o => o.Handle)); // las que ya estaban no son «nuevas» + _seenReady = true; _sessionPending = [.. match.Missing]; _sessionUntil = DateTime.Now + SessionAdoption; foreach (var (entry, window) in match.Matched) @@ -1268,55 +1286,138 @@ private void SessionWindowGoneLocked(nint handle) return Execute(new ApplyScene(entries, []) { View = scene.View, Weights = scene.Weights }); } - /// - /// Adopta las ventanas de la última sesión que aparecen tarde (p. ej. apps que se abren al iniciar - /// Windows después que FocusWShell). Sólo ventanas libres: no mueve nada de lo que el usuario ya puso. - /// - public ControllerResult? AdoptLateSessionWindows() + /// Las ventanas que ya se vieron (libres o en un panel): sólo una ventana nueva vuelve sola a su panel. + private readonly HashSet _seen = []; + + /// Si ya se tomó nota de las ventanas que había al arrancar. + private bool _seenReady; + + /// Apps que FocusWShell está abriendo (deck, escena): su ventana la acomoda quien la abrió. + private readonly Dictionary _launching = new(StringComparer.OrdinalIgnoreCase); + + private void Launching(IEnumerable keys, bool start) { - List pending; lock (_gate) { - pending = [.. _sessionPending]; - } - - if (pending.Count == 0) - { - return null; + foreach (var key in keys) + { + var n = _launching.GetValueOrDefault(key) + (start ? 1 : -1); + if (n > 0) + { + _launching[key] = n; + } + else + { + _launching.Remove(key); + } + } } + } + /// + /// Vuelve a poner en su panel las apps que aparecen después de arrancar, las abras por donde las abras + /// (barra de tareas, Inicio, un acceso directo). Sólo ventanas libres: nunca mueve lo que el usuario ya + /// puso. Tres casos, en orden: + /// + /// Durante el arranque (): las de la última sesión, emparejadas como al + /// arrancar (estricto), aunque la ventana ya estuviera abierta. + /// Una ventana nueva de una app de la sesión que aún no volvió, sin límite de tiempo: la + /// primera vez que aparece tras reiniciar. Después, otra ventana de esa app queda libre. + /// Una ventana nueva de una app fijada en un panel, si ninguna ventana suya está ya en un + /// panel: el icono apagado del deck promete ese lugar. + /// + /// + public ControllerResult? AdoptReturningWindows() + { var windows = Refresh(); lock (_gate) { - var free = windows.Where(w => !_workspace.IsManaged(w.Handle)) - .Select(w => new OpenWindow(w.Handle, MinSizeCatalog.KeyFor(w), w.Title)) - .ToList(); - var match = SceneMatcher.Match(new SavedScene(SessionName, pending), free, strict: true); - if (match.Matched.Count == 0) + var free = windows.Where(w => !_workspace.IsManaged(w.Handle) && !w.IsOwnProcess).ToList(); + if (!_seenReady) { + _seenReady = true; + _seen.UnionWith(windows.Select(w => w.Handle)); return null; } - _sessionPending = [.. match.Missing]; var commands = new List(); - foreach (var (entry, window) in match.Matched) + var taken = new HashSet(); + + void AdoptEntry(SceneWindow entry, nint handle) { - var panel = _workspace.FindPanel(entry.PanelId ?? Workspace.WorkPanel); - if (panel is null) + if (_workspace.FindPanel(entry.PanelId ?? Workspace.WorkPanel) is not { } panel) { - continue; // su panel ya no existe: queda libre + return; // su panel ya no existe: queda libre } - commands.Add(new Adopt(window.Handle, entry.Label, panel.Id)); - _sessionAdopted[window.Handle] = entry; + taken.Add(handle); + commands.Add(new Adopt(handle, entry.Label, panel.Id)); + _sessionAdopted[handle] = entry; if (entry.Placement == ScenePlacement.Parked) { - commands.Add(new Park(window.Handle)); + commands.Add(new Park(handle)); } else if (entry.Placement == ScenePlacement.Center && _workspace.Focused is null) { - commands.Add(new Promote(window.Handle)); + commands.Add(new Promote(handle)); + } + } + + OpenWindow Open(WindowSnapshot w) => new(w.Handle, MinSizeCatalog.KeyFor(w), w.Title); + var launchable = free.Where(w => !_launching.ContainsKey(MinSizeCatalog.KeyFor(w))).ToList(); + + // 1. Arranque: la sesión, estricta, con todas las ventanas libres. + if (_sessionPending.Count > 0 && DateTime.Now < _sessionUntil) + { + var match = SceneMatcher.Match(new SavedScene(SessionName, _sessionPending), [.. launchable.Select(Open)], strict: true); + _sessionPending = [.. match.Missing]; + foreach (var (entry, window) in match.Matched) + { + AdoptEntry(entry, window.Handle); + } + } + + var fresh = launchable.Where(w => !_seen.Contains(w.Handle) && !taken.Contains(w.Handle)).ToList(); + + // 2. Una ventana nueva de una app de la sesión que aún no volvió. + if (_sessionPending.Count > 0 && fresh.Count > 0) + { + var match = SceneMatcher.Match(new SavedScene(SessionName, _sessionPending), [.. fresh.Select(Open)]); + _sessionPending = [.. match.Missing]; + foreach (var (entry, window) in match.Matched) + { + AdoptEntry(entry, window.Handle); + } + } + + // 3. Una ventana nueva de una app fijada, si su lugar está vacío. + var managedKeys = _workspace.Windows + .Where(w => _snapshots.ContainsKey(w.Handle)) + .Select(w => MinSizeCatalog.KeyFor(_snapshots[w.Handle])) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + var trayKeys = _inTray.Values.Select(t => t.AppKey).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var w in fresh.Where(w => !taken.Contains(w.Handle))) + { + var key = MinSizeCatalog.KeyFor(w); + if (managedKeys.Contains(key) || trayKeys.Contains(key) + || _catalog.Find(key) is not { Pinned: true, Hidden: false, LastPanelId: { } panelId } app + || _workspace.FindPanel(panelId) is not { } panel) + { + continue; } + + managedKeys.Add(key); // una sola ventana por app + taken.Add(w.Handle); + commands.Add(new Adopt(w.Handle, app.Name, panel.Id)); + } + + // Todas las ventanas de ahora ya se vieron, también las de los paneles: una que el usuario suelte + // después no es nueva y no vuelve sola. Las que está abriendo FocusWShell, todavía no: si quien la + // abrió no la encuentra, se acomoda aquí. Se olvidan las que se cerraron. + _seen.IntersectWith(windows.Select(w => w.Handle)); + foreach (var w in windows.Where(w => !_launching.ContainsKey(MinSizeCatalog.KeyFor(w)))) + { + _seen.Add(w.Handle); } return commands.Count > 0 ? RunLocked(commands) : null; @@ -1465,6 +1566,20 @@ public SceneResult ApplySavedScene(string name) /// panel y, si en la escena estaba en el foco o estacionada, ahí. Si su panel no se resuelve, queda libre. /// private void OpenSceneApps(string sceneName, List<(SceneWindow Entry, CatalogApp App, string? PanelId)> opening) + { + var keys = opening.Select(o => o.App.AppKey).ToList(); + Launching(keys, start: true); + try + { + OpenSceneAppsCore(sceneName, opening); + } + finally + { + Launching(keys, start: false); + } + } + + private void OpenSceneAppsCore(string sceneName, List<(SceneWindow Entry, CatalogApp App, string? PanelId)> opening) { HashSet before; lock (_gate) diff --git a/src/FocusWShell.App/Strings.Designer.cs b/src/FocusWShell.App/Strings.Designer.cs index 5905f63..fd8b7c9 100644 --- a/src/FocusWShell.App/Strings.Designer.cs +++ b/src/FocusWShell.App/Strings.Designer.cs @@ -69,12 +69,27 @@ public static class Strings /// Día anterior public static string Activity_PrevDay => ResourceManager.GetString("Activity_PrevDay", Culture)!; + /// Navegación privada + public static string Activity_PrivateSite => ResourceManager.GetString("Activity_PrivateSite", Culture)!; + /// {0} % del tiempo activo public static string Activity_Share => ResourceManager.GetString("Activity_Share", Culture)!; /// En paralelo public static string Activity_SideBySide => ResourceManager.GetString("Activity_SideBySide", Culture)!; + /// Medir también los sitios + public static string Activity_Sites => ResourceManager.GetString("Activity_Sites", Culture)!; + + /// {0} sitios + public static string Activity_SitesCount => ResourceManager.GetString("Activity_SitesCount", Culture)!; + + /// En Chrome y Edge, guarda sólo el sitio (github.com), nunca la página ni su títul + public static string Activity_SitesHelp => ResourceManager.GetString("Activity_SitesHelp", Culture)!; + + /// 1 sitio + public static string Activity_SitesOne => ResourceManager.GetString("Activity_SitesOne", Culture)!; + /// {0} veces public static string Activity_Times => ResourceManager.GetString("Activity_Times", Culture)!; @@ -363,6 +378,12 @@ public static class Strings /// No hay pestañas que leer en Chrome ni en Edge. public static string Deck_PagesNone => ResourceManager.GetString("Deck_PagesNone", Culture)!; + /// VENTANAS PRIVADAS + public static string Deck_PagesPrivate => ResourceManager.GetString("Deck_PagesPrivate", Culture)!; + + /// Ventana privada · {0} pestañas + public static string Deck_PagesPrivateWindow => ResourceManager.GetString("Deck_PagesPrivateWindow", Culture)!; + /// {0} · {1} public static string Deck_PagesSite => ResourceManager.GetString("Deck_PagesSite", Culture)!; diff --git a/src/FocusWShell.App/Strings.en.resx b/src/FocusWShell.App/Strings.en.resx index b0293be..e04bb4c 100644 --- a/src/FocusWShell.App/Strings.en.resx +++ b/src/FocusWShell.App/Strings.en.resx @@ -390,6 +390,8 @@ Restore them now? Pages… SITES SINGLE PAGES + PRIVATE WINDOWS + Private window · {0} tabs ‹ Sites {0} · {1} Close all @@ -493,4 +495,9 @@ Restore them now? Delete history Delete all the saved activity? This can't be undone. The saved activity was deleted. + Also measure sites + In Chrome and Edge, saves only the site (github.com), never the page or its title. Private windows count as “Private browsing”, with no site. + Private browsing + {0} sites + 1 site diff --git a/src/FocusWShell.App/Strings.resx b/src/FocusWShell.App/Strings.resx index df7a010..aa9cb89 100644 --- a/src/FocusWShell.App/Strings.resx +++ b/src/FocusWShell.App/Strings.resx @@ -390,6 +390,8 @@ Páginas… SITIOS PÁGINAS SUELTAS + VENTANAS PRIVADAS + Ventana privada · {0} pestañas ‹ Sitios {0} · {1} Cerrar todas @@ -493,4 +495,9 @@ Borrar historial ¿Borrar toda la actividad guardada? No se puede deshacer. Se borró la actividad guardada. + Medir también los sitios + En Chrome y Edge, guarda sólo el sitio (github.com), nunca la página ni su título. Las ventanas privadas cuentan como «Navegación privada», sin sitio. + Navegación privada + {0} sitios + 1 sitio diff --git a/src/FocusWShell.Core/Activity/ActivityDay.cs b/src/FocusWShell.Core/Activity/ActivityDay.cs index 67b18a7..ff085f0 100644 --- a/src/FocusWShell.Core/Activity/ActivityDay.cs +++ b/src/FocusWShell.Core/Activity/ActivityDay.cs @@ -1,7 +1,12 @@ namespace FocusWShell.Core.Activity; +/// El tiempo de un sitio dentro de un navegador en un día. +/// Su host, o para las ventanas privadas. +public sealed record ActivitySiteTotal(string Site, TimeSpan InFocus, TimeSpan InUse); + /// El tiempo de una app en un día: en el foco y en uso (ADR 0019). -public sealed record ActivityAppTotal(string Key, string Name, string? PanelId, TimeSpan InFocus, TimeSpan InUse); +/// En un navegador, sus sitios, del más usado al menos (vacío si no se midieron). +public sealed record ActivityAppTotal(string Key, string Name, string? PanelId, TimeSpan InFocus, TimeSpan InUse, IReadOnlyList Sites); /// El resumen de un día de actividad, calculado a partir de sus tramos. /// Tiempo presente (con algo en el foco o en uso). @@ -27,6 +32,7 @@ public static ActivityDay From(IEnumerable segments) var longest = TimeSpan.Zero; string? longestApp = null; var apps = new Dictionary(StringComparer.OrdinalIgnoreCase); + var sites = new Dictionary>(StringComparer.OrdinalIgnoreCase); ActivityApp? lastFocus = null; // la última app que hubo en el foco, aunque luego quedara vacío DateTime? streakEnd = null; @@ -53,6 +59,7 @@ public static ActivityDay From(IEnumerable segments) Count(focus, s.Duration, inFocus: true); // Llegó al foco: otra app que la última (tras una pausa, la misma no cuenta otra vez). + // Otro sitio en el mismo navegador no es otra llegada. if (!focus.SameApp(lastFocus)) { toFocus++; @@ -70,7 +77,7 @@ public static ActivityDay From(IEnumerable segments) } var totals = apps - .Select(a => new ActivityAppTotal(a.Key, a.Value.Name, a.Value.PanelId, a.Value.Focus, a.Value.Use)) + .Select(a => new ActivityAppTotal(a.Key, a.Value.Name, a.Value.PanelId, a.Value.Focus, a.Value.Use, SitesOf(a.Key))) .OrderByDescending(a => a.InFocus + a.InUse) .ThenBy(a => a.Name, StringComparer.CurrentCultureIgnoreCase) .ToList(); @@ -78,9 +85,31 @@ public static ActivityDay From(IEnumerable segments) void Count(ActivityApp app, TimeSpan duration, bool inFocus) { + var focusPart = inFocus ? duration : TimeSpan.Zero; + var usePart = inFocus ? TimeSpan.Zero : duration; var c = apps.TryGetValue(app.Key, out var found) ? found : (Name: app.Name, PanelId: app.PanelId, Focus: TimeSpan.Zero, Use: TimeSpan.Zero); // El nombre y el panel, los últimos que tuvo en el día. - apps[app.Key] = (app.Name, app.PanelId ?? c.PanelId, c.Focus + (inFocus ? duration : TimeSpan.Zero), c.Use + (inFocus ? TimeSpan.Zero : duration)); + apps[app.Key] = (app.Name, app.PanelId ?? c.PanelId, c.Focus + focusPart, c.Use + usePart); + + if (app.Site is { } site) + { + if (!sites.TryGetValue(app.Key, out var bySite)) + { + sites[app.Key] = bySite = new(StringComparer.OrdinalIgnoreCase); + } + + var t = bySite.GetValueOrDefault(site); + bySite[site] = (t.Focus + focusPart, t.Use + usePart); + } } + + List SitesOf(string key) => sites.TryGetValue(key, out var bySite) + ? + [ + .. bySite.Select(s => new ActivitySiteTotal(s.Key, s.Value.Focus, s.Value.Use)) + .OrderByDescending(s => s.InFocus + s.InUse) + .ThenBy(s => s.Site, StringComparer.OrdinalIgnoreCase), + ] + : []; } } diff --git a/src/FocusWShell.Core/Activity/ActivityTracker.cs b/src/FocusWShell.Core/Activity/ActivityTracker.cs index 7b9e879..8f05272 100644 --- a/src/FocusWShell.Core/Activity/ActivityTracker.cs +++ b/src/FocusWShell.Core/Activity/ActivityTracker.cs @@ -2,7 +2,8 @@ namespace FocusWShell.Core.Activity; /// Una app para la actividad (ADR 0019): su clave (la de paneles y escenas), su nombre y su panel. /// Su panel, o null si es libre o no la organiza FocusWShell. -public sealed record ActivityApp(string Key, string Name, string? PanelId = null) +/// En un navegador, el sitio que mostraba (), si se miden los sitios. +public sealed record ActivityApp(string Key, string Name, string? PanelId = null, string? Site = null) { /// La misma app, aunque cambie su panel o su nombre. public bool SameApp(ActivityApp? other) => other is not null && string.Equals(Key, other.Key, StringComparison.OrdinalIgnoreCase); @@ -128,5 +129,7 @@ private void Add(List segments, DateTime start, DateTime end) } } - private static bool Same(ActivityApp? a, ActivityApp? b) => a is null ? b is null : a.SameApp(b); + /// La misma app con el mismo sitio: otro sitio en el navegador corta el tramo. + private static bool Same(ActivityApp? a, ActivityApp? b) => + a is null ? b is null : a.SameApp(b) && string.Equals(a.Site, b!.Site, StringComparison.OrdinalIgnoreCase); } diff --git a/src/FocusWShell.Core/Browsers/SiteHost.cs b/src/FocusWShell.Core/Browsers/SiteHost.cs new file mode 100644 index 0000000..33bf2ed --- /dev/null +++ b/src/FocusWShell.Core/Browsers/SiteHost.cs @@ -0,0 +1,46 @@ +using System.Globalization; + +namespace FocusWShell.Core.Browsers; + +/// +/// El sitio de una dirección para la actividad (ADR 0019, sitios): sólo el host, sin www., en +/// minúsculas. Nunca la ruta, la consulta ni el puerto. Lo que no es una página web (una búsqueda escrita, una +/// página interna del navegador, un archivo local) no tiene sitio. +/// +public static class SiteHost +{ + /// El sitio de una ventana privada: se cuenta el tiempo, nunca qué se vio. + public const string Private = "(private)"; + + /// El host de lo que muestra la barra de direcciones, o null si no es una página web. + /// Chrome oculta el https:// y Edge lo muestra: se aceptan las dos formas. + public static string? From(string? address) + { + var value = address?.Trim(); + if (string.IsNullOrEmpty(value) || value.Any(char.IsWhiteSpace)) + { + return null; + } + + bool hasScheme = value.Contains("://", StringComparison.Ordinal); + if (!Uri.TryCreate(hasScheme ? value : "https://" + value, UriKind.Absolute, out var uri) + || (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)) + { + return null; // edge://, chrome://, about:, file:// y lo demás + } + + var host = uri.Host.ToLower(CultureInfo.InvariantCulture); + if (uri.HostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6 || host == "localhost") + { + return uri.Host.ToLower(CultureInfo.InvariantCulture); + } + + // Sin punto, sin esquema, es una palabra suelta que se está buscando («hola»), no un sitio. + if (!host.Contains('.', StringComparison.Ordinal) || host.StartsWith('.') || host.EndsWith('.')) + { + return null; + } + + return host.StartsWith("www.", StringComparison.Ordinal) ? host[4..] : host; + } +} diff --git a/src/FocusWShell.Win32/BrowserAddress.cs b/src/FocusWShell.Win32/BrowserAddress.cs new file mode 100644 index 0000000..559ae74 --- /dev/null +++ b/src/FocusWShell.Win32/BrowserAddress.cs @@ -0,0 +1,99 @@ +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Windows.Automation; + +namespace FocusWShell.Win32; + +/// Lo que muestra la barra de direcciones de una ventana de navegador. +/// El texto de la barra (sin leer si es privada o si se está escribiendo en ella). +/// Ventana de incógnito (Chrome) o InPrivate (Edge). +/// La barra tiene el teclado: lo que muestra es lo que se escribe, no la página. +public sealed record BrowserAddress(string? Value, bool Private, bool Editing); + +/// +/// La barra de direcciones y si la ventana es privada, con UI Automation (ADR 0019, sitios), sin extensión. +/// Las dos están en la interfaz del navegador, fuera de la página: no se entra en el contenido web. Una +/// ventana privada se reconoce por su botón «Incognito» o «InPrivate», cuyo nombre depende del idioma del +/// navegador. Unos 15 a 30 ms por ventana: se llama desde un hilo de fondo, nunca desde el de la UI. +/// +public static partial class BrowserAddressReader +{ + /// «Incognito», «Incógnito», «Inkognito», «InPrivate», «Navegación InPrivate»… + [GeneratedRegex(@"in[ck]ogn|inprivate", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex PrivateName(); + + /// La barra de la ventana, o null si no se encontró (una app web, o la ventana ya no está). + public static BrowserAddress? Read(nint handle) + { + try + { + var window = AutomationElement.FromHandle(handle); + AutomationElement? bar = null; + // Edge lo dice también en el título; Chrome, sólo con su botón. + bool isPrivate = (window.Current.Name ?? string.Empty).Contains("InPrivate", StringComparison.Ordinal); + Walk(window, 0, ref bar, ref isPrivate); + if (bar is null) + { + return isPrivate ? new BrowserAddress(null, true, false) : null; + } + + if (isPrivate) + { + return new BrowserAddress(null, true, false); + } + + if (bar.Current.HasKeyboardFocus) + { + return new BrowserAddress(null, false, true); + } + + return bar.TryGetCurrentPattern(ValuePattern.Pattern, out var pattern) + ? new BrowserAddress(((ValuePattern)pattern).Current.Value, false, false) + : null; + } + catch (Exception ex) when (ex is ElementNotAvailableException or InvalidOperationException or COMException or TimeoutException or ArgumentException) + { + return null; + } + } + + /// Sólo si la ventana es privada (para la lista de páginas del deck). + public static bool IsPrivate(nint handle) => Read(handle)?.Private == true; + + /// La primera caja de texto fuera de la página es la barra; cualquier botón privado marca la ventana. + private static void Walk(AutomationElement element, int depth, ref AutomationElement? bar, ref bool isPrivate) + { + if (depth > 12 || (bar is not null && isPrivate)) + { + return; + } + + var walker = TreeWalker.ControlViewWalker; + for (var child = walker.GetFirstChild(element); child is not null; child = walker.GetNextSibling(child)) + { + var type = child.Current.ControlType; + if (type == ControlType.Document) + { + continue; // la página: ni su contenido ni sus cajas de texto + } + + if (type == ControlType.Edit) + { + bar ??= child; + continue; + } + + if (type == ControlType.Button && PrivateName().IsMatch(child.Current.Name ?? string.Empty)) + { + isPrivate = true; + continue; + } + + Walk(child, depth + 1, ref bar, ref isPrivate); + if (bar is not null && isPrivate) + { + return; + } + } + } +} diff --git a/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs b/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs index 81d453d..405c097 100644 --- a/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs +++ b/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs @@ -42,7 +42,7 @@ public void IdleClosesAtTheLastInputAndActiveStartsAgain() t.Active(At(0)); t.Observe(At(0), Code, Code); - var closed = t.Idle(At(12)); // detectado a los 15, la última entrada fue a los 12 + var closed = t.Idle(At(12)); // detectado a los 15, la última entrada fue a los 12 Assert.Equal([new ActivitySegment(At(0), At(12), Code, Code)], closed); Assert.Empty(t.Observe(At(20), Docs, Docs)); // inactivo: no abre tramo @@ -114,4 +114,40 @@ public void TheSameAppAfterAPauseIsNotANewArrivalButBreaksTheStreak() Assert.Equal(1, day.ToFocus); Assert.Equal(TimeSpan.FromMinutes(20), day.LongestFocus); } + + private static readonly ActivityApp Edge = new("msedge", "Microsoft Edge", "work"); + + [Fact] + public void AnotherSiteInTheBrowserCutsTheSegment() + { + var t = new ActivityTracker(); + t.Active(At(0)); + t.Observe(At(0), Edge with { Site = "github.com" }, Edge with { Site = "github.com" }); + + var closed = t.Observe(At(5), Edge with { Site = "youtube.com" }, Edge with { Site = "youtube.com" }); + + Assert.Equal("github.com", Assert.Single(closed).Focus!.Site); + } + + [Fact] + public void SitesAddUpUnderTheirBrowserWithoutNewArrivals() + { + var day = ActivityDay.From( + [ + new(At(0), At(20), Edge with { Site = "github.com" }, Edge with { Site = "github.com" }), + new(At(20), At(30), Edge with { Site = Core.Browsers.SiteHost.Private }, Slack), + new(At(30), At(40), Edge, Edge), // sin sitio: pestaña nueva + new(At(40), At(45), Edge with { Site = "GitHub.com" }, Edge with { Site = "github.com" }), + ]); + + Assert.Equal(1, day.ToFocus); // otro sitio no es otra llegada + Assert.Equal(TimeSpan.FromMinutes(45), day.LongestFocus); + + var edge = day.Apps.Single(a => a.Key == "msedge"); + Assert.Equal(TimeSpan.FromMinutes(45), edge.InFocus); + Assert.Equal(2, edge.Sites.Count); + Assert.Equal(new ActivitySiteTotal("github.com", TimeSpan.FromMinutes(25), TimeSpan.FromMinutes(25)), edge.Sites[0]); + Assert.Equal(Core.Browsers.SiteHost.Private, edge.Sites[1].Site); + Assert.Empty(day.Apps.Single(a => a.Key == "slack").Sites); + } } diff --git a/tests/FocusWShell.Core.Tests/Browsers/SiteHostTests.cs b/tests/FocusWShell.Core.Tests/Browsers/SiteHostTests.cs new file mode 100644 index 0000000..9440861 --- /dev/null +++ b/tests/FocusWShell.Core.Tests/Browsers/SiteHostTests.cs @@ -0,0 +1,26 @@ +using FocusWShell.Core.Browsers; + +namespace FocusWShell.Core.Tests.Browsers; + +public class SiteHostTests +{ + [Theory] + [InlineData("https://www.github.com/proteo5/FocusWShell/pulls?q=is%3Aopen", "github.com")] // Edge: con esquema + [InlineData("github.com/proteo5/FocusWShell", "github.com")] // Chrome: sin esquema + [InlineData("docs.google.com/document/d/abc/edit#heading=h.1", "docs.google.com")] + [InlineData("http://Example.COM:8080/x", "example.com")] + [InlineData("localhost:5000/portal/index.html#/", "localhost")] + [InlineData("http://192.168.1.10/admin", "192.168.1.10")] + public void KeepsOnlyTheHost(string address, string host) => Assert.Equal(host, SiteHost.From(address)); + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("hola mundo")] // una búsqueda que se escribe + [InlineData("hola")] + [InlineData("edge://settings/profiles")] + [InlineData("chrome://newtab")] + [InlineData("about:blank")] + [InlineData("file:///C:/Users/ana/notas.html")] + public void WhatIsNotAWebPageHasNoSite(string? address) => Assert.Null(SiteHost.From(address)); +}