From 38b3048614d915492f21e65c3380335e93014ce7 Mon Sep 17 00:00:00 2001 From: Alfredo Pinto Date: Tue, 17 Nov 2026 15:57:00 -0800 Subject: [PATCH] Alfa 0.4.0: Actividad y la app en uso en el deck --- .github/release-notes/v0.4.0-alpha.md | 63 ++ CHANGELOG.md | 8 +- Directory.Build.props | 2 +- README.es.md | 2 +- README.md | 2 +- docs/05-hoja-de-ruta.md | 1 + docs/README.md | 1 + docs/adr/0019-actividad-foco-y-uso.md | 69 ++ site/_config.yml | 2 +- site/deck.md | 4 +- site/es/comentarios.md | 2 +- site/es/deck.md | 4 +- site/es/instalar.md | 2 +- site/es/ventana-principal.md | 8 + site/feedback.md | 2 +- site/install.md | 2 +- site/main-window.md | 8 + src/FocusWShell.App/ActivityRecorder.cs | 192 ++++++ src/FocusWShell.App/App.xaml.cs | 40 ++ src/FocusWShell.App/AppSettings.cs | 6 + src/FocusWShell.App/DeckWindow.cs | 79 ++- src/FocusWShell.App/MainWindow.Activity.cs | 195 ++++++ src/FocusWShell.App/MainWindow.xaml | 30 + src/FocusWShell.App/MainWindow.xaml.cs | 8 +- src/FocusWShell.App/ShellController.cs | 32 + src/FocusWShell.App/Strings.Designer.cs | 628 +++++++++++------- src/FocusWShell.App/Strings.en.resx | 26 +- src/FocusWShell.App/Strings.resx | 26 +- src/FocusWShell.Core/Activity/ActivityDay.cs | 86 +++ .../Activity/ActivityTracker.cs | 132 ++++ src/FocusWShell.Win32/NativeMethods.txt | 4 + .../Persistence/ActivityStore.cs | 111 ++++ src/FocusWShell.Win32/WindowEnumerator.cs | 14 + .../Activity/ActivityTests.cs | 117 ++++ 34 files changed, 1646 insertions(+), 262 deletions(-) create mode 100644 .github/release-notes/v0.4.0-alpha.md create mode 100644 docs/adr/0019-actividad-foco-y-uso.md create mode 100644 src/FocusWShell.App/ActivityRecorder.cs create mode 100644 src/FocusWShell.App/MainWindow.Activity.cs create mode 100644 src/FocusWShell.Core/Activity/ActivityDay.cs create mode 100644 src/FocusWShell.Core/Activity/ActivityTracker.cs create mode 100644 src/FocusWShell.Win32/Persistence/ActivityStore.cs create mode 100644 tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs diff --git a/.github/release-notes/v0.4.0-alpha.md b/.github/release-notes/v0.4.0-alpha.md new file mode 100644 index 0000000..6975091 --- /dev/null +++ b/.github/release-notes/v0.4.0-alpha.md @@ -0,0 +1,63 @@ +**FocusWShell 0.4.0-alpha: see how you work, with an app in focus and another in use.** [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 + +### Activity + +With FocusWShell you can keep one app **in focus**, in view in the center, while you type in another that stays in its panel: a document in view while you answer the chat. The new **Activity** section in the main window measures it: + +- how long each app spends **in focus** (blue bar) and **in use**, the one that gets the keyboard and mouse (green bar); +- the time **side by side**, with one app in focus and another in use; +- how many times you brought an app to the focus, and your longest stretch with the same app in focus. + +It is **off** until you turn on **Measure activity**. It stays on your PC, without window titles, for 90 days, and **Delete history** deletes all of it. Time stops counting after 3 minutes without touching the keyboard or mouse, and when you lock or sleep. + +### The deck + +- **The app in use, next to the focus.** When you type in an app that isn't the focus app, the focus tile shows it next to it, smaller, with a white border. The window title is gone: in browsers it was long and didn't help. +- **Tabs that don't move.** In a panel in tabs (or Fill), tapping a hidden tab shows it in its panel and gives it the keyboard, without moving it to the focus: you work in the focus and in it at the same time. Tapping the tab you see (underlined) brings it to the focus. The icons keep their place, and the app that leaves the focus comes back as the tab you see. + +## Install or update + +1. Download `FocusWShell-0.4.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.4.0-alpha: mira cómo trabajas, con una app en el foco y otra en uso.** + +> **Mueve tus ventanas.** Si algo sale mal, **Ctrl+Alt+Mayús+Retroceso** devuelve todas las ventanas a su sitio, en cualquier momento. + +### Novedades + +#### Actividad + +Con FocusWShell puedes tener una app **en el foco**, a la vista en el centro, mientras escribes en otra que sigue en su panel: un documento a la vista mientras respondes el chat. La nueva sección **Actividad** de la ventana principal lo mide: + +- cuánto pasa cada app **en el foco** (barra azul) y **en uso**, la que recibe el teclado y el ratón (barra verde); +- el tiempo **en paralelo**, con una app en el foco y otra en uso; +- cuántas veces llevaste una app al foco, y tu racha más larga con la misma app en el foco. + +Está **apagada** hasta que prendas **Medir la actividad**. Se queda en tu equipo, sin títulos de ventanas, durante 90 días, y **Borrar historial** lo borra todo. El tiempo deja de contar tras 3 minutos sin tocar el teclado ni el ratón, y al bloquear o suspender. + +#### El deck + +- **La app en uso, junto al foco.** Cuando escribes en una app que no es la del foco, el tile del foco la muestra a su lado, más pequeña y con borde blanco. Ya no sale el título de la ventana: en los navegadores era largo y no ayudaba. +- **Pestañas que no se mueven.** En un panel en pestañas (o Llenar), tocar una pestaña oculta la muestra en su panel y le da el teclado, sin moverla al foco: trabajas en el foco y en ella a la vez. Tocar la que se ve (subrayada) la lleva al foco. Los iconos no cambian de lugar, y la app que sale del foco vuelve como la pestaña que se ve. + +### Instalar o actualizar + +1. Descarga `FocusWShell-0.4.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 31aee83..99f6a32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,17 @@ 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.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. + +- New Activity section in the main window: how long each app spends in focus and in use, and the time side by side (one app in focus, the keyboard in another). It is off until you turn it on, and it stays on your PC. / Nueva sección Actividad en la ventana principal: cuánto pasa cada app en el foco y en uso, y el tiempo en paralelo (una app en el foco, el teclado en otra). Está apagada hasta que la prendas, y se queda en tu equipo. +- In the deck, the focus tile also shows the app in use when it is another one, and no longer shows the window title. / En el deck, el tile del foco muestra también la app en uso cuando es otra, y ya no muestra el título de la ventana. - In the deck, in a panel in tabs (or Fill), tapping a hidden tab shows it in its panel and gives it the keyboard, without moving it to the focus; tapping the tab you see (underlined) brings it to the focus. The icons keep their place. / En el deck, en un panel en pestañas (o Llenar), tocar una pestaña oculta la muestra en su panel y le da el teclado, sin moverla al foco; tocar la que se ve (subrayada) la lleva al foco. Los iconos no cambian de lugar. - The app that leaves the focus comes back to a panel in tabs as the tab you see, instead of sometimes hiding behind another. / La app que sale del foco vuelve a un panel en pestañas como la pestaña que se ve, en lugar de quedar a veces oculta detrás de otra. +Notes / Notas: [v0.4.0-alpha](.github/release-notes/v0.4.0-alpha.md) + ## 0.3.1-alpha Your apps come back to their panels after restarting Windows. / Tus apps vuelven a sus paneles después de reiniciar Windows. diff --git a/Directory.Build.props b/Directory.Build.props index b9ce2a8..c374921 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,7 +7,7 @@ latest-recommended true - 0.3.1-alpha + 0.4.0-alpha diff --git a/README.es.md b/README.es.md index 2c58eaf..10f8d94 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.3.1-alpha-win-x64.zip` desde [Releases](https://github.com/proteo5/FocusWShell/releases). +1. Descarga `FocusWShell-0.4.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 70e4b19..c7c73cc 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.3.1-alpha-win-x64.zip` from [Releases](https://github.com/proteo5/FocusWShell/releases). +1. Download `FocusWShell-0.4.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 aa659ff..a5f79f7 100644 --- a/docs/05-hoja-de-ruta.md +++ b/docs/05-hoja-de-ruta.md @@ -57,6 +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. 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/README.md b/docs/README.md index f66a2c2..409206f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -40,6 +40,7 @@ Esta carpeta es la documentación de ingeniería del proyecto. Parte de las nota | [0016](adr/0016-escritorios-virtuales.md) | Seguir los escritorios virtuales de Windows: un foco y unas apps por escritorio | Propuesta (fase 1 hecha) | | [0017](adr/0017-ventana-principal-wpf-ui.md) | La ventana principal con WPF-UI: configurar y ver el estado | Aceptada | | [0018](adr/0018-apps-en-la-bandeja.md) | Apps que se cierran a la bandeja: no mostrarlas nosotros | Aceptada | +| [0019](adr/0019-actividad-foco-y-uso.md) | Actividad: tiempo en el foco y en uso, local y opcional | Aceptada | ## Fuentes diff --git a/docs/adr/0019-actividad-foco-y-uso.md b/docs/adr/0019-actividad-foco-y-uso.md new file mode 100644 index 0000000..096597d --- /dev/null +++ b/docs/adr/0019-actividad-foco-y-uso.md @@ -0,0 +1,69 @@ +# ADR 0019 — Actividad: tiempo en el foco y en uso + +- **Estado:** Aceptada (fase 1 en 0.4.0-alpha) +- **Fecha:** 2026-11-17 + +## Contexto + +Con FocusWShell aparece una forma de trabajar que antes no existía. Una app queda en el foco, a la vista en el centro, mientras se escribe en otra que está en su panel: por ejemplo, el foco en un documento y el teclado en el chat. Es cómodo, y medirlo sirve para dos cosas: + +- **Para quien lo usa:** entender en qué se le va el día y con qué apps trabaja a la vez. +- **Para el proyecto:** es la evidencia que pide la [validación de uso](../06-validacion.md): qué se promueve al foco y con qué frecuencia, y cuándo falta el contexto. Hoy eso se anota a mano. + +FocusWShell ya sabe las dos cosas en cada momento. Sabe qué app está en el foco, porque es su modelo, y qué app tiene el teclado, porque es la que marca con borde blanco en el deck. Solo falta llevar la cuenta. + +En inglés de Windows, *focus* significa «la ventana con teclado», y en FocusWShell «foco» es el lugar central. Hace falta otro nombre para la app con teclado. + +## Decisión + +### Términos + +| Español | English | Qué es | +| --- | --- | --- | +| **En el foco** | **In focus** | La app en el lugar central del principal. | +| **En uso** | **In use** | La app que recibe el teclado y el ratón (la ventana en primer plano para Windows). | +| **En paralelo** | **Side by side** | Tiempo en que la app en uso no es la del foco. | + +«En uso» reemplaza a «al frente (recibe el teclado)» en el deck y en el manual. + +### En el deck + +El tile del foco muestra también la app en uso cuando no es la misma: un segundo icono, más pequeño, con su nombre y «en uso». Así se ve de un vistazo que se trabaja en paralelo. Cuando son la misma, el tile queda como hoy. + +La app en uso conserva el borde blanco en su panel, pero su tooltip dice «en uso». + +### Medición + +- **Tramos, no totales.** Se guarda cada tramo con su inicio, su fin, la app en el foco y la app en uso. Por ejemplo: «10:02–10:17, foco Docs, uso Chat». Con tramos se pueden calcular después los totales, los pares, la línea del día y las tendencias; con totales, no. +- **Solo tiempo presente.** El tramo se corta tras unos minutos sin entrada (`GetLastInputInfo`; 3 min por defecto) y al bloquear, suspender o apagar. +- **Por app, no por ventana.** Se guarda la clave de la app (la misma de paneles y escenas), su nombre y, aparte, el panel y el monitor. Nunca el título de la ventana. Las apps web (`._crx_`) cuentan como apps propias. +- **La lógica en Core.** Un `ActivityTracker` sin Win32, que recibe «cambió el foco», «cambió la app en uso», «inactivo» y «activo» con un reloj inyectable, y emite tramos. Se prueba con xUnit. La capa App solo le pasa los eventos y escribe los tramos. +- **Almacenamiento:** un archivo JSON Lines por día en `%LOCALAPPDATA%\FocusWShell\actividad\AAAA-MM-DD.jsonl`, unas cientos de líneas al día. El tramo abierto se escribe al cerrarse, y también al congelar la sesión al apagar. + +### Privacidad + +- **Un interruptor** en la sección Actividad, apagado por defecto. Al prenderlo se explica qué se guarda y qué no. +- **Solo en este equipo.** Nunca se envía nada, y el diagnóstico y los reportes no lo incluyen. +- **90 días** por defecto, configurable. Hay un botón para borrar todo el historial. + +### Dónde se ve + +Hay una sección nueva, **Actividad**, en la ventana principal. El deck no lleva estadística: es para actuar, no para consultar. Las features se dan por fases: + +1. **MVP:** la medición y el día: una barra por app con su tiempo en el foco y en uso, y el total en paralelo. +2. **Pares** (en el foco ← en uso) y **línea del día**, con la racha más larga y los cambios de foco por hora. +3. **Por panel y monitor**, la **semana**, el uso del **deck frente a atajos y ratón**, y **exportar** a CSV o JSON (opcionalmente, en el formato del diario de validación). + +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. + +## Consecuencias + +- Es la primera vez que FocusWShell guarda un historial de lo que se hace. Por eso es opcional, local y se puede borrar. +- 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. diff --git a/site/_config.yml b/site/_config.yml index 98f7ddd..6c457d4 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.3.1-alpha +version: 0.4.0-alpha markdown: kramdown kramdown: input: GFM diff --git a/site/deck.md b/site/deck.md index 7d26d56..3f4adde 100644 --- a/site/deck.md +++ b/site/deck.md @@ -18,7 +18,7 @@ Open or hide it with Ctrl+Alt+Shift+DCtrl+Alt+Mayús+1…9. Ver [Guardar tu configuración como escena]({{ '/es/guias/#escenas' | relative_url }}). +## Actividad + +Cuánto pasa cada app **en el foco** (a la vista, en el centro) y **en uso** (la que recibe el teclado y el ratón). **En paralelo** es el tiempo con el foco en una app y el uso en otra: por ejemplo, un documento a la vista mientras escribes en el chat. + +Está apagada hasta que prendas **Medir la actividad**. Se guarda sólo en este equipo, sin títulos de ventanas, durante 90 días; **Borrar historial** lo borra todo. El tiempo deja de contar tras 3 minutos sin tocar el teclado ni el ratón, y al bloquear o suspender. + +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). + ## 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 deb5c0c..6dcbdd2 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.3.1-alpha*. +- **The version:** the first line of the tray menu or General → About, for example *FocusWShell 0.4.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 9e1941f..b3b24ba 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.3.1-alpha-win-x64.zip -Algorithm SHA256 +Get-FileHash .\FocusWShell-0.4.0-alpha-win-x64.zip -Algorithm SHA256 ``` ## Start with Windows diff --git a/site/main-window.md b/site/main-window.md index fe8f077..511ca97 100644 --- a/site/main-window.md +++ b/site/main-window.md @@ -61,6 +61,14 @@ The shortcuts in use, and **Change shortcuts…** to set new ones. Under *Window Apply, delete and save scenes: which apps are in each panel and in the focus. They also apply with Ctrl+Alt+Shift+1…9. See [Save your setup as a scene]({{ '/guides/#save-your-setup-as-a-scene' | relative_url }}). +## Activity + +How long each app spends **in focus** (in view, in the center) and **in use** (the one that gets the keyboard and mouse). **Side by side** is the time with one app in focus and another in use: for example, a document in view while you type in the chat. + +It is off until you turn on **Measure activity**. It is kept only on this PC, without window titles, for 90 days; **Delete history** deletes all of it. Time stops counting after 3 minutes without touching the keyboard or mouse, and when you lock or sleep. + +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). + ## 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 new file mode 100644 index 0000000..7fd3de6 --- /dev/null +++ b/src/FocusWShell.App/ActivityRecorder.cs @@ -0,0 +1,192 @@ +using System.Windows.Threading; +using FocusWShell.Core.Activity; +using FocusWShell.Win32; +using FocusWShell.Win32.Persistence; +using Microsoft.Win32; + +namespace FocusWShell.App; + +/// +/// 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 . +/// Vive en el hilo de la interfaz. +/// +public sealed class ActivityRecorder : IDisposable +{ + /// Sin tocar teclado ni ratón este rato, el tiempo deja de contar. + public static readonly TimeSpan IdleAfter = TimeSpan.FromMinutes(3); + + private static readonly TimeSpan Tick = TimeSpan.FromSeconds(15); + private static readonly TimeSpan FlushEvery = TimeSpan.FromMinutes(5); + + private readonly ShellController _controller; + private readonly ActivityTracker _tracker = new(); + private readonly DispatcherTimer _timer; + private DateTime _lastFlush = DateTime.Now; + private bool _paused; // bloqueado o suspendido + + public ActivityRecorder(ShellController controller, ActivityStore store) + { + _controller = controller; + Store = store; + _timer = new DispatcherTimer { Interval = Tick }; + _timer.Tick += (_, _) => OnTick(); + SystemEvents.SessionSwitch += OnSessionSwitch; + SystemEvents.PowerModeChanged += OnPowerModeChanged; + } + + public ActivityStore Store { get; } + + /// Se escribieron tramos nuevos (para refrescar la sección Actividad si está abierta). + public event Action? Saved; + + public bool Enabled => _timer.IsEnabled; + + public void Start() + { + if (_timer.IsEnabled) + { + return; + } + + _timer.Start(); + _paused = false; + _tracker.Active(DateTime.Now); + Observe(); + } + + /// Deja de medir y guarda lo medido. + public void Stop() + { + if (!_timer.IsEnabled) + { + return; + } + + Write(_tracker.Idle(DateTime.Now)); + _timer.Stop(); + } + + /// Cambió la app en uso o lo que hay en el foco. + public void Observe() + { + if (_timer.IsEnabled && !_paused) + { + var (focus, inUse) = _controller.ActivityNow(); + Write(_tracker.Observe(DateTime.Now, focus, inUse)); + } + } + + /// Guarda el tramo abierto (al apagar o reiniciar, o para ver el día al momento). + public void Flush() + { + if (_timer.IsEnabled) + { + Write(_tracker.Flush(DateTime.Now)); + } + } + + private void OnTick() + { + if (_paused) + { + return; + } + + var now = DateTime.Now; + var idle = WindowEnumerator.IdleTime(); + if (idle >= IdleAfter) + { + if (_tracker.Running) + { + Write(_tracker.Idle(now - idle)); + } + + return; + } + + if (!_tracker.Running) + { + _tracker.Active(now); + } + + Observe(); // por si algo cambió sin aviso (el foco desde otro lado) + if (now - _lastFlush >= FlushEvery) + { + Flush(); + } + } + + private void OnSessionSwitch(object? sender, SessionSwitchEventArgs e) + { + if (e.Reason is SessionSwitchReason.SessionLock or SessionSwitchReason.ConsoleDisconnect or SessionSwitchReason.RemoteDisconnect) + { + Pause(); + } + else if (e.Reason is SessionSwitchReason.SessionUnlock or SessionSwitchReason.ConsoleConnect or SessionSwitchReason.RemoteConnect) + { + Resume(); + } + } + + private void OnPowerModeChanged(object? sender, PowerModeChangedEventArgs e) + { + if (e.Mode == PowerModes.Suspend) + { + Pause(); + } + else if (e.Mode == PowerModes.Resume) + { + Resume(); + } + } + + // Los eventos del sistema llegan en otro hilo: se pasan al de la interfaz. + private void Pause() => _timer.Dispatcher.BeginInvoke(() => + { + _paused = true; + if (_timer.IsEnabled) + { + Write(_tracker.Idle(DateTime.Now)); + } + }); + + private void Resume() => _timer.Dispatcher.BeginInvoke(() => + { + _paused = false; + if (_timer.IsEnabled) + { + _tracker.Active(DateTime.Now); + Observe(); + } + }); + + private void Write(IReadOnlyList segments) + { + _lastFlush = DateTime.Now; + if (segments.Count == 0) + { + return; + } + + try + { + Store.Append(segments); + Saved?.Invoke(); + } + catch (System.IO.IOException) + { + // Sin disco no se pierde nada más que estos minutos de actividad. + } + catch (UnauthorizedAccessException) + { + } + } + + public void Dispose() + { + Stop(); + SystemEvents.SessionSwitch -= OnSessionSwitch; + SystemEvents.PowerModeChanged -= OnPowerModeChanged; + } +} diff --git a/src/FocusWShell.App/App.xaml.cs b/src/FocusWShell.App/App.xaml.cs index bf3445c..e8e0ff9 100644 --- a/src/FocusWShell.App/App.xaml.cs +++ b/src/FocusWShell.App/App.xaml.cs @@ -4,6 +4,7 @@ using FocusWShell.Core.Input; using FocusWShell.Core.Layout; using FocusWShell.Win32; +using FocusWShell.Win32.Persistence; using Forms = System.Windows.Forms; namespace FocusWShell.App; @@ -25,6 +26,7 @@ public partial class App : Application private MainWindow? _main; private StripManager? _strips; private ListManager? _lists; + private ActivityRecorder? _activity; private DisplayChangeListener? _displays; private readonly DisplayKeepAwake _keepAwake = new(); private AppSettings _settings = new(); @@ -293,6 +295,7 @@ protected override void OnStartup(StartupEventArgs e) _strips?.Refresh(); _lists?.Refresh(); RefreshDeck(); + _activity?.Observe(); // otra app en el foco }); _controller.CatalogChanged += () => Dispatcher.BeginInvoke(() => { @@ -303,6 +306,7 @@ protected override void OnStartup(StartupEventArgs e) { _lists?.OnForeground(hwnd); _deck?.UpdateForeground(hwnd); // el indicador de «al frente», sin esperar al siguiente repaso + _activity?.Observe(); }); _controller.PauseChanged += _ => Dispatcher.BeginInvoke(FollowPause); _controller.FocusGestureEnabled = g => g switch @@ -363,6 +367,7 @@ protected override void OnStartup(StartupEventArgs e) _tray = new TrayIcon(ShowMain, ToggleKeepAwake, RestoreFromTray, ExitAndRestore, () => Dispatcher.BeginInvoke(ToggleDeck), ToggleStartup); ShowStartup(); SetKeepAwake(_settings.KeepDisplayOn, announce: false); + StartActivity(); RefreshTrayScenes(); _controller.ScenesChanged += () => Dispatcher.BeginInvoke(RefreshTrayScenes); StartHotkeys(announce: true); @@ -989,6 +994,7 @@ private void ToggleStartup() /// private void FreezeSession() { + _activity?.Flush(); // lo medido hasta ahora, antes de que Windows cierre las apps if (!_sessionReady || _sessionFrozen) { return; @@ -1009,6 +1015,38 @@ private void FreezeSession() /// Apagar, reiniciar o cerrar sesión desde Windows (no desde el deck). private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e) => FreezeSession(); + /// La actividad (ADR 0019): se mide sólo si está prendida; se guardan los días que diga la configuración. + private void StartActivity() + { + _activity ??= new ActivityRecorder(_controller, new ActivityStore(ActivityStore.DefaultFolder)); + if (!_settings.ActivityEnabled) + { + _activity.Stop(); + return; + } + + try + { + _activity.Store.Prune(_settings.ActivityKeepDays, DateOnly.FromDateTime(DateTime.Now)); + } + catch (System.IO.IOException) + { + } + + _activity.Start(); + } + + /// La actividad, para la sección Actividad de la ventana principal. + internal ActivityRecorder? Activity => _activity; + + /// Prender o apagar la medición de la actividad (sección Actividad). + internal void SetActivity(bool enabled) + { + _settings.ActivityEnabled = enabled; + _settings.Save(); + StartActivity(); + } + /// Guarda la sesión unos segundos después del último cambio. private void ScheduleSessionSave() { @@ -1070,6 +1108,8 @@ private void ExitAndRestore() _controller.SaveSession(); } + _activity?.Dispose(); + IsExiting = true; TryRestoreAll(); Shutdown(); diff --git a/src/FocusWShell.App/AppSettings.cs b/src/FocusWShell.App/AppSettings.cs index 5c15383..0aae1b4 100644 --- a/src/FocusWShell.App/AppSettings.cs +++ b/src/FocusWShell.App/AppSettings.cs @@ -30,6 +30,12 @@ public sealed class AppSettings /// Mantener la pantalla encendida (ADR 0010). Se recuerda entre sesiones. public bool KeepDisplayOn { get; set; } + /// Medir la actividad: tiempo en el foco y en uso (ADR 0019). Apagado por defecto. + public bool ActivityEnabled { get; set; } + + /// Cuántos días se guarda la actividad. + public int ActivityKeepDays { get; set; } = 90; + /// 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/DeckWindow.cs b/src/FocusWShell.App/DeckWindow.cs index 3014ea9..f917cf3 100644 --- a/src/FocusWShell.App/DeckWindow.cs +++ b/src/FocusWShell.App/DeckWindow.cs @@ -1197,34 +1197,33 @@ private DockPanel DeckHeader(DeckState state) /// private Button FocusTile(DeckState state) { - var content = new StackPanel { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; + // La app en uso (la que recibe el teclado), si no es la del foco: va a su lado, más pequeña y con el + // borde blanco que la marca en su panel (ADR 0019). + var inUse = ForegroundMark(state) is { } fg + ? state.Panels.SelectMany(p => p.Apps).Concat(state.Free).FirstOrDefault(a => a.Handle == fg) + : null; + + UIElement content; if (state.Focus is { } focus) { - if (focus.App is { } app && AppIcons.Get(app) is { } icon) + var main = TileApp(focus.App, focus.Name, From(state, focus.PanelId), big: true); + if (inUse is null) { - content.Children.Add(new Image { Source = icon, Width = 40, Height = 40, Margin = new Thickness(0, 0, 0, 4) }); + content = main; } - - content.Children.Add(new TextBlock - { - Text = focus.Name, - Foreground = TextBrush, - FontSize = 18, - FontWeight = FontWeights.SemiBold, - TextAlignment = TextAlignment.Center, - TextTrimming = TextTrimming.CharacterEllipsis, - }); - // En una línea, para que quepa en la tablet: de qué panel viene y el título de su ventana. - var from = state.Panels.FirstOrDefault(p => p.Id == focus.PanelId) is { } home ? Core.Text.F(Strings.Deck_FocusFrom, home.Name) : null; - var detail = string.Join(" · ", new[] { from, focus.Title }.Where(t => !string.IsNullOrEmpty(t))); - if (detail.Length > 0) + else { - content.Children.Add(new TextBlock { Text = detail, Foreground = TextBrush, FontSize = 11, TextAlignment = TextAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(0, 2, 0, 0) }); + var both = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; + main.MaxWidth = 150; + both.Children.Add(main); + both.Children.Add(new Border { Width = 1, Background = DimBrush, Margin = new Thickness(12, 4, 12, 4) }); + both.Children.Add(TileApp(inUse.App, inUse.Name, Strings.Deck_InUse, big: false)); + content = both; } } else { - content.Children.Add(new TextBlock { Text = Strings.Deck_FocusEmptyTile, Foreground = DimBrush, FontSize = 14, TextAlignment = TextAlignment.Center }); + content = new TextBlock { Text = Strings.Deck_FocusEmptyTile, Foreground = DimBrush, FontSize = 14, TextAlignment = TextAlignment.Center, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; } var tile = new Button @@ -1246,6 +1245,48 @@ private Button FocusTile(DeckState state) return tile; } + /// «de Trabajo»: de qué panel viene una app, o null si es libre. + private static string? From(DeckState state, string? panelId) => + state.Panels.FirstOrDefault(p => p.Id == panelId) is { } home ? Core.Text.F(Strings.Deck_FocusFrom, home.Name) : null; + + /// + /// Una app en el tile del foco: icono, nombre y una línea corta debajo. Grande, la del foco; pequeña y con + /// borde blanco en el icono, la que está en uso. Sin el título de la ventana: en los navegadores es largo + /// y no ayuda (ADR 0019). + /// + private static StackPanel TileApp(CatalogApp? app, string name, string? detail, bool big) + { + var panel = new StackPanel { VerticalAlignment = VerticalAlignment.Center }; + if (app is not null && AppIcons.Get(app) is { } icon) + { + var size = big ? 40 : 28; + UIElement image = new Image { Source = icon, Width = size, Height = size }; + if (!big) + { + image = new Border { Child = image, BorderBrush = TextBrush, BorderThickness = new Thickness(2), Padding = new Thickness(2), CornerRadius = new CornerRadius(4), HorizontalAlignment = HorizontalAlignment.Center }; + } + + ((FrameworkElement)image).Margin = new Thickness(0, 0, 0, 4); + panel.Children.Add(image); + } + + panel.Children.Add(new TextBlock + { + Text = name, + Foreground = TextBrush, + FontSize = big ? 18 : 14, + FontWeight = big ? FontWeights.SemiBold : FontWeights.Normal, + TextAlignment = TextAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis, + }); + if (!string.IsNullOrEmpty(detail)) + { + panel.Children.Add(new TextBlock { Text = detail, Foreground = TextBrush, FontSize = 11, TextAlignment = TextAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(0, 2, 0, 0) }); + } + + return panel; + } + /// El borde del lugar del foco en un modo: el mismo que llevaría su app, o el de destino al mover. private void MarkFocusTarget(Button target, DeckState state) { diff --git a/src/FocusWShell.App/MainWindow.Activity.cs b/src/FocusWShell.App/MainWindow.Activity.cs new file mode 100644 index 0000000..f8b96ea --- /dev/null +++ b/src/FocusWShell.App/MainWindow.Activity.cs @@ -0,0 +1,195 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Media; +using FocusWShell.Core.Activity; +using WC = System.Windows.Controls; + +namespace FocusWShell.App; + +/// La sección Actividad (ADR 0019): el tiempo de cada app en el foco y en uso, día por día. +public partial class MainWindow +{ + /// El verde de «en uso», junto al azul del foco. + private static readonly SolidColorBrush InUseGreen = new(Color.FromRgb(0x1D, 0x9E, 0x75)); + + private DateOnly _activityDay = DateOnly.FromDateTime(DateTime.Now); + private bool _activityHooked; + + private static App Host => (App)Application.Current; + + /// Muestra la sección: el interruptor, el día elegido y sus cifras. + private void BuildActivity() + { + if (!_activityHooked && Host.Activity is { } recorder) + { + _activityHooked = true; + recorder.Saved += () => Dispatcher.BeginInvoke(() => + { + if (ActivitySection.Visibility == Visibility.Visible) + { + BuildActivity(); + } + }); + } + + _loadingGestures = true; + ActivitySwitch.IsChecked = _settings.ActivityEnabled; + _loadingGestures = false; + ActivityPrivacy.Text = Core.Text.F(Strings.Activity_MeasureHelp, _settings.ActivityKeepDays); + + var today = DateOnly.FromDateTime(DateTime.Now); + var culture = CultureInfo.GetCultureInfo(CultureInfo.CurrentUICulture.Name); // la fecha en el idioma de la interfaz + var date = _activityDay.ToString(Strings.Activity_DateFormat, culture); + ActivityDate.Text = _activityDay == today ? Core.Text.F(Strings.Activity_Today, date) + : _activityDay == today.AddDays(-1) ? Core.Text.F(Strings.Activity_Yesterday, date) + : char.ToUpper(date[0], culture) + date[1..]; + ActivityNextButton.IsEnabled = _activityDay < today; + + ActivityContent.Children.Clear(); + var segments = Host.Activity?.Store.Load(_activityDay) ?? []; + if (segments.Count == 0) + { + var empty = _settings.ActivityEnabled || _activityDay != today ? Strings.Activity_Empty : Strings.Activity_Off; + ActivityContent.Children.Add(Text(empty, "TextFillColorSecondaryBrush")); + return; + } + + var day = ActivityDay.From(segments); + var share = day.Active > TimeSpan.Zero ? (int)Math.Round(100 * day.SideBySide / day.Active) : 0; + var figures = new WC.Primitives.UniformGrid { Columns = 4, Margin = new Thickness(0, 0, 0, 16) }; + figures.Children.Add(Figure(Strings.Activity_Active, Duration(day.Active), null)); + figures.Children.Add(Figure(Strings.Activity_SideBySide, Duration(day.SideBySide), Core.Text.F(Strings.Activity_Share, share))); + figures.Children.Add(Figure(Strings.Activity_ToFocus, Core.Text.F(Strings.Activity_Times, day.ToFocus), null)); + figures.Children.Add(Figure(Strings.Activity_Longest, Duration(day.LongestFocus), day.LongestFocusApp)); + ActivityContent.Children.Add(figures); + + var legend = new WC.StackPanel { Orientation = WC.Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 8) }; + legend.Children.Add(Swatch(FocusBlue, Strings.Activity_InFocus)); + legend.Children.Add(Swatch(InUseGreen, Strings.Activity_InUse)); + ActivityContent.Children.Add(legend); + + var panels = _controller.Panels().ToDictionary(p => p.Id, p => p.Name); + var max = day.Apps.Max(a => Math.Max(a.InFocus.Ticks, a.InUse.Ticks)); + var rows = new WC.StackPanel(); + 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)); + } + + ActivityContent.Children.Add(CardRow(rows)); + } + + /// 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) + { + var panel = new WC.StackPanel(); + panel.Children.Add(Text(label, "TextFillColorSecondaryBrush", 12)); + var big = Text(value, size: 22); + big.FontWeight = FontWeights.SemiBold; + panel.Children.Add(big); + if (!string.IsNullOrEmpty(detail)) + { + panel.Children.Add(Text(detail, "TextFillColorSecondaryBrush", 12)); + } + + var card = CardRow(panel); + card.Margin = new Thickness(0, 0, 8, 0); + return card; + } + + private static WC.StackPanel Swatch(Brush color, string label) + { + var panel = new WC.StackPanel { Orientation = WC.Orientation.Horizontal, Margin = new Thickness(0, 0, 16, 0) }; + panel.Children.Add(new WC.Border { Width = 12, Height = 12, CornerRadius = new CornerRadius(2), Background = color, Margin = new Thickness(0, 0, 6, 0), VerticalAlignment = VerticalAlignment.Center }); + panel.Children.Add(Text(label, "TextFillColorSecondaryBrush", 12)); + 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) + { + var row = new WC.Grid { Margin = new Thickness(0, 4, 0, 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)); + 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)); + WC.Grid.SetColumn(bars, 1); + row.Children.Add(bars); + + var times = Text($"{Duration(app.InFocus)} · {Duration(app.InUse)}", "TextFillColorSecondaryBrush", 13); + times.HorizontalAlignment = HorizontalAlignment.Right; + times.ToolTip = $"{Strings.Activity_InFocus}: {Duration(app.InFocus)} · {Strings.Activity_InUse}: {Duration(app.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) + { + var bar = new WC.Grid { Height = 10, 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) }); + return bar; + } + + /// «6 h 05», «25 min», «< 1 min» o «0 min». + private static string Duration(TimeSpan t) => + t.TotalHours >= 1 ? $"{(int)t.TotalHours} h {t.Minutes:00}" + : t > TimeSpan.Zero && t < TimeSpan.FromMinutes(1) ? "< 1 min" + : $"{(int)t.TotalMinutes} min"; + + private void Activity_Changed(object sender, RoutedEventArgs e) + { + if (!_loadingGestures) + { + Host.SetActivity(ActivitySwitch.IsChecked == true); + BuildActivity(); + } + } + + private void ActivityPrev_Click(object sender, RoutedEventArgs e) + { + _activityDay = _activityDay.AddDays(-1); + BuildActivity(); + } + + private void ActivityNext_Click(object sender, RoutedEventArgs e) + { + var today = DateOnly.FromDateTime(DateTime.Now); + _activityDay = _activityDay < today ? _activityDay.AddDays(1) : today; + BuildActivity(); + } + + private void ActivityDelete_Click(object sender, RoutedEventArgs e) + { + if (Host.Activity is not { } recorder + || System.Windows.MessageBox.Show(this, Strings.Activity_DeleteAsk, "FocusWShell", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) + { + return; + } + + try + { + recorder.Flush(); // lo abierto también se va + recorder.Store.DeleteAll(); + SetStatus(Strings.Activity_Deleted); + } + catch (System.IO.IOException ex) + { + SetStatus(ex.Message); + } + + BuildActivity(); + } +} diff --git a/src/FocusWShell.App/MainWindow.xaml b/src/FocusWShell.App/MainWindow.xaml index 7c9a6cf..36f1c97 100644 --- a/src/FocusWShell.App/MainWindow.xaml +++ b/src/FocusWShell.App/MainWindow.xaml @@ -77,6 +77,7 @@ + @@ -285,6 +286,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/FocusWShell.App/MainWindow.xaml.cs b/src/FocusWShell.App/MainWindow.xaml.cs index 3b3c6d5..ad6eb9a 100644 --- a/src/FocusWShell.App/MainWindow.xaml.cs +++ b/src/FocusWShell.App/MainWindow.xaml.cs @@ -96,12 +96,18 @@ private void Nav_SelectionChanged(object sender, WC.SelectionChangedEventArgs e) foreach (var (name, section) in new (string, FrameworkElement)[] { ("Home", HomeSection), ("Windows", WindowsSection), ("Panels", PanelsSection), ("Apps", AppsSection), - ("Shortcuts", ShortcutsSection), ("Scenes", ScenesSection), ("Excluded", ExcludedSection), ("General", GeneralSection), + ("Shortcuts", ShortcutsSection), ("Scenes", ScenesSection), ("Activity", ActivitySection), ("Excluded", ExcludedSection), ("General", GeneralSection), }) { section.Visibility = name == page ? Visibility.Visible : Visibility.Collapsed; } + if (page == "Activity") + { + Host.Activity?.Flush(); // el tramo abierto, para ver el día al momento + BuildActivity(); + } + if (page == "Shortcuts") { BuildShortcuts(); diff --git a/src/FocusWShell.App/ShellController.cs b/src/FocusWShell.App/ShellController.cs index 9df58fa..8c2c4a4 100644 --- a/src/FocusWShell.App/ShellController.cs +++ b/src/FocusWShell.App/ShellController.cs @@ -320,6 +320,38 @@ string Where(Panel p) => p.Display is null } } + // --- Actividad (ADR 0019) ------------------------------------------------------------------------- + + /// + /// 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() + { + var foreground = WindowMover.Foreground(); + lock (_gate) + { + Core.Activity.ActivityApp? Of(WindowSnapshot s) + { + if (s.IsOwnProcess) + { + return null; // el deck o la ventana principal: no es una app en la que se trabaje + } + + 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); + } + + var focus = _workspace.Focused is { } f && !_elsewhere.ContainsKey(f.Handle) && _snapshots.TryGetValue(f.Handle, out var fs) ? Of(fs) : null; + var inUse = foreground == 0 + ? null + : _snapshots.TryGetValue(foreground, out var us) ? Of(us) : WindowEnumerator.Snapshot(foreground) is { } other ? Of(other) : null; + return (focus, inUse); + } + } + // --- Páginas de los navegadores (spike S12) ----------------------------------------------------- /// Las ventanas de Chrome y Edge que se conocen: las de aquí y las de otro escritorio. diff --git a/src/FocusWShell.App/Strings.Designer.cs b/src/FocusWShell.App/Strings.Designer.cs index f86ea9d..5905f63 100644 --- a/src/FocusWShell.App/Strings.Designer.cs +++ b/src/FocusWShell.App/Strings.Designer.cs @@ -21,6 +21,72 @@ public static class Strings /// Selecciona una ventana de la lista. public static string Act_SelectWindow => ResourceManager.GetString("Act_SelectWindow", Culture)!; + /// Tiempo activo + public static string Activity_Active => ResourceManager.GetString("Activity_Active", Culture)!; + + /// dddd d 'de' MMMM + public static string Activity_DateFormat => ResourceManager.GetString("Activity_DateFormat", Culture)!; + + /// Borrar historial + public static string Activity_Delete => ResourceManager.GetString("Activity_Delete", Culture)!; + + /// ¿Borrar toda la actividad guardada? No se puede deshacer. + public static string Activity_DeleteAsk => ResourceManager.GetString("Activity_DeleteAsk", Culture)!; + + /// Se borró la actividad guardada. + public static string Activity_Deleted => ResourceManager.GetString("Activity_Deleted", Culture)!; + + /// No hay actividad este día. + public static string Activity_Empty => ResourceManager.GetString("Activity_Empty", Culture)!; + + /// Cuánto pasa cada app en el foco y en uso. En paralelo es el tiempo con el foco e + public static string Activity_Help => ResourceManager.GetString("Activity_Help", Culture)!; + + /// En el foco + public static string Activity_InFocus => ResourceManager.GetString("Activity_InFocus", Culture)!; + + /// En uso + public static string Activity_InUse => ResourceManager.GetString("Activity_InUse", Culture)!; + + /// Racha más larga en el foco + public static string Activity_Longest => ResourceManager.GetString("Activity_Longest", Culture)!; + + /// Medir la actividad + public static string Activity_Measure => ResourceManager.GetString("Activity_Measure", Culture)!; + + /// Sólo en este equipo, sin títulos de ventanas. Se guardan los últimos {0} días. + public static string Activity_MeasureHelp => ResourceManager.GetString("Activity_MeasureHelp", Culture)!; + + /// Día siguiente + public static string Activity_NextDay => ResourceManager.GetString("Activity_NextDay", Culture)!; + + /// sin panel + public static string Activity_NoPanel => ResourceManager.GetString("Activity_NoPanel", Culture)!; + + /// La medición está apagada. Préndela para empezar a ver tu actividad. + public static string Activity_Off => ResourceManager.GetString("Activity_Off", Culture)!; + + /// Día anterior + public static string Activity_PrevDay => ResourceManager.GetString("Activity_PrevDay", 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)!; + + /// {0} veces + public static string Activity_Times => ResourceManager.GetString("Activity_Times", Culture)!; + + /// Al foco + public static string Activity_ToFocus => ResourceManager.GetString("Activity_ToFocus", Culture)!; + + /// Hoy, {0} + public static string Activity_Today => ResourceManager.GetString("Activity_Today", Culture)!; + + /// Ayer, {0} + public static string Activity_Yesterday => ResourceManager.GetString("Activity_Yesterday", Culture)!; + /// FocusWShell ya se está ejecutando. Búscalo en el área de notificación. public static string App_AlreadyRunning => ResourceManager.GetString("App_AlreadyRunning", Culture)!; @@ -81,6 +147,24 @@ public static class Strings /// Panel para abrir {0} public static string Apps_TargetName => ResourceManager.GetString("Apps_TargetName", Culture)!; + /// Paneles a los dos lados + public static string Arr_Center => ResourceManager.GetString("Arr_Center", Culture)!; + + /// Sólo la columna izquierda + public static string Arr_ContextOnly => ResourceManager.GetString("Arr_ContextOnly", Culture)!; + + /// Solo foco + public static string Arr_FocusOnly => ResourceManager.GetString("Arr_FocusOnly", Culture)!; + + /// Paneles a la derecha + public static string Arr_Left => ResourceManager.GetString("Arr_Left", Culture)!; + + /// Paneles a la izquierda + public static string Arr_Right => ResourceManager.GetString("Arr_Right", Culture)!; + + /// Sólo la columna derecha + public static string Arr_WorkOnly => ResourceManager.GetString("Arr_WorkOnly", Culture)!; + /// Al foco public static string Assign_Focus => ResourceManager.GetString("Assign_Focus", Culture)!; @@ -102,12 +186,18 @@ public static class Strings /// Pantalla completa en public static string DeckMenu_FullscreenOn => ResourceManager.GetString("DeckMenu_FullscreenOn", Culture)!; + /// Ir a su escritorio + public static string DeckMenu_GoToDesktop => ResourceManager.GetString("DeckMenu_GoToDesktop", Culture)!; + /// Mover a public static string DeckMenu_MoveTo => ResourceManager.GetString("DeckMenu_MoveTo", Culture)!; /// Abrir en su panel public static string DeckMenu_OpenInPanel => ResourceManager.GetString("DeckMenu_OpenInPanel", Culture)!; + /// Páginas… + public static string DeckMenu_Pages => ResourceManager.GetString("DeckMenu_Pages", Culture)!; + /// Minimizar public static string DeckMenu_Park => ResourceManager.GetString("DeckMenu_Park", Culture)!; @@ -123,7 +213,7 @@ public static class Strings /// Al foco public static string DeckMenu_ToFocus => ResourceManager.GetString("DeckMenu_ToFocus", Culture)!; - /// Recuperar + /// Restaurar public static string DeckMenu_Unpark => ResourceManager.GetString("DeckMenu_Unpark", Culture)!; /// Desanclar @@ -150,6 +240,8 @@ public static class Strings /// Pantalla encendida: sí public static string Deck_AwakeOn => ResourceManager.GetString("Deck_AwakeOn", Culture)!; + /// Traer {0} a este lado + public static string Deck_BorrowTip => ResourceManager.GetString("Deck_BorrowTip", Culture)!; /// Cerrar una app public static string Deck_Close => ResourceManager.GetString("Deck_Close", Culture)!; @@ -160,22 +252,47 @@ public static class Strings /// Cerrando… public static string Deck_Closing => ResourceManager.GetString("Deck_Closing", Culture)!; + /// Prender o apagar {0} en el principal + public static string Deck_ColumnTip => ResourceManager.GetString("Deck_ColumnTip", Culture)!; + /// vacío public static string Deck_FocusEmpty => ResourceManager.GetString("Deck_FocusEmpty", Culture)!; + /// Foco vacío + public static string Deck_FocusEmptyTile => ResourceManager.GetString("Deck_FocusEmptyTile", Culture)!; + + /// de {0} + public static string Deck_FocusFrom => ResourceManager.GetString("Deck_FocusFrom", Culture)!; + + /// {0} · en el foco. Toca para ver qué hacer con ella. + public static string Deck_FocusTip => ResourceManager.GetString("Deck_FocusTip", Culture)!; + + /// {0} · {1} apps + public static string Deck_HeaderTab => ResourceManager.GetString("Deck_HeaderTab", Culture)!; + /// Ocultar el deck public static string Deck_Hide => ResourceManager.GetString("Deck_Hide", Culture)!; - /// {0} está al frente (recibe el teclado), pero no es la del foco + /// {0} está en uso (recibe el teclado y el ratón), pero no es la del foco public static string Deck_InFrontTip => ResourceManager.GetString("Deck_InFrontTip", Culture)!; - /// {0}: tócala para verla en su panel y escribir en ella; otra vez, al foco - public static string Deck_ShowTabTip => ResourceManager.GetString("Deck_ShowTabTip", Culture)!; + /// {0} · en la bandeja. Tócala para mostrarla. + public static string Deck_InTrayTip => ResourceManager.GetString("Deck_InTrayTip", Culture)!; - /// {0} es la pestaña que se ve en su panel: tócala para llevarla al foco - public static string Deck_VisibleTabTip => ResourceManager.GetString("Deck_VisibleTabTip", Culture)!; + /// en uso + public static string Deck_InUse => ResourceManager.GetString("Deck_InUse", Culture)!; + /// Izquierda + public static string Deck_LeftColumn => ResourceManager.GetString("Deck_LeftColumn", Culture)!; + /// Minimizar + public static string Deck_Minimize => ResourceManager.GetString("Deck_Minimize", Culture)!; + + /// Toca una app para minimizarla en su panel; tócala otra vez para traerla de vuelt + public static string Deck_MinimizeTip => ResourceManager.GetString("Deck_MinimizeTip", Culture)!; + + /// Minimizando… + public static string Deck_Minimizing => ResourceManager.GetString("Deck_Minimizing", Culture)!; /// +{0} más public static string Deck_More => ResourceManager.GetString("Deck_More", Culture)!; @@ -184,13 +301,6 @@ public static class Strings public static string Deck_MoreName => ResourceManager.GetString("Deck_MoreName", Culture)!; /// Ratón al foco - public static string Deck_Minimize => ResourceManager.GetString("Deck_Minimize", Culture)!; - public static string Deck_Minimizing => ResourceManager.GetString("Deck_Minimizing", Culture)!; - public static string Deck_MinimizeTip => ResourceManager.GetString("Deck_MinimizeTip", Culture)!; - public static string Deck_HeaderTab => ResourceManager.GetString("Deck_HeaderTab", Culture)!; - public static string Deck_FocusFrom => ResourceManager.GetString("Deck_FocusFrom", Culture)!; - public static string Deck_FocusEmptyTile => ResourceManager.GetString("Deck_FocusEmptyTile", Culture)!; - public static string Deck_FocusTip => ResourceManager.GetString("Deck_FocusTip", Culture)!; public static string Deck_Mouse => ResourceManager.GetString("Deck_Mouse", Culture)!; /// Ratón @@ -223,9 +333,57 @@ public static class Strings /// {0} no tiene paneles. Créalos en la ventana de FocusWShell, pestaña Paneles: esc public static string Deck_NoPanels => ResourceManager.GetString("Deck_NoPanels", Culture)!; + /// {0} · en otro escritorio. Tócala para ir allí. + public static string Deck_OtherDesktopTip => ResourceManager.GetString("Deck_OtherDesktopTip", Culture)!; + + /// Cerrar la página {0} + public static string Deck_PageCloseName => ResourceManager.GetString("Deck_PageCloseName", Culture)!; + + /// Ir a la página {0} + public static string Deck_PageName => ResourceManager.GetString("Deck_PageName", Culture)!; + + /// {0} · {1} + public static string Deck_PageWhere => ResourceManager.GetString("Deck_PageWhere", Culture)!; + + /// ‹ Sitios + public static string Deck_PagesBack => ResourceManager.GetString("Deck_PagesBack", Culture)!; + + /// Cerrar todas + public static string Deck_PagesCloseAll => ResourceManager.GetString("Deck_PagesCloseAll", Culture)!; + + /// ¿Cerrar {0}? Toca otra vez + public static string Deck_PagesCloseAllConfirm => ResourceManager.GetString("Deck_PagesCloseAllConfirm", Culture)!; + + /// Leyendo las páginas… + public static string Deck_PagesLoading => ResourceManager.GetString("Deck_PagesLoading", Culture)!; + + /// PÁGINAS SUELTAS + public static string Deck_PagesLoose => ResourceManager.GetString("Deck_PagesLoose", Culture)!; + + /// No hay pestañas que leer en Chrome ni en Edge. + public static string Deck_PagesNone => ResourceManager.GetString("Deck_PagesNone", Culture)!; + + /// {0} · {1} + public static string Deck_PagesSite => ResourceManager.GetString("Deck_PagesSite", Culture)!; + + /// SITIOS + public static string Deck_PagesSites => ResourceManager.GetString("Deck_PagesSites", Culture)!; + + /// Páginas + public static string Deck_PagesTab => ResourceManager.GetString("Deck_PagesTab", Culture)!; + + /// Páginas · {0} + public static string Deck_PagesTabCount => ResourceManager.GetString("Deck_PagesTabCount", Culture)!; + + /// Páginas de los navegadores + public static string Deck_PagesTabName => ResourceManager.GetString("Deck_PagesTabName", Culture)!; + /// sin apps (suelta aquí una app) public static string Deck_PanelEmpty => ResourceManager.GetString("Deck_PanelEmpty", Culture)!; + /// apagado + public static string Deck_PanelOff => ResourceManager.GetString("Deck_PanelOff", Culture)!; + /// Anclar public static string Deck_Pin => ResourceManager.GetString("Deck_Pin", Culture)!; @@ -274,13 +432,17 @@ public static class Strings /// Deck: Liberar {0} public static string Deck_ReleaseName => ResourceManager.GetString("Deck_ReleaseName", Culture)!; + /// Restablecer ancho + public static string Deck_ResetWidth => ResourceManager.GetString("Deck_ResetWidth", Culture)!; + /// Liberar todas public static string Deck_RestoreAll => ResourceManager.GetString("Deck_RestoreAll", Culture)!; /// ¿Seguro? Otra vez public static string Deck_RestoreSure => ResourceManager.GetString("Deck_RestoreSure", Culture)!; - + /// Derecha + public static string Deck_RightColumn => ResourceManager.GetString("Deck_RightColumn", Culture)!; /// FOCO public static string Deck_SecFocus => ResourceManager.GetString("Deck_SecFocus", Culture)!; @@ -294,7 +456,6 @@ public static class Strings /// ENERGÍA public static string Deck_SecPower => ResourceManager.GetString("Deck_SecPower", Culture)!; - /// SISTEMA public static string Deck_SecSystem => ResourceManager.GetString("Deck_SecSystem", Culture)!; @@ -304,6 +465,12 @@ public static class Strings /// Mandar el deck a public static string Deck_SendTo => ResourceManager.GetString("Deck_SendTo", Culture)!; + /// {0}: tócala para verla en su panel y escribir en ella; otra vez, al foco + public static string Deck_ShowTabTip => ResourceManager.GetString("Deck_ShowTabTip", Culture)!; + + /// Sitio {0}, {1} páginas + public static string Deck_SiteName => ResourceManager.GetString("Deck_SiteName", Culture)!; + /// {0} (desconectado) public static string Deck_TabDisconnected => ResourceManager.GetString("Deck_TabDisconnected", Culture)!; @@ -319,8 +486,14 @@ public static class Strings /// Al panel public static string Deck_ToPanelShort => ResourceManager.GetString("Deck_ToPanelShort", Culture)!; + /// {0} es la pestaña que se ve en su panel: tócala para llevarla al foco + public static string Deck_VisibleTabTip => ResourceManager.GetString("Deck_VisibleTabTip", Culture)!; + /// {0} ya está abierta en otro escritorio. Cambia a ese escritorio para usarla. + public static string Desktop_OpenElsewhere => ResourceManager.GetString("Desktop_OpenElsewhere", Culture)!; + /// {0} está en otro escritorio: te llevo allí. + public static string Desktop_Switched => ResourceManager.GetString("Desktop_Switched", Culture)!; /// un monitor public static string Display_AMonitor => ResourceManager.GetString("Display_AMonitor", Culture)!; @@ -409,6 +582,87 @@ public static class Strings /// No hay ninguna ventana en el foco. public static string Focus_Empty => ResourceManager.GetString("Focus_Empty", Culture)!; + /// Acerca de + public static string Gen_About => ResourceManager.GetString("Gen_About", Culture)!; + + /// Funciona sólo en tu PC: no se conecta a la red, no tiene cuenta y no envía telem + public static string Gen_AboutPrivacy => ResourceManager.GetString("Gen_AboutPrivacy", Culture)!; + + /// Mantiene la app en la que trabajas en una zona amplia y protegida de tu monitor + public static string Gen_AboutText => ResourceManager.GetString("Gen_AboutText", Culture)!; + + /// Mantener la pantalla encendida + public static string Gen_Awake => ResourceManager.GetString("Gen_Awake", Culture)!; + + /// Evita que la pantalla se apague y que el equipo se suspenda. + public static string Gen_AwakeHelp => ResourceManager.GetString("Gen_AwakeHelp", Culture)!; + + /// Idioma + public static string Gen_Language => ResourceManager.GetString("Gen_Language", Culture)!; + + /// Se aplica al reiniciar FocusWShell. + public static string Gen_LanguageHelp => ResourceManager.GetString("Gen_LanguageHelp", Culture)!; + + /// Licencia + public static string Gen_License => ResourceManager.GetString("Gen_License", Culture)!; + + /// Código abierto: puedes usarlo, modificarlo y compartirlo. + public static string Gen_LicenseHelp => ResourceManager.GetString("Gen_LicenseHelp", Culture)!; + + /// Manual + public static string Gen_Manual => ResourceManager.GetString("Gen_Manual", Culture)!; + + /// Instalar, primeros pasos, guías paso a paso, el deck y los atajos. + public static string Gen_ManualHelp => ResourceManager.GetString("Gen_ManualHelp", Culture)!; + + /// Versiones + public static string Gen_Releases => ResourceManager.GetString("Gen_Releases", Culture)!; + + /// Descarga la última versión y sus notas. + public static string Gen_ReleasesHelp => ResourceManager.GetString("Gen_ReleasesHelp", Culture)!; + + /// Reportar un problema + public static string Gen_Report => ResourceManager.GetString("Gen_Report", Culture)!; + + /// Un problema o una idea, en GitHub. Incluye la versión y tus monitores. + public static string Gen_ReportHelp => ResourceManager.GetString("Gen_ReportHelp", Culture)!; + + /// Abrir la carpeta de configuración + public static string Gen_Settings => ResourceManager.GetString("Gen_Settings", Culture)!; + + /// Código fuente + public static string Gen_Source => ResourceManager.GetString("Gen_Source", Culture)!; + + /// Iniciar con Windows + public static string Gen_Startup => ResourceManager.GetString("Gen_Startup", Culture)!; + + /// Abre FocusWShell al iniciar sesión. + public static string Gen_StartupHelp => ResourceManager.GetString("Gen_StartupHelp", Culture)!; + + /// Un gestor de atención visual para Windows. + public static string Gen_Tagline => ResourceManager.GetString("Gen_Tagline", Culture)!; + + /// Tema + public static string Gen_Theme => ResourceManager.GetString("Gen_Theme", Culture)!; + + /// Automático (el de Windows) + public static string Gen_ThemeAuto => ResourceManager.GetString("Gen_ThemeAuto", Culture)!; + + /// Oscuro + public static string Gen_ThemeDark => ResourceManager.GetString("Gen_ThemeDark", Culture)!; + + /// El de esta ventana. El deck tiene su propio aspecto. + public static string Gen_ThemeHelp => ResourceManager.GetString("Gen_ThemeHelp", Culture)!; + + /// Claro + public static string Gen_ThemeLight => ResourceManager.GetString("Gen_ThemeLight", Culture)!; + + /// Usa estos componentes de código abierto: + public static string Gen_ThirdParty => ResourceManager.GetString("Gen_ThirdParty", Culture)!; + + /// Versión {0} + public static string Gen_Version => ResourceManager.GetString("Gen_Version", Culture)!; + /// {0}: elegida con Alt+Tab; pasa al foco. public static string Gesture_AltTab => ResourceManager.GetString("Gesture_AltTab", Culture)!; @@ -481,12 +735,50 @@ public static class Strings /// FocusWShell · atajos public static string Hk_WindowTitle => ResourceManager.GetString("Hk_WindowTitle", Culture)!; + /// Acciones rápidas + public static string Home_Actions => ResourceManager.GetString("Home_Actions", Culture)!; + + /// Foco: {0} + public static string Home_Focus => ResourceManager.GetString("Home_Focus", Culture)!; + + /// Foco vacío + public static string Home_FocusEmpty => ResourceManager.GetString("Home_FocusEmpty", Culture)!; + + /// Solo foco: {0} + public static string Home_FocusFull => ResourceManager.GetString("Home_FocusFull", Culture)!; + + /// Disposición del principal + public static string Home_Layout => ResourceManager.GetString("Home_Layout", Culture)!; + + /// Arrastra el borde entre dos ventanas para cambiar un ancho. + public static string Home_LayoutHint => ResourceManager.GetString("Home_LayoutHint", Culture)!; + + /// Principal + public static string Home_Main => ResourceManager.GetString("Home_Main", Culture)!; + + /// Tus monitores + public static string Home_Monitors => ResourceManager.GetString("Home_Monitors", Culture)!; + + /// Sin paneles + public static string Home_NoPanels => ResourceManager.GetString("Home_NoPanels", Culture)!; + + /// Abrir el deck + public static string Home_OpenDeck => ResourceManager.GetString("Home_OpenDeck", Culture)!; + + /// {0} · {1} + public static string Home_PanelLine => ResourceManager.GetString("Home_PanelLine", Culture)!; + + /// {0} devuelve todas las ventanas a su sitio, en cualquier momento. «Salir», en la + public static string Home_SafetyText => ResourceManager.GetString("Home_SafetyText", Culture)!; + + /// Si algo sale mal + public static string Home_SafetyTitle => ResourceManager.GetString("Home_SafetyTitle", Culture)!; + /// Otra aplicación ya usa: {0}. «Liberar todas» sigue en el menú de la bandeja. public static string Hotkeys_InUse => ResourceManager.GetString("Hotkeys_InUse", Culture)!; /// cerrada public static string ListState_Closed => ResourceManager.GetString("ListState_Closed", Culture)!; - public static string ListState_InTray => ResourceManager.GetString("ListState_InTray", Culture)!; /// fuera de layout public static string ListState_Detached => ResourceManager.GetString("ListState_Detached", Culture)!; @@ -497,6 +789,12 @@ public static class Strings /// en el panel public static string ListState_InPanel => ResourceManager.GetString("ListState_InPanel", Culture)!; + /// en la bandeja + public static string ListState_InTray => ResourceManager.GetString("ListState_InTray", Culture)!; + + /// en otro escritorio + public static string ListState_OtherDesktop => ResourceManager.GetString("ListState_OtherDesktop", Culture)!; + /// minimizada public static string ListState_Parked => ResourceManager.GetString("ListState_Parked", Culture)!; @@ -520,14 +818,19 @@ public static class Strings /// {0} · cerrada. Clic: abrirla en este panel. public static string List_TipClosed => ResourceManager.GetString("List_TipClosed", Culture)!; - public static string List_TipInTray => ResourceManager.GetString("List_TipInTray", Culture)!; /// {0} · está en el foco. public static string List_TipInFocus => ResourceManager.GetString("List_TipInFocus", Culture)!; + /// {0} · en la bandeja. Clic: mostrarla en este panel. + public static string List_TipInTray => ResourceManager.GetString("List_TipInTray", Culture)!; + /// {0} · {1}. Clic: al foco. public static string List_TipOpen => ResourceManager.GetString("List_TipOpen", Culture)!; + /// {0} · en otro escritorio. Clic: ir allí. + public static string List_TipOtherDesktop => ResourceManager.GetString("List_TipOtherDesktop", Culture)!; + /// Aplicar public static string Main_Apply => ResourceManager.GetString("Main_Apply", Culture)!; @@ -636,18 +939,15 @@ public static class Strings /// Minimizar public static string Main_Park => ResourceManager.GetString("Main_Park", Culture)!; - /// Aparta la ventana seleccionada (minimizada) sin quitarle su panel. También pasa + /// Minimiza la ventana seleccionada sin quitarle su panel. También pasa si la minim public static string Main_ParkTip => ResourceManager.GetString("Main_ParkTip", Culture)!; - /// Al Centro + /// Al foco public static string Main_Promote => ResourceManager.GetString("Main_Promote", Culture)!; - /// Lleva la ventana seleccionada al Centro + /// Lleva la ventana seleccionada al foco public static string Main_PromoteTip => ResourceManager.GetString("Main_PromoteTip", Culture)!; - - - /// Reencajar public static string Main_Reattach => ResourceManager.GetString("Main_Reattach", Culture)!; @@ -663,13 +963,16 @@ public static class Strings /// Devuelve la ventana seleccionada a su sitio original y deja de gestionarla public static string Main_ReleaseTip => ResourceManager.GetString("Main_ReleaseTip", Culture)!; + /// Vuelve al ancho por defecto de esta disposición (el ancho se ajusta arrastrando + public static string Main_ResetWidthTip => ResourceManager.GetString("Main_ResetWidthTip", Culture)!; + /// Liberar todas public static string Main_RestoreAll => ResourceManager.GetString("Main_RestoreAll", Culture)!; - /// Centro al panel + /// Foco al panel public static string Main_Return => ResourceManager.GetString("Main_Return", Culture)!; - /// Devuelve la ventana del Centro a su panel + /// Devuelve la ventana del foco a su panel public static string Main_ReturnTip => ResourceManager.GetString("Main_ReturnTip", Culture)!; /// Guardar escena actual @@ -693,7 +996,7 @@ public static class Strings /// Volver a la anterior public static string Main_Swap => ResourceManager.GetString("Main_Swap", Culture)!; - /// Devuelve al Centro la ventana que estaba antes + /// Devuelve al foco la ventana que estaba antes public static string Main_SwapTip => ResourceManager.GetString("Main_SwapTip", Culture)!; /// Pestaña Apps @@ -717,21 +1020,18 @@ public static class Strings /// Pestaña Ventanas public static string Main_TabWindowsName => ResourceManager.GetString("Main_TabWindowsName", Culture)!; - /// Recuperar + /// Restaurar public static string Main_Unpark => ResourceManager.GetString("Main_Unpark", Culture)!; - /// Devuelve una ventana estacionada a su panel, en el puesto que tenía. También pas + /// Devuelve una ventana minimizada a su panel, en el puesto que tenía. También pasa public static string Main_UnparkTip => ResourceManager.GetString("Main_UnparkTip", Culture)!; - /// Vista: public static string Main_ViewLabel => ResourceManager.GetString("Main_ViewLabel", Culture)!; - /// Vista public static string Main_ViewName => ResourceManager.GetString("Main_ViewName", Culture)!; - /// Dónde va el foco en el monitor principal public static string Main_ViewTip => ResourceManager.GetString("Main_ViewTip", Culture)!; @@ -750,6 +1050,33 @@ public static class Strings /// Principal public static string Monitor_Principal => ResourceManager.GetString("Monitor_Principal", Culture)!; + /// Actividad + public static string Nav_Activity => ResourceManager.GetString("Nav_Activity", Culture)!; + + /// Apps + public static string Nav_Apps => ResourceManager.GetString("Nav_Apps", Culture)!; + + /// Excluidas + public static string Nav_Excluded => ResourceManager.GetString("Nav_Excluded", Culture)!; + + /// General + public static string Nav_General => ResourceManager.GetString("Nav_General", Culture)!; + + /// Inicio + public static string Nav_Home => ResourceManager.GetString("Nav_Home", Culture)!; + + /// Paneles + public static string Nav_Panels => ResourceManager.GetString("Nav_Panels", Culture)!; + + /// Escenas + public static string Nav_Scenes => ResourceManager.GetString("Nav_Scenes", Culture)!; + + /// Atajos y gestos + public static string Nav_Shortcuts => ResourceManager.GetString("Nav_Shortcuts", Culture)!; + + /// Ventanas + public static string Nav_Windows => ResourceManager.GetString("Nav_Windows", Culture)!; + /// {0} abierta en {1}. public static string Open_Done => ResourceManager.GetString("Open_Done", Culture)!; @@ -762,6 +1089,15 @@ public static class Strings /// Esa app ya no está en el catálogo. public static string Open_NotInCatalog => ResourceManager.GetString("Open_NotInCatalog", Culture)!; + /// libre + public static string Pages_Free => ResourceManager.GetString("Pages_Free", Culture)!; + + /// en el foco + public static string Pages_InFocus => ResourceManager.GetString("Pages_InFocus", Culture)!; + + /// ⧉ en otro escritorio + public static string Pages_OtherDesktop => ResourceManager.GetString("Pages_OtherDesktop", Culture)!; + /// Crear panel public static string Panel_Create => ResourceManager.GetString("Panel_Create", Culture)!; @@ -837,6 +1173,21 @@ public static class Strings /// derecha public static string Report_Right => ResourceManager.GetString("Report_Right", Culture)!; + /// Cambiar atajos… + public static string Sc_Edit => ResourceManager.GetString("Sc_Edit", Culture)!; + + /// Gestos de Windows + public static string Sc_Gestures => ResourceManager.GetString("Sc_Gestures", Culture)!; + + /// Llevar al foco la ventana de un panel cuando la eliges con: + public static string Sc_GesturesHelp => ResourceManager.GetString("Sc_GesturesHelp", Culture)!; + + /// Atajos de teclado + public static string Sc_Keys => ResourceManager.GetString("Sc_Keys", Culture)!; + + /// Todos usan Ctrl+Alt+Mayús y una tecla, para no chocar con tus apps. + public static string Sc_KeysHelp => ResourceManager.GetString("Sc_KeysHelp", Culture)!; + /// Escena «{0}» aplicada. public static string Scene_Applied => ResourceManager.GetString("Scene_Applied", Culture)!; @@ -879,6 +1230,18 @@ public static class Strings /// el foco public static string Scene_TheFocus => ResourceManager.GetString("Scene_TheFocus", Culture)!; + /// Una escena guarda qué apps están en cada panel y en el foco. Aplicarla las reaco + public static string Scn_Help => ResourceManager.GetString("Scn_Help", Culture)!; + + /// Nombre de la escena + public static string Scn_NamePlaceholder => ResourceManager.GetString("Scn_NamePlaceholder", Culture)!; + + /// Guardar lo de ahora como escena + public static string Scn_SaveTitle => ResourceManager.GetString("Scn_SaveTitle", Culture)!; + + /// Escenas guardadas + public static string Scn_Saved => ResourceManager.GetString("Scn_Saved", Culture)!; + /// Según la ventana (tamaño fijo) public static string Size_AutoFixed => ResourceManager.GetString("Size_AutoFixed", Culture)!; @@ -945,7 +1308,7 @@ public static class Strings /// {0} · está en el foco y volverá aquí. Clic: devolverla. public static string Strip_TipInFocus => ResourceManager.GetString("Strip_TipInFocus", Culture)!; - /// {0} · estacionada. Clic: recuperarla. Doble clic: al foco. + /// {0} · minimizada. Clic: restaurarla. Doble clic: al foco. public static string Strip_TipParked => ResourceManager.GetString("Strip_TipParked", Culture)!; /// Al foco @@ -1062,7 +1425,6 @@ public static class Strings /// no se puede mover public static string Unmanageable_Generic => ResourceManager.GetString("Unmanageable_Generic", Culture)!; - /// {0}, izquierda public static string Where_AuxLeft => ResourceManager.GetString("Where_AuxLeft", Culture)!; @@ -1084,203 +1446,15 @@ public static class Strings /// principal, derecha public static string Where_PrincipalRightShort => ResourceManager.GetString("Where_PrincipalRightShort", Culture)!; - public static string Desktop_Switched => ResourceManager.GetString("Desktop_Switched", Culture)!; - - public static string Desktop_OpenElsewhere => ResourceManager.GetString("Desktop_OpenElsewhere", Culture)!; - - public static string Deck_OtherDesktopTip => ResourceManager.GetString("Deck_OtherDesktopTip", Culture)!; - public static string Deck_InTrayTip => ResourceManager.GetString("Deck_InTrayTip", Culture)!; - - public static string ListState_OtherDesktop => ResourceManager.GetString("ListState_OtherDesktop", Culture)!; - - public static string List_TipOtherDesktop => ResourceManager.GetString("List_TipOtherDesktop", Culture)!; - - public static string DeckMenu_GoToDesktop => ResourceManager.GetString("DeckMenu_GoToDesktop", Culture)!; - - public static string Pages_InFocus => ResourceManager.GetString("Pages_InFocus", Culture)!; - - public static string Pages_Free => ResourceManager.GetString("Pages_Free", Culture)!; - - public static string Pages_OtherDesktop => ResourceManager.GetString("Pages_OtherDesktop", Culture)!; - - public static string Deck_PagesTab => ResourceManager.GetString("Deck_PagesTab", Culture)!; - - public static string Deck_PagesTabCount => ResourceManager.GetString("Deck_PagesTabCount", Culture)!; - - public static string Deck_PagesTabName => ResourceManager.GetString("Deck_PagesTabName", Culture)!; - - public static string Deck_PagesLoading => ResourceManager.GetString("Deck_PagesLoading", Culture)!; - - public static string Deck_PagesNone => ResourceManager.GetString("Deck_PagesNone", Culture)!; - - - public static string Deck_PageName => ResourceManager.GetString("Deck_PageName", Culture)!; - - public static string Deck_PageCloseName => ResourceManager.GetString("Deck_PageCloseName", Culture)!; - - public static string DeckMenu_Pages => ResourceManager.GetString("DeckMenu_Pages", Culture)!; - - public static string Deck_PagesSites => ResourceManager.GetString("Deck_PagesSites", Culture)!; - - public static string Deck_PagesLoose => ResourceManager.GetString("Deck_PagesLoose", Culture)!; - - public static string Deck_PagesBack => ResourceManager.GetString("Deck_PagesBack", Culture)!; - - public static string Deck_PagesSite => ResourceManager.GetString("Deck_PagesSite", Culture)!; - - public static string Deck_PagesCloseAll => ResourceManager.GetString("Deck_PagesCloseAll", Culture)!; - - public static string Deck_PagesCloseAllConfirm => ResourceManager.GetString("Deck_PagesCloseAllConfirm", Culture)!; - - public static string Deck_SiteName => ResourceManager.GetString("Deck_SiteName", Culture)!; - - public static string Deck_PageWhere => ResourceManager.GetString("Deck_PageWhere", Culture)!; - - public static string Deck_PanelOff => ResourceManager.GetString("Deck_PanelOff", Culture)!; - - public static string Deck_LeftColumn => ResourceManager.GetString("Deck_LeftColumn", Culture)!; - - public static string Deck_RightColumn => ResourceManager.GetString("Deck_RightColumn", Culture)!; - - public static string Deck_ColumnTip => ResourceManager.GetString("Deck_ColumnTip", Culture)!; - - public static string Deck_BorrowTip => ResourceManager.GetString("Deck_BorrowTip", Culture)!; - - public static string Deck_ResetWidth => ResourceManager.GetString("Deck_ResetWidth", Culture)!; - - public static string Arr_Center => ResourceManager.GetString("Arr_Center", Culture)!; - - public static string Arr_Right => ResourceManager.GetString("Arr_Right", Culture)!; - - public static string Arr_Left => ResourceManager.GetString("Arr_Left", Culture)!; - - public static string Arr_ContextOnly => ResourceManager.GetString("Arr_ContextOnly", Culture)!; - - public static string Arr_WorkOnly => ResourceManager.GetString("Arr_WorkOnly", Culture)!; - - public static string Arr_FocusOnly => ResourceManager.GetString("Arr_FocusOnly", Culture)!; - - public static string Main_ResetWidthTip => ResourceManager.GetString("Main_ResetWidthTip", Culture)!; - - public static string Nav_Home => ResourceManager.GetString("Nav_Home", Culture)!; - - public static string Nav_Windows => ResourceManager.GetString("Nav_Windows", Culture)!; - - public static string Nav_Panels => ResourceManager.GetString("Nav_Panels", Culture)!; - - public static string Nav_Apps => ResourceManager.GetString("Nav_Apps", Culture)!; - - public static string Nav_Shortcuts => ResourceManager.GetString("Nav_Shortcuts", Culture)!; - - public static string Nav_Scenes => ResourceManager.GetString("Nav_Scenes", Culture)!; - - public static string Nav_Excluded => ResourceManager.GetString("Nav_Excluded", Culture)!; - - public static string Nav_General => ResourceManager.GetString("Nav_General", Culture)!; - - public static string Home_Monitors => ResourceManager.GetString("Home_Monitors", Culture)!; - - public static string Home_Layout => ResourceManager.GetString("Home_Layout", Culture)!; - - public static string Home_Actions => ResourceManager.GetString("Home_Actions", Culture)!; - - public static string Home_OpenDeck => ResourceManager.GetString("Home_OpenDeck", Culture)!; - - public static string Home_SafetyTitle => ResourceManager.GetString("Home_SafetyTitle", Culture)!; - - public static string Home_SafetyText => ResourceManager.GetString("Home_SafetyText", Culture)!; - - public static string Home_Focus => ResourceManager.GetString("Home_Focus", Culture)!; - - public static string Home_FocusEmpty => ResourceManager.GetString("Home_FocusEmpty", Culture)!; - - public static string Home_FocusFull => ResourceManager.GetString("Home_FocusFull", Culture)!; - - public static string Home_PanelLine => ResourceManager.GetString("Home_PanelLine", Culture)!; - - public static string Home_Main => ResourceManager.GetString("Home_Main", Culture)!; - - public static string Home_LayoutHint => ResourceManager.GetString("Home_LayoutHint", Culture)!; - - public static string Win_Help => ResourceManager.GetString("Win_Help", Culture)!; - + /// App public static string Win_ColApp => ResourceManager.GetString("Win_ColApp", Culture)!; + /// Panel public static string Win_ColPanel => ResourceManager.GetString("Win_ColPanel", Culture)!; - public static string Win_More => ResourceManager.GetString("Win_More", Culture)!; - - public static string Sc_Keys => ResourceManager.GetString("Sc_Keys", Culture)!; - - public static string Sc_KeysHelp => ResourceManager.GetString("Sc_KeysHelp", Culture)!; - - public static string Sc_Edit => ResourceManager.GetString("Sc_Edit", Culture)!; - - public static string Sc_Gestures => ResourceManager.GetString("Sc_Gestures", Culture)!; - - public static string Sc_GesturesHelp => ResourceManager.GetString("Sc_GesturesHelp", Culture)!; - - public static string Scn_Help => ResourceManager.GetString("Scn_Help", Culture)!; - - public static string Scn_Saved => ResourceManager.GetString("Scn_Saved", Culture)!; - - public static string Scn_SaveTitle => ResourceManager.GetString("Scn_SaveTitle", Culture)!; - - public static string Scn_NamePlaceholder => ResourceManager.GetString("Scn_NamePlaceholder", Culture)!; - - public static string Gen_Language => ResourceManager.GetString("Gen_Language", Culture)!; - - public static string Gen_LanguageHelp => ResourceManager.GetString("Gen_LanguageHelp", Culture)!; - - public static string Gen_Startup => ResourceManager.GetString("Gen_Startup", Culture)!; - - public static string Gen_StartupHelp => ResourceManager.GetString("Gen_StartupHelp", Culture)!; - - public static string Gen_Awake => ResourceManager.GetString("Gen_Awake", Culture)!; - - public static string Gen_AwakeHelp => ResourceManager.GetString("Gen_AwakeHelp", Culture)!; - - public static string Gen_About => ResourceManager.GetString("Gen_About", Culture)!; - - public static string Gen_Version => ResourceManager.GetString("Gen_Version", Culture)!; - - public static string Gen_Manual => ResourceManager.GetString("Gen_Manual", Culture)!; - - public static string Gen_Report => ResourceManager.GetString("Gen_Report", Culture)!; - - public static string Gen_Settings => ResourceManager.GetString("Gen_Settings", Culture)!; - - public static string Gen_Tagline => ResourceManager.GetString("Gen_Tagline", Culture)!; - - public static string Home_NoPanels => ResourceManager.GetString("Home_NoPanels", Culture)!; - - public static string Gen_Theme => ResourceManager.GetString("Gen_Theme", Culture)!; - - public static string Gen_ThemeHelp => ResourceManager.GetString("Gen_ThemeHelp", Culture)!; - - public static string Gen_ThemeAuto => ResourceManager.GetString("Gen_ThemeAuto", Culture)!; - - public static string Gen_ThemeLight => ResourceManager.GetString("Gen_ThemeLight", Culture)!; - - public static string Gen_ThemeDark => ResourceManager.GetString("Gen_ThemeDark", Culture)!; - - public static string Gen_AboutText => ResourceManager.GetString("Gen_AboutText", Culture)!; - - public static string Gen_AboutPrivacy => ResourceManager.GetString("Gen_AboutPrivacy", Culture)!; - - public static string Gen_ManualHelp => ResourceManager.GetString("Gen_ManualHelp", Culture)!; - - public static string Gen_Releases => ResourceManager.GetString("Gen_Releases", Culture)!; - - public static string Gen_ReleasesHelp => ResourceManager.GetString("Gen_ReleasesHelp", Culture)!; - - public static string Gen_ReportHelp => ResourceManager.GetString("Gen_ReportHelp", Culture)!; - - public static string Gen_Source => ResourceManager.GetString("Gen_Source", Culture)!; - - public static string Gen_License => ResourceManager.GetString("Gen_License", Culture)!; - - public static string Gen_LicenseHelp => ResourceManager.GetString("Gen_LicenseHelp", Culture)!; + /// Las ventanas que FocusWShell puede organizar. Elige su panel y se aplica al mome + public static string Win_Help => ResourceManager.GetString("Win_Help", Culture)!; - public static string Gen_ThirdParty => ResourceManager.GetString("Gen_ThirdParty", Culture)!; + /// Más acciones de {0} + public static string Win_More => ResourceManager.GetString("Win_More", Culture)!; } diff --git a/src/FocusWShell.App/Strings.en.resx b/src/FocusWShell.App/Strings.en.resx index 300dac3..b0293be 100644 --- a/src/FocusWShell.App/Strings.en.resx +++ b/src/FocusWShell.App/Strings.en.resx @@ -56,7 +56,8 @@ Closing… empty Hide the deck - {0} is in front (it gets the keyboard), but it isn't the focus app + {0} is in use (it gets the keyboard and mouse), but it isn't the focus app + in use {0}: tap to show it in its panel and type in it; tap again to bring it to the focus {0} is the tab shown in its panel: tap to bring it to the focus +{0} more @@ -469,4 +470,27 @@ Restore them now? License Open source: you can use, change and share it. Built with these open source components: + Activity + How long each app spends in focus and in use. Side by side is the time with one app in focus and the keyboard in another: for example, a document in view while you type in the chat. + Measure activity + Only on this PC, without window titles. The last {0} days are kept. + Previous day + Next day + dddd, MMMM d + Today, {0} + Yesterday, {0} + Active time + Side by side + {0}% of active time + To the focus + {0} times + Longest in focus + In focus + In use + no panel + No activity on this day. + Measuring is off. Turn it on to start seeing your activity. + Delete history + Delete all the saved activity? This can't be undone. + The saved activity was deleted. diff --git a/src/FocusWShell.App/Strings.resx b/src/FocusWShell.App/Strings.resx index 29c116c..df7a010 100644 --- a/src/FocusWShell.App/Strings.resx +++ b/src/FocusWShell.App/Strings.resx @@ -56,7 +56,8 @@ Cerrando… vacío Ocultar el deck - {0} está al frente (recibe el teclado), pero no es la del foco + {0} está en uso (recibe el teclado y el ratón), pero no es la del foco + en uso {0}: tócala para verla en su panel y escribir en ella; otra vez, al foco {0} es la pestaña que se ve en su panel: tócala para llevarla al foco +{0} más @@ -469,4 +470,27 @@ Licencia Código abierto: puedes usarlo, modificarlo y compartirlo. Usa estos componentes de código abierto: + Actividad + Cuánto pasa cada app en el foco y en uso. En paralelo es el tiempo con el foco en una app y el teclado en otra: por ejemplo, un documento a la vista mientras escribes en el chat. + Medir la actividad + Sólo en este equipo, sin títulos de ventanas. Se guardan los últimos {0} días. + Día anterior + Día siguiente + dddd d 'de' MMMM + Hoy, {0} + Ayer, {0} + Tiempo activo + En paralelo + {0} % del tiempo activo + Al foco + {0} veces + Racha más larga en el foco + En el foco + En uso + sin panel + No hay actividad este día. + La medición está apagada. Préndela para empezar a ver tu actividad. + Borrar historial + ¿Borrar toda la actividad guardada? No se puede deshacer. + Se borró la actividad guardada. diff --git a/src/FocusWShell.Core/Activity/ActivityDay.cs b/src/FocusWShell.Core/Activity/ActivityDay.cs new file mode 100644 index 0000000..67b18a7 --- /dev/null +++ b/src/FocusWShell.Core/Activity/ActivityDay.cs @@ -0,0 +1,86 @@ +namespace FocusWShell.Core.Activity; + +/// 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); + +/// El resumen de un día de actividad, calculado a partir de sus tramos. +/// Tiempo presente (con algo en el foco o en uso). +/// Tiempo con el foco en una app y el uso en otra. +/// Cuántas veces llegó una app al foco. +/// La racha más larga con la misma app en el foco, sin pausas. +/// Por app, de la más usada a la menos (foco + uso). +public sealed record ActivityDay( + TimeSpan Active, + TimeSpan SideBySide, + int ToFocus, + TimeSpan LongestFocus, + string? LongestFocusApp, + IReadOnlyList Apps) +{ + public static ActivityDay Empty { get; } = new(TimeSpan.Zero, TimeSpan.Zero, 0, TimeSpan.Zero, null, []); + + public static ActivityDay From(IEnumerable segments) + { + var active = TimeSpan.Zero; + var side = TimeSpan.Zero; + var toFocus = 0; + var longest = TimeSpan.Zero; + string? longestApp = null; + var apps = new Dictionary(StringComparer.OrdinalIgnoreCase); + + ActivityApp? lastFocus = null; // la última app que hubo en el foco, aunque luego quedara vacío + DateTime? streakEnd = null; + var streak = TimeSpan.Zero; + foreach (var s in segments.OrderBy(s => s.Start)) + { + active += s.Duration; + if (s.SideBySide) + { + side += s.Duration; + } + + if (s.InUse is { } use) + { + Count(use, s.Duration, inFocus: false); + } + + if (s.Focus is not { } focus) + { + streakEnd = null; // el foco quedó vacío: la racha se corta + continue; + } + + Count(focus, s.Duration, inFocus: true); + + // Llegó al foco: otra app que la última (tras una pausa, la misma no cuenta otra vez). + if (!focus.SameApp(lastFocus)) + { + toFocus++; + } + + // La racha sigue si es la misma app y sin hueco (una pausa por inactividad la corta). + streak = focus.SameApp(lastFocus) && streakEnd == s.Start ? streak + s.Duration : s.Duration; + streakEnd = s.End; + lastFocus = focus; + if (streak > longest) + { + longest = streak; + longestApp = focus.Name; + } + } + + var totals = apps + .Select(a => new ActivityAppTotal(a.Key, a.Value.Name, a.Value.PanelId, a.Value.Focus, a.Value.Use)) + .OrderByDescending(a => a.InFocus + a.InUse) + .ThenBy(a => a.Name, StringComparer.CurrentCultureIgnoreCase) + .ToList(); + return new ActivityDay(active, side, toFocus, longest, longestApp, totals); + + void Count(ActivityApp app, TimeSpan duration, bool inFocus) + { + 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)); + } + } +} diff --git a/src/FocusWShell.Core/Activity/ActivityTracker.cs b/src/FocusWShell.Core/Activity/ActivityTracker.cs new file mode 100644 index 0000000..7b9e879 --- /dev/null +++ b/src/FocusWShell.Core/Activity/ActivityTracker.cs @@ -0,0 +1,132 @@ +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) +{ + /// 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); +} + +/// +/// Un tramo de tiempo presente con la misma app en el foco y la misma en uso. Nunca cruza la medianoche. +/// +/// La app en el foco, o null si el foco estaba vacío. +/// La app que recibía el teclado y el ratón, o null si no se supo. +public sealed record ActivitySegment(DateTime Start, DateTime End, ActivityApp? Focus, ActivityApp? InUse) +{ + public TimeSpan Duration => End - Start; + + /// En paralelo: el foco en una app y el uso en otra. + public bool SideBySide => Focus is not null && InUse is not null && !Focus.SameApp(InUse); +} + +/// +/// Cuenta el tiempo en el foco y en uso (ADR 0019). No sabe de Windows: recibe qué hay en el foco y qué está +/// en uso cada vez que cambia, y cuándo se deja de tocar el equipo; devuelve los tramos que se cierran. +/// Las horas son locales (los días de la actividad son los del reloj de quien la usa). +/// +public sealed class ActivityTracker +{ + /// Un tramo más corto no se guarda: un cambio de ventana al pasar con Alt+Tab no es actividad. + public static readonly TimeSpan MinSegment = TimeSpan.FromSeconds(1); + + private ActivityApp? _focus; + private ActivityApp? _inUse; + private DateTime? _start; // null: inactivo (sin tramo abierto) + private bool _idle; + + /// Si hay un tramo abierto. + public bool Running => _start is not null; + + /// Cambió la app en el foco o en uso (o las dos). Si no cambia nada, no corta el tramo. + public IReadOnlyList Observe(DateTime now, ActivityApp? focus, ActivityApp? inUse) + { + if (Same(_focus, focus) && Same(_inUse, inUse)) + { + // Mismo estado; sólo puede cambiar el nombre o el panel, que se toman para el tramo siguiente. + _focus = focus; + _inUse = inUse; + return []; + } + + var closed = Close(now); + _focus = focus; + _inUse = inUse; + if (!_idle) + { + _start = now; + } + + return closed; + } + + /// + /// Se dejó de tocar el equipo, se bloqueó o se suspende: el tramo se cierra en + /// (la última entrada), no ahora, para no contar los minutos de espera. + /// + public IReadOnlyList Idle(DateTime since) + { + var closed = Close(since); + _idle = true; + return closed; + } + + /// Se volvió a tocar el equipo: empieza un tramo con lo que hay ahora. + public void Active(DateTime now) + { + if (_idle || _start is null) + { + _idle = false; + _start = now; + } + } + + /// Cierra el tramo abierto y abre otro igual: para guardar lo medido (al apagar, cada tanto). + public IReadOnlyList Flush(DateTime now) + { + var closed = Close(now); + if (!_idle) + { + _start = now; + } + + return closed; + } + + private List Close(DateTime end) + { + if (_start is not { } start) + { + return []; + } + + _start = null; + if (end <= start) + { + return []; + } + + // Partido en la medianoche: cada tramo va al archivo de su día. + var segments = new List(); + while (start.Date < end.Date) + { + var midnight = start.Date.AddDays(1); + Add(segments, start, midnight); + start = midnight; + } + + Add(segments, start, end); + return segments; + } + + private void Add(List segments, DateTime start, DateTime end) + { + if (end - start >= MinSegment && (_focus is not null || _inUse is not null)) + { + segments.Add(new ActivitySegment(start, end, _focus, _inUse)); + } + } + + private static bool Same(ActivityApp? a, ActivityApp? b) => a is null ? b is null : a.SameApp(b); +} diff --git a/src/FocusWShell.Win32/NativeMethods.txt b/src/FocusWShell.Win32/NativeMethods.txt index bacfdc9..fa795eb 100644 --- a/src/FocusWShell.Win32/NativeMethods.txt +++ b/src/FocusWShell.Win32/NativeMethods.txt @@ -143,3 +143,7 @@ SetSuspendState // Pestañas de navegadores (S12) ScreenToClient PostMessage + +// Actividad (ADR 0019): tiempo sin entrada +GetLastInputInfo +LASTINPUTINFO diff --git a/src/FocusWShell.Win32/Persistence/ActivityStore.cs b/src/FocusWShell.Win32/Persistence/ActivityStore.cs new file mode 100644 index 0000000..c36c387 --- /dev/null +++ b/src/FocusWShell.Win32/Persistence/ActivityStore.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using System.Text.Json; +using FocusWShell.Core.Activity; + +namespace FocusWShell.Win32.Persistence; + +/// +/// La actividad (ADR 0019): un archivo JSON Lines por día en %LOCALAPPDATA%\FocusWShell\actividad, +/// un tramo por línea. Sólo en este equipo; nunca guarda títulos de ventanas. +/// +public sealed class ActivityStore(string folder) +{ + private static readonly JsonSerializerOptions Options = new() + { + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + }; + + private readonly Lock _gate = new(); + + public static string DefaultFolder { get; } = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "FocusWShell", + "actividad"); + + public string Folder { get; } = folder; + + private string FileOf(DateOnly day) => Path.Combine(Folder, day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".jsonl"); + + /// Agrega tramos, cada uno al archivo de su día. + public void Append(IEnumerable segments) + { + lock (_gate) + { + foreach (var day in segments.GroupBy(s => DateOnly.FromDateTime(s.Start))) + { + Directory.CreateDirectory(Folder); + File.AppendAllLines(FileOf(day.Key), day.Select(s => JsonSerializer.Serialize(s, Options))); + } + } + } + + /// Los tramos de un día. Una línea dañada se salta. + public List Load(DateOnly day) + { + lock (_gate) + { + var path = FileOf(day); + if (!File.Exists(path)) + { + return []; + } + + var result = new List(); + foreach (var line in File.ReadLines(path)) + { + try + { + if (JsonSerializer.Deserialize(line, Options) is { } s) + { + result.Add(s); + } + } + catch (JsonException) + { + // Una línea a medias (un apagado al escribir): se pierde sólo ese tramo. + } + } + + return result; + } + } + + /// Los días con actividad guardada, del más reciente al más antiguo. + public List Days() + { + if (!Directory.Exists(Folder)) + { + return []; + } + + return [.. Directory.EnumerateFiles(Folder, "*.jsonl") + .Select(f => DateOnly.TryParseExact(Path.GetFileNameWithoutExtension(f), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d : (DateOnly?)null) + .OfType() + .OrderDescending()]; + } + + /// Borra los días anteriores a días. + public void Prune(int keepDays, DateOnly today) + { + lock (_gate) + { + foreach (var day in Days().Where(d => d < today.AddDays(-keepDays))) + { + File.Delete(FileOf(day)); + } + } + } + + /// Borra todo el historial. + public void DeleteAll() + { + lock (_gate) + { + if (Directory.Exists(Folder)) + { + Directory.Delete(Folder, recursive: true); + } + } + } +} diff --git a/src/FocusWShell.Win32/WindowEnumerator.cs b/src/FocusWShell.Win32/WindowEnumerator.cs index f26720a..cae3224 100644 --- a/src/FocusWShell.Win32/WindowEnumerator.cs +++ b/src/FocusWShell.Win32/WindowEnumerator.cs @@ -5,6 +5,7 @@ using Windows.Win32.Foundation; using Windows.Win32.Graphics.Dwm; using Windows.Win32.Graphics.Gdi; +using Windows.Win32.UI.Input.KeyboardAndMouse; using Windows.Win32.UI.Shell.PropertiesSystem; using Windows.Win32.UI.WindowsAndMessaging; @@ -40,6 +41,19 @@ public static IReadOnlyList EnumerateTopLevel() return result; } + /// Una sola ventana (p. ej. la que está en uso), o null si ya no existe. + public static WindowSnapshot? Snapshot(nint hwnd) => + hwnd == 0 ? null : TrySnapshot((HWND)hwnd, Environment.ProcessId, []); + + /// Cuánto hace de la última tecla o movimiento del ratón, en todo el equipo. + public static unsafe TimeSpan IdleTime() + { + var info = new LASTINPUTINFO { cbSize = (uint)sizeof(LASTINPUTINFO) }; + return PInvoke.GetLastInputInfo(ref info) + ? TimeSpan.FromMilliseconds(unchecked((uint)Environment.TickCount - info.dwTime)) + : TimeSpan.Zero; + } + /// Nivel de integridad del proceso actual. public static IntegrityLevel CurrentIntegrity() => ProcessInfo.CurrentIntegrity(); diff --git a/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs b/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs new file mode 100644 index 0000000..81d453d --- /dev/null +++ b/tests/FocusWShell.Core.Tests/Activity/ActivityTests.cs @@ -0,0 +1,117 @@ +using FocusWShell.Core.Activity; + +namespace FocusWShell.Core.Tests.Activity; + +public class ActivityTests +{ + private static readonly ActivityApp Code = new("code", "VS Code", "work"); + private static readonly ActivityApp Slack = new("slack", "Slack", "context"); + private static readonly ActivityApp Docs = new("docs", "Docs", "work"); + private static readonly DateTime T0 = new(2026, 11, 17, 10, 0, 0); + + private static DateTime At(int minutes) => T0.AddMinutes(minutes); + + [Fact] + public void ASegmentClosesWhenTheInUseAppChanges() + { + var t = new ActivityTracker(); + t.Active(At(0)); + Assert.Empty(t.Observe(At(0), Code, Code)); + + var closed = t.Observe(At(10), Code, Slack); + + Assert.Equal([new ActivitySegment(At(0), At(10), Code, Code)], closed); + Assert.Equal([new ActivitySegment(At(10), At(25), Code, Slack)], t.Flush(At(25))); + } + + [Fact] + public void TheSameAppsDoNotCutTheSegment() + { + var t = new ActivityTracker(); + t.Active(At(0)); + t.Observe(At(0), Code, Slack); + + Assert.Empty(t.Observe(At(5), Code with { PanelId = "other" }, Slack)); + Assert.Single(t.Flush(At(10))); + } + + [Fact] + public void IdleClosesAtTheLastInputAndActiveStartsAgain() + { + var t = new ActivityTracker(); + 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 + Assert.Equal([new ActivitySegment(At(0), At(12), Code, Code)], closed); + + Assert.Empty(t.Observe(At(20), Docs, Docs)); // inactivo: no abre tramo + Assert.False(t.Running); + + t.Active(At(30)); + Assert.Equal([new ActivitySegment(At(30), At(40), Docs, Docs)], t.Flush(At(40))); + } + + [Fact] + public void ASegmentIsSplitAtMidnight() + { + var t = new ActivityTracker(); + var night = new DateTime(2026, 11, 17, 23, 50, 0); + t.Active(night); + t.Observe(night, Code, Code); + + var closed = t.Flush(night.AddMinutes(20)); + + Assert.Equal(2, closed.Count); + Assert.Equal(new DateTime(2026, 11, 18), closed[0].End); + Assert.Equal(new DateTime(2026, 11, 18), closed[1].Start); + } + + [Fact] + public void VeryShortSegmentsAreNotKept() + { + var t = new ActivityTracker(); + t.Active(At(0)); + t.Observe(At(0), Code, Code); + + Assert.Empty(t.Observe(At(0).AddMilliseconds(400), Code, Slack)); + } + + [Fact] + public void TheDayCountsFocusInUseAndSideBySide() + { + var day = ActivityDay.From( + [ + new(At(0), At(30), Code, Code), + new(At(30), At(50), Code, Slack), // en paralelo + new(At(50), At(60), Docs, Docs), + new(At(70), At(80), Code, Code), // tras una pausa + ]); + + Assert.Equal(TimeSpan.FromMinutes(70), day.Active); + Assert.Equal(TimeSpan.FromMinutes(20), day.SideBySide); + Assert.Equal(3, day.ToFocus); // Code, Docs, Code + Assert.Equal(TimeSpan.FromMinutes(50), day.LongestFocus); + Assert.Equal("VS Code", day.LongestFocusApp); + + var code = day.Apps[0]; + Assert.Equal("code", code.Key); + Assert.Equal(TimeSpan.FromMinutes(60), code.InFocus); + Assert.Equal(TimeSpan.FromMinutes(40), code.InUse); + Assert.Equal(TimeSpan.FromMinutes(20), day.Apps.Single(a => a.Key == "slack").InUse); + Assert.Equal(TimeSpan.Zero, day.Apps.Single(a => a.Key == "slack").InFocus); + } + + [Fact] + public void TheSameAppAfterAPauseIsNotANewArrivalButBreaksTheStreak() + { + var day = ActivityDay.From( + [ + new(At(0), At(20), Code, Code), + new(At(30), At(40), Code, Code), + ]); + + Assert.Equal(1, day.ToFocus); + Assert.Equal(TimeSpan.FromMinutes(20), day.LongestFocus); + } +}