A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
Refactor AppBar to support left and right edges, add tests for edge reservations
CristianOlivera12709c7ce0590
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c4e7d04..0dd4936 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -25,6 +25,10 @@ jobs:shell: pwshrun: ./scripts/Test-WingetAutomation.ps1+ - name: Check code-signing policy without network, credentials or trust changes+ shell: pwsh+ run: ./scripts/Test-CodeSigning.ps1+# The settings app embeds its built front end at compile time.- name: Build settings UIworking-directory: apps/settingsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex a460392..c0ea6d2 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -7,6 +7,8 @@ name: Releaseon:push:tags: ['v*']+ # Manual runs exercise test-signing only, with no release or updater output.+ workflow_dispatch:permissions:contents: write@@ -32,15 +34,27 @@ jobs:cache-dependency-path: apps/settings/pnpm-lock.yaml- uses: Swatinem/rust-cache@v2- - name: Check the tag matches the version+ - name: Select signing lane and validate release configurationshell: pwsh+ env:+ SIGNPATH_ORGANIZATION_ID: ${{ vars.SIGNPATH_ORGANIZATION_ID }}+ SIGNPATH_PROJECT_SLUG: ${{ vars.SIGNPATH_PROJECT_SLUG }}+ SIGNPATH_SIGNING_POLICY_SLUG: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}+ SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT: ${{ vars.SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT }}+ SIGNPATH_API_TOKEN: ${{ secrets.SIGNPATH_API_TOKEN }}run: |$version = (cargo metadata --format-version 1 --no-deps | ConvertFrom-Json).packages |Where-Object name -eq 'muelle' | Select-Object -ExpandProperty version- if ("v$version" -ne $env:GITHUB_REF_NAME) {- throw "Tag $env:GITHUB_REF_NAME does not match the workspace version $version"- }- "VERSION=$version" >> $env:GITHUB_ENV+ $lane = ./scripts/Get-ReleaseSigningMode.ps1 -EventName $env:GITHUB_EVENT_NAME `+ -Version $version -RefName $env:GITHUB_REF_NAME `+ -Organization $env:SIGNPATH_ORGANIZATION_ID -Project $env:SIGNPATH_PROJECT_SLUG `+ -Policy $env:SIGNPATH_SIGNING_POLICY_SLUG `+ -ProductionThumbprint $env:SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT `+ -TokenPresent ([bool]$env:SIGNPATH_API_TOKEN)+ "VERSION=$($lane.Version)" >> $env:GITHUB_ENV+ "SIGNING_MODE=$($lane.Mode)" >> $env:GITHUB_ENV+ "SIGNING_POLICY=$($lane.Policy)" >> $env:GITHUB_ENV+ Write-Host "Signing lane: $($lane.Mode)"- name: Install settings dependenciesworking-directory: apps/settings@@ -49,18 +63,18 @@ jobs:- name: Build installershell: pwshenv:- TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}- TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ TAURI_SIGNING_PRIVATE_KEY: ${{ env.SIGNING_MODE != 'Test' && secrets.TAURI_SIGNING_PRIVATE_KEY || '' }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ env.SIGNING_MODE != 'Test' && secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD || '' }}run: ./scripts/build-installer.ps1# Windows code signing through SignPath Foundation (FIRMA-DE-CODIGO.md).- # It runs only once the SignPath repository variables exist; until then- # the release is built unsigned, as before. Two signing requests, each+ # Tag pushes without SignPath remain unsigned, as before. Manual runs+ # are isolated test builds; configured tags require production. Two requests,# approved by hand in SignPath: first the two programs, then the# installer rebuilt around them. The installer must be signed before the# updater signature (.sig) is made, or the updater rejects it.- name: Collect the programs to sign- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ if: env.SIGNING_MODE != 'Unsigned'shell: pwshrun: |New-Item -ItemType Directory -Force sign/binaries | Out-Null@@ -68,7 +82,7 @@ jobs:Copy-Item apps/settings/src-tauri/binaries/muelle-x86_64-pc-windows-msvc.exe sign/binaries/muelle.exe- name: Upload the programs to sign- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ if: env.SIGNING_MODE != 'Unsigned'id: unsigned-binariesuses: actions/upload-artifact@v7with:@@ -76,13 +90,13 @@ jobs:path: sign/binaries- name: Sign the programs- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ if: env.SIGNING_MODE != 'Unsigned'uses: signpath/github-action-submit-signing-request@v3with:api-token: ${{ secrets.SIGNPATH_API_TOKEN }}organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}project-slug: ${{ vars.SIGNPATH_PROJECT_SLUG }}- signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}+ signing-policy-slug: ${{ env.SIGNING_POLICY }}artifact-configuration-slug: binariesgithub-artifact-id: ${{ steps.unsigned-binaries.outputs.artifact-id }}wait-for-completion: true@@ -90,12 +104,24 @@ jobs:wait-for-completion-timeout-in-seconds: 3600output-artifact-directory: sign/binaries-signed+ - name: Verify both signed programs+ if: env.SIGNING_MODE != 'Unsigned'+ shell: pwsh+ env:+ PRODUCTION_THUMBPRINT: ${{ vars.SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT }}+ run: |+ ./scripts/Assert-Authenticode.ps1 -Mode $env:SIGNING_MODE `+ -ProductionThumbprint $env:PRODUCTION_THUMBPRINT -ReportDirectory sign/verification-binaries `+ -Path sign/binaries-signed/muelle.exe,sign/binaries-signed/muelle-settings.exe+# Tauri marks the settings program while bundling; it is already marked# from the first build, so bundling again keeps the signature intact# (checked locally with a test certificate).- name: Rebuild the installer around the signed programs- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ if: env.SIGNING_MODE != 'Unsigned'shell: pwsh+ env:+ PRODUCTION_THUMBPRINT: ${{ vars.SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT }}run: |Copy-Item sign/binaries-signed/muelle-settings.exe target/release/ -ForceCopy-Item sign/binaries-signed/muelle.exe apps/settings/src-tauri/binaries/muelle-x86_64-pc-windows-msvc.exe -Force@@ -104,11 +130,14 @@ jobs:pnpm tauri bundle --bundles nsis --config src-tauri/tauri.bundle.conf.json --config ../../no-updater.jsonif ($LASTEXITCODE) { throw 'tauri bundle failed' }Pop-Location+ ./scripts/Assert-Authenticode.ps1 -Mode $env:SIGNING_MODE `+ -ProductionThumbprint $env:PRODUCTION_THUMBPRINT -ReportDirectory sign/verification-bundled `+ -Path target/release/muelle-settings.exe,apps/settings/src-tauri/binaries/muelle-x86_64-pc-windows-msvc.exeNew-Item -ItemType Directory -Force sign/installer | Out-NullCopy-Item "target/release/bundle/nsis/Muelle_${env:VERSION}_x64-setup.exe" sign/installer/Muelle-Setup.exe- name: Upload the installer to sign- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ if: env.SIGNING_MODE != 'Unsigned'id: unsigned-installeruses: actions/upload-artifact@v7with:@@ -116,56 +145,69 @@ jobs:path: sign/installer- name: Sign the installer- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ if: env.SIGNING_MODE != 'Unsigned'uses: signpath/github-action-submit-signing-request@v3with:api-token: ${{ secrets.SIGNPATH_API_TOKEN }}organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}project-slug: ${{ vars.SIGNPATH_PROJECT_SLUG }}- signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}+ signing-policy-slug: ${{ env.SIGNING_POLICY }}artifact-configuration-slug: installergithub-artifact-id: ${{ steps.unsigned-installer.outputs.artifact-id }}wait-for-completion: truewait-for-completion-timeout-in-seconds: 3600output-artifact-directory: sign/installer-signed- - name: Sign the signed installer for the updater- if: vars.SIGNPATH_ORGANIZATION_ID != ''+ - name: Verify and use the signed installer+ if: env.SIGNING_MODE != 'Unsigned'+ shell: pwsh+ env:+ PRODUCTION_THUMBPRINT: ${{ vars.SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT }}+ run: |+ $setup = (Resolve-Path "target/release/bundle/nsis").Path + "/Muelle_${env:VERSION}_x64-setup.exe"+ Copy-Item sign/installer-signed/Muelle-Setup.exe $setup -Force+ ./scripts/Assert-Authenticode.ps1 -Mode $env:SIGNING_MODE `+ -ProductionThumbprint $env:PRODUCTION_THUMBPRINT -ReportDirectory sign/verification-installer -Path $setup++ - name: Sign the final production installer for the updater+ if: env.SIGNING_MODE == 'Production'shell: pwshenv:TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}- SIGNPATH_SIGNING_POLICY_SLUG: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}run: |$setup = (Resolve-Path "target/release/bundle/nsis").Path + "/Muelle_${env:VERSION}_x64-setup.exe"- Copy-Item sign/installer-signed/Muelle-Setup.exe $setup -Force- $signature = Get-AuthenticodeSignature -LiteralPath $setup- if (-not $signature.SignerCertificate) { throw 'The installer has no Authenticode signer certificate' }- if ($env:SIGNPATH_SIGNING_POLICY_SLUG -eq 'test-signing') {- $testThumbprint = '3A93532146A10D3B1FA8DEAF4192AD4A232FFCAC'- if ($signature.SignerCertificate.Thumbprint -ne $testThumbprint) {- throw "Unexpected SignPath test certificate: $($signature.SignerCertificate.Thumbprint)"- }- $certificatePath = Join-Path $env:RUNNER_TEMP 'muelle-signpath-test.cer'- [IO.File]::WriteAllBytes(- $certificatePath,- $signature.SignerCertificate.Export(- [Security.Cryptography.X509Certificates.X509ContentType]::Cert- )- )- Import-Certificate -FilePath $certificatePath -CertStoreLocation Cert:\CurrentUser\Root | Out-Null- Remove-Item -LiteralPath $certificatePath- $signature = Get-AuthenticodeSignature -LiteralPath $setup- }- if ($signature.Status -ne 'Valid') { throw "The installer signature is $($signature.Status)" }Push-Location apps/settingspnpm tauri signer sign --app-version $env:VERSION $setupif ($LASTEXITCODE) { throw 'tauri signer sign failed' }Pop-Location+ - name: Keep signing artifacts and diagnostics+ if: always() && env.SIGNING_MODE != '' && env.SIGNING_MODE != 'Unsigned'+ uses: actions/upload-artifact@v7+ with:+ name: signpath-${{ env.SIGNING_MODE }}-${{ env.VERSION }}+ path: |+ sign/binaries-signed/+ sign/installer-signed/+ sign/verification-*/+ retention-days: 14+ if-no-files-found: warn++ - name: Explain the test result+ if: always() && env.SIGNING_MODE == 'Test'+ shell: pwsh+ run: |+ @'+ SignPath test lane only. No draft release, latest.json or updater signature is produced.+ Review the verification steps and the signpath-Test artifact, including signature-report.json.+ If a signature remains invalid, send its status/message and the signing request IDs to SignPath support.+ '@ >> $env:GITHUB_STEP_SUMMARY+# latest.json is what the in-app updater reads; Muelle-Setup.exe is a# stable name for the website's "latest" download link.- name: Prepare release files+ if: env.SIGNING_MODE != 'Test'shell: pwshrun: |$nsis = 'target/release/bundle/nsis'@@ -200,6 +242,7 @@ jobs:$section | Set-Content -Encoding utf8NoBOM notes.md- name: Create draft release+ if: env.SIGNING_MODE != 'Test'shell: pwshenv:GH_TOKEN: ${{ github.token }}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6e64f09..eada9d3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,16 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- Settings → Dock → Position on screen: Left, Bottom or Right, as on macOS.+ Bottom stays the default. On a side the dock runs top to bottom below the+ menu bar, icons grow and show their names inward, menus, groups and window+ previews open beside the icon, the genie flies sideways into the dock, a+ hidden dock comes out of its side edge (on any display), and maximized+ windows end beside it. No top position: that edge belongs to the menu bar.+- Separated manual SignPath test builds from public releases and updater output.+ Signature verification now records Windows' detailed result and the file hash,+ checks the expected signer, and keeps strict integrity checks in both modes.+ Test-certificate trust is temporary and restricted to GitHub-hosted runners.- Settings → Menu bar → Show what's playing (issue #28). The music half ofthe island could not be turned off; now it can, and with AI usage off toothe menu bar shows no island at all. Off, Muelle also stops following media@@ -18,6 +28,10 @@ copia la sección de la versión que se publica a la release de GitHub.inside dock groups (issue #26). Force termination runs outside the UI threadagainst process handles captured for that menu. Explorer, critical/shared hostsand inaccessible processes are excluded; cancelling the menu changes nothing.+- Hardened "End task" against windows closed or added while its menu is open,+ including independent windows outside the dock's current desktop. All selected+ processes are checked before termination; an outdated selection is refused+ instead of ending a background process or partially applying the request.- Settings → Windows → Genie speed (issue #27): Normal, Fast or Faster.Normal is the speed the genie always had (0.5 s, close to the macOS Dock)and stays the default; Fast takes 0.35 s and Faster 0.25 s, minimizing and@@ -63,6 +77,17 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Ajustes → Dock → Posición en la pantalla: Izquierda, Abajo o Derecha, como+ en macOS. Abajo sigue siendo la predeterminada. En un lateral el dock va de+ arriba abajo bajo la barra superior, los iconos crecen y muestran su nombre+ hacia dentro, los menús, grupos y vistas previas se abren junto al icono, el+ genio vuela de lado hacia el dock, el dock oculto sale por su borde lateral+ (en cualquier pantalla) y las ventanas maximizadas terminan a su lado. No hay+ posición arriba: ese borde es de la barra superior.+- Separadas las pruebas manuales de SignPath de las releases y el actualizador.+ La verificación registra el detalle de Windows y el hash, comprueba el firmante+ previsto y exige firmas válidas en ambos modos. La confianza del certificado+ de prueba es temporal y se limita a runners alojados de GitHub.- Ajustes → Barra superior → Mostrar lo que se reproduce (issue #28). La partede música de la isla no se podía apagar; ahora sí, y si también desactivas eluso de IA la barra superior no muestra ninguna isla. Apagado, Muelle deja@@ -72,6 +97,10 @@ copia la sección de la versión que se publica a la release de GitHub.del hilo de interfaz y usa los procesos capturados para ese menú. Se excluyenExplorer, procesos críticos/hosts compartidos y procesos sin permisos; cancelarel menú no realiza ninguna acción.+- Reforzado «Finalizar tarea» si se cierran o aparecen ventanas mientras el menú+ sigue abierto, también fuera del escritorio que muestra el dock. Se comprueban+ todos los procesos antes de finalizar: una selección antigua se rechaza en vez+ de terminar un proceso en segundo plano o aplicar parcialmente la petición.- Ajustes → Ventanas → Velocidad del genio (issue #27): Normal, Rápida o Muyrápida. Normal es la velocidad de siempre (0,5 s, cercana al Dock de macOS)y sigue siendo la predeterminada; Rápida dura 0,35 s y Muy rápida 0,25 s,diff --git a/Cargo.lock b/Cargo.lockindex f5a2654..314ed01 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3803,6 +3803,7 @@ name = "spikes"version = "0.0.0"dependencies = ["anyhow",+ "muelle-core","muelle-shell","serde","serde_json",diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 9264a7a..bfc61ba 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -22,10 +22,11 @@ use std::{};use anyhow::{Context, Result};-use muelle_config::{Config, DockGroup};+use muelle_config::{Config, DockGroup, DockPosition};use muelle_core::{attention::Attention,bounce,+ frame::{DockEdge, Frame as DockFrame},layout::{ItemKind, Layout, Metrics, Rect, layout},magnify::{Magnifier, magnify},roster::{Group, Roster},@@ -103,7 +104,7 @@ use crate::{mascot,menu::{self, MenuItem},menubar::{MenuBar, MenuBarWidgets},- multi_window_view::MultiWindowView,+ multi_window_view::{self, MultiWindowView},scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},shell_work::{self, Action as ShellAction},strings::{self, text},@@ -164,6 +165,8 @@ const ATTENTION_HOPS: f32 = 3.0;const FLOAT_MARGIN: f32 = 8.0;const SHADOW_ROOM: f32 = 44.0;const LABEL_ROOM: f32 = 60.0;+/// Widest room kept beside a side dock for an app's name, in logical pixels.+const SIDE_LABEL_MAX: f32 = 320.0;/// Hysteresis distances: the effect starts at the first distance and ends at the second.const ENTER_HALO: f32 = 5.0;const LEAVE_HALO: f32 = 15.0;@@ -422,10 +425,11 @@ enum Outside {copy: bool,},Menu(MenuRequest),- /// The shortcuts folder's contents, as a menu above its icon.+ /// The shortcuts folder's contents, as a menu beside its icon.FolderMenu {folder: String,anchor: POINT,+ placement: menu::Placement,dark: bool,},InputMenu {@@ -446,6 +450,7 @@ struct MenuRequest {target: MenuTarget,items: Vec<MenuItem>,anchor: POINT,+ placement: menu::Placement,dark: bool,}@@ -550,6 +555,11 @@ struct Bounce {#[derive(PartialEq)]struct StageKey {screen: RECT,+ /// The screen edge the dock sits on.+ edge: DockEdge,+ /// The menu bar's strip at the top of this screen: a side dock is+ /// centred in the height below it.+ top_inset: i32,scale: f32,light: bool,glass: bool,@@ -647,17 +657,92 @@ struct Stage {icon: f32,gap: f32,scale: f32,- dock_origin: POINT,- /// Position of the resting dock inside the visual window.- origin: (f32, f32),+ /// The resting dock on the screen: maps dock coordinates (along, across)+ /// to screen pixels and back, whatever edge it is on.+ frame: DockFrame,+ /// The same, inside the visual window.+ window_frame: DockFrame,rest_zone: RECT,hover_zone: RECT,/// Thin strip at the screen edge that reveals the dock when auto-hide is on.edge_zone: RECT,- /// How far the dock slides down to hide completely.+ /// How far the dock slides toward its screen edge to hide completely.slide_distance: f32,}+impl Stage {+ /// Dock coordinates (along, across) of a screen point. Across is+ /// negative away from the screen edge.+ fn to_dock(&self, point: POINT) -> (f32, f32) {+ self.frame.to_dock(point.x as f32, point.y as f32)+ }++ /// The screen box of a box in dock coordinates.+ fn screen_rect(&self, rect: Rect) -> RECT {+ let rect = self.frame.rect(rect);+ RECT {+ left: rect.x.round() as i32,+ top: rect.y.round() as i32,+ right: (rect.x + rect.width).round() as i32,+ bottom: (rect.y + rect.height).round() as i32,+ }+ }++ /// The screen point `gap` pixels off the box `rect` (dock coordinates)+ /// on its side away from the screen edge, centred: where menus and+ /// popups for an icon hang.+ fn beside(&self, rect: Rect, gap: i32) -> POINT {+ let r = self.frame.rect(rect);+ let (middle_x, middle_y) = (+ (r.x + r.width / 2.0).round() as i32,+ (r.y + r.height / 2.0).round() as i32,+ );+ match self.frame.edge {+ DockEdge::Bottom => POINT {+ x: middle_x,+ y: r.y.round() as i32 - gap,+ },+ DockEdge::Left => POINT {+ x: (r.x + r.width).round() as i32 + gap,+ y: middle_y,+ },+ DockEdge::Right => POINT {+ x: r.x.round() as i32 - gap,+ y: middle_y,+ },+ }+ }++ /// Which way a menu or popup for an icon opens: away from the edge.+ fn menu_placement(&self) -> menu::Placement {+ match self.frame.edge {+ DockEdge::Bottom => menu::Placement::Above,+ DockEdge::Left => menu::Placement::Right,+ DockEdge::Right => menu::Placement::Left,+ }+ }++ /// Where the dock starts along the screen axis it runs on.+ fn along_origin(&self) -> f32 {+ if self.frame.edge.is_vertical() {+ self.frame.origin.1+ } else {+ self.frame.origin.0+ }+ }++ /// Whether `point` is within the span of the reveal strip (the pointer+ /// came out of it toward the dock rather than past its end).+ fn spans_reveal(&self, point: POINT) -> bool {+ let zone = self.edge_zone;+ if self.frame.edge.is_vertical() {+ point.y >= zone.top && point.y < zone.bottom+ } else {+ point.x >= zone.left && point.x < zone.right+ }+ }+}+struct ReorderMotion {started: Instant,offsets: Vec<f32>,@@ -694,7 +779,9 @@ struct App {attention_enabled: bool,assets: HashMap<String, Asset>,/// Scale, theme and icon pixel size the cached assets were drawn for.- assets_for: (f32, bool, u32),+ /// Scale, theme, icon size and dock edge the assets were drawn for+ /// (labels point at their icon, so they depend on the edge).+ assets_for: (f32, bool, u32, DockEdge),placeholder: Option<CompositionSurfaceBrush>,remove_label: Option<LabelBrush>,config: Config,@@ -982,15 +1069,15 @@ impl App {}/// `wanted` is the pixel side icons are drawn at: their magnified size.- fn prepare_assets(&mut self, wanted: u32, scale: f32, light: bool) {- if self.assets_for != (scale, light, wanted) {+ fn prepare_assets(&mut self, wanted: u32, scale: f32, light: bool, edge: DockEdge) {+ if self.assets_for != (scale, light, wanted, edge) {self.assets.clear();self.remove_label = None;self.placeholder = None;- self.assets_for = (scale, light, wanted);+ self.assets_for = (scale, light, wanted, edge);}if self.remove_label.is_none() {- self.remove_label = self.gfx.label_brush(text().remove, scale, light).ok();+ self.remove_label = self.gfx.label_brush(text().remove, scale, light, edge).ok();}if self.placeholder.is_none() {self.placeholder = self.gfx.placeholder_brush(wanted, light).ok();@@ -1035,7 +1122,12 @@ impl App {.collect();let label = self.gfx- .label_brush(&shorten(&names.join(", "), GROUP_LABEL_CHARS), scale, light)+ .label_brush(+ &shorten(&names.join(", "), GROUP_LABEL_CHARS),+ scale,+ light,+ edge,+ ).inspect_err(|error| eprintln!("muelle: etiqueta del grupo `{id}`: {error:#}")).ok();self.assets.insert(@@ -1067,7 +1159,7 @@ impl App {}if let Some(hwnd) = window_of(id) {let title = shorten(&tracker::title(hwnd), WINDOW_TITLE_CHARS);- let label = self.gfx.label_brush(&title, scale, light).ok();+ let label = self.gfx.label_brush(&title, scale, light, edge).ok();self.assets.insert(id.clone(),Asset {@@ -1080,7 +1172,7 @@ impl App {}if id == START_ID {let icon = self.gfx.start_brush(wanted).ok();- let label = self.gfx.label_brush(text().start, scale, light).ok();+ let label = self.gfx.label_brush(text().start, scale, light, edge).ok();self.assets.insert(id.clone(),Asset {@@ -1104,7 +1196,7 @@ impl App {let name = visual.map_or_else(|| fallback_name(id), |visual| visual.name.clone());let label = self.gfx- .label_brush(&name, scale, light)+ .label_brush(&name, scale, light, edge).inspect_err(|error| eprintln!("muelle: etiqueta de `{id}`: {error:#}")).ok();self.assets.insert(@@ -1169,8 +1261,11 @@ impl App {let monitor = self.dock_monitor().context("no se pudo consultar el monitor del dock")?;+ let edge = self.position();let key = StageKey {screen: monitor.screen,+ edge,+ top_inset: self.menu_bar_inset(monitor.screen, edge),scale: monitor.scale,light: uses_light_theme(),// A backdrop brush made while Windows had transparency off stays@@ -1208,13 +1303,33 @@ impl App {let px = |logical: f32| (logical * scale).round();let screen = monitor.screen;let screen_width = (screen.right - screen.left) as f32;+ // On a side, the dock runs down the height left under the menu bar.+ let span_start = (screen.top + key.top_inset) as f32;+ let length_room = if edge.is_vertical() {+ screen.bottom as f32 - span_start+ } else {+ screen_width+ };let kinds: Vec<ItemKind> = key.entries.iter().map(|entry| entry.kind).collect();let mut dock = layout(&kinds, &metrics);- let available = (screen_width - 2.0 * px(FLOAT_MARGIN)).max(1.0);- if dock.width > available {+ let available = (length_room - 2.0 * px(FLOAT_MARGIN)).max(1.0);+ // A side dock often fills the height. Magnified, it spreads by up to+ // half its growth past each end, which would put the first icon+ // under the menu bar and the last off screen: room is kept for it.+ // It scales with the icons, so one ratio fits both exactly.+ let spread = if edge.is_vertical() {+ Magnifier {+ range: RANGE_IN_ICONS * (metrics.icon + metrics.gap),+ max_scale,+ }+ .max_growth()+ } else {+ 0.0+ };+ if dock.width + spread > available {// Keep the roster reachable on a smaller display without// changing the user's saved icon size.- metrics = metrics.scaled(available / dock.width);+ metrics = metrics.scaled(available / (dock.width + spread));dock = layout(&kinds, &metrics);}dock.width = dock.width.round();@@ -1225,6 +1340,7 @@ impl App {(metrics.icon * max_scale).round().max(1.0) as u32,scale,theme.light,+ edge,);let magnifier = Magnifier {@@ -1237,26 +1353,81 @@ impl App {// Position relative to the screen, not the work area; the work area// already excludes the strip reserved by the dock.- let dock_x = screen.left as f32 + ((screen_width - dock.width) / 2.0).round();- let dock_y = screen.bottom as f32 - px(FLOAT_MARGIN) - dock.height;+ let margin = px(FLOAT_MARGIN);+ let centred = span_start + ((length_room - dock.width) / 2.0).round();+ let (dock_x, dock_y) = match edge {+ DockEdge::Bottom => (+ screen.left as f32 + ((screen_width - dock.width) / 2.0).round(),+ screen.bottom as f32 - margin - dock.height,+ ),+ DockEdge::Left => (screen.left as f32 + margin, centred),+ DockEdge::Right => (screen.right as f32 - margin - dock.height, centred),+ };+ let frame = DockFrame::new(edge, (dock_x, dock_y), dock.height);// A hidden dock leaves the whole screen to maximized windows.let strip = if self.config.auto_hide {0} else {- (dock.height + 2.0 * px(FLOAT_MARGIN)) as i32+ (dock.height + 2.0 * margin) as i32};- let (dock_right, dock_bottom) = (dock_x + dock.width, dock_y + dock.height);- let zone = move |left: f32, top: f32, right: f32, bottom: f32| RECT {- left: (dock_x - left) as i32,- top: (dock_y - top) as i32,- right: (dock_right + right) as i32,- // A display below this one must not receive the sliding dock- // or its mouse input while the animation crosses the edge.- bottom: ((dock_bottom + bottom) as i32).min(screen.bottom),+ // The resting dock's box on screen: across the edge it is as deep as+ // the layout is tall.+ let (box_width, box_height) = if edge.is_vertical() {+ (dock.height, dock.width)+ } else {+ (dock.width, dock.height)+ };+ let (dock_right, dock_bottom) = (dock_x + box_width, dock_y + box_height);+ // Room around the dock, in its own terms: before and after it along+ // the edge, inward (where icons grow and labels show) and outward.+ // Outward never passes the screen edge: a display beyond it must not+ // receive the sliding dock or its mouse input while it slides.+ let zone = move |before: f32, inward: f32, after: f32, outward: f32| match edge {+ DockEdge::Bottom => RECT {+ left: (dock_x - before) as i32,+ top: (dock_y - inward) as i32,+ right: (dock_right + after) as i32,+ bottom: ((dock_bottom + outward) as i32).min(screen.bottom),+ },+ DockEdge::Left => RECT {+ left: ((dock_x - outward) as i32).max(screen.left),+ top: (dock_y - before) as i32,+ right: (dock_right + inward) as i32,+ bottom: (dock_bottom + after) as i32,+ },+ DockEdge::Right => RECT {+ left: (dock_x - inward) as i32,+ top: (dock_y - before) as i32,+ right: ((dock_right + outward) as i32).min(screen.right),+ bottom: (dock_bottom + after) as i32,+ },};let room = px(SHADOW_ROOM);- let (room_x, room_top) = (room + side_growth, rise + px(LABEL_ROOM));+ // Labels show inward of the icon: above it on the bottom, beside it+ // on a side, where they need their full width.+ let label_room = if edge.is_vertical() {+ let widest = self+ .assets+ .values()+ .filter_map(|asset| asset.label.as_ref())+ .chain(&self.remove_label)+ .map(|label| label.width)+ .fold(0.0_f32, f32::max);+ px(12.0) + widest.min(px(SIDE_LABEL_MAX))+ } else {+ px(LABEL_ROOM)+ };+ let (room_x, room_top) = (room + side_growth, rise + label_room);+ let window_zone = zone(room_x, room_top, room_x, room);+ let window_frame = DockFrame::new(+ edge,+ (+ dock_x - window_zone.left as f32,+ dock_y - window_zone.top as f32,+ ),+ dock.height,+ );let contents: Vec<SlotContent<'_>> = self.entries.iter()@@ -1284,7 +1455,7 @@ impl App {contents: &contents,theme,scale,- origin: (room_x, room_top),+ frame: window_frame,remove_label: self.remove_label.as_ref(),},)?;@@ -1292,6 +1463,7 @@ impl App {// Do not interpolate between monitors or on a theme-only rebuild.if self.fullscreen|| previous.key.screen != key.screen+ || previous.key.edge != key.edge|| previous.scale != scale|| previous.key@@ -1329,10 +1501,10 @@ impl App {};// Start from the currently drawn icon, including any earlier// move still in progress when the user crosses another slot.- previous- .scene- .slot_x(index)- .map_or(0.0, |x| previous.dock_origin.x as f32 + x - dock_x - rect.x)+ let along = if edge.is_vertical() { dock_y } else { dock_x };+ previous.scene.slot_along(index).map_or(0.0, |drawn| {+ previous.along_origin() + drawn - along - rect.x+ })}).collect();offsets@@ -1348,18 +1520,15 @@ impl App {let (enter, leave) = (px(ENTER_HALO), px(LEAVE_HALO));let stage = Stage {key,- window_zone: zone(room_x, room_top, room_x, room),+ window_zone,scene,reorder,magnifier,icon: metrics.icon,gap: metrics.gap,scale,- origin: (room_x, room_top),- dock_origin: POINT {- x: dock_x as i32,- y: dock_y as i32,- },+ frame,+ window_frame,rest_zone: zone(enter, enter, enter, enter),hover_zone: zone(side_growth + leave,@@ -1367,11 +1536,27 @@ impl App {side_growth + leave,leave,),- edge_zone: RECT {- left: (dock_x - side_growth) as i32,- top: screen.bottom - REVEAL_STRIP,- right: (dock_right + side_growth) as i32,- bottom: screen.bottom,+ // The thin strip at the screen edge that reveals a hidden dock,+ // as long as the dock (plus how far its icons spread).+ edge_zone: match edge {+ DockEdge::Bottom => RECT {+ left: (dock_x - side_growth) as i32,+ top: screen.bottom - REVEAL_STRIP,+ right: (dock_right + side_growth) as i32,+ bottom: screen.bottom,+ },+ DockEdge::Left => RECT {+ left: screen.left,+ top: (dock_y - side_growth) as i32,+ right: screen.left + REVEAL_STRIP,+ bottom: (dock_bottom + side_growth) as i32,+ },+ DockEdge::Right => RECT {+ left: screen.right - REVEAL_STRIP,+ top: (dock_y - side_growth) as i32,+ right: screen.right,+ bottom: (dock_bottom + side_growth) as i32,+ },},slide_distance: dock.height + px(FLOAT_MARGIN) + room,layout: dock,@@ -1391,7 +1576,12 @@ impl App {} else {screen};- appbar.reserve(Edge::Bottom, reservation, strip);+ let side = match edge {+ DockEdge::Bottom => Edge::Bottom,+ DockEdge::Left => Edge::Left,+ DockEdge::Right => Edge::Right,+ };+ appbar.reserve(side, reservation, strip);}Ok(())}@@ -1478,10 +1668,7 @@ impl App {.entries.iter().position(|entry| entry.id.as_deref() == Some(drag.id.as_str()))?,- center: (- (drag.point.x - stage.dock_origin.x) as f32,- (drag.point.y - stage.dock_origin.y) as f32,- ),+ center: stage.to_dock(drag.point),removing: drag.removing,ghost: drag.from_group,})@@ -1525,12 +1712,9 @@ impl App {let visible = !self.fullscreen;for (entry, rect) in self.entries.iter().zip(&state.rects) {if let Some(hwnd) = entry.id.as_deref().and_then(window_of) {- let slot = (- stage.origin.0 + rect.x,- stage.origin.1 + rect.y + slide,- rect.width,- rect.height,- );+ let box_ = stage.window_frame.rect(*rect);+ let (slide_x, slide_y) = stage.window_frame.outward(slide);+ let slot = (box_.x + slide_x, box_.y + slide_y, box_.width, box_.height);let has_badge = self.windows.iter()@@ -1574,14 +1758,14 @@ impl App {.iter().position(|entry| entry.members.contains(&id))})?;- let rect = stage.layout.slots.get(index)?.rect;+ let rect = stage.frame.rect(stage.layout.slots.get(index)?.rect);let (width, height) = if aspect >= 1.0 {(rect.width, rect.width / aspect)} else {(rect.height * aspect, rect.height)};- let left = stage.dock_origin.x as f32 + rect.x + (rect.width - width) / 2.0;- let top = stage.dock_origin.y as f32 + rect.y + (rect.height - height) / 2.0;+ let left = rect.x + (rect.width - width) / 2.0;+ let top = rect.y + (rect.height - height) / 2.0;Some(RECT {left: left as i32,top: top as i32,@@ -1697,6 +1881,7 @@ impl App {slot,screen,self.config.genie_speed.seconds(),+ self.position(),)});let Some(flight) = flight else {@@ -1757,6 +1942,7 @@ impl App {frame,screen,self.config.genie_speed.seconds(),+ self.position(),) {self.flights.push(flight);self.last_frame = Instant::now();@@ -1773,9 +1959,9 @@ impl App {// SAFETY: `point` remains alive for the duration of the call.unsafe { GetCursorPos(&mut point)? };- let origin_x = stage.dock_origin.x;+ let (along, _) = stage.to_dock(point);if self.update_drag(point) {- self.cursor = (point.x - origin_x) as f32;+ self.cursor = along;return self.drag_to(point);}let Some(stage) = &self.stage else {@@ -1784,12 +1970,12 @@ impl App {// Keep the active-area boundary aligned with the icons as they grow.let rise = stage.icon * (stage.magnifier.max_scale - 1.0) * self.amount.value;- let ceiling = stage.dock_origin.y as f32 - rise - LEAVE_HALO * stage.scale;- if self.hovering && (point.y as f32) < ceiling {+ let (along, across) = stage.to_dock(point);+ if self.hovering && across < -rise - LEAVE_HALO * stage.scale {return self.on_mouse_leave();}- self.cursor = (point.x - stage.dock_origin.x) as f32;+ self.cursor = along;if !self.hovering {self.hovering = true;self.amount.target = 1.0;@@ -1904,19 +2090,17 @@ impl App {&stage.magnifier,);let rect = &state.rects[index];- let anchor = RECT {- left: stage.dock_origin.x + rect.x.round() as i32,- top: stage.dock_origin.y + rect.y.round() as i32,- right: stage.dock_origin.x + (rect.x + rect.width).round() as i32,- bottom: stage.dock_origin.y + (rect.y + rect.height).round() as i32,- };+ let anchor = stage.screen_rect(*rect);let windows = self.preview_order.windows_of(&self.windows, &candidate);self.preview = Some(MultiWindowView::show(&self.gfx,candidate,windows,- anchor,- stage.key.screen,+ &multi_window_view::Anchor {+ icon: anchor,+ screen: stage.key.screen,+ edge: stage.frame.edge,+ },stage.scale,Theme::for_system(stage.key.light, stage.key.glass),)?);@@ -2313,16 +2497,27 @@ impl App {}}- /// The top edge of the dock, for the crab to walk on. An auto-hidden+ /// The dock's inner rim, for the crab to walk on. An auto-hidden/// dock comes up for the act and goes down after it, as the macOS Dock/// does when something asks for attention.fn dock_edge(&self) -> Option<mascot::Place> {let stage = self.stage.as_ref()?;let margin = (stage.icon / 2.0) as i32;+ let frame = stage.frame;+ // The rim is the dock's side away from the screen edge (dock+ // coordinate across = 0), and the walk runs the dock's length.+ let start = frame.point(0.0, 0.0);+ let end = frame.point(stage.layout.width, 0.0);+ let (from, to, rim) = if frame.edge.is_vertical() {+ (start.1, end.1, start.0)+ } else {+ (start.0, end.0, start.1)+ };Some(mascot::Place::Along {- left: stage.dock_origin.x - margin,- right: stage.dock_origin.x + stage.layout.width as i32 + margin,- top: stage.dock_origin.y,+ left: from as i32 - margin,+ right: to as i32 + margin,+ top: rim as i32,+ edge: frame.edge,})}@@ -2454,7 +2649,7 @@ impl App {return Ok(None);}}- self.hover_at(point.x)?;+ self.hover_at(point)?;self.track_leave()?;Ok(Some(point))}@@ -2508,9 +2703,9 @@ impl App {let id = drag.id.clone();let pinned = self.roster.is_pinned(&id);let group = self.roster.is_group(&id);- let top = stage.dock_origin.y as f32- - stage.icon * (stage.magnifier.max_scale - 1.0 + REMOVE_DISTANCE);- let above = (point.y as f32) < top;+ // How far the pointer is from the dock, away from the screen edge.+ let (_, across) = stage.to_dock(point);+ let above = across < -stage.icon * (stage.magnifier.max_scale - 1.0 + REMOVE_DISTANCE);// A group never leaves the dock this way (it can be ungrouped from// its menu), and an app taken out of a group stays in the dock,// where it was last placed, wherever it is released.@@ -2528,7 +2723,7 @@ impl App {);let explorer = explorer_id();let rise = stage.icon * (stage.magnifier.max_scale - 1.0);- let in_dock = (point.y as f32) >= stage.dock_origin.y as f32 - rise;+ let in_dock = across >= -rise;if !group && in_dock {drag.merge = self.entries@@ -2539,11 +2734,7 @@ impl App {&& entry.id.as_ref().is_some_and(|other| {*other != id && *other != explorer && self.roster.is_pinned(other)})- && group_drop_contains(- rect,- self.cursor,- (point.y - stage.dock_origin.y) as f32,- )+ && group_drop_contains(rect, self.cursor, across)}).and_then(|(entry, _)| entry.id.clone());if drag.merge.is_some() {@@ -2607,11 +2798,11 @@ impl App {/// Hover driven by a drag from another app: OLE takes the mouse, so the/// dock gets no WM_MOUSEMOVE meanwhile.- fn hover_at(&mut self, x: i32) -> Result<()> {+ fn hover_at(&mut self, point: POINT) -> Result<()> {let Some(stage) = &self.stage else {return Ok(());};- self.cursor = (x - stage.dock_origin.x) as f32;+ self.cursor = stage.to_dock(point).0;if !self.hovering {self.hovering = true;self.amount.target = 1.0;@@ -2679,7 +2870,7 @@ impl App {DropAction::Pin { id, before }}- fn on_drag_enter(&mut self, incoming: Vec<String>, x: i32) -> Result<DROPEFFECT> {+ fn on_drag_enter(&mut self, incoming: Vec<String>, point: POINT) -> Result<DROPEFFECT> {self.close_preview();// What a single dropped app or shortcut would pin, worked out once:// drag-over runs on every mouse move, and reading a shortcut is a@@ -2691,11 +2882,11 @@ impl App {};self.incoming = incoming;self.drag_over = true;- self.on_drag_over(x)+ self.on_drag_over(point)}- fn on_drag_over(&mut self, x: i32) -> Result<DROPEFFECT> {- self.hover_at(x)?;+ fn on_drag_over(&mut self, point: POINT) -> Result<DROPEFFECT> {+ self.hover_at(point)?;self.aim_spring();Ok(self.drop_action().effect())}@@ -2770,9 +2961,9 @@ impl App {Ok(self.activating(windows))}- fn on_drop(&mut self, x: i32) -> Result<DROPEFFECT> {+ fn on_drop(&mut self, point: POINT) -> Result<DROPEFFECT> {self.end_drag_over();- self.hover_at(x)?;+ self.hover_at(point)?;let action = self.drop_action();let effect = action.effect();let files = std::mem::take(&mut self.incoming);@@ -2990,9 +3181,13 @@ impl App {/// The shortcuts folder's menu, above its icon. The label hides while/// the menu is open, as for the context menu.fn folder_menu(&mut self, folder: String) -> Result<Option<Outside>> {- let Some(anchor) = self.hovered.and_then(|index| self.anchor_above(index)) else {+ let Some(anchor) = self.hovered.and_then(|index| self.anchor_beside(index)) else {return Ok(None);};+ let placement = self+ .stage+ .as_ref()+ .map_or(menu::Placement::Above, Stage::menu_placement);self.close_preview();self.close_group_view();self.hovered = None;@@ -3001,12 +3196,14 @@ impl App {Ok(Some(Outside::FolderMenu {folder,anchor,+ placement,dark: !uses_light_theme(),}))}- /// Where a menu for the icon at `index` opens: centered just above it.- fn anchor_above(&self, index: usize) -> Option<POINT> {+ /// Where a menu for the icon at `index` opens: just off it, on the side+ /// away from the screen edge (see `Stage::menu_placement`).+ fn anchor_beside(&self, index: usize) -> Option<POINT> {let stage = self.stage.as_ref()?;let state = magnify(&stage.layout,@@ -3016,10 +3213,7 @@ impl App {);let rect = state.rects.get(index)?;let gap = (stage.gap / 2.0).round() as i32;- Some(POINT {- x: stage.dock_origin.x + (rect.x + rect.width / 2.0).round() as i32,- y: stage.dock_origin.y + rect.y.round() as i32 - gap,- })+ Some(stage.beside(*rect, gap))}/// What clicking the app `id` does, in the dock or in an unfolded group:@@ -3064,7 +3258,7 @@ impl App {}}- /// Unfolds the group `id` above its icon.+ /// Unfolds the group `id` beside its icon, away from the screen edge.fn open_group_view(&mut self, id: &str) -> Result<()> {self.close_preview();self.close_group_view();@@ -3087,17 +3281,11 @@ impl App {let Some(rect) = state.rects.get(index) else {return Ok(());};- let anchor = RECT {- left: stage.dock_origin.x + rect.x.round() as i32,- top: stage.dock_origin.y + rect.y.round() as i32,- right: stage.dock_origin.x + (rect.x + rect.width).round() as i32,- bottom: stage.dock_origin.y + (rect.y + rect.height).round() as i32,- };+ let anchor = stage.screen_rect(*rect);let (icon, scale) = (stage.icon.round(), stage.scale);let theme = Theme::for_system(stage.key.light, stage.key.glass);- let Some(monitor) = primary_monitor() else {- return Ok(());- };+ // The dock's own display, which a hidden dock can move between.+ let (screen, edge) = (stage.key.screen, stage.frame.edge);let items = self.group_items(id, icon as u32);self.group_view = Some(GroupView::show(&self.gfx,@@ -3105,7 +3293,8 @@ impl App {&items,&Placement {anchor,- screen: monitor.screen,+ screen,+ edge,scale,icon,theme,@@ -3205,7 +3394,7 @@ impl App {});self.refresh()?;if let Some(stage) = &self.stage {- self.cursor = (point.x - stage.dock_origin.x) as f32;+ self.cursor = stage.to_dock(point).0;}// SAFETY: Capture keeps mouse input while dragging outside the dock.unsafe {@@ -3263,6 +3452,7 @@ impl App {},items,anchor,+ placement: menu::Placement::Above,dark: !uses_light_theme(),})))}@@ -3310,14 +3500,12 @@ impl App {Some((entry.id.clone()?, entry.role, *state.rects.get(index)?))});let gap = (stage.gap / 2.0).round() as i32;+ let stage_placement = stage.menu_placement();let (target, items, anchor) = match target_entry {Some((id, role, rect)) => {let windows = self.windows_of(&id);- let anchor = POINT {- x: stage.dock_origin.x + (rect.x + rect.width / 2.0).round() as i32,- y: stage.dock_origin.y + rect.y.round() as i32 - gap,- };+ let anchor = stage.beside(rect, gap);let (items, end_task) = self.entry_menu(&id, role, &windows);(MenuTarget::Entry {@@ -3331,10 +3519,15 @@ impl App {)}None => {- let anchor = POINT {- x: stage.dock_origin.x + self.cursor.round() as i32,- y: stage.dock_origin.y - gap,- };+ let anchor = stage.beside(+ Rect {+ x: self.cursor,+ y: 0.0,+ width: 0.0,+ height: stage.layout.height,+ },+ gap,+ );let hiding = if self.config.auto_hide {text().turn_hiding_off} else {@@ -3360,6 +3553,7 @@ impl App {target,items,anchor,+ placement: stage_placement,dark: !uses_light_theme(),})))}@@ -3583,7 +3777,7 @@ impl App {if config.language != self.config.language {strings::set_language(config.language);// Labels are drawn text: redraw them in the new language.- self.assets_for = (0.0, false, 0);+ self.assets_for = (0.0, false, 0, DockEdge::Bottom);}if !config.genie {self.restore_transitions();@@ -3593,7 +3787,12 @@ impl App {self.slide.target = if config.auto_hide { 1.0 } else { 0.0 };self.last_frame = Instant::now();}+ let moved = config.dock_position != self.config.dock_position;self.config = config;+ if moved {+ // A hidden dock comes out of its new edge on every display.+ self.apply_edge_settings();+ }// Updates may have been turned on or off.self.schedule_update();self.sync_thumbnails();@@ -4011,6 +4210,33 @@ impl App {self.apply_edge_settings();}+ /// The screen edge chosen in Settings.+ fn position(&self) -> DockEdge {+ match self.config.dock_position {+ DockPosition::Bottom => DockEdge::Bottom,+ DockPosition::Left => DockEdge::Left,+ DockPosition::Right => DockEdge::Right,+ }+ }++ /// How much of `screen`'s top the menu bar keeps, for a dock on a side+ /// edge to start below it. Zero on the bottom edge (not needed there),+ /// when the bar is off or hides itself, and on other displays (the bar+ /// is on the primary one).+ fn menu_bar_inset(&self, screen: RECT, edge: DockEdge) -> i32 {+ if !edge.is_vertical() {+ return 0;+ }+ // From the settings, not the live bar: at startup the dock is placed+ // before the bar exists, and it must not move once the bar appears.+ if !self.config.menu_bar || self.config.menu_bar_auto_hide {+ return 0;+ }+ primary_monitor()+ .filter(|primary| primary.screen == screen)+ .map_or(0, |primary| MenuBar::strip_height(primary.scale))+ }+fn dock_monitor(&self) -> Option<Monitor> {self.dock_display.filter(|_| self.config.auto_hide)@@ -4032,7 +4258,7 @@ impl App {// One display already has the dock's own reveal strip.screens.clear();}- edge_watch::set_dock_monitors(screens);+ edge_watch::set_dock_monitors(screens, self.position());let enabled = watch_dock || (self.menubar.is_some() && self.config.menu_bar_auto_hide);if enabled && self.edge_watch.is_none() {self.edge_watch = EdgeWatch::start(self.visual)@@ -4139,7 +4365,7 @@ impl App {if self.stage.as_ref()- .is_some_and(|stage| point.x >= stage.edge_zone.left && point.x < stage.edge_zone.right)+ .is_some_and(|stage| stage.spans_reveal(point)){return self.on_mouse_move();}@@ -4601,20 +4827,24 @@ pub fn menu_bar_tick() {});}-pub fn drag_enter(files: Vec<String>, x: i32, _y: i32) -> DROPEFFECT {- with_app_value("arrastre de archivos", |app| app.on_drag_enter(files, x))+pub fn drag_enter(files: Vec<String>, x: i32, y: i32) -> DROPEFFECT {+ with_app_value("arrastre de archivos", |app| {+ app.on_drag_enter(files, POINT { x, y })+ })}-pub fn drag_over(x: i32, _y: i32) -> DROPEFFECT {- with_app_value("arrastre de archivos", |app| app.on_drag_over(x))+pub fn drag_over(x: i32, y: i32) -> DROPEFFECT {+ with_app_value("arrastre de archivos", |app| {+ app.on_drag_over(POINT { x, y })+ })}pub fn drag_leave() {with_app("arrastre de archivos", App::on_drag_leave);}-pub fn drop_files(x: i32, _y: i32) -> DROPEFFECT {- with_app_value("soltar archivos", |app| app.on_drop(x))+pub fn drop_files(x: i32, y: i32) -> DROPEFFECT {+ with_app_value("soltar archivos", |app| app.on_drop(POINT { x, y }))}/// Checks the recycle bin on a background thread by scanning each drive@@ -4775,6 +5005,7 @@ fn run_outside(outside: Outside) {&request.items,request.anchor,request.dark,+ request.placement,);with_app("menú cerrado", App::after_menu);if let Some(command) = chosen {@@ -4786,13 +5017,14 @@ fn run_outside(outside: Outside) {Outside::FolderMenu {folder,anchor,+ placement,dark,} => {with_app("abrir carpeta de accesos directos", |app| {app.menu_open = true;app.render()});- let chosen = folder_menu::show(main_window(), &folder, anchor, dark);+ let chosen = folder_menu::show(main_window(), &folder, anchor, dark, placement);with_app("menú cerrado", App::after_menu);if let Some(path) = chosen {submit(ShellAction::Open { id: path });@@ -5167,7 +5399,7 @@ pub fn run() -> Result<()> {attention: Attention::default(),attention_enabled: status::taskbar_badges_enabled(),assets: HashMap::new(),- assets_for: (0.0, false, 0),+ assets_for: (0.0, false, 0, DockEdge::Bottom),placeholder: None,remove_label: None,config,diff --git a/apps/dock/src/edge_watch.rs b/apps/dock/src/edge_watch.rsindex d6572eb..1a9e240 100644--- a/apps/dock/src/edge_watch.rs+++ b/apps/dock/src/edge_watch.rs@@ -7,6 +7,7 @@ use std::{};use anyhow::Result;+use muelle_core::frame::DockEdge;use windows::Win32::{Foundation::{HWND, LPARAM, POINT, RECT, WPARAM},System::Threading::GetCurrentThreadId,@@ -47,7 +48,9 @@ pub enum Reveal {struct Edges {window: isize,top: Option<RECT>,- bottoms: Vec<RECT>,+ /// The displays a hidden dock can be revealed on, and the edge it sits on.+ screens: Vec<RECT>,+ dock_edge: DockEdge,pointer_screen: Option<RECT>,target: Option<Target>,entered: Option<Instant>,@@ -56,7 +59,8 @@ struct Edges {static EDGES: Mutex<Edges> = Mutex::new(Edges {window: 0,top: None,- bottoms: Vec::new(),+ screens: Vec::new(),+ dock_edge: DockEdge::Bottom,pointer_screen: None,target: None,entered: None,@@ -70,13 +74,18 @@ impl Edges {}) {return Some(Target::MenuBar);}+ // The menu bar, checked first, keeps the top corners.screen- .filter(|screen| point.y >= screen.bottom - EDGE_DEPTH)+ .filter(|screen| match self.dock_edge {+ DockEdge::Bottom => point.y >= screen.bottom - EDGE_DEPTH,+ DockEdge::Left => point.x < screen.left + EDGE_DEPTH,+ DockEdge::Right => point.x >= screen.right - EDGE_DEPTH,+ }).map(Target::Dock)}fn observe(&mut self, point: POINT, now: Instant) -> bool {- let screen = self.bottoms.iter().copied().find(|screen| {+ let screen = self.screens.iter().copied().find(|screen| {(screen.left..screen.right).contains(&point.x)&& (screen.top..screen.bottom).contains(&point.y)});@@ -101,14 +110,15 @@ impl Edges {}}- fn set_bottoms(&mut self, bottoms: Vec<RECT>) {+ fn set_screens(&mut self, screens: Vec<RECT>, edge: DockEdge) {if let Some(Target::Dock(screen)) = self.target- && !bottoms.contains(&screen)+ && (!screens.contains(&screen) || edge != self.dock_edge){self.target = None;self.entered = None;}- self.bottoms = bottoms;+ self.screens = screens;+ self.dock_edge = edge;}fn dwell(&mut self, point: POINT, now: Instant) -> Reveal {@@ -134,8 +144,9 @@ pub fn set_menu_bar(top: Option<RECT>) {lock().set_top(top);}-pub fn set_dock_monitors(bottoms: Vec<RECT>) {- lock().set_bottoms(bottoms);+/// The displays a hidden dock can come out on, from `edge` of each.+pub fn set_dock_monitors(screens: Vec<RECT>, edge: DockEdge) {+ lock().set_screens(screens, edge);}pub fn poll(point: POINT) -> Reveal {@@ -303,6 +314,37 @@ mod tests {}}+ #[test]+ fn a_side_dock_comes_out_of_its_side_and_the_menu_bar_keeps_the_corner() {+ let screen = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };+ let mut edges = Edges::default();+ edges.set_top(Some(RECT {+ bottom: 35,+ ..screen+ }));+ edges.set_screens(vec![screen], DockEdge::Left);+ assert_eq!(+ edges.at(POINT { x: 0, y: 500 }, Some(screen)),+ Some(Target::Dock(screen))+ );+ assert_eq!(edges.at(POINT { x: 900, y: 1079 }, Some(screen)), None);+ assert_eq!(+ edges.at(POINT { x: 0, y: 0 }, Some(screen)),+ Some(Target::MenuBar)+ );+ edges.set_screens(vec![screen], DockEdge::Right);+ assert_eq!(+ edges.at(POINT { x: 1919, y: 500 }, Some(screen)),+ Some(Target::Dock(screen))+ );+ assert_eq!(edges.at(POINT { x: 0, y: 500 }, Some(screen)), None);+ }+#[test]fn menu_bar_reveals_sooner_without_changing_dock_switching_delay() {let start = Instant::now();@@ -316,7 +358,7 @@ mod tests {let bottom = POINT { x: 700, y: 1079 };let mut edges = Edges::default();edges.set_top(Some(screen));- edges.set_bottoms(vec![screen]);+ edges.set_screens(vec![screen], DockEdge::Bottom);edges.observe(top, start);assert!(matches!(edges.dwell(top, start + MENU_DWELL),@@ -369,7 +411,7 @@ mod tests {bottom: 824,};let mut edges = Edges::default();- edges.set_bottoms(vec![primary, secondary]);+ edges.set_screens(vec![primary, secondary], DockEdge::Bottom);let start = Instant::now();let left = POINT { x: -700, y: 823 };let right = POINT { x: 700, y: 1079 };@@ -379,7 +421,7 @@ mod tests {assert!(matches!(edges.dwell(left, start + DWELL * 2), Reveal::Ready(Target::Dock(screen)) if screen == secondary));- edges.set_bottoms(vec![primary]);+ edges.set_screens(vec![primary], DockEdge::Bottom);assert!(matches!(edges.dwell(left, start + DWELL * 3), Reveal::Idle));}@@ -397,7 +439,7 @@ mod tests {..primary};let mut edges = Edges::default();- edges.set_bottoms(vec![primary, secondary]);+ edges.set_screens(vec![primary, secondary], DockEdge::Bottom);let now = Instant::now();assert!(edges.observe(POINT { x: 700, y: 500 }, now));assert!(edges.observe(POINT { x: 2500, y: 500 }, now));@@ -408,12 +450,15 @@ mod tests {#[test]fn pending_reveal_cancels_when_the_pointer_crosses_the_edge() {let mut edges = Edges::default();- edges.set_bottoms(vec![RECT {- left: 0,- top: -900,- right: 1600,- bottom: 0,- }]);+ edges.set_screens(+ vec![RECT {+ left: 0,+ top: -900,+ right: 1600,+ bottom: 0,+ }],+ DockEdge::Bottom,+ );let start = Instant::now();assert!(edges.observe(POINT { x: 800, y: -1 }, start));assert!(matches!(diff --git a/apps/dock/src/flight.rs b/apps/dock/src/flight.rsindex 0b7d5d6..5c2f1e4 100644--- a/apps/dock/src/flight.rs+++ b/apps/dock/src/flight.rs@@ -40,6 +40,12 @@//! Many DWM thumbnails instead of a snapshot were measured and rejected: DWM//! drops frames beyond about 16 of them (plan section 8).//!+//! On a dock at the left or right edge the genie runs the same way, in a+//! frame turned a quarter ([`Turn`]): the window flows "down" into the slot+//! in that frame, which the overlay shows turned toward the dock. The copy+//! of the window is turned to match on the capture worker. A pure rotation,+//! never a mirror, so its pixels stay as they were.+//!//! Everything lives on a transparent overlay window that exists only while//! the animation runs. The system's own minimize animation must already be//! off for the window (see `App::calm_windows`): it starts before the dock@@ -56,7 +62,10 @@ use std::{};use anyhow::Result;-use muelle_core::genie::{Edges, Genie};+use muelle_core::{+ frame::DockEdge,+ genie::{Edges, Genie},+};use muelle_shell::{icons::IconImage, screen, tracker};use windows::{Foundation::TimeSpan,@@ -81,7 +90,7 @@ use windows::{},core::{HSTRING, Interface, h, w},};-use windows_numerics::{Matrix3x2, Vector2};+use windows_numerics::{Matrix3x2, Matrix4x4, Vector2};use crate::gfx::Gfx;@@ -130,9 +139,11 @@ impl Drop for CapturePermit {/// Half the resolution in each direction: a quarter of the memory, and the/// softness does not show in a half-second animation.pub struct Snapshot {+ /// Turned for the dock's edge at the time (see [`Turn`]).image: IconImage,/// Where the window was, in screen coordinates.window: RECT,+ edge: DockEdge,}impl Snapshot {@@ -143,6 +154,117 @@ impl Snapshot {}}+/// The genie's frame on a dock at the left or right edge: the overlay+/// (`width` x `height` screen pixels) turned a quarter, so the window flows+/// toward the dock as it flows down toward a bottom dock.+#[derive(Clone, Copy, Debug, PartialEq)]+struct Turn {+ edge: DockEdge,+ width: f32,+ height: f32,+}++impl Turn {+ fn new(edge: DockEdge, screen: RECT) -> Self {+ Self {+ edge,+ width: (screen.right - screen.left) as f32,+ height: (screen.bottom - screen.top) as f32,+ }+ }++ /// The frame's size: the overlay's, turned on the sides.+ fn size(self) -> (f32, f32) {+ if self.edge.is_vertical() {+ (self.height, self.width)+ } else {+ (self.width, self.height)+ }+ }++ /// Overlay-local edges in the frame.+ fn edges(self, local: Edges) -> Edges {+ match self.edge {+ DockEdge::Bottom => local,+ // Frame x runs down the screen, frame y toward the left edge.+ DockEdge::Left => Edges {+ left: local.top,+ right: local.bottom,+ top: self.width - local.right,+ bottom: self.width - local.left,+ },+ // Frame x runs up the screen, frame y toward the right edge.+ DockEdge::Right => Edges {+ left: self.height - local.bottom,+ right: self.height - local.top,+ top: local.left,+ bottom: local.right,+ },+ }+ }++ /// The frame shown in the overlay (row vectors, as Composition).+ fn matrix(self) -> Option<Matrix4x4> {+ let (m11, m12, m21, m22, m41, m42) = match self.edge {+ DockEdge::Bottom => return None,+ DockEdge::Left => (0.0, 1.0, -1.0, 0.0, self.width, 0.0),+ DockEdge::Right => (0.0, -1.0, 1.0, 0.0, 0.0, self.height),+ };+ Some(Matrix4x4 {+ M11: m11,+ M12: m12,+ M21: m21,+ M22: m22,+ M33: 1.0,+ M41: m41,+ M42: m42,+ M44: 1.0,+ ..Matrix4x4::default()+ })+ }++ /// Turns the overlay's root into the frame. Its size becomes the+ /// frame's, or the clip at the slot would cut the turned strips off.+ fn apply(self, root: &ContainerVisual) -> Result<()> {+ if let Some(matrix) = self.matrix() {+ let (width, height) = self.size();+ root.SetRelativeSizeAdjustment(Vector2 { X: 0.0, Y: 0.0 })?;+ root.SetSize(Vector2 {+ X: width,+ Y: height,+ })?;+ root.SetTransformMatrix(matrix)?;+ }+ Ok(())+ }++ /// A copy of the window as it reads in the frame.+ fn image(self, image: IconImage) -> IconImage {+ if !self.edge.is_vertical() {+ return image;+ }+ let (w, h) = (image.width as usize, image.height as usize);+ let mut bgra = vec![0u8; w * h * 4];+ // In the frame the image is `h` wide and `w` tall.+ for fy in 0..w {+ for fx in 0..h {+ let (x, y) = match self.edge {+ DockEdge::Left => (w - 1 - fy, fx),+ _ => (fy, h - 1 - fx),+ };+ let from = (y * w + x) * 4;+ let to = (fy * h + fx) * 4;+ bgra[to..to + 4].copy_from_slice(&image.bgra[from..from + 4]);+ }+ }+ IconImage {+ width: image.height,+ height: image.width,+ bgra,+ }+ }+}+struct Piece {visual: SpriteVisual,/// First source row and row count, in snapshot pixels.@@ -190,6 +312,9 @@ pub struct Flight {root: ContainerVisual,/// The monitor the overlay covers.screen: RECT,+ /// The frame the genie runs in, and the window's screen rectangle.+ turn: Turn,+ source: RECT,genie: Genie,/// The dock slot is known (a minimize learns it a little after it starts).aimed: bool,@@ -457,8 +582,8 @@ fn launch(}/// Nothing is drawn below the slot: strips vanish as they enter it.-fn clip_at_slot(gfx: &Gfx, root: &ContainerVisual, genie: &Genie, screen: RECT) -> Result<()> {- let below = (screen.bottom - screen.top) as f32 - genie.slot.bottom;+fn clip_at_slot(gfx: &Gfx, root: &ContainerVisual, genie: &Genie, turn: Turn) -> Result<()> {+ let below = turn.size().1 - genie.slot.bottom;let clip = gfx.compositor.CreateInsetClipWithInsets(0.0, 0.0, 0.0, below.max(0.0))?;@@ -491,7 +616,9 @@ impl Flight {frame: RECT,screen: RECT,seconds: f32,+ edge: DockEdge,) -> Option<Self> {+ let turn = Turn::new(edge, screen);// A timed-out GDI call cannot be cancelled safely. Keep at most one// outstanding copy, including a worker whose overlay was abandoned.let capture_permit = CapturePermit::acquire()?;@@ -511,6 +638,14 @@ impl Flight {}return None;};+ if turn.apply(&root).is_err() {+ // SAFETY: Our own windows, destroyed once.+ unsafe {+ let _ = DestroyWindow(stand);+ let _ = DestroyWindow(overlay);+ }+ return None;+ }// SAFETY: Both are the live windows created above; they are destroyed// here on failure, or by `Drop`.let thumbnail = unsafe {@@ -557,9 +692,12 @@ impl Flight {.name("muelle-capture".into()).spawn(move || {let _permit = capture_permit;- let shot = screen::capture(visible).map(|image| Captured {- restore: halved(&image),- image,+ let shot = screen::capture(visible).map(|image| {+ let image = turn.image(image);+ Captured {+ restore: halved(&image),+ image,+ }});let _ = sender.send(shot);});@@ -572,7 +710,7 @@ impl Flight {}return None;}- let window = local(visible, screen);+ let window = turn.edges(local(visible, screen));Some(Self {hwnd,created_at: Instant::now(),@@ -583,6 +721,8 @@ impl Flight {_target: target,root,screen,+ turn,+ source: visible,// Until `aim`, the slot is the window itself.genie: Genie {window,@@ -611,20 +751,26 @@ impl Flight {slot: RECT,screen: RECT,seconds: f32,+ edge: DockEdge,) -> Option<Self> {- let window = intersect(snapshot.window, screen);- if is_empty(window) {+ // A copy turned for another edge (the dock moved meanwhile) would+ // fly sideways: the window just comes back.+ let source = intersect(snapshot.window, screen);+ if is_empty(source) || snapshot.edge != edge {return None;}+ let turn = Turn::new(edge, screen);let (overlay, target, root) = create_overlay(gfx, screen)?;- let height = (window.bottom - window.top) as u32;let genie = Genie {- window: local(window, screen),- slot: local(slot, screen),+ window: turn.edges(local(source, screen)),+ slot: turn.edges(local(slot, screen)),};+ let height = (genie.window.bottom - genie.window.top) as u32;let image = &snapshot.image;let size = (image.width as f32, image.height as f32);- let drive = clip_at_slot(gfx, &root, &genie, screen)+ let drive = turn+ .apply(&root)+ .and_then(|()| clip_at_slot(gfx, &root, &genie, turn)).and_then(|()| cut(gfx, &root, image, height)).and_then(|pieces| bind(gfx, &genie, &pieces, size, true)).and_then(|drive| launch(gfx, &genie, &drive, true, seconds).map(|()| drive));@@ -645,6 +791,8 @@ impl Flight {_target: target,root,screen,+ turn,+ source,genie,aimed: true,phase: Phase::Flying {@@ -738,11 +886,11 @@ impl Flight {/// Gives a minimize its dock slot (a screen rectangle).pub fn aim(&mut self, gfx: &Gfx, slot: RECT) {- self.genie.slot = local(slot, self.screen);+ self.genie.slot = self.turn.edges(local(slot, self.screen));self.aimed = true;// Without the clip the flight still works; strips would only show a// little below the slot.- let _ = clip_at_slot(gfx, &self.root, &self.genie, self.screen);+ let _ = clip_at_slot(gfx, &self.root, &self.genie, self.turn);}/// Puts the flight right under `dock` in the z-order, so a window flying@@ -770,11 +918,11 @@ impl Flight {activation_is_current(self.restoring, self.foreground, self.hwnd, foreground)}- /// Width of the flying window divided by its height.+ /// Width of the flying window divided by its height, on screen.#[must_use]pub fn aspect(&self) -> f32 {- let window = self.genie.window;- (window.right - window.left) / (window.bottom - window.top).max(1.0)+ let window = self.source;+ (window.right - window.left) as f32 / (window.bottom - window.top).max(1) as f32}/// `true`, once, when the real window has to be restored: the restore@@ -787,9 +935,12 @@ impl Flight {/// The snapshot of a window that has just been minimized, to restore it/// with the genie later.pub fn take_snapshot_for_restore(&mut self) -> Option<Snapshot> {- self.captured- .take()- .map(|(image, window)| Snapshot { image, window })+ let edge = self.turn.edge;+ self.captured.take().map(|(image, window)| Snapshot {+ image,+ window,+ edge,+ })}/// Opacity (0..=255) of the dock's own thumbnail for this window: it@@ -811,13 +962,7 @@ impl Flight {/// genie and starts it.fn take_off(&mut self, gfx: &Gfx, captured: Captured) -> Result<CompositionPropertySet> {let Captured { image, restore } = captured;- let edges = self.genie.window;- let window = RECT {- left: edges.left as i32 + self.screen.left,- top: edges.top as i32 + self.screen.top,- right: edges.right as i32 + self.screen.left,- bottom: edges.bottom as i32 + self.screen.top,- };+ let window = self.source;let pieces = cut(gfx, &self.root, &image, image.height)?;let size = (image.width as f32, image.height as f32);let drive = bind(gfx, &self.genie, &pieces, size, false)?;@@ -864,6 +1009,76 @@ impl Drop for Flight {mod tests {use super::*;+ fn edges(left: f32, top: f32, right: f32, bottom: f32) -> Edges {+ Edges {+ left,+ top,+ right,+ bottom,+ }+ }++ /// The frame shown through `matrix` puts every point back where it was+ /// on screen, and the slot (at the dock) is "below" the window in it.+ #[test]+ fn a_turned_frame_maps_back_to_the_screen_and_flows_toward_the_dock() {+ let screen = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };+ let window = edges(600.0, 200.0, 1400.0, 800.0);+ for (edge, slot) in [+ (DockEdge::Left, edges(20.0, 500.0, 70.0, 550.0)),+ (DockEdge::Right, edges(1850.0, 500.0, 1900.0, 550.0)),+ ] {+ let turn = Turn::new(edge, screen);+ let m = turn.matrix().unwrap_or_default();+ let show =+ |x: f32, y: f32| (x * m.M11 + y * m.M21 + m.M41, x * m.M12 + y * m.M22 + m.M42);+ let frame = turn.edges(window);+ // Two opposite corners land on two opposite corners of the window.+ let corners = [show(frame.left, frame.top), show(frame.right, frame.bottom)];+ for (x, y) in corners {+ assert!(x == window.left || x == window.right, "{edge:?} {x}");+ assert!(y == window.top || y == window.bottom, "{edge:?} {y}");+ }+ let slot = turn.edges(slot);+ assert!(+ slot.top > frame.bottom,+ "{edge:?}: the slot is beyond the window"+ );+ let (width, height) = turn.size();+ assert!(frame.right <= width && slot.bottom <= height);+ }+ }++ #[test]+ fn a_turned_copy_keeps_every_pixel_once() {+ // 3x2 image, each pixel's blue channel its index.+ let image = IconImage {+ width: 3,+ height: 2,+ bgra: (0..6u8).flat_map(|i| [i, 0, 0, 255]).collect(),+ };+ let screen = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };+ for edge in [DockEdge::Left, DockEdge::Right] {+ let turned = Turn::new(edge, screen).image(image.clone());+ assert_eq!((turned.width, turned.height), (2, 3));+ let mut seen: Vec<u8> = turned.bgra.chunks(4).map(|px| px[0]).collect();+ seen.sort_unstable();+ assert_eq!(seen, vec![0, 1, 2, 3, 4, 5]);+ }+ let same = Turn::new(DockEdge::Bottom, screen).image(image.clone());+ assert_eq!(same, image);+ }+#[test]fn minimizing_keeps_its_capture_when_focus_passes_to_the_next_window() {assert!(activation_is_current(false, 10, 10, 20));@@ -972,8 +1187,16 @@ mod native_tests {right: 250,bottom: 170,};- let mut flight = Flight::start(&gfx, source.0.0 as isize, from, from, screen, 0.5)- .ok_or_else(|| anyhow::anyhow!("could not create the native animation"))?;+ let mut flight = Flight::start(+ &gfx,+ source.0.0 as isize,+ from,+ from,+ screen,+ 0.5,+ DockEdge::Bottom,+ )+ .ok_or_else(|| anyhow::anyhow!("could not create the native animation"))?;let overlay = flight.overlay;let stand = flight.stand;let unrelated = if flight.foreground != 123 { 123 } else { 124 };diff --git a/apps/dock/src/folder_menu.rs b/apps/dock/src/folder_menu.rsindex 7da5d0b..fbcb392 100644--- a/apps/dock/src/folder_menu.rs+++ b/apps/dock/src/folder_menu.rs@@ -19,8 +19,8 @@ use windows::{UI::WindowsAndMessaging::{CreatePopupMenu, DestroyMenu, GetForegroundWindow, GetMenuItemCount, HMENU,InsertMenuItemW, MENUITEMINFOW, MFS_DISABLED, MIIM_BITMAP, MIIM_ID, MIIM_STATE,- MIIM_STRING, MIIM_SUBMENU, PostMessageW, SetForegroundWindow, TPM_BOTTOMALIGN,- TPM_CENTERALIGN, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx, WM_NULL,+ MIIM_STRING, MIIM_SUBMENU, PostMessageW, SetForegroundWindow, TPM_RETURNCMD,+ TPM_RIGHTBUTTON, TrackPopupMenuEx, WM_NULL,},},core::{HSTRING, PWSTR},@@ -60,14 +60,20 @@ thread_local! {static OPEN: RefCell<Option<Open>> = const { RefCell::new(None) };}-/// Shows the contents of `folder` as a menu whose bottom edge is centered-/// at `anchor`, and returns the path of the item chosen (`None` if+/// Shows the contents of `folder` as a menu on the `placement` side of+/// `anchor`, and returns the path of the item chosen (`None` if/// dismissed). Folders inside are submenus and are never returned.////// Runs a modal loop that keeps dispatching messages to the dock, whose/// window procedure hands `WM_INITMENUPOPUP` to [`init_popup`]. The caller/// must not hold the app state meanwhile.-pub fn show(owner: HWND, folder: &str, anchor: POINT, dark: bool) -> Option<String> {+pub fn show(+ owner: HWND,+ folder: &str,+ anchor: POINT,+ dark: bool,+ placement: crate::menu::Placement,+) -> Option<String> {crate::menu::apply_theme(dark);// SAFETY: The menu is destroyed below, with its submenus.let root = unsafe { CreatePopupMenu() }.ok()?;@@ -81,7 +87,7 @@ pub fn show(owner: HWND, folder: &str, anchor: POINT, dark: bool) -> Option<Strilet _ = SetForegroundWindow(owner);let chosen = TrackPopupMenuEx(root,- (TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_BOTTOMALIGN | TPM_CENTERALIGN).0,+ (TPM_RETURNCMD | TPM_RIGHTBUTTON | placement.native_flags()).0,anchor.x,anchor.y,owner,diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rsindex 9da4c5b..569452a 100644--- a/apps/dock/src/gfx.rs+++ b/apps/dock/src/gfx.rs@@ -2,6 +2,7 @@//! icons and masks to be drawn on compositor surfaces.use anyhow::{Context, Result};+use muelle_core::frame::DockEdge;use muelle_shell::icons::IconImage;use windows::{Foundation::Size,@@ -397,9 +398,16 @@ impl Gfx {})}- /// Creates an app-name label: a dark pill (light in light theme) with a- /// downward-pointing arrow.- pub fn label_brush(&self, text: &str, scale: f32, light: bool) -> Result<LabelBrush> {+ /// Creates an app-name label: a dark pill (light in light theme) with an+ /// arrow pointing at the icon: down on a bottom dock, toward the screen+ /// edge on a side dock (the label sits beside the icon there).+ pub fn label_brush(+ &self,+ text: &str,+ scale: f32,+ light: bool,+ edge: DockEdge,+ ) -> Result<LabelBrush> {let (pad_x, pad_y, arrow) = (11.0 * scale, 5.0 * scale, 6.0 * scale);let (fill, ink) = if light {(rgb(0.96, 0.96, 0.97, 0.92), rgb(0.0, 0.0, 0.0, 0.88))@@ -428,51 +436,65 @@ impl Gfx {};let body_height = (metrics.height + 2.0 * pad_y).ceil();- let width = (metrics.width + 2.0 * pad_x).ceil();- let height = body_height + arrow;+ let body_width = (metrics.width + 2.0 * pad_x).ceil();+ let (width, height) = if edge.is_vertical() {+ (body_width + arrow, body_height)+ } else {+ (body_width, body_height + arrow)+ };+ // Where the pill starts: after the arrow on a left dock's label.+ let body_left = if edge == DockEdge::Left { arrow } else { 0.0 };+ // The arrow: its base on the pill (1 px into it, so no seam shows)+ // and its tip pointing at the icon.+ let (base_a, base_b, tip) = match edge {+ DockEdge::Bottom => (+ (width / 2.0 - arrow, body_height - 1.0),+ (width / 2.0 + arrow, body_height - 1.0),+ (width / 2.0, height),+ ),+ DockEdge::Left => (+ (arrow + 1.0, height / 2.0 - arrow),+ (arrow + 1.0, height / 2.0 + arrow),+ (0.0, height / 2.0),+ ),+ DockEdge::Right => (+ (body_width - 1.0, height / 2.0 - arrow),+ (body_width - 1.0, height / 2.0 + arrow),+ (width, height / 2.0),+ ),+ };let brush = self.draw(width as u32, height as u32, |dc| {let body = D2D1_ROUNDED_RECT {rect: D2D_RECT_F {- left: 0.0,+ left: body_left,top: 0.0,- right: width,+ right: body_left + body_width,bottom: body_height,},radiusX: 7.0 * scale,radiusY: 7.0 * scale,};- let middle = width / 2.0;// SAFETY: All created objects remain alive until the end of the block.unsafe {let fill = dc.CreateSolidColorBrush(&fill, None)?;dc.FillRoundedRectangle(&body, &fill);- // The arrow triangle hangs from the center of the pill and- // overlaps it by 1 px to avoid a visible seam.let triangle = dc.GetFactory()?.CreatePathGeometry()?;let sink = triangle.Open()?;- sink.BeginFigure(- Vector2 {- X: middle - arrow,- Y: body_height - 1.0,- },- D2D1_FIGURE_BEGIN_FILLED,- );- sink.AddLine(Vector2 {- X: middle + arrow,- Y: body_height - 1.0,- });- sink.AddLine(Vector2 {- X: middle,- Y: height,- });+ let point = |(x, y): (f32, f32)| Vector2 { X: x, Y: y };+ sink.BeginFigure(point(base_a), D2D1_FIGURE_BEGIN_FILLED);+ sink.AddLine(point(base_b));+ sink.AddLine(point(tip));sink.EndFigure(D2D1_FIGURE_END_CLOSED);sink.Close()?;dc.FillGeometry(&triangle, &fill, None);let ink = dc.CreateSolidColorBrush(&ink, None)?;dc.DrawTextLayout(- Vector2 { X: pad_x, Y: pad_y },+ Vector2 {+ X: body_left + pad_x,+ Y: pad_y,+ },&layout,&ink,D2D1_DRAW_TEXT_OPTIONS_NONE,diff --git a/apps/dock/src/group_view.rs b/apps/dock/src/group_view.rsindex b0a7f63..9c9bb71 100644--- a/apps/dock/src/group_view.rs+++ b/apps/dock/src/group_view.rs@@ -7,6 +7,7 @@use std::time::Instant;use anyhow::Result;+use muelle_core::frame::DockEdge;use muelle_shell::{system::animations_enabled, tracker};use windows::{UI::{@@ -87,6 +88,8 @@ pub struct Placement {/// The group's icon on screen.pub anchor: RECT,pub screen: RECT,+ /// The screen edge the dock is on: the group opens away from it.+ pub edge: DockEdge,pub scale: f32,/// Side of the apps' icons, in pixels.pub icon: f32,@@ -115,7 +118,17 @@ struct GroupLayout {}impl GroupLayout {- fn new(screen: RECT, anchor: RECT, scale: f32, icon: f32, count: usize) -> Self {+ fn new(+ screen: RECT,+ anchor: RECT,+ edge: DockEdge,+ scale: f32,+ icon: f32,+ count: usize,+ ) -> Self {+ if edge.is_vertical() {+ return Self::beside(screen, anchor, edge, scale, icon, count);+ }let center = (anchor.left + anchor.right) as f32 / 2.0;let bottom = anchor.top as f32 - LIFT * scale;let pitch = icon + FAN_SPACING * scale;@@ -175,11 +188,68 @@ impl GroupLayout {/// Rows of cells on a panel centered over the group. Apps that would/// not fit on the screen are left out (it takes a hundred or so).fn grid(screen: RECT, center: f32, bottom: f32, scale: f32, icon: f32, count: usize) -> Self {+ let usable = (+ (screen.right - screen.left) as f32 - 2.0 * MARGIN * scale,+ bottom - screen.top as f32 - MARGIN * scale,+ );+ Self::grid_in(scale, icon, count, usable, |width, height| {+ let left = (center - width / 2.0).round().clamp(+ screen.left as f32,+ (screen.right as f32 - width).max(screen.left as f32),+ );+ (left, (bottom - height).round().max(screen.top as f32))+ })+ }++ /// On a side dock, the same grid beside the group, centred on it and+ /// away from the screen edge (a fan is a column: it has no side).+ fn beside(+ screen: RECT,+ anchor: RECT,+ edge: DockEdge,+ scale: f32,+ icon: f32,+ count: usize,+ ) -> Self {+ let gap = LIFT * scale;+ let margin = MARGIN * scale;+ let middle = (anchor.top + anchor.bottom) as f32 / 2.0;+ let (start, end) = if edge == DockEdge::Left {+ (anchor.right as f32 + gap, screen.right as f32 - margin)+ } else {+ (screen.left as f32 + margin, anchor.left as f32 - gap)+ };+ let usable = (+ end - start,+ (screen.bottom - screen.top) as f32 - 2.0 * margin,+ );+ Self::grid_in(scale, icon, count, usable, |width, height| {+ let left = if edge == DockEdge::Left {+ start+ } else {+ end - width+ };+ let top = (middle - height / 2.0).round().clamp(+ screen.top as f32,+ (screen.bottom as f32 - height).max(screen.top as f32),+ );+ (left.round(), top)+ })+ }++ /// The grid's cells for `count` apps within `usable` (width, height),+ /// the panel placed where `place` (its size) says.+ fn grid_in(+ scale: f32,+ icon: f32,+ count: usize,+ usable: (f32, f32),+ place: impl Fn(f32, f32) -> (f32, f32),+ ) -> Self {let pad = GRID_PADDING * scale;let cell_width = (icon * 1.8).max(GRID_CELL_MIN * scale).round();let cell_height = (icon + (2.0 * GRID_ICON_TOP + GRID_TEXT) * scale).round();- let usable_width = (screen.right - screen.left) as f32 - 2.0 * MARGIN * scale;- let usable_height = bottom - screen.top as f32 - MARGIN * scale;+ let (usable_width, usable_height) = usable;let max_columns = (((usable_width - 2.0 * pad) / cell_width).floor() as usize).max(1);let max_rows = (((usable_height - 2.0 * pad) / cell_height).floor() as usize).max(1);let columns = ((count as f32).sqrt().ceil() as usize)@@ -189,11 +259,7 @@ impl GroupLayout {let rows = shown.div_ceil(columns).max(1);let width = 2.0 * pad + columns as f32 * cell_width;let height = 2.0 * pad + rows as f32 * cell_height;- let left = (center - width / 2.0).round().clamp(- screen.left as f32,- (screen.right as f32 - width).max(screen.left as f32),- );- let top = (bottom - height).round().max(screen.top as f32);+ let (left, top) = place(width, height);let bounds = RECT {left: left as i32,top: top as i32,@@ -279,6 +345,7 @@ pub struct GroupView {targets: Vec<RECT>,panel: Option<ContainerVisual>,anchor: RECT,+ edge: DockEdge,scale: f32,theme: Theme,opened: Instant,@@ -299,6 +366,7 @@ impl GroupView {let layout = GroupLayout::new(place.screen,place.anchor,+ place.edge,place.scale,place.icon,items.len(),@@ -341,6 +409,7 @@ impl GroupView {targets: Vec::new(),panel: None,anchor: place.anchor,+ edge: place.edge,scale: place.scale,theme: place.theme,opened: Instant::now(),@@ -555,11 +624,17 @@ impl GroupView {let eased = 1.0 - (1.0 - progress).powi(3);let side = (icon.right - icon.left) as f32;let (left, top) = (icon.left as f32, icon.top as f32);- // The fan comes out of the group's icon; the grid rises a little.+ // The fan comes out of the group's icon; the grid comes a little+ // way out of the dock.+ let rise = 24.0 * self.scale;let (from_x, from_y) = if self.layout.fan {(start.0 - side / 2.0, start.1 - side)} else {- (left, top + 24.0 * self.scale)+ match self.edge {+ DockEdge::Bottom => (left, top + rise),+ DockEdge::Left => (left - rise, top),+ DockEdge::Right => (left + rise, top),+ }};visual.root.SetOffset(v3(from_x + (left - from_x) * eased,@@ -893,7 +968,7 @@ mod tests {#[test]fn a_few_apps_should_unfold_as_a_fan_going_up_from_the_group() {- let layout = GroupLayout::new(SCREEN, anchor(900), 1.0, 48.0, 4);+ let layout = GroupLayout::new(SCREEN, anchor(900), DockEdge::Bottom, 1.0, 48.0, 4);assert!(layout.fan);assert!(layout.bounds.bottom <= anchor(900).top);let tops: Vec<i32> = layout.icons.iter().map(|icon| icon.top).collect();@@ -906,7 +981,7 @@ mod tests {#[test]fn many_apps_or_a_short_screen_should_unfold_as_a_grid() {- assert!(!GroupLayout::new(SCREEN, anchor(900), 1.0, 48.0, 30).fan);+ assert!(!GroupLayout::new(SCREEN, anchor(900), DockEdge::Bottom, 1.0, 48.0, 30).fan);let short = RECT {bottom: 400,..SCREEN@@ -916,7 +991,7 @@ mod tests {bottom: 388,..anchor(900)};- assert!(!GroupLayout::new(short, low, 1.0, 48.0, 8).fan);+ assert!(!GroupLayout::new(short, low, DockEdge::Bottom, 1.0, 48.0, 8).fan);}#[test]@@ -924,7 +999,14 @@ mod tests {for scale in [1.0, 1.5, 2.0] {for left in [0, 900, 1872] {for count in [1, 3, 10, 40] {- let layout = GroupLayout::new(SCREEN, anchor(left), scale, 48.0 * scale, count);+ let layout = GroupLayout::new(+ SCREEN,+ anchor(left),+ DockEdge::Bottom,+ scale,+ 48.0 * scale,+ count,+ );let bounds = layout.bounds;assert!(bounds.left >= SCREEN.left && bounds.right <= SCREEN.right);assert!(bounds.top >= SCREEN.top && bounds.bottom <= anchor(left).top);@@ -938,9 +1020,45 @@ mod tests {}}+ #[test]+ fn on_a_side_dock_the_group_opens_beside_it_and_on_screen() {+ for (edge, icon) in [+ (+ DockEdge::Left,+ RECT {+ left: 14,+ top: 500,+ right: 62,+ bottom: 548,+ },+ ),+ (+ DockEdge::Right,+ RECT {+ left: 1858,+ top: 500,+ right: 1906,+ bottom: 548,+ },+ ),+ ] {+ for count in [2, 9, 60] {+ let layout = GroupLayout::new(SCREEN, icon, edge, 1.25, 60.0, count);+ let bounds = layout.bounds;+ assert!(!layout.fan);+ assert!(bounds.top >= SCREEN.top && bounds.bottom <= SCREEN.bottom);+ if edge == DockEdge::Left {+ assert!(bounds.left >= icon.right && bounds.right <= SCREEN.right);+ } else {+ assert!(bounds.right <= icon.left && bounds.left >= SCREEN.left);+ }+ }+ }+ }+#[test]fn grid_cells_should_not_overlap() {- let layout = GroupLayout::new(SCREEN, anchor(900), 1.0, 48.0, 23);+ let layout = GroupLayout::new(SCREEN, anchor(900), DockEdge::Bottom, 1.0, 48.0, 23);assert_eq!(layout.cells.len(), 23);for (index, cell) in layout.cells.iter().enumerate() {let center = POINT {diff --git a/apps/dock/src/mascot.rs b/apps/dock/src/mascot.rsindex 7f595f5..7910a51 100644--- a/apps/dock/src/mascot.rs+++ b/apps/dock/src/mascot.rs@@ -12,6 +12,7 @@use std::time::{Duration, Instant};use anyhow::Result;+use muelle_core::frame::DockEdge;use muelle_shell::icons::IconImage;use windows::{Foundation::TimeSpan,@@ -30,7 +31,7 @@ use windows::{},core::{HSTRING, Interface, h, w},};-use windows_numerics::{Vector2, Vector3};+use windows_numerics::{Matrix4x4, Vector2, Vector3};use crate::gfx::Gfx;@@ -299,8 +300,58 @@ pub enum Place {/// Below a point of the menu bar's island: `x` is the centre, `top` the/// bar's bottom edge.Under { x: i32, top: i32 },- /// Walking on an edge (the top of the dock): `top` is the edge.- Along { left: i32, right: i32, top: i32 },+ /// Walking on the dock's inner rim. `left..right` is the span along the+ /// dock and `top` the rim (screen y on a bottom dock; the screen x of its+ /// inner side on a left or right one, where the crab walks up the wall).+ Along {+ left: i32,+ right: i32,+ top: i32,+ edge: DockEdge,+ },+}++/// The act is choreographed upright, in a "scene" `width` long and `height`+/// tall with the rim at the bottom; on a side dock the window holds it+/// turned a quarter (a pure rotation, so the sprites are never mirrored).+#[derive(Clone, Copy)]+struct Turn {+ edge: DockEdge,+ width: f32,+ height: f32,+}++impl Turn {+ /// Scene point of a point in the window.+ fn to_scene(self, x: f32, y: f32) -> (f32, f32) {+ match self.edge {+ DockEdge::Bottom => (x, y),+ // Head toward the screen's inside: right on a left dock...+ DockEdge::Left => (y, self.height - x),+ // ...left on a right dock, walking from the bottom up.+ DockEdge::Right => (self.width - y, x),+ }+ }++ /// The scene's transform into the window (row vectors, as Composition).+ fn matrix(self) -> Option<Matrix4x4> {+ let (m11, m12, m21, m22, m41, m42) = match self.edge {+ DockEdge::Bottom => return None,+ DockEdge::Left => (0.0, 1.0, -1.0, 0.0, self.height, 0.0),+ DockEdge::Right => (0.0, -1.0, 1.0, 0.0, 0.0, self.width),+ };+ Some(Matrix4x4 {+ M11: m11,+ M12: m12,+ M21: m21,+ M22: m22,+ M33: 1.0,+ M41: m41,+ M42: m42,+ M44: 1.0,+ ..Matrix4x4::default()+ })+ }}/// One act, in seconds and cells, independent of the screen.@@ -443,6 +494,8 @@ pub struct Mascot {started: Instant,/// The window's top-left corner on screen, and the crab's size.origin: POINT,+ /// How the upright scene sits in the window.+ turn: Turn,crab: (f32, f32),crab_top: f32,cell: f32,@@ -487,8 +540,13 @@ impl Mascot {headroom,)}- Place::Along { left, right, top } => {- // Feet one cell into the edge, as if standing on its rim.+ // Feet one cell into the rim, as if standing on it.+ Place::Along {+ left,+ right,+ top,+ edge: DockEdge::Bottom,+ } => {let bottom = top + cell as i32;(RECT {@@ -500,9 +558,41 @@ impl Mascot {headroom,)}+ Place::Along {+ left: start,+ right: end,+ top: rim,+ edge,+ } => {+ let feet = if edge == DockEdge::Left {+ rim - cell as i32+ } else {+ rim + cell as i32 - height as i32+ };+ (+ RECT {+ left: feet,+ top: start,+ right: feet + height as i32,+ bottom: end,+ },+ headroom,+ )+ }+ };+ let turn = match place {+ Place::Along { edge, .. } if edge.is_vertical() => Turn {+ edge,+ width: (rect.bottom - rect.top) as f32,+ height,+ },+ _ => Turn {+ edge: DockEdge::Bottom,+ width: (rect.right - rect.left) as f32,+ height: (rect.bottom - rect.top) as f32,+ },};- let width = (rect.right - rect.left) as f32;- let script = Script::new(act, width, crab.0);+ let script = Script::new(act, turn.width, crab.0);let hwnd = create_window(rect)?;let built = || -> Result<(DesktopWindowTarget, ContainerVisual, SpriteVisual)> {@@ -513,6 +603,9 @@ impl Mascot {.CreateDesktopWindowTarget(hwnd, true)?};let (root, reaction, poke_heart) = choreograph(gfx, &script, crab, crab_top, cell)?;+ if let Some(matrix) = turn.matrix() {+ root.SetTransformMatrix(matrix)?;+ }target.SetRoot(&root)?;Ok((target, reaction, poke_heart))};@@ -541,6 +634,7 @@ impl Mascot {x: rect.left,y: rect.top,},+ turn,crab,crab_top,cell,@@ -566,9 +660,13 @@ impl Mascot {{return;}- let left = self.origin.x as f32 + self.script.x_at(t);- let top = self.origin.y as f32 + self.crab_top;- let (x, y) = (point.x as f32, point.y as f32);+ // Compared in the upright scene, whichever way the window holds it.+ let left = self.script.x_at(t);+ let top = self.crab_top;+ let (x, y) = self.turn.to_scene(+ (point.x - self.origin.x) as f32,+ (point.y - self.origin.y) as f32,+ );if x < left|| x >= left + self.crab.0|| y < top - 3.0 * self.cell@@ -933,3 +1031,33 @@ mod tests {Ok(())}}++#[cfg(test)]+mod turn_tests {+ use super::*;++ /// The scene's rim (bottom) lands on the dock side of the window, and+ /// `to_scene` undoes the window transform.+ #[test]+ fn a_turned_scene_stands_on_the_dock_and_maps_back() {+ for edge in [DockEdge::Left, DockEdge::Right] {+ let turn = Turn {+ edge,+ width: 600.0,+ height: 80.0,+ };+ let m = turn.matrix().unwrap_or_default();+ let to_window =+ |x: f32, y: f32| (x * m.M11 + y * m.M21 + m.M41, x * m.M12 + y * m.M22 + m.M42);+ // Feet (scene bottom) at the dock: left side of a left dock's+ // window, right side of a right dock's.+ let (feet_x, _) = to_window(300.0, 80.0);+ assert_eq!(feet_x, if edge == DockEdge::Left { 0.0 } else { 80.0 });+ for (x, y) in [(0.0, 0.0), (123.0, 40.0), (600.0, 80.0)] {+ let (wx, wy) = to_window(x, y);+ let (sx, sy) = turn.to_scene(wx, wy);+ assert!((sx - x).abs() < 1e-3 && (sy - y).abs() < 1e-3, "{edge:?}");+ }+ }+ }+}diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rsindex 3c0ebe3..054a59d 100644--- a/apps/dock/src/menu.rs+++ b/apps/dock/src/menu.rs@@ -51,7 +51,8 @@ use windows::{SPI_GETSCREENREADER, SW_SHOWNA, SWP_NOACTIVATE,SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetCursor, SetForegroundWindow, SetTimer,SetWindowPos, ShowWindow, SystemParametersInfoW, TPM_BOTTOMALIGN, TPM_CENTERALIGN,- TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TPM_TOPALIGN, TrackPopupMenuEx,+ TPM_LEFTALIGN, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTALIGN, TPM_RIGHTBUTTON,+ TPM_TOPALIGN, TPM_VCENTERALIGN, TRACK_POPUP_MENU_FLAGS, TrackPopupMenuEx,TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CANCELMODE, WM_CAPTURECHANGED,WM_CHAR, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE,WM_NULL, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SYSKEYDOWN, WM_TIMER,@@ -88,13 +89,20 @@ impl MenuItem {}}-/// Shows the menu with its bottom edge centered at `anchor` and returns the+/// Shows the menu on the `placement` side of `anchor` and returns the/// selected command (`None` if dismissed).////// Runs a modal loop that continues dispatching messages to dock windows./// The caller must not hold the app state while this function runs.-pub fn show(gfx: &Gfx, owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {- show_at(gfx, owner, items, anchor, dark, Placement::Above)+pub fn show(+ gfx: &Gfx,+ owner: HWND,+ items: &[MenuItem],+ anchor: POINT,+ dark: bool,+ placement: Placement,+) -> Option<u32> {+ show_at(gfx, owner, items, anchor, dark, placement)}pub fn show_below(@@ -107,10 +115,39 @@ pub fn show_below(show_at(gfx, owner, items, anchor, dark, Placement::Below)}-#[derive(Clone, Copy)]-enum Placement {+/// Where a menu opens from its anchor point: above it, centred (an icon on+/// a bottom dock), below it, or beside it, centred vertically (an icon on a+/// side dock: to its right on a left dock, to its left on a right one).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Placement {Above,Below,+ Right,+ Left,+}++impl Placement {+ /// The same placement for `TrackPopupMenuEx`.+ #[must_use]+ pub fn native_flags(self) -> TRACK_POPUP_MENU_FLAGS {+ match self {+ Self::Above => TPM_CENTERALIGN | TPM_BOTTOMALIGN,+ Self::Below => TPM_CENTERALIGN | TPM_TOPALIGN,+ Self::Right => TPM_LEFTALIGN | TPM_VCENTERALIGN,+ Self::Left => TPM_RIGHTALIGN | TPM_VCENTERALIGN,+ }+ }++ /// Top-left corner of a `w` x `h` menu placed from `anchor`, before+ /// keeping it on screen.+ fn corner(self, anchor: POINT, w: i32, h: i32) -> (i32, i32) {+ match self {+ Self::Above => (anchor.x - w / 2, anchor.y - h),+ Self::Below => (anchor.x - w / 2, anchor.y),+ Self::Right => (anchor.x, anchor.y - h / 2),+ Self::Left => (anchor.x - w, anchor.y - h / 2),+ }+ }}fn show_at(@@ -360,7 +397,7 @@ impl Popup {}}- // Above the anchor, centered on it, and inside its monitor.+ // Placed from the anchor, and inside its monitor.let mut monitor = MONITORINFO {cbSize: size_of::<MONITORINFO>() as u32,..Default::default()@@ -375,15 +412,12 @@ impl Popup {let screen: RECT = monitor.rcMonitor;let (w, h) = (width as i32, height as i32);let margin = px(MARGIN) as i32;- let left = (anchor.x - w / 2).clamp(+ let (left, top) = placement.corner(anchor, w, h);+ let left = left.clamp(screen.left + margin,(screen.right - margin - w).max(screen.left + margin),);- let top = match placement {- Placement::Above => anchor.y - h,- Placement::Below => anchor.y,- }- .clamp(+ let top = top.clamp(screen.top + margin,(screen.bottom - margin - h).max(screen.top + margin),);@@ -880,15 +914,7 @@ fn show_native(let _ = SetForegroundWindow(owner);let chosen = TrackPopupMenuEx(menu,- (TPM_RETURNCMD- | TPM_NONOTIFY- | TPM_RIGHTBUTTON- | TPM_CENTERALIGN- | match placement {- Placement::Above => TPM_BOTTOMALIGN,- Placement::Below => TPM_TOPALIGN,- })- .0,+ (TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON | placement.native_flags()).0,anchor.x,anchor.y,owner,diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 6bbc4cf..f827803 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -1033,6 +1033,12 @@ impl MenuBar {}/// Hidden while an app is full screen.+ /// How tall the bar is at `scale`: the strip it keeps at the top of the+ /// primary display unless it hides itself. A side dock starts below it.+ pub fn strip_height(scale: f32) -> i32 {+ (HEIGHT * scale).round() as i32+ }+pub fn set_visible(&mut self, visible: bool) -> Result<()> {if self.visible == visible {return Ok(());diff --git a/apps/dock/src/multi_window_view.rs b/apps/dock/src/multi_window_view.rsindex f50a86b..0060382 100644--- a/apps/dock/src/multi_window_view.rs+++ b/apps/dock/src/multi_window_view.rs@@ -4,6 +4,7 @@use std::time::{Duration, Instant};use anyhow::Result;+use muelle_core::frame::DockEdge;use muelle_shell::{system::animations_enabled, tracker};use windows::{UI::{@@ -54,11 +55,21 @@ struct MultiWindowLayout {bounds: RECT,cards: Vec<RECT>,per_page: usize,+ /// The screen edge the dock is on: the view opens away from it.+ edge: DockEdge,}impl MultiWindowLayout {- fn new(screen: RECT, anchor: RECT, scale: f32, count: usize) -> Self {- let available = ((screen.right - screen.left) as f32 - 32.0 * scale).max(1.0);+ fn new(screen: RECT, anchor: RECT, edge: DockEdge, scale: f32, count: usize) -> Self {+ let gap = (10.0 * scale) as i32;+ // On a side dock the row of previews sits beside the icon, in the+ // width left between the dock and the far side of the screen.+ let room = match edge {+ DockEdge::Bottom => screen.right - screen.left,+ DockEdge::Left => screen.right - anchor.right - gap,+ DockEdge::Right => anchor.left - gap - screen.left,+ };+ let available = (room as f32 - 32.0 * scale).max(1.0);let per_page = (((available - 2.0 * PADDING * scale) / ((CARD_WIDTH + GAP) * scale))as usize).clamp(1, 5);@@ -70,9 +81,17 @@ impl MultiWindowLayout {+ shown.saturating_sub(1) as f32 * GAP * scale).ceil() as i32;let height = ((2.0 * PADDING + header + CARD_HEIGHT + ARC) * scale).ceil() as i32;- let left = ((anchor.left + (anchor.right - anchor.left) / 2) - width / 2)- .clamp(screen.left, (screen.right - width).max(screen.left));- let top = (anchor.top - height - (10.0 * scale) as i32).max(screen.top);+ let middle_y = (anchor.top + (anchor.bottom - anchor.top) / 2) - height / 2;+ let beside_top = middle_y.clamp(screen.top, (screen.bottom - height).max(screen.top));+ let (left, top) = match edge {+ DockEdge::Bottom => (+ ((anchor.left + (anchor.right - anchor.left) / 2) - width / 2)+ .clamp(screen.left, (screen.right - width).max(screen.left)),+ (anchor.top - height - gap).max(screen.top),+ ),+ DockEdge::Left => ((anchor.right + gap).min(screen.right - width), beside_top),+ DockEdge::Right => ((anchor.left - gap - width).max(screen.left), beside_top),+ };let cards = (0..shown).map(|index| {let across = if shown > 1 {@@ -99,6 +118,7 @@ impl MultiWindowLayout {},cards,per_page,+ edge,}}@@ -110,17 +130,23 @@ impl MultiWindowLayout {if contains(self.bounds, point) || contains(anchor, point) {return true;}- // A bridge just above the source icon lets the pointer reach the view- // without keeping the popup open over unrelated applications.- contains(- RECT {- left: anchor.left,- right: anchor.right,+ // A bridge between the source icon and the view lets the pointer reach+ // it without keeping the popup open over unrelated applications.+ let bridge = match self.edge {+ DockEdge::Bottom => RECT {top: self.bounds.bottom.min(anchor.top),- bottom: anchor.bottom,+ ..anchor+ },+ DockEdge::Left => RECT {+ right: self.bounds.left.max(anchor.right),+ ..anchor},- point,- )+ DockEdge::Right => RECT {+ left: self.bounds.right.min(anchor.left),+ ..anchor+ },+ };+ contains(bridge, point)}}@@ -153,13 +179,20 @@ pub struct MultiWindowView {foreground: isize,}+/// Where the view opens: the app's icon and display, and the screen edge+/// the dock is on.+pub struct Anchor {+ pub icon: RECT,+ pub screen: RECT,+ pub edge: DockEdge,+}+impl MultiWindowView {pub fn show(gfx: &Gfx,app_id: String,windows: Vec<isize>,- anchor: RECT,- screen: RECT,+ at: &Anchor,scale: f32,theme: Theme,) -> Result<Self> {@@ -195,9 +228,9 @@ impl MultiWindowView {hwnd,target: None,thumbnails: Thumbnails::new(hwnd),- layout: MultiWindowLayout::new(screen, anchor, scale, windows.len()),+ layout: MultiWindowLayout::new(at.screen, at.icon, at.edge, scale, windows.len()),windows,- anchor,+ anchor: at.icon,scale,theme,page: 0,@@ -395,11 +428,22 @@ impl MultiWindowView {let hovered = self.layout.hit(self.local_cursor()?);let center = (self.anchor.left + (self.anchor.right - self.anchor.left) / 2- self.layout.bounds.left) as f32;+ let travel = (1.0 - eased) * 36.0 * self.scale;for (index, (card, rect)) in self.cards.iter().zip(&self.layout.cards).enumerate() {let width = (rect.right - rect.left) as f32;- let start_x = center - width / 2.0;- let x = start_x + (rect.left as f32 - start_x) * eased;- let y = rect.top as f32 + (1.0 - eased) * 36.0 * self.scale;+ // Above a bottom dock the cards fan out of the icon and rise; beside+ // a side dock they slide out of it.+ let (x, y) = match self.layout.edge {+ DockEdge::Bottom => {+ let start_x = center - width / 2.0;+ (+ start_x + (rect.left as f32 - start_x) * eased,+ rect.top as f32 + travel,+ )+ }+ DockEdge::Left => (rect.left as f32 - travel, rect.top as f32),+ DockEdge::Right => (rect.left as f32 + travel, rect.top as f32),+ };card.root.SetOffset(Vector3 { X: x, Y: y, Z: 0.0 })?;card.root.SetOpacity(eased)?;card.highlight@@ -604,17 +648,20 @@ mod tests {&gfx,"test".into(),windows.clone(),- RECT {- left: 280,- top: 600,- right: 340,- bottom: 670,- },- RECT {- left: 0,- top: 0,- right: 640,- bottom: 720,+ &Anchor {+ icon: RECT {+ left: 280,+ top: 600,+ right: 340,+ bottom: 670,+ },+ screen: RECT {+ left: 0,+ top: 0,+ right: 640,+ bottom: 720,+ },+ edge: DockEdge::Bottom,},1.0,theme,@@ -681,7 +728,7 @@ mod tests {right: left + 60,bottom: 1020,};- let layout = MultiWindowLayout::new(screen, anchor, scale, 12);+ let layout = MultiWindowLayout::new(screen, anchor, DockEdge::Bottom, scale, 12);assert!(layout.bounds.left >= screen.left && layout.bounds.right <= screen.right);for rect in &layout.cards {assert!(@@ -695,6 +742,50 @@ mod tests {}}+ #[test]+ fn beside_a_side_dock_the_previews_open_inward_and_keep_a_bridge() {+ let screen = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };+ for (edge, anchor) in [+ (+ DockEdge::Left,+ RECT {+ left: 14,+ top: 480,+ right: 74,+ bottom: 540,+ },+ ),+ (+ DockEdge::Right,+ RECT {+ left: 1846,+ top: 480,+ right: 1906,+ bottom: 540,+ },+ ),+ ] {+ let layout = MultiWindowLayout::new(screen, anchor, edge, 1.25, 7);+ let bounds = layout.bounds;+ assert!(bounds.left >= screen.left && bounds.right <= screen.right);+ assert!(bounds.top >= screen.top && bounds.bottom <= screen.bottom);+ let gap_x = if edge == DockEdge::Left {+ assert!(bounds.left >= anchor.right);+ (anchor.right + bounds.left) / 2+ } else {+ assert!(bounds.right <= anchor.left);+ (bounds.right + anchor.left) / 2+ };+ assert!(layout.keeps_open(anchor, POINT { x: gap_x, y: 510 }));+ assert!(!layout.keeps_open(anchor, POINT { x: gap_x, y: 40 }));+ }+ }+#[test]fn pointer_should_cross_gap_from_icon_without_dismissing() {let anchor = RECT {@@ -711,6 +802,7 @@ mod tests {bottom: 1080,},anchor,+ DockEdge::Bottom,1.0,2,);@@ -745,6 +837,7 @@ mod tests {right: 660,bottom: 730,},+ DockEdge::Bottom,1.0,20,);diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rsindex b84baa7..382ccee 100644--- a/apps/dock/src/scene.rs+++ b/apps/dock/src/scene.rs@@ -5,6 +5,7 @@ use std::cell::Cell;use anyhow::Result;use muelle_core::{+ frame::{DockEdge, Frame as DockFrame},layout::{ItemKind, Layout, Rect},magnify::Magnified,};@@ -211,7 +212,9 @@ pub struct SceneInput<'a> {pub contents: &'a [SlotContent<'a>],pub theme: Theme,pub scale: f32,- pub origin: (f32, f32),+ /// Where the resting dock sits in the visual window, and on which edge:+ /// every position the scene draws goes through it.+ pub frame: DockFrame,/// Shown above an icon dragged out of the dock.pub remove_label: Option<&'a LabelBrush>,}@@ -348,7 +351,7 @@ mod attention_tests {contents: &contents,theme: Theme::for_system(light, true),scale,- origin: (0.0, 0.0),+ frame: DockFrame::new(DockEdge::Bottom, (0.0, 0.0), layout.height),remove_label: None,},)?;@@ -404,7 +407,7 @@ mod attention_tests {#[derive(Clone, Copy)]pub struct Drag {pub index: usize,- /// Icon center, relative to the resting dock origin.+ /// Icon center in dock coordinates (along, across the dock).pub center: (f32, f32),/// Released here, the icon would leave the dock.pub removing: bool,@@ -422,7 +425,8 @@ pub struct Frame<'a> {pub drag: Option<Drag>,/// The icon the dragged app would join in a group if released now.pub target: Option<usize>,- /// Vertical offset of the whole dock (auto-hide), in pixels.+ /// How far the whole dock has slid toward the screen edge (auto-hide),+ /// in pixels.pub slide: f32,/// Align to whole pixels; only at rest, where sharpness matters.pub snap: bool,@@ -450,7 +454,7 @@ impl Label {pub struct Scene {pub root: ContainerVisual,- origin: (f32, f32),+ frame: DockFrame,height: f32,stroke: f32,label_gap: f32,@@ -478,8 +482,21 @@ pub struct Scene {}impl Scene {- pub fn slot_x(&self, index: usize) -> Option<f32> {- Some(self.slots.get(index)?.Offset().ok()?.X)+ /// Where the slot is drawn now, along the dock, in dock coordinates.+ pub fn slot_along(&self, index: usize) -> Option<f32> {+ let offset = self.slots.get(index)?.Offset().ok()?;+ let size = self.slots.get(index)?.Size().ok()?;+ // The box's top-left maps from a different dock corner on each edge;+ // its centre maps from its centre on all of them.+ let (along, _) = self+ .frame+ .to_dock(offset.X + size.X / 2.0, offset.Y + size.Y / 2.0);+ let length = if self.frame.edge.is_vertical() {+ size.Y+ } else {+ size.X+ };+ Some(along - length / 2.0)}pub fn build(gfx: &Gfx, input: &SceneInput<'_>) -> Result<Self> {@@ -488,7 +505,7 @@ impl Scene {layout,theme,scale,- origin,+ frame,..} = *input;let radius = layout.height * 0.36;@@ -519,8 +536,8 @@ impl Scene {layers.InsertAtTop(&glass)?;layers.InsertAtTop(&rim)?;+ // Children are placed in window coordinates through `frame`.let content = c.CreateContainerVisual()?;- content.SetOffset(v3(origin.0, origin.1))?;let children = content.Children()?;let indicator_size = (4.0 * scale).round();let dot = c.CreateEllipseGeometry()?;@@ -592,7 +609,7 @@ impl Scene {Ok(Self {root,- origin,+ frame,height: layout.height,stroke,label_gap: 8.0 * scale,@@ -647,7 +664,9 @@ impl Scene {snap,} = *frame;let fit = |value: f32| if snap { value.round() } else { value };- self.root.SetOffset(v3(0.0, slide))?;+ let place = |rect: Rect| self.frame.rect(rect);+ let (slide_x, slide_y) = self.frame.outward(slide);+ self.root.SetOffset(v3(slide_x, slide_y))?;self.raise(drag.map(|drag| drag.index))?;self.place_merge(target.and_then(|index| {Some((@@ -656,8 +675,14 @@ impl Scene {))}))?;- let size = v2(fit(state.right - state.left), self.height);- let offset = v3(self.origin.0 + fit(state.left), self.origin.1);+ let plate = place(Rect {+ x: fit(state.left),+ y: 0.0,+ width: fit(state.right - state.left),+ height: self.height,+ });+ let size = v2(plate.width, plate.height);+ let offset = v3(plate.x, plate.y);for frame in &self.frames {frame.SetSize(size)?;frame.SetOffset(offset)?;@@ -678,6 +703,24 @@ impl Scene {Some(drag) => (drag.center.0 - width / 2.0, drag.center.1 - height / 2.0),None => (x, y - lifts.get(index).copied().unwrap_or(0.0)),};+ // In dock coordinates up to here; from here on, in the window.+ let dot = place(Rect {+ x: x + (width - self.indicator_size) / 2.0,+ y: self.indicator_y,+ width: self.indicator_size,+ height: self.indicator_size,+ });+ let Rect {+ x,+ y,+ width,+ height,+ } = place(Rect {+ x,+ y,+ width,+ height,+ });if let Some(visual) = self.slots.get(index) {visual.SetOffset(v3(fit(x), fit(y)))?;@@ -718,22 +761,35 @@ impl Scene {}if let Some(Some(indicator)) = self.indicators.get(index) {indicator.SetIsVisible(dragged.is_none())?;- indicator.SetOffset(v3(- fit(x + (width - self.indicator_size) / 2.0),- self.indicator_y,- ))?;+ indicator.SetOffset(v3(fit(dot.x), fit(dot.y)))?;}if let Some(Some(label)) = self.labels.get(index) {let shown = hovered == Some(index) && drag.is_none();label.visual.SetIsVisible(shown)?;if shown {- self.place_label(label, x, y, width)?;+ self.place_label(+ label,+ Rect {+ x,+ y,+ width,+ height,+ },+ )?;}}if let (Some(label), Some(drag)) = (&self.remove_label, dragged) {label.visual.SetIsVisible(drag.removing)?;if drag.removing {- self.place_label(label, x, y, width)?;+ self.place_label(+ label,+ Rect {+ x,+ y,+ width,+ height,+ },+ )?;}}}@@ -775,10 +831,13 @@ impl Scene {self.merge.SetIsVisible(false)?;return Ok(());};+ let rect = self.frame.rect(Rect {+ y: rect.y - lift,+ ..rect+ });let pad = (rect.width * 0.1).round();let size = v2(rect.width + 2.0 * pad, rect.height + 2.0 * pad);- self.merge- .SetOffset(v3(rect.x - pad, rect.y - pad - lift))?;+ self.merge.SetOffset(v3(rect.x - pad, rect.y - pad))?;self.merge.SetSize(size)?;self.merge_geometry.SetSize(v2(size.X - self.merge_stroke, size.Y - self.merge_stroke))?;@@ -788,11 +847,25 @@ impl Scene {Ok(())}- fn place_label(&self, label: &Label, x: f32, y: f32, width: f32) -> Result<()> {- label.visual.SetOffset(v3(- (x + (width - label.width) / 2.0).round(),- (y - self.label_gap - label.height).round(),- ))?;+ /// Beside the icon, on the side away from the screen edge: above it on+ /// a bottom dock, to its right on a left dock, to its left on a right one.+ fn place_label(&self, label: &Label, icon: Rect) -> Result<()> {+ let Rect {+ x,+ y,+ width,+ height,+ } = icon;+ let middle = y + (height - label.height) / 2.0;+ let (left, top) = match self.frame.edge {+ DockEdge::Bottom => (+ x + (width - label.width) / 2.0,+ y - self.label_gap - label.height,+ ),+ DockEdge::Left => (x + width + self.label_gap, middle),+ DockEdge::Right => (x - self.label_gap - label.width, middle),+ };+ label.visual.SetOffset(v3(left.round(), top.round()))?;Ok(())}}diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rsindex ffb6110..5733254 100644--- a/apps/dock/src/strings.rs+++ b/apps/dock/src/strings.rs@@ -64,7 +64,7 @@ const ES: Strings = Strings {show_in_explorer: "Mostrar en el &Explorador",quit_app: "&Salir",end_task: "&Finalizar tarea",- end_task_failed: "No se pudo finalizar la tarea. Abre el Administrador de tareas con Ctrl+Mayús+Esc; puede requerir permisos de administrador.",+ end_task_failed: "No se pudo finalizar la tarea. La app puede haber cambiado o requerir más permisos. Vuelve a abrir su menú o usa el Administrador de tareas (Ctrl+Mayús+Esc).",empty_bin: "&Vaciar papelera",turn_hiding_on: "Activar &ocultación automática",turn_hiding_off: "Desactivar &ocultación automática",@@ -111,7 +111,7 @@ const EN: Strings = Strings {show_in_explorer: "Show in &Explorer",quit_app: "&Quit",end_task: "&End task",- end_task_failed: "The task could not be ended. Open Task Manager with Ctrl+Shift+Esc; administrator permissions may be required.",+ end_task_failed: "The task could not be ended. The app may have changed or need more permissions. Reopen its menu or use Task Manager (Ctrl+Shift+Esc).",empty_bin: "&Empty Recycle Bin",turn_hiding_on: "Turn Hiding &On",turn_hiding_off: "Turn Hiding &Off",@@ -158,7 +158,7 @@ const FR: Strings = Strings {show_in_explorer: "Afficher dans l'&Explorateur",quit_app: "&Quitter",end_task: "&Forcer l’arrêt",- end_task_failed: "Impossible de terminer la tâche. Ouvrez le Gestionnaire des tâches avec Ctrl+Maj+Échap ; des droits administrateur peuvent être nécessaires.",+ end_task_failed: "Impossible de terminer la tâche. L’application a pu changer ou nécessiter plus de droits. Rouvrez son menu ou utilisez le Gestionnaire des tâches (Ctrl+Maj+Échap).",empty_bin: "&Vider la Corbeille",turn_hiding_on: "Activer le &masquage automatique",turn_hiding_off: "Désactiver le &masquage automatique",diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex 440d0d7..977d756 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -4,6 +4,7 @@ import { getCurrentWindow } from "@tauri-apps/api/window";import { useCallback, useEffect, useRef, useState } from "react";import {type Config,+ type DockPosition,type GenieSpeed,type IslandStyle,type Language,@@ -312,6 +313,18 @@ export function App() {onChange={(magnifiedSize) => update({ magnifiedSize })}/></SubRow>+ <Row label={t.dockPosition}>+ <Segmented<DockPosition>+ label={t.dockPosition}+ value={config.dockPosition}+ options={[+ { value: "left", label: t.dockPositionLeft },+ { value: "bottom", label: t.dockPositionBottom },+ { value: "right", label: t.dockPositionRight },+ ]}+ onChange={(dockPosition) => update({ dockPosition })}+ />+ </Row></Card><Card title={t.groupBehavior}><Row label={t.autoHide} hint={t.autoHideHint}>diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex 5190637..144dddb 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -3,6 +3,7 @@ import { invoke } from "@tauri-apps/api/core";export type Language = "auto" | "es" | "en" | "fr";export type IslandStyle = "notch" | "bubble";export type GenieSpeed = "normal" | "fast" | "faster";+export type DockPosition = "left" | "bottom" | "right";/** Mirrors `muelle_config::Config`. */export interface Config {@@ -13,6 +14,7 @@ export interface Config {iconSize: number;magnification: boolean;magnifiedSize: number;+ dockPosition: DockPosition;genie: boolean;genieSpeed: GenieSpeed;showMinimized: boolean;diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonindex fac3203..f061558 100644--- a/apps/settings/src/i18n/en.json+++ b/apps/settings/src/i18n/en.json@@ -7,8 +7,12 @@"magnification": "Magnification","magnificationHint": "Icons grow as the pointer passes over them.","magnifiedSize": "Magnified size",+ "dockPosition": "Position on screen",+ "dockPositionLeft": "Left",+ "dockPositionBottom": "Bottom",+ "dockPositionRight": "Right","autoHide": "Automatically hide and show the Dock",- "autoHideHint": "Rest the pointer at the bottom edge of any display to reveal the Dock there.",+ "autoHideHint": "Rest the pointer at the screen edge where the Dock sits to reveal it, on any display.","genie": "Genie effect","genieHint": "While it is on, windows do not use the Windows animations for maximizing or closing.","genieSpeed": "Genie speed",diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.jsonindex 5c9e5e9..796eb43 100644--- a/apps/settings/src/i18n/es.json+++ b/apps/settings/src/i18n/es.json@@ -7,8 +7,12 @@"magnification": "Ampliación","magnificationHint": "Los iconos crecen al pasar el cursor.","magnifiedSize": "Tamaño ampliado",+ "dockPosition": "Posición en la pantalla",+ "dockPositionLeft": "Izquierda",+ "dockPositionBottom": "Abajo",+ "dockPositionRight": "Derecha","autoHide": "Ocultar y mostrar el Dock automáticamente",- "autoHideHint": "Deja el puntero en el borde inferior de cualquier pantalla para mostrar el Dock allí.",+ "autoHideHint": "Deja el puntero en el borde de la pantalla donde está el Dock para mostrarlo; con varias pantallas, en cualquiera de ellas.","genie": "Efecto genio","genieHint": "Mientras está activo, las ventanas no usan las animaciones de Windows al maximizar ni al cerrar.","genieSpeed": "Velocidad del genio",diff --git a/apps/settings/src/i18n/fr.json b/apps/settings/src/i18n/fr.jsonindex 55167c0..844ea2b 100644--- a/apps/settings/src/i18n/fr.json+++ b/apps/settings/src/i18n/fr.json@@ -7,8 +7,12 @@"magnification": "Agrandissement","magnificationHint": "Les icônes grossissent au passage du pointeur.","magnifiedSize": "Taille agrandie",+ "dockPosition": "Position à l'écran",+ "dockPositionLeft": "Gauche",+ "dockPositionBottom": "Bas",+ "dockPositionRight": "Droite","autoHide": "Masquer et afficher automatiquement le Dock",- "autoHideHint": "Laissez le pointeur sur le bord inférieur d'un écran pour y afficher le Dock.",+ "autoHideHint": "Laissez le pointeur sur le bord de l'écran où se trouve le Dock pour l'afficher, sur n'importe quel écran.","genie": "Effet génie","genieHint": "Tant qu'il est activé, les fenêtres n'utilisent pas les animations de Windows pour l'agrandissement et la fermeture.","genieSpeed": "Vitesse du génie",diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsindex d97b933..ea34012 100644--- a/crates/muelle-config/src/lib.rs+++ b/crates/muelle-config/src/lib.rs@@ -56,6 +56,9 @@ pub struct Config {pub magnification: bool,/// Side of the icon under the cursor, in logical pixels.pub magnified_size: u32,+ /// The screen edge the dock sits on. Bottom by default, as on macOS;+ /// never the top, which belongs to the menu bar.+ pub dock_position: DockPosition,/// Genie effect when minimizing. On by default; while enabled, the dock/// turns off the system's own window transitions (see plan, "Efecto genio").pub genie: bool,@@ -121,6 +124,19 @@ pub struct DockGroup {/// Speed of the genie. Three steps, not a slider: a duration in milliseconds/// would ask the user to guess, and these three cover what anyone asked for.+/// The screen edge the dock sits on: the three macOS offers.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum DockPosition {+ Left,+ Right,+ /// Also what an unknown value from a newer version reads as (serde+ /// needs this fallback last).+ #[default]+ #[serde(other)]+ Bottom,+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum GenieSpeed {@@ -210,6 +226,7 @@ impl Default for Config {auto_hide: false,icon_size: 48,magnification: true,+ dock_position: DockPosition::Bottom,magnified_size: 77,genie: true,genie_speed: GenieSpeed::Normal,@@ -624,6 +641,16 @@ mod tests {assert_eq!(Config::default().genie_speed, GenieSpeed::Normal);}+ #[test]+ fn the_dock_stays_at_the_bottom_unless_moved() {+ for json in [r#"{}"#, r#"{"dockPosition":"top"}"#] {+ let config: Config = serde_json::from_str(json).unwrap_or_default();+ assert_eq!(config.dock_position, DockPosition::Bottom);+ }+ let left: Config = serde_json::from_str(r#"{"dockPosition":"left"}"#).unwrap_or_default();+ assert_eq!(left.dock_position, DockPosition::Left);+ }+#[test]fn genie_speed_keeps_the_original_speed_unless_chosen() {// Files from before the setting, and values from newer versions.diff --git a/crates/muelle-core/src/frame.rs b/crates/muelle-core/src/frame.rsnew file mode 100644index 0000000..9ebefbf--- /dev/null+++ b/crates/muelle-core/src/frame.rs@@ -0,0 +1,201 @@+//! Where the dock sits on the screen, and the one mapping between the dock's+//! own coordinates and the screen's.+//!+//! [`layout`](crate::layout::layout) and [`magnify`](crate::magnify::magnify)+//! work in *dock coordinates*: `u` runs along the dock (their `x`), `v`+//! across it (their `y`), with `v = thickness` on the side of the screen+//! edge and icons growing toward smaller `v`. Everything the dock places on+//! screen, and every pointer position it reads, goes through a [`Frame`]:+//! no other code needs to know which edge the dock is on.+//!+//! The dock can sit on the bottom, left or right edge, as on macOS. Not on+//! the top: that edge belongs to the menu bar.+//!+//! On the sides the first item is at the top, as on macOS. Icons are square+//! and the mapping only moves boxes, never rotates their content, so nothing+//! has to be counter-rotated to stay upright.++use crate::layout::Rect;++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub enum DockEdge {+ #[default]+ Bottom,+ Left,+ Right,+}++impl DockEdge {+ /// The dock runs from top to bottom.+ #[must_use]+ pub const fn is_vertical(self) -> bool {+ matches!(self, Self::Left | Self::Right)+ }+}++/// The dock's coordinates placed in a target space (a window or the screen):+/// `origin` is the top-left corner of the dock's resting box there, and+/// `thickness` its depth across (the layout's height).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Frame {+ pub edge: DockEdge,+ pub origin: (f32, f32),+ pub thickness: f32,+}++impl Frame {+ #[must_use]+ pub const fn new(edge: DockEdge, origin: (f32, f32), thickness: f32) -> Self {+ Self {+ edge,+ origin,+ thickness,+ }+ }++ /// The target-space point of dock coordinates `(u, v)`.+ #[must_use]+ pub fn point(&self, u: f32, v: f32) -> (f32, f32) {+ let (ox, oy) = self.origin;+ match self.edge {+ DockEdge::Bottom => (ox + u, oy + v),+ DockEdge::Left => (ox + self.thickness - v, oy + u),+ DockEdge::Right => (ox + v, oy + u),+ }+ }++ /// The target-space box of a box in dock coordinates.+ #[must_use]+ pub fn rect(&self, rect: Rect) -> Rect {+ let (ox, oy) = self.origin;+ match self.edge {+ DockEdge::Bottom => Rect {+ x: ox + rect.x,+ y: oy + rect.y,+ ..rect+ },+ DockEdge::Left => Rect {+ x: ox + self.thickness - (rect.y + rect.height),+ y: oy + rect.x,+ width: rect.height,+ height: rect.width,+ },+ DockEdge::Right => Rect {+ x: ox + rect.y,+ y: oy + rect.x,+ width: rect.height,+ height: rect.width,+ },+ }+ }++ /// Dock coordinates `(u, v)` of a target-space point: the inverse of+ /// [`point`](Self::point), for pointer input.+ #[must_use]+ pub fn to_dock(&self, x: f32, y: f32) -> (f32, f32) {+ let (ox, oy) = self.origin;+ match self.edge {+ DockEdge::Bottom => (x - ox, y - oy),+ DockEdge::Left => (y - oy, self.thickness - (x - ox)),+ DockEdge::Right => (y - oy, x - ox),+ }+ }++ /// A move of `distance` away from the screen edge (a bounce, a label's+ /// gap), as a target-space offset.+ #[must_use]+ pub fn inward(&self, distance: f32) -> (f32, f32) {+ match self.edge {+ DockEdge::Bottom => (0.0, -distance),+ DockEdge::Left => (distance, 0.0),+ DockEdge::Right => (-distance, 0.0),+ }+ }++ /// A move of `distance` toward the screen edge, as a target-space offset+ /// (the auto-hidden dock sliding out of view).+ #[must_use]+ pub fn outward(&self, distance: f32) -> (f32, f32) {+ let (x, y) = self.inward(distance);+ (-x, -y)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const EDGES: [DockEdge; 3] = [DockEdge::Bottom, DockEdge::Left, DockEdge::Right];++ fn rect(x: f32, y: f32, width: f32, height: f32) -> Rect {+ Rect {+ x,+ y,+ width,+ height,+ }+ }++ #[test]+ fn bottom_is_the_identity_shifted_by_the_origin() {+ let frame = Frame::new(DockEdge::Bottom, (100.0, 900.0), 66.0);+ assert_eq!(frame.point(10.0, 9.0), (110.0, 909.0));+ assert_eq!(+ frame.rect(rect(10.0, 9.0, 48.0, 48.0)),+ rect(110.0, 909.0, 48.0, 48.0)+ );+ assert_eq!(frame.inward(5.0), (0.0, -5.0));+ }++ #[test]+ fn points_go_back_to_where_they_came_from() {+ for edge in EDGES {+ let frame = Frame::new(edge, (40.0, 300.0), 66.0);+ for (u, v) in [(0.0, 0.0), (123.5, 9.0), (500.0, -40.0), (12.0, 66.0)] {+ let (x, y) = frame.point(u, v);+ let (back_u, back_v) = frame.to_dock(x, y);+ assert!(+ (back_u - u).abs() < 1e-4 && (back_v - v).abs() < 1e-4,+ "{edge:?}"+ );+ }+ }+ }++ #[test]+ fn side_docks_run_top_to_bottom_with_the_first_item_at_the_top() {+ for edge in [DockEdge::Left, DockEdge::Right] {+ let frame = Frame::new(edge, (0.0, 200.0), 66.0);+ let first = frame.rect(rect(9.0, 9.0, 48.0, 48.0));+ let second = frame.rect(rect(69.0, 9.0, 48.0, 48.0));+ assert!(first.y < second.y, "{edge:?}");+ assert_eq!((first.width, first.height), (48.0, 48.0));+ }+ }++ #[test]+ fn the_screen_edge_side_and_growth_point_the_right_way() {+ // Dock coordinate v = thickness is the screen-edge side; icons grow+ // toward smaller v, so into the screen.+ let left = Frame::new(DockEdge::Left, (0.0, 0.0), 66.0);+ assert_eq!(left.point(0.0, 66.0).0, 0.0);+ assert!(left.point(0.0, -20.0).0 > 66.0);+ assert!(left.inward(1.0).0 > 0.0);++ let right = Frame::new(DockEdge::Right, (1854.0, 0.0), 66.0);+ assert_eq!(right.point(0.0, 66.0).0, 1920.0);+ assert!(right.point(0.0, -20.0).0 < 1854.0);+ assert!(right.inward(1.0).0 < 0.0);+ }++ #[test]+ fn a_magnified_icon_keeps_its_base_on_the_edge_side() {+ // A 72 px icon grown from a 48 px one, base still at v = 57.+ let grown = rect(0.0, 57.0 - 72.0, 72.0, 72.0);+ let left = Frame::new(DockEdge::Left, (0.0, 0.0), 66.0).rect(grown);+ assert_eq!(left.x, 66.0 - 57.0);+ assert_eq!(left.width, 72.0);+ let right = Frame::new(DockEdge::Right, (0.0, 0.0), 66.0).rect(grown);+ assert_eq!(right.x + right.width, 57.0);+ }+}diff --git a/crates/muelle-core/src/lib.rs b/crates/muelle-core/src/lib.rsindex a87dadc..b77b814 100644--- a/crates/muelle-core/src/lib.rs+++ b/crates/muelle-core/src/lib.rs@@ -2,6 +2,7 @@pub mod attention;pub mod bounce;+pub mod frame;pub mod genie;pub mod layout;pub mod magnify;diff --git a/crates/muelle-shell/src/appbar.rs b/crates/muelle-shell/src/appbar.rsindex 193e1ad..df4de19 100644--- a/crates/muelle-shell/src/appbar.rs+++ b/crates/muelle-shell/src/appbar.rs@@ -1,14 +1,15 @@-//! Registering the dock as an *AppBar* reserves a bottom strip of the screen-//! so maximized windows end above the dock, and notifies the dock when an app-//! enters or exits full-screen mode.+//! Registering the dock as an *AppBar* reserves a strip along a screen edge+//! (bottom, left or right for the dock, top for the menu bar) so maximized+//! windows end beside it, and notifies when an app enters or exits+//! full-screen mode.use std::mem::size_of;use windows::Win32::{Foundation::{HWND, RECT},UI::Shell::{- ABE_BOTTOM, ABE_TOP, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS, APPBARDATA,- SHAppBarMessage,+ ABE_BOTTOM, ABE_LEFT, ABE_RIGHT, ABE_TOP, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS,+ APPBARDATA, SHAppBarMessage,},};@@ -18,6 +19,52 @@ pub const ABN_FULLSCREENAPP: usize = 2;pub enum Edge {Top,Bottom,+ Left,+ Right,+}++/// The strip `thickness` pixels deep along `edge` of `screen`.+fn strip(edge: Edge, screen: RECT, thickness: i32) -> RECT {+ match edge {+ Edge::Top => RECT {+ bottom: screen.top + thickness,+ ..screen+ },+ Edge::Bottom => RECT {+ top: screen.bottom - thickness,+ ..screen+ },+ Edge::Left => RECT {+ right: screen.left + thickness,+ ..screen+ },+ Edge::Right => RECT {+ left: screen.right - thickness,+ ..screen+ },+ }+}++/// `rect` given back its depth from the edge: another bar on the same edge+/// (the Windows taskbar before it hides) pushes it inward.+fn keep_thickness(edge: Edge, mut rect: RECT, thickness: i32) -> RECT {+ match edge {+ Edge::Top => rect.bottom = rect.top + thickness,+ Edge::Bottom => rect.top = rect.bottom - thickness,+ Edge::Left => rect.right = rect.left + thickness,+ Edge::Right => rect.left = rect.right - thickness,+ }+ rect+}++/// The system granted the strip: right edge, right depth. Along the edge it+/// may be shorter (a side bar ends at the menu bar on top), which is fine;+/// demanding the full length would retry, and notify, forever.+fn granted(edge: Edge, got: RECT, wanted: RECT) -> bool {+ match edge {+ Edge::Top | Edge::Bottom => got.top == wanted.top && got.bottom == wanted.bottom,+ Edge::Left | Edge::Right => got.left == wanted.left && got.right == wanted.right,+ }}pub struct AppBar {@@ -49,16 +96,7 @@ impl AppBar {/// reservation triggers a settings-change notification; repeating it would/// create a loop.pub fn reserve(&mut self, edge: Edge, screen: RECT, thickness: i32) {- let wanted = match edge {- Edge::Top => RECT {- bottom: screen.top + thickness,- ..screen- },- Edge::Bottom => RECT {- top: screen.bottom - thickness,- ..screen- },- };+ let wanted = strip(edge, screen, thickness);if self.reserved == Some(wanted) {return;}@@ -69,6 +107,8 @@ impl AppBar {uEdge: match edge {Edge::Top => ABE_TOP,Edge::Bottom => ABE_BOTTOM,+ Edge::Left => ABE_LEFT,+ Edge::Right => ABE_RIGHT,},rc: wanted,..Default::default()@@ -78,15 +118,12 @@ impl AppBar {SHAppBarMessage(ABM_QUERYPOS, &mut data);// Another bar on the same edge (the Windows taskbar, before it is// hidden) pushes the strip inward, so preserve its thickness.- match edge {- Edge::Top => data.rc.bottom = data.rc.top + thickness,- Edge::Bottom => data.rc.top = data.rc.bottom - thickness,- }+ data.rc = keep_thickness(edge, data.rc, thickness);SHAppBarMessage(ABM_SETPOS, &mut data);}// Treat the reservation as complete only if the system granted the// requested area; otherwise, retry on the next call.- self.reserved = (data.rc == wanted).then_some(wanted);+ self.reserved = granted(edge, data.rc, wanted).then_some(wanted);}}@@ -101,3 +138,43 @@ impl Drop for AppBar {unsafe { SHAppBarMessage(ABM_REMOVE, &mut data) };}}++#[cfg(test)]+mod tests {+ use super::*;++ const SCREEN: RECT = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };++ #[test]+ fn each_edge_reserves_its_own_strip() {+ assert_eq!(strip(Edge::Bottom, SCREEN, 90).top, 990);+ assert_eq!(strip(Edge::Top, SCREEN, 35).bottom, 35);+ let left = strip(Edge::Left, SCREEN, 90);+ assert_eq!(+ (left.left, left.right, left.top, left.bottom),+ (0, 90, 0, 1080)+ );+ let right = strip(Edge::Right, SCREEN, 90);+ assert_eq!((right.left, right.right), (1830, 1920));+ }++ #[test]+ fn a_side_strip_shortened_by_the_menu_bar_still_counts_as_granted() {+ let wanted = strip(Edge::Left, SCREEN, 90);+ let below_bar = RECT { top: 35, ..wanted };+ assert!(granted(Edge::Left, below_bar, wanted));+ let pushed = RECT {+ left: 48,+ right: 138,+ ..wanted+ };+ assert!(!granted(Edge::Left, pushed, wanted));+ assert_eq!(keep_thickness(Edge::Left, pushed, 90).right, 138);+ assert_eq!(keep_thickness(Edge::Right, wanted, 60).left, 30);+ }+}diff --git a/crates/muelle-shell/src/end_task.rs b/crates/muelle-shell/src/end_task.rsindex a027361..7e6e07a 100644--- a/crates/muelle-shell/src/end_task.rs+++ b/crates/muelle-shell/src/end_task.rs@@ -9,14 +9,18 @@ use std::{use windows::{Win32::{- Foundation::{HANDLE, HWND, WAIT_OBJECT_0},+ Foundation::{HANDLE, HWND, LPARAM, WAIT_OBJECT_0},Storage::Packaging::Appx::GetApplicationUserModelId,System::Threading::{GetCurrentProcessId, IsProcessCritical, OpenProcess, PROCESS_NAME_WIN32,PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,QueryFullProcessImageNameW, TerminateProcess, WaitForSingleObject,},- UI::WindowsAndMessaging::{GetShellWindow, GetWindowThreadProcessId},+ UI::WindowsAndMessaging::{+ EnumWindows, GW_OWNER, GWL_EXSTYLE, GetShellWindow, GetWindow, GetWindowLongW,+ GetWindowThreadProcessId, IsWindowVisible, WS_EX_APPWINDOW, WS_EX_NOACTIVATE,+ WS_EX_TOOLWINDOW,+ },},core::{BOOL, PWSTR},};@@ -24,7 +28,32 @@ use windows::{use crate::tracker::{self, TrackedWindow};pub struct PreparedEndTask {- processes: Vec<OwnedHandle>,+ processes: Vec<(u32, OwnedHandle)>,+ windows: Vec<(isize, u32)>,+}++fn independent_windows() -> windows::core::Result<Vec<(isize, u32)>> {+ unsafe extern "system" fn collect(hwnd: HWND, data: LPARAM) -> BOOL {+ // SAFETY: EnumWindows keeps the local Vec alive for this callback.+ let windows = unsafe { &mut *(data.0 as *mut Vec<(isize, u32)>) };+ let style = unsafe { GetWindowLongW(hwnd, GWL_EXSTYLE) } as u32;+ if unsafe { IsWindowVisible(hwnd) }.as_bool()+ && style & WS_EX_TOOLWINDOW.0 == 0+ && (style & WS_EX_APPWINDOW.0 != 0+ || (style & WS_EX_NOACTIVATE.0 == 0+ && unsafe { GetWindow(hwnd, GW_OWNER) }.is_err()))+ {+ let raw = hwnd.0 as isize;+ windows.push((raw, window_pid(raw)));+ }+ true.into()+ }+ let mut windows = Vec::new();+ // SAFETY: A read-only enumeration, no title/COM/message calls into the apps.+ unsafe {+ EnumWindows(Some(collect), LPARAM(&raw mut windows as isize))?;+ }+ Ok(windows)}fn window_pid(window: isize) -> u32 {@@ -70,6 +99,7 @@ impl PreparedEndTask {.collect();let mut seen = HashSet::new();let mut processes = Vec::new();+ let mut selected = Vec::new();for &window in windows {let pid = window_pid(window);if pid == 0 {@@ -78,6 +108,7 @@ impl PreparedEndTask {if protected_pid(pid, own, shell) {return None;}+ selected.push((window, pid));if seen.contains(&pid) {continue;}@@ -143,16 +174,68 @@ impl PreparedEndTask {return None;}seen.insert(pid);- processes.push(handle);+ processes.push((pid, handle));+ }+ let selection = Self {+ processes,+ windows: selected,+ };+ if selection.processes.is_empty() {+ return None;+ }+ // Also covers windows outside the current virtual desktop, which the+ // visible dock roster intentionally excludes. Never terminate through+ // an incomplete selection of independent windows sharing that process.+ if !selection.includes(&independent_windows().ok()?) {+ return None;+ }+ Some(selection)+ }++ fn includes(&self, current: &[(isize, u32)]) -> bool {+ !current.iter().any(|&(window, pid)| {+ self.processes.iter().any(|(target, _)| *target == pid)+ && !self.windows.contains(&(window, pid))+ })+ }++ fn validate(&self) -> windows::core::Result<()> {+ let denied =+ || windows::core::Error::from_hresult(windows::Win32::Foundation::E_ACCESSDENIED);+ if !self.includes(&independent_windows()?) {+ return Err(denied());}- (!processes.is_empty()).then_some(Self { processes })+ // Validate every target before ending any. A background process whose+ // selected windows all closed must survive a stale context menu.+ for (pid, process) in &self.processes {+ let handle = HANDLE(process.as_raw_handle());+ if unsafe { WaitForSingleObject(handle, 0) } == WAIT_OBJECT_0 {+ continue;+ }+ if !self+ .windows+ .iter()+ .any(|&(window, owner)| owner == *pid && window_pid(window) == *pid)+ {+ return Err(denied());+ }+ let mut critical = BOOL::default();+ unsafe {+ IsProcessCritical(handle, &mut critical)?;+ }+ if critical.as_bool() {+ return Err(denied());+ }+ }+ Ok(())}/// Requests termination without waiting on the UI or calling into a hung/// window. Natural exits during an open menu are harmless no-ops.pub fn terminate(self) -> windows::core::Result<()> {+ self.validate()?;let mut failure = None;- for process in self.processes {+ for (_, process) in self.processes {let handle = HANDLE(process.as_raw_handle());if unsafe { WaitForSingleObject(handle, 0) } == WAIT_OBJECT_0 {continue;@@ -189,13 +272,14 @@ mod tests {io::{BufRead, BufReader, Write},os::windows::process::CommandExt,process::{Child, Command, Stdio},- sync::mpsc,+ sync::mpsc::{self, Receiver},time::Duration,};struct Fixture {child: Child,windows: [isize; 2],+ events: Receiver<String>,}impl Drop for Fixture {fn drop(&mut self) {@@ -213,28 +297,26 @@ mod tests {"--nocapture",]).creation_flags(0x0800_0000)+ .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?;+ let mut child = child;+ let stdout = child.stdout.take().ok_or("missing fixture stdout")?;+ let (send, receive) = mpsc::channel();let mut fixture = Self {child,windows: [0, 0],+ events: receive,};- let stdout = fixture- .child- .stdout- .take()- .ok_or("missing fixture stdout")?;- let (send, receive) = mpsc::channel();std::thread::spawn(move || {for line in BufReader::new(stdout).lines().map_while(Result::ok) {if let Some(handles) = line.strip_prefix("MUELLE_END_TASK_FIXTURE ") {let _ = send.send(handles.to_owned());- break;}}});- let handles = receive.recv_timeout(Duration::from_secs(5))?;+ let handles = fixture.events.recv_timeout(Duration::from_secs(5))?;let handles: Vec<isize> = handles.split_whitespace().map(str::parse)@@ -244,6 +326,16 @@ mod tests {.map_err(|_| "wrong fixture window count")?;Ok(fixture)}+ fn command(&mut self, command: &str) -> Result<(), Box<dyn std::error::Error>> {+ let stdin = self.child.stdin.as_mut().ok_or("missing fixture stdin")?;+ writeln!(stdin, "{command}")?;+ stdin.flush()?;+ let reply = self.events.recv_timeout(Duration::from_secs(5))?;+ if reply != "OK" {+ return Err("unexpected fixture reply".into());+ }+ Ok(())+ }fn app() -> Result<String, Box<dyn std::error::Error>> {Ok(tracker::normalize_id(&std::env::current_exe()?.to_string_lossy(),@@ -255,7 +347,8 @@ mod tests {#[ignore = "Internal subprocess fixture, started only by the native end-task tests"]fn end_task_frozen_fixture() -> windows::core::Result<()> {use windows::Win32::UI::WindowsAndMessaging::{- CreateWindowExW, WS_EX_TOOLWINDOW, WS_OVERLAPPEDWINDOW,+ CreateWindowExW, DestroyWindow, SW_SHOWNOACTIVATE, ShowWindow, WS_EX_APPWINDOW,+ WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_OVERLAPPEDWINDOW,};let create = || unsafe {CreateWindowExW(@@ -281,7 +374,35 @@ mod tests {);let _ = std::io::stdout().flush();// Deliberately no message pump: Quit/WM_CLOSE cannot make progress.- std::thread::sleep(Duration::from_secs(60));+ // Commands mutate test-owned HWNDs on their owning thread only.+ for command in std::io::stdin().lock().lines().map_while(Result::ok) {+ match command.as_str() {+ "close" => unsafe {+ let _ = DestroyWindow(first);+ let _ = DestroyWindow(second);+ },+ "new" => unsafe {+ let added = CreateWindowExW(+ WS_EX_APPWINDOW | WS_EX_NOACTIVATE,+ windows::core::w!("STATIC"),+ windows::core::w!("Muelle extra window test"),+ WS_OVERLAPPEDWINDOW,+ -32000,+ -32000,+ 160,+ 120,+ None,+ None,+ None,+ None,+ )?;+ let _ = ShowWindow(added, SW_SHOWNOACTIVATE);+ },+ _ => {}+ }+ println!("MUELLE_END_TASK_FIXTURE OK");+ let _ = std::io::stdout().flush();+ }Ok(())}@@ -354,6 +475,82 @@ mod tests {Ok(())}+ #[test]+ #[ignore = "Uses test-owned children; never closes user applications"]+ fn native_end_task_refuses_closed_windows_and_windows_added_while_the_menu_is_open()+ -> Result<(), Box<dyn std::error::Error>> {+ let app = Fixture::app()?;+ let mut closed = Fixture::spawn()?;+ let selection =+ PreparedEndTask::capture(&app, &closed.windows, &[]).ok_or("capture failed")?;+ closed.command("close")?;+ assert!(selection.terminate().is_err());+ assert!(closed.child.try_wait()?.is_none());+ let mut changed = Fixture::spawn()?;+ let selection =+ PreparedEndTask::capture(&app, &changed.windows, &[]).ok_or("capture failed")?;+ changed.command("new")?;+ assert!(selection.terminate().is_err());+ assert!(changed.child.try_wait()?.is_none());+ assert!(PreparedEndTask::capture(&app, &changed.windows, &[]).is_none());+ Ok(())+ }++ #[test]+ #[ignore = "Uses test-owned children to check all targets before any termination"]+ fn native_end_task_does_not_partially_end_a_multi_process_selection_that_changed()+ -> Result<(), Box<dyn std::error::Error>> {+ let app = Fixture::app()?;+ let mut first = Fixture::spawn()?;+ let mut second = Fixture::spawn()?;+ let windows: Vec<isize> = first.windows.into_iter().chain(second.windows).collect();+ let selection = PreparedEndTask::capture(&app, &windows, &[]).ok_or("capture failed")?;+ second.command("new")?;+ assert!(selection.terminate().is_err());+ assert!(first.child.try_wait()?.is_none());+ assert!(second.child.try_wait()?.is_none());+ Ok(())+ }++ #[test]+ #[ignore = "Measures native menu preparation and handle release on test-owned processes"]+ fn native_end_task_menu_preparation_releases_handles_after_repeated_cancellation()+ -> Result<(), Box<dyn std::error::Error>> {+ use windows::Win32::System::Threading::{GetCurrentProcess, GetProcessHandleCount};+ let mut fixture = Fixture::spawn()?;+ let app = Fixture::app()?;+ let handles = || -> windows::core::Result<u32> {+ let mut count = 0;+ unsafe {+ GetProcessHandleCount(GetCurrentProcess(), &mut count)?;+ }+ Ok(count)+ };+ // Repeating handles simulates the largest permitted multi-window menu+ // without creating 128 real windows on the user's desktop.+ let windows: Vec<isize> = fixture.windows.into_iter().cycle().take(128).collect();+ drop(PreparedEndTask::capture(&app, &windows, &[]).ok_or("capture failed")?);+ let before = handles()?;+ let mut times = Vec::new();+ for _ in 0..64 {+ let started = std::time::Instant::now();+ let selection =+ PreparedEndTask::capture(&app, &windows, &[]).ok_or("capture failed")?;+ assert_eq!(selection.processes.len(), 1);+ drop(selection);+ times.push(started.elapsed().as_micros());+ }+ assert_eq!(handles()?, before, "cancelled menus leaked process handles");+ assert!(fixture.child.try_wait()?.is_none());+ times.sort_unstable();+ println!(+ "end-task capture, 128 slots/1 process, 64 cancelled menus: median={} us, max={} us, handle delta=0",+ times[times.len() / 2],+ times[times.len() - 1]+ );+ Ok(())+ }+#[test]fn end_task_refuses_system_shell_self_and_shared_hosts() {for pid in [0, 4, 100, 200] {diff --git a/muelle/src/components/showcase/Mascot.astro b/muelle/src/components/showcase/Mascot.astroindex 033f74a..4f55cc5 100644--- a/muelle/src/components/showcase/Mascot.astro+++ b/muelle/src/components/showcase/Mascot.astro@@ -214,6 +214,7 @@ import "@/styles/showcase.css";bottom: 14px;z-index: 2;display: flex;+ width: max-content;gap: 6px;padding: 7px 10px;translate: -50% 0;diff --git a/scripts/Assert-Authenticode.ps1 b/scripts/Assert-Authenticode.ps1new file mode 100644index 0000000..2bd2150--- /dev/null+++ b/scripts/Assert-Authenticode.ps1@@ -0,0 +1,85 @@+# Verify bytes and trust, not merely the presence of a certificate.+[CmdletBinding()]+param(+ [Parameter(Mandatory)][string[]]$Path,+ [Parameter(Mandatory)][ValidateSet('Test', 'Production')][string]$Mode,+ [string]$ProductionThumbprint = '',+ [string]$ReportDirectory = ''+)+$ErrorActionPreference = 'Stop'+$testThumbprint = '3A93532146A10D3B1FA8DEAF4192AD4A232FFCAC'+if ($Mode -eq 'Production' -and ($ProductionThumbprint -cnotmatch '\A[0-9A-Fa-f]{40}\z' -or $ProductionThumbprint -eq $testThumbprint)) {+ throw 'A pinned production certificate thumbprint is required; a test certificate cannot be used.'+}+$store = $null+$added = $false+$reports = [Collections.Generic.List[object]]::new()+try {+ foreach ($file in $Path) {+ $resolved = (Resolve-Path -LiteralPath $file).Path+ $signature = Get-AuthenticodeSignature -LiteralPath $resolved+ $cert = $signature.SignerCertificate+ $row = [ordered]@{+ file = [IO.Path]::GetFileName($resolved)+ sha256 = (Get-FileHash -LiteralPath $resolved -Algorithm SHA256).Hash+ mode = $Mode+ initialStatus = [string]$signature.Status+ initialMessage = $signature.StatusMessage+ subject = if ($cert) { $cert.Subject } else { $null }+ issuer = if ($cert) { $cert.Issuer } else { $null }+ thumbprint = if ($cert) { $cert.Thumbprint } else { $null }+ status = [string]$signature.Status+ message = $signature.StatusMessage+ }+ $reports.Add($row)+ Write-Host ($row | ConvertTo-Json -Compress)+ if (-not $cert -or $signature.Status -eq 'NotSigned') { throw "$file has no Authenticode signature." }+ if ($signature.Status -in @('HashMismatch', 'NotSupportedFileFormat', 'Incompatible')) {+ throw "Invalid signed file ${file}: $($signature.Status): $($signature.StatusMessage)"+ }+ if ($Mode -eq 'Test') {+ if ($cert.Thumbprint -ne $testThumbprint) { throw "Unexpected SignPath test certificate: $($cert.Thumbprint). Check the certificate in SignPath, not the artifact alone." }+ # Never import an arbitrary signer or change a developer's trust.+ if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_ENVIRONMENT -ne 'github-hosted') {+ throw 'Test certificate trust may only be installed temporarily on a GitHub-hosted Actions runner.'+ }+ if (-not $store) {+ $store = [Security.Cryptography.X509Certificates.X509Store]::new('Root', 'CurrentUser')+ $store.Open([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)+ $existing = $store.Certificates.Find(+ [Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint, $testThumbprint, $false)+ if ($existing.Count -eq 0) { $store.Add($cert); $added = $true }+ }+ $signature = Get-AuthenticodeSignature -LiteralPath $resolved+ } elseif ($cert.Thumbprint -eq $testThumbprint -or $cert.Subject -eq $cert.Issuer) {+ throw "$file uses a test/self-signed certificate and cannot be released. Configure the production certificate in SignPath."+ } elseif ($cert.Thumbprint -ne $ProductionThumbprint) {+ throw "Unexpected production signer for ${file}: $($cert.Thumbprint). Confirm the configured production certificate in SignPath."+ }+ $row.status = [string]$signature.Status+ $row.message = $signature.StatusMessage+ Write-Host "Final Authenticode status for ${file}: $($signature.Status): $($signature.StatusMessage)"+ if ($signature.Status -ne 'Valid') {+ throw "Authenticode verification failed for ${file}: $($signature.Status): $($signature.StatusMessage). See signature-report.json; do not bypass this check."+ }+ }+} finally {+ try {+ if ($store) {+ try {+ if ($added) {+ foreach ($certificate in $store.Certificates.Find(+ [Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint, $testThumbprint, $false)) {+ $store.Remove($certificate)+ }+ }+ } finally { $store.Close() }+ }+ } finally {+ if ($ReportDirectory) {+ New-Item -ItemType Directory -Path $ReportDirectory -Force | Out-Null+ ConvertTo-Json -InputObject @($reports.ToArray()) -Depth 4 |+ Set-Content -LiteralPath (Join-Path $ReportDirectory 'signature-report.json') -Encoding utf8NoBOM+ }+ }+}diff --git a/scripts/Get-ReleaseSigningMode.ps1 b/scripts/Get-ReleaseSigningMode.ps1new file mode 100644index 0000000..7f6d2a1--- /dev/null+++ b/scripts/Get-ReleaseSigningMode.ps1@@ -0,0 +1,36 @@+# Select a signing lane before building. Test signatures never reach Releases.+[CmdletBinding()]+param(+ [Parameter(Mandatory)][ValidateSet('push', 'workflow_dispatch')][string]$EventName,+ [Parameter(Mandatory)][string]$Version,+ [string]$RefName = '',+ [string]$Organization = '',+ [string]$Project = '',+ [string]$Policy = '',+ [string]$ProductionThumbprint = '',+ [bool]$TokenPresent = $false+)+$ErrorActionPreference = 'Stop'+if ($Version -cnotmatch '\A(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)\z') {+ throw 'A stable workspace version is required.'+}+if ($EventName -eq 'push' -and $RefName -cne "v$Version") {+ throw "Tag $RefName does not match the workspace version $Version"+}+if ($EventName -eq 'push' -and -not $Organization.Trim()) {+ return [pscustomobject]@{ Mode = 'Unsigned'; Policy = ''; Version = $Version }+}+if (-not $Organization.Trim() -or -not $Project.Trim() -or -not $TokenPresent) {+ throw 'Configure SIGNPATH_ORGANIZATION_ID, SIGNPATH_PROJECT_SLUG and the SIGNPATH_API_TOKEN secret before requesting signing.'+}+if ($EventName -eq 'workflow_dispatch') {+ return [pscustomobject]@{ Mode = 'Test'; Policy = 'test-signing'; Version = $Version }+}+if ($Policy -cne 'release-signing') {+ throw 'A public release requires SIGNPATH_SIGNING_POLICY_SLUG=release-signing. Use Actions > Release > Run workflow for isolated test-signing; it does not create a release.'+}+if ($ProductionThumbprint -cnotmatch '\A[0-9A-Fa-f]{40}\z' -or+ $ProductionThumbprint -eq '3A93532146A10D3B1FA8DEAF4192AD4A232FFCAC') {+ throw 'Set SIGNPATH_PRODUCTION_CERTIFICATE_THUMBPRINT to the production certificate thumbprint confirmed in SignPath.'+}+[pscustomobject]@{ Mode = 'Production'; Policy = $Policy; Version = $Version }diff --git a/scripts/Test-CodeSigning.ps1 b/scripts/Test-CodeSigning.ps1new file mode 100644index 0000000..ed891e8--- /dev/null+++ b/scripts/Test-CodeSigning.ps1@@ -0,0 +1,96 @@+# Offline policy tests: no account, key, network, or certificate-store changes.+$ErrorActionPreference = 'Stop'+$modeScript = Join-Path $PSScriptRoot 'Get-ReleaseSigningMode.ps1'+$verifyScript = Join-Path $PSScriptRoot 'Assert-Authenticode.ps1'+$root = Join-Path ([IO.Path]::GetTempPath()) "muelle-signing-test-$([guid]::NewGuid())"+$testPin = '3A93532146A10D3B1FA8DEAF4192AD4A232FFCAC'+$prodPin = '1111111111111111111111111111111111111111'+$savedActions = $env:GITHUB_ACTIONS+$savedRunner = $env:RUNNER_ENVIRONMENT+$state = @{ status = 'Valid'; thumbprint = $prodPin; subject = 'CN=Publisher'; issuer = 'CN=Issuer'; missing = $false }+function Get-AuthenticodeSignature {+ param($LiteralPath)+ [pscustomobject]@{+ Status = $state.status; StatusMessage = 'Native verification fixture detail'+ SignerCertificate = if ($state.missing) { $null } else {+ [pscustomobject]@{ Thumbprint = $state.thumbprint; Subject = $state.subject; Issuer = $state.issuer }+ }+ }+}+Set-Item Function:Get-AuthenticodeSignature -Value ((Get-Command Get-AuthenticodeSignature -CommandType Function).ScriptBlock.GetNewClosure())+function Assert-Rejected([string]$Name, [scriptblock]$Action, [string]$Message) {+ try { & $Action | Out-Null }+ catch {+ if ($_.Exception.Message -notlike $Message) { throw }+ Write-Host "PASS: $Name"+ return+ }+ throw "Failed to reject: $Name"+}+try {+ $env:GITHUB_ACTIONS = ''+ $env:RUNNER_ENVIRONMENT = ''+ New-Item -ItemType Directory -Path $root | Out-Null+ $fixture = Join-Path $root 'fixture.exe'+ Set-Content -LiteralPath $fixture -Value 'test-owned bytes only'+ foreach ($script in @($modeScript, $verifyScript, $PSCommandPath)) {+ $tokens = $null; $errors = $null+ $null = [Management.Automation.Language.Parser]::ParseFile($script, [ref]$tokens, [ref]$errors)+ if ($errors) { throw ($errors | Out-String) }+ }+ $common = @{ Version = '0.1.17'; RefName = 'v0.1.17'; Organization = 'configured'; Project = 'Muelle'; TokenPresent = $true }+ $lane = & $modeScript -EventName workflow_dispatch @common -Policy release-signing+ if ($lane.Mode -ne 'Test' -or $lane.Policy -ne 'test-signing') { throw 'Manual runs must always be tests.' }+ Write-Host 'PASS: manual run uses only test-signing, even with production configured'+ $lane = & $modeScript -EventName push -Version 0.1.17 -RefName v0.1.17+ if ($lane.Mode -ne 'Unsigned') { throw 'Unsigned release compatibility lost.' }+ Write-Host 'PASS: absent organization preserves unsigned tag releases'+ $lane = & $modeScript -EventName push @common -Policy release-signing -ProductionThumbprint $prodPin+ if ($lane.Mode -ne 'Production') { throw 'Production lane missing.' }+ Write-Host 'PASS: configured production tag uses production lane'+ Assert-Rejected 'test policy on public release' { & $modeScript -EventName push @common -Policy test-signing } '*public release requires*'+ Assert-Rejected 'unknown policy on public release' { & $modeScript -EventName push @common -Policy typo } '*public release requires*'+ Assert-Rejected 'missing production pin' { & $modeScript -EventName push @common -Policy release-signing } '*production certificate thumbprint*'+ Assert-Rejected 'test certificate as production pin' { & $modeScript -EventName push @common -Policy release-signing -ProductionThumbprint $testPin } '*production certificate thumbprint*'+ Assert-Rejected 'test without configuration' { & $modeScript -EventName workflow_dispatch -Version 0.1.17 } '*Configure SIGNPATH*'+ Assert-Rejected 'tag mismatch' { & $modeScript -EventName push -Version 0.1.17 -RefName v0.1.16 } '*does not match*'+ & $verifyScript -Mode Production -ProductionThumbprint $prodPin -Path $fixture -ReportDirectory $root+ $report = @(Get-Content (Join-Path $root 'signature-report.json') -Raw | ConvertFrom-Json)+ if ($report[0].sha256 -ne (Get-FileHash $fixture).Hash -or $report[0].status -ne 'Valid') { throw 'Verification report lost hash/status.' }+ Write-Host 'PASS: expected valid production signer records hash and status'+ foreach ($status in @('UnknownError', 'NotTrusted', 'HashMismatch', 'NotSigned', 'Incompatible')) {+ $state.status = $status+ $expectedMessage = if ($status -eq 'NotSigned') { '*no Authenticode signature*' } else { "*${status}: Native verification fixture detail*" }+ Assert-Rejected "production $status" { & $verifyScript -Mode Production -ProductionThumbprint $prodPin -Path $fixture -ReportDirectory $root } $expectedMessage+ $report = @(Get-Content (Join-Path $root 'signature-report.json') -Raw | ConvertFrom-Json)+ if ($report[0].initialStatus -ne $status -or $report[0].initialMessage -ne 'Native verification fixture detail') { throw 'Failure diagnostics missing.' }+ }+ $state.status = 'Valid'+ $state.thumbprint = $testPin+ Assert-Rejected 'valid but test-signed production artifact' { & $verifyScript -Mode Production -ProductionThumbprint $prodPin -Path $fixture } '*test/self-signed*'+ Assert-Rejected 'test trust on a developer machine' { & $verifyScript -Mode Test -Path $fixture } '*GitHub-hosted*'+ $state.status = 'HashMismatch'+ Assert-Rejected 'modified test artifact before trust changes' { & $verifyScript -Mode Test -Path $fixture } '*Invalid signed file*'+ $state.status = 'Valid'; $state.thumbprint = $prodPin; $state.subject = $state.issuer+ Assert-Rejected 'self-signed production artifact' { & $verifyScript -Mode Production -ProductionThumbprint $prodPin -Path $fixture } '*test/self-signed*'+ $state.subject = 'CN=Publisher'; $state.thumbprint = '2222222222222222222222222222222222222222'+ Assert-Rejected 'unexpected production publisher' { & $verifyScript -Mode Production -ProductionThumbprint $prodPin -Path $fixture } '*Unexpected production signer*'+ Assert-Rejected 'unexpected test certificate' { & $verifyScript -Mode Test -Path $fixture } '*Unexpected SignPath test certificate*'+ $state.missing = $true+ Assert-Rejected 'missing signer' { & $verifyScript -Mode Production -ProductionThumbprint $prodPin -Path $fixture } '*no Authenticode signature*'+ $workflow = Get-Content (Join-Path $PSScriptRoot '../.github/workflows/release.yml') -Raw+ foreach ($name in @('Prepare release files', 'Create draft release')) {+ if ($workflow -notmatch ("- name: " + [regex]::Escape($name) + "\r?\n if: env.SIGNING_MODE != 'Test'")) {+ throw "$name must exclude the test lane."+ }+ }+ if ($workflow -notmatch "- name: Sign the final production installer for the updater\r?\n if: env.SIGNING_MODE == 'Production'") {+ throw 'Test lane must never generate an updater signature.'+ }+ Write-Host 'PASS: tests cannot prepare release files, updater signatures or draft releases'+} finally {+ $env:GITHUB_ACTIONS = $savedActions+ $env:RUNNER_ENVIRONMENT = $savedRunner+ # root is a newly created, test-owned absolute temp directory.+ if (Test-Path -LiteralPath $root) { Remove-Item -LiteralPath $root -Recurse -Force }+}diff --git a/spikes/Cargo.toml b/spikes/Cargo.tomlindex 3c62d3c..9bf36e8 100644--- a/spikes/Cargo.toml+++ b/spikes/Cargo.toml@@ -58,6 +58,7 @@ windows = { workspace = true, features = [windows-numerics.workspace = trueanyhow.workspace = truewindows-core.workspace = true+muelle-core.workspace = truemuelle-shell.workspace = truewindows-collections = "0.3"serde.workspace = truediff --git a/spikes/src/bin/spike_mascot.rs b/spikes/src/bin/spike_mascot.rsindex c02125b..e4372d0 100644--- a/spikes/src/bin/spike_mascot.rs+++ b/spikes/src/bin/spike_mascot.rs@@ -55,10 +55,18 @@ fn main() {.collect();let exact = match (std::env::args().nth(3).as_deref(), numbers.as_slice()) {(Some("under"), [x, top]) => Some(mascot::Place::Under { x: *x, top: *top }),+ // A trailing `left` or `right` plays it on a side dock's inner+ // wall: `left`/`right` then span the dock vertically and `top` is+ // the wall's x.(Some("along"), [left, right, top]) => Some(mascot::Place::Along {left: *left,right: *right,top: *top,+ edge: match std::env::args().nth(7).as_deref() {+ Some("left") => muelle_core::frame::DockEdge::Left,+ Some("right") => muelle_core::frame::DockEdge::Right,+ _ => muelle_core::frame::DockEdge::Bottom,+ },}),_ => None,};@@ -80,6 +88,7 @@ fn main() {left: 560,right: 1360,top: 900,+ edge: muelle_core::frame::DockEdge::Bottom,},RECT {left: 540,