Skip to content

A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.

feat: group dock icons into stacks

AzureAD\davidlama6c399b9f31da
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79a622b..6005287 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,26 @@ copia la sección de la versión que se publica a la release de GitHub.
## [Unreleased]
+### English
+
+- Dock groups: drag a pinned app onto the middle of another one (a blue frame
+ shows it) to put both in a group that takes a single place in the dock;
+ drop more apps on the group to add them. A group shows its first apps'
+ icons on a framed tile, and lists their names on hover. Clicking it fans
+ its apps out above it (a grid when there are many); drag one out of the
+ fan to take it out of the group, into the dock where it is dropped.
+ Right-click a group to ungroup it.
+
+### Español
+
+- Grupos en el dock: arrastra una app fijada al centro de otra (un marco azul
+ lo indica) para reunirlas en un grupo que ocupa un solo lugar en el dock;
+ suelta más apps sobre el grupo para añadirlas. Un grupo muestra los iconos
+ de sus primeras apps en un mosaico enmarcado, y sus nombres al pasar el
+ puntero. Al hacer clic se despliegan en abanico encima (en cuadrícula si son
+ muchas); arrastra una fuera del abanico para sacarla del grupo, al lugar del
+ dock donde la sueltes. Clic derecho en un grupo para desagruparlo.
+
## [0.1.12]
### English
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 791b988..d54f0e0 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -22,17 +22,19 @@ use std::{
};
use anyhow::{Context, Result};
-use muelle_config::Config;
+use muelle_config::{Config, DockGroup};
use muelle_core::{
bounce,
layout::{ItemKind, Layout, Metrics, layout},
magnify::{Magnifier, magnify},
- roster::Roster,
+ roster::{Group, Roster},
spring::Spring,
};
use muelle_shell::{
appbar::{ABN_FULLSCREENAPP, AppBar, Edge},
- files, launcher,
+ files,
+ icons::IconImage,
+ launcher,
pins::{self, app_exists, taskbar_pins, taskbar_pins_if_readable},
power,
recycle_bin::{self, BinWatch},
@@ -91,6 +93,7 @@ use crate::{
drop::DropTarget,
flight::{Flight, Snapshot},
gfx::{Gfx, LabelBrush},
+ group_view::{DragGhost, GroupItem, GroupView, Placement, Released},
mascot,
menu::{self, MenuItem},
menubar::MenuBar,
@@ -225,6 +228,12 @@ const SLIDE_OMEGA: f32 = 24.0;
const REVEAL_STRIP: i32 = 2;
/// An icon released this far above the magnified dock, in icon heights, leaves it.
const REMOVE_DISTANCE: f32 = 0.8;
+/// A dragged app joins the icon under it (in a group) when released over
+/// its middle, past this fraction of its width from either side; over its
+/// sides, it moves between icons as usual.
+const MERGE_SIDE: f32 = 0.25;
+/// Longest hover label of a group, which lists its apps.
+const GROUP_LABEL_CHARS: usize = 48;
const START_ID: &str = "muelle:start";
const WINDOW_ID_PREFIX: &str = "muelle:window:";
@@ -246,6 +255,7 @@ const CMD_RUN_AS_ADMIN: u32 = 11;
const CMD_SHOW_DESKTOP: u32 = 12;
const CMD_TASK_MANAGER: u32 = 13;
const CMD_TASKBAR_SETTINGS: u32 = 14;
+const CMD_UNGROUP: u32 = 15;
const CMD_WINDOW: u32 = 100;
const MENU_WINDOWS: usize = 12;
const MENU_TITLE_CHARS: usize = 60;
@@ -308,11 +318,16 @@ struct Entry {
id: Option<String>,
role: Role,
running: bool,
+ /// A group's apps, in order; empty for anything else. Part of the
+ /// scene's key: the group's tile shows them.
+ members: Vec<String>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
App,
+ /// Pinned apps gathered in one icon; a click unfolds them.
+ Group,
Start,
/// A minimized window, shown as a live thumbnail.
Window,
@@ -374,6 +389,8 @@ enum MenuTarget {
struct Asset {
icon: Option<CompositionSurfaceBrush>,
label: Option<LabelBrush>,
+ /// A group's apps when its tile was drawn; empty for anything else.
+ drawn_for: Vec<String>,
}
struct Press {
@@ -385,6 +402,10 @@ struct Dragging {
id: String,
point: POINT,
removing: bool,
+ /// The pinned app or group it would join if released now.
+ merge: Option<String>,
+ /// Dragged out of an open group (see `start_group_drag`).
+ from_group: bool,
}
/// What dropping the dragged files at a given place would do.
@@ -571,6 +592,13 @@ struct App {
hovered: Option<usize>,
preview_candidate: Option<String>,
preview: Option<MultiWindowView>,
+ /// A group's apps, unfolded above it after a click.
+ group_view: Option<GroupView>,
+ /// The group whose view a press on the dock closed: releasing on that
+ /// group then leaves it closed rather than opening it again.
+ group_was_open: Option<String>,
+ /// The icon following the pointer while an app is dragged out of a group.
+ ghost: Option<DragGhost>,
/// The crab, while it is out (see `perform`).
mascot: Option<mascot::Mascot>,
/// Charging and energy saver at the last power change.
@@ -621,13 +649,26 @@ fn load_config() -> Config {
}
}
-/// The Explorer is always pinned, like Finder.
+/// The Explorer is always pinned, like Finder, on its own.
fn roster_from(config: &Config) -> Roster {
let explorer = explorer_id();
let mut pinned = config.pinned.clone();
pinned.retain(|id| *id != explorer);
- pinned.insert(0, explorer);
- Roster::new(pinned, config.recent.clone())
+ pinned.insert(0, explorer.clone());
+ let groups = config
+ .groups
+ .iter()
+ .map(|group| Group {
+ id: group.id.clone(),
+ apps: group
+ .apps
+ .iter()
+ .filter(|id| **id != explorer)
+ .cloned()
+ .collect(),
+ })
+ .collect();
+ Roster::new(pinned, config.recent.clone()).with_groups(groups)
}
fn save_settings(roster: &Roster, config: &Config) {
@@ -639,6 +680,14 @@ fn save_settings(roster: &Roster, config: &Config) {
}
let config = Config {
pinned: roster.pinned().to_vec(),
+ groups: roster
+ .groups()
+ .iter()
+ .map(|group| DockGroup {
+ id: group.id.clone(),
+ apps: group.apps.clone(),
+ })
+ .collect(),
recent: roster.recent().to_vec(),
..config.clone()
};
@@ -707,19 +756,27 @@ impl App {
id: None,
role: Role::Folder,
running: false,
+ members: Vec::new(),
};
let icon = |id: &str, role: Role, running: bool| Entry {
kind: ItemKind::Icon,
id: Some(id.to_owned()),
role,
running,
+ members: Vec::new(),
};
let mut entries: Vec<Entry> = self
.roster
.apps()
.iter()
- .map(|app| icon(&app.id, Role::App, app.running))
+ .map(|app| match self.roster.group(&app.id) {
+ Some(group) => Entry {
+ members: group.apps.clone(),
+ ..icon(&app.id, Role::Group, app.running)
+ },
+ None => icon(&app.id, Role::App, app.running),
+ })
.collect();
entries.insert(0, icon(START_ID, Role::Start, false));
if self.config.show_recents && !self.roster.recent().is_empty() {
@@ -762,7 +819,59 @@ impl App {
if self.placeholder.is_none() {
self.placeholder = self.gfx.placeholder_brush(wanted, light).ok();
}
- for id in self.entries.iter().filter_map(|entry| entry.id.as_ref()) {
+ for entry in &self.entries {
+ let Some(id) = entry.id.as_ref() else {
+ continue;
+ };
+ if entry.role == Role::Group {
+ if self
+ .assets
+ .get(id)
+ .is_some_and(|asset| asset.drawn_for == entry.members)
+ {
+ continue;
+ }
+ // Every app is asked for, not only the four on the tile: the
+ // unfolded group shows them all.
+ for member in &entry.members {
+ let _ = self.icons.get(member, "");
+ }
+ let images: Vec<Option<&IconImage>> = entry
+ .members
+ .iter()
+ .take(4)
+ .map(|member| self.icons.peek(member, "").map(|visual| &visual.icon))
+ .collect();
+ let icon = self
+ .gfx
+ .group_brush(wanted, &images, entry.members.len(), light)
+ .inspect_err(|error| eprintln!("muelle: icono del grupo `{id}`: {error:#}"))
+ .ok()
+ .or_else(|| self.placeholder.clone());
+ let names: Vec<String> = entry
+ .members
+ .iter()
+ .map(|member| {
+ self.icons
+ .peek(member, "")
+ .map_or_else(|| fallback_name(member), |visual| visual.name.clone())
+ })
+ .collect();
+ let label = self
+ .gfx
+ .label_brush(&shorten(&names.join(", "), GROUP_LABEL_CHARS), scale, light)
+ .inspect_err(|error| eprintln!("muelle: etiqueta del grupo `{id}`: {error:#}"))
+ .ok();
+ self.assets.insert(
+ id.clone(),
+ Asset {
+ icon,
+ label,
+ drawn_for: entry.members.clone(),
+ },
+ );
+ continue;
+ }
let variant = if id == recycle_bin::PARSING_NAME {
if self.bin_full { "llena" } else { "vacia" }
} else {
@@ -779,13 +888,27 @@ 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();
- self.assets.insert(id.clone(), Asset { icon: None, label });
+ self.assets.insert(
+ id.clone(),
+ Asset {
+ icon: None,
+ label,
+ drawn_for: Vec::new(),
+ },
+ );
continue;
}
if id == START_ID {
let icon = self.gfx.start_brush(wanted).ok();
let label = self.gfx.label_brush(text().start, scale, light).ok();
- self.assets.insert(id.clone(), Asset { icon, label });
+ self.assets.insert(
+ id.clone(),
+ Asset {
+ icon,
+ label,
+ drawn_for: Vec::new(),
+ },
+ );
continue;
}
// A missing icon should not prevent the rest of the dock from rendering.
@@ -804,16 +927,27 @@ impl App {
.label_brush(&name, scale, light)
.inspect_err(|error| eprintln!("muelle: etiqueta de `{id}`: {error:#}"))
.ok();
- self.assets.insert(id.clone(), Asset { icon, label });
+ self.assets.insert(
+ id.clone(),
+ Asset {
+ icon,
+ label,
+ drawn_for: Vec::new(),
+ },
+ );
}
let entries = &self.entries;
self.assets
.retain(|id, _| entries.iter().any(|entry| entry.id.as_ref() == Some(id)));
let windows = &self.windows;
let explorer = explorer_id();
+ // The apps in groups keep their icons: their group's tile and its
+ // unfolded view draw them.
self.icons.retain(|id| {
id == explorer
- || entries.iter().any(|entry| entry.id.as_deref() == Some(id))
+ || entries.iter().any(|entry| {
+ entry.id.as_deref() == Some(id) || entry.members.iter().any(|app| app == id)
+ })
|| windows.iter().any(|window| window.app_id == id)
});
}
@@ -827,6 +961,16 @@ impl App {
self.assets.remove(id);
self.names.remove(id);
}
+ // A group's tile and label show its apps' icons and names.
+ let groups: Vec<String> = self
+ .entries
+ .iter()
+ .filter(|entry| entry.members.iter().any(|app| loaded.contains(app)))
+ .filter_map(|entry| entry.id.clone())
+ .collect();
+ for id in &groups {
+ self.assets.remove(id);
+ }
self.stage = None;
self.refresh()?;
self.update_menu_bar_app()
@@ -858,6 +1002,15 @@ impl App {
return Ok(());
}
self.close_preview();
+ // An unfolded group shows its apps as they were: it closes if they changed.
+ if let Some(view) = &self.group_view
+ && self
+ .roster
+ .group(&view.group_id)
+ .is_none_or(|group| group.apps.as_slice() != view.apps())
+ {
+ self.close_group_view();
+ }
let scale = monitor.scale;
let max_scale = key.max_scale;
@@ -1029,18 +1182,23 @@ impl App {
.flatten();
let now = Instant::now();
+ let lift_of = |id: &str| {
+ self.bounces.get(id).map_or(0.0, |bounce| {
+ let elapsed = now.duration_since(bounce.start).as_secs_f32();
+ bounce::lift(elapsed, stage.icon * BOUNCE_HEIGHT)
+ })
+ };
+ // A group bounces for any of its apps (opening, asking for attention).
let lifts: Vec<f32> = self
.entries
.iter()
- .map(|entry| {
- entry
- .id
- .as_ref()
- .and_then(|id| self.bounces.get(id))
- .map_or(0.0, |bounce| {
- let elapsed = now.duration_since(bounce.start).as_secs_f32();
- bounce::lift(elapsed, stage.icon * BOUNCE_HEIGHT)
- })
+ .map(|entry| match entry.role {
+ Role::Group => entry
+ .members
+ .iter()
+ .map(|app| lift_of(app.as_str()))
+ .fold(0.0, f32::max),
+ _ => entry.id.as_deref().map_or(0.0, lift_of),
})
.collect();
@@ -1055,11 +1213,27 @@ impl App {
(drag.point.y - stage.dock_origin.y) as f32,
),
removing: drag.removing,
+ ghost: drag.from_group,
})
});
+ let target = self
+ .drag
+ .as_ref()
+ .and_then(|drag| drag.merge.as_deref())
+ .and_then(|merge| {
+ self.entries
+ .iter()
+ .position(|entry| entry.id.as_deref() == Some(merge))
+ });
if drag.is_some() {
self.hovered = None;
}
+ // The open group's name would cover its unfolded apps.
+ let open_group = self.group_view.as_ref().and_then(|view| {
+ self.entries
+ .iter()
+ .position(|entry| entry.id.as_deref() == Some(view.group_id.as_str()))
+ });
let at_rest = self.amount.value == 0.0
&& self.bounces.is_empty()
&& self.slide.is_settled()
@@ -1067,9 +1241,12 @@ impl App {
let slide = self.slide.value * stage.slide_distance;
stage.scene.apply(&Frame {
state: &state,
- hovered: self.hovered.filter(|_| self.preview.is_none()),
+ hovered: self
+ .hovered
+ .filter(|&index| self.preview.is_none() && open_group != Some(index)),
lifts: &lifts,
drag,
+ target,
slide,
snap: at_rest,
})?;
@@ -1116,10 +1293,16 @@ impl App {
} else {
window_id(hwnd)
};
+ // An app in a group lives in its group's icon.
let index = self
.entries
.iter()
- .position(|entry| entry.id.as_deref() == Some(id.as_str()))?;
+ .position(|entry| entry.id.as_deref() == Some(id.as_str()))
+ .or_else(|| {
+ self.entries
+ .iter()
+ .position(|entry| entry.members.contains(&id))
+ })?;
let rect = stage.layout.slots.get(index)?.rect;
let (width, height) = if aspect >= 1.0 {
(rect.width, rect.width / aspect)
@@ -1349,6 +1532,7 @@ impl App {
|| self.drag_over
|| self.fullscreen
|| self.switching
+ || self.group_view.is_some()
{
return None;
}
@@ -1525,6 +1709,7 @@ impl App {
}
self.switching = true;
self.close_preview();
+ self.close_group_view();
self.flights.clear();
self.switch_started = Instant::now();
// SAFETY: Timers on our own window.
@@ -1701,6 +1886,11 @@ impl App {
self.entries
.iter()
.position(|entry| entry.role == Role::App && entry.id.as_ref() == Some(&app))
+ .or_else(|| {
+ self.entries
+ .iter()
+ .position(|entry| entry.members.contains(&app))
+ })
});
let (Some(index), Some(stage)) = (index, &self.stage) else {
return self.stop_following();
@@ -1923,6 +2113,7 @@ impl App {
|| self.drag.is_some()
|| self.switching
|| self.preview.is_some()
+ || self.group_view.is_some()
{
return Ok(());
}
@@ -1931,10 +2122,10 @@ impl App {
self.place_windows()
}
- /// Only running or pinned apps can be dragged; the Explorer, Start,
- /// recent apps, Downloads, and the recycle bin stay in place.
+ /// Only running or pinned apps, and groups, can be dragged; the Explorer,
+ /// Start, recent apps, Downloads, and the recycle bin stay in place.
fn is_draggable(&self, entry: &Entry) -> bool {
- entry.role == Role::App
+ matches!(entry.role, Role::App | Role::Group)
&& entry.id.as_ref().is_some_and(|id| {
*id != explorer_id() && (self.roster.is_pinned(id) || self.roster.is_running(id))
})
@@ -1942,6 +2133,10 @@ impl App {
fn on_press(&mut self) -> Result<()> {
self.close_preview();
+ // Any press on the dock closes an unfolded group; on the group
+ // itself, `on_click` then leaves it closed.
+ self.group_was_open = self.group_view.as_ref().map(|view| view.group_id.clone());
+ self.close_group_view();
let Some(at) = self.pointer_at_click()? else {
return Ok(());
};
@@ -2001,6 +2196,8 @@ impl App {
id: press.id.clone(),
point,
removing: false,
+ merge: None,
+ from_group: false,
});
}
}
@@ -2008,17 +2205,28 @@ impl App {
}
/// Moves the dragged icon and reorders the pinned apps live, as in macOS.
+ /// Held over the middle of another pinned app or a group, the dragged
+ /// app would join it in a group instead (see `MERGE_SIDE`).
fn drag_to(&mut self, point: POINT) -> Result<()> {
let (Some(stage), Some(drag)) = (&self.stage, &mut self.drag) else {
return Ok(());
};
drag.point = point;
+ if let Some(ghost) = &self.ghost {
+ ghost.move_to(point);
+ }
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);
- drag.removing = pinned && (point.y as f32) < top;
- if drag.removing {
+ let above = (point.y as f32) < top;
+ // 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.
+ drag.removing = pinned && above && !group && !drag.from_group;
+ drag.merge = None;
+ if drag.removing || (above && drag.from_group) {
return self.render();
}
@@ -2029,13 +2237,35 @@ impl App {
&stage.magnifier,
);
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;
+ if !group && in_dock {
+ drag.merge = self
+ .entries
+ .iter()
+ .zip(&state.rects)
+ .find(|(entry, rect)| {
+ let side = rect.width * MERGE_SIDE;
+ matches!(entry.role, Role::App | Role::Group)
+ && entry.id.as_ref().is_some_and(|other| {
+ *other != id && *other != explorer && self.roster.is_pinned(other)
+ })
+ && self.cursor >= rect.x + side
+ && self.cursor <= rect.x + rect.width - side
+ })
+ .and_then(|(entry, _)| entry.id.clone());
+ if drag.merge.is_some() {
+ return self.render();
+ }
+ }
+
let mut before: Option<String> = None;
let mut pinned_end = f32::MIN;
for (entry, rect) in self.entries.iter().zip(&state.rects) {
let Some(other) = entry.id.as_ref() else {
continue;
};
- if entry.role != Role::App
+ if !matches!(entry.role, Role::App | Role::Group)
|| *other == id
|| *other == explorer
|| !self.roster.is_pinned(other)
@@ -2110,7 +2340,7 @@ impl App {
.all(|file| files::same_volume(file, &id)),
folder: id,
},
- Role::App | Role::Start | Role::Window => DropAction::Nothing,
+ Role::App | Role::Group | Role::Start | Role::Window => DropAction::Nothing,
}
}
@@ -2125,7 +2355,7 @@ impl App {
.iter()
.zip(&state.rects)
.find(|(entry, rect)| {
- entry.role == Role::App
+ matches!(entry.role, Role::App | Role::Group)
&& entry.id.as_ref().is_some_and(|other| {
*other != explorer && *other != id && self.roster.is_pinned(other)
})
@@ -2287,12 +2517,16 @@ impl App {
unsafe {
let _ = ReleaseCapture();
}
- if drag.removing {
+ self.ghost = None;
+ if let Some(target) = &drag.merge {
+ self.roster.group_with(&drag.id, target);
+ } else if drag.removing {
self.roster.unpin(&drag.id);
}
save_settings(&self.roster, &self.config);
self.refresh()?;
self.leave_if_outside(drag.point)?;
+ self.after_group_drag(&drag)?;
Ok(None)
}
@@ -2303,11 +2537,27 @@ impl App {
let Some(drag) = self.drag.take() else {
return Ok(());
};
+ self.ghost = None;
save_settings(&self.roster, &self.config);
self.leave_if_outside(drag.point)?;
+ self.after_group_drag(&drag)?;
self.render()
}
+ /// A drag out of a group starts away from the dock, so no hover ends
+ /// with it: the input area shrinks back now, and an auto-hidden dock
+ /// goes down.
+ fn after_group_drag(&mut self, drag: &Dragging) -> Result<()> {
+ if !drag.from_group || self.hovering {
+ return Ok(());
+ }
+ if self.config.auto_hide {
+ // SAFETY: Timer on our own window.
+ unsafe { SetTimer(Some(self.input), HIDE_TIMER, HIDE_DELAY_MS, None) };
+ }
+ self.place_windows()
+ }
+
fn leave_if_outside(&mut self, point: POINT) -> Result<()> {
let Some(stage) = &self.stage else {
return Ok(());
@@ -2336,6 +2586,7 @@ impl App {
/// foreground. Clicking the app that is already in front minimizes it, as
/// the Windows taskbar does; the next click brings it back.
fn on_click(&mut self) -> Result<Option<Outside>> {
+ let group_was_open = self.group_was_open.take();
if self.pointer_at_click()?.is_none() {
return Ok(None);
}
@@ -2345,47 +2596,259 @@ impl App {
let (Some(id), role) = (entry.id.clone(), entry.role) else {
return Ok(None);
};
- let windows = self.windows_of(&id);
+ Ok(match role {
+ Role::App => self.click_app(id),
+ // A click unfolds the group; another click on it folds it back.
+ Role::Group => {
+ if group_was_open.as_deref() != Some(id.as_str()) {
+ self.open_group_view(&id)?;
+ }
+ None
+ }
+ Role::Start => Some(Outside::OpenStart),
+ Role::Window => window_of(&id).and_then(|hwnd| self.activating(vec![hwnd])),
+ Role::Folder | Role::Trash => Some(Outside::Open(id)),
+ })
+ }
+
+ /// What clicking the app `id` does, in the dock or in an unfolded group:
+ /// open it, bring its windows to the front, or minimize them if it is the
+ /// app in front.
+ fn click_app(&mut self, id: String) -> Option<Outside> {
+ let windows = self.windows_of(&id);
// As on the Windows taskbar: Shift+click opens another window of the
// app, Ctrl+Shift+click opens it as administrator.
- if role == Role::App {
- // SAFETY: Read-only keyboard state queries.
- let (shift, ctrl) = unsafe {
- (
- GetKeyState(i32::from(VK_SHIFT.0)) < 0,
- GetKeyState(i32::from(VK_CONTROL.0)) < 0,
- )
- };
- if shift {
- self.start_bounce(id.clone(), None);
- return Ok(Some(if ctrl {
- Outside::OpenAsAdmin(id)
- } else {
- Outside::Open(id)
- }));
- }
+ // SAFETY: Read-only keyboard state queries.
+ let (shift, ctrl) = unsafe {
+ (
+ GetKeyState(i32::from(VK_SHIFT.0)) < 0,
+ GetKeyState(i32::from(VK_CONTROL.0)) < 0,
+ )
+ };
+ if shift {
+ self.start_bounce(id.clone(), None);
+ return Some(if ctrl {
+ Outside::OpenAsAdmin(id)
+ } else {
+ Outside::Open(id)
+ });
}
+ if windows.is_empty() {
+ self.start_bounce(id.clone(), None);
+ Some(Outside::Open(id))
+ } else if windows.contains(&tracker::foreground_window()) {
+ Some(Outside::Minimize(windows))
+ } else {
+ self.activating(windows)
+ }
+ }
- Ok(match role {
- Role::App if windows.is_empty() => {
- self.start_bounce(id.clone(), None);
- Some(Outside::Open(id))
+ /// Unfolds the group `id` above its icon.
+ fn open_group_view(&mut self, id: &str) -> Result<()> {
+ self.close_preview();
+ self.close_group_view();
+ let Some(stage) = &self.stage else {
+ return Ok(());
+ };
+ let Some(index) = self
+ .entries
+ .iter()
+ .position(|entry| entry.id.as_deref() == Some(id))
+ else {
+ return Ok(());
+ };
+ let state = magnify(
+ &stage.layout,
+ self.cursor,
+ self.amount.value,
+ &stage.magnifier,
+ );
+ 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 (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(());
+ };
+ let items = self.group_items(id, icon as u32);
+ self.group_view = Some(GroupView::show(
+ &self.gfx,
+ id.to_owned(),
+ &items,
+ &Placement {
+ anchor,
+ screen: monitor.screen,
+ scale,
+ icon,
+ theme,
+ dock: self.input,
+ },
+ )?);
+ self.render()
+ }
+
+ /// The apps of the group `id`, drawn `side` pixels wide.
+ fn group_items(&mut self, id: &str, side: u32) -> Vec<GroupItem> {
+ let apps = self
+ .roster
+ .group(id)
+ .map(|group| group.apps.clone())
+ .unwrap_or_default();
+ let mut items = Vec::with_capacity(apps.len());
+ for app in apps {
+ let visual = self.icons.get(&app, "");
+ let icon = visual
+ .and_then(|visual| {
+ self.gfx
+ .icon_brush(&visual.icon, side.min(visual.icon.width))
+ .inspect_err(|error| eprintln!("muelle: icono de `{app}`: {error:#}"))
+ .ok()
+ })
+ .or_else(|| self.placeholder.clone());
+ let name = visual.map_or_else(|| fallback_name(&app), |visual| visual.name.clone());
+ items.push(GroupItem {
+ running: self.roster.is_running(&app),
+ id: app,
+ name,
+ icon,
+ });
+ }
+ items
+ }
+
+ fn close_group_view(&mut self) {
+ if self.group_view.take().is_some()
+ && self.config.auto_hide
+ && !self.hovering
+ && self.drag.is_none()
+ {
+ // SAFETY: Timer on our own window.
+ unsafe { SetTimer(Some(self.input), HIDE_TIMER, HIDE_DELAY_MS, None) };
+ }
+ }
+
+ /// The pointer moved over the unfolded group: past the drag threshold,
+ /// the app pressed leaves the group.
+ fn group_view_moved(&mut self) -> Result<()> {
+ let Some(view) = &mut self.group_view else {
+ return Ok(());
+ };
+ if let Some((id, point)) = view.drag_started()? {
+ return self.start_group_drag(id, point);
+ }
+ view.update()
+ }
+
+ /// An app dragged out of an unfolded group: it leaves the group for the
+ /// dock, right after the group, and the drag goes on as a dock drag. So
+ /// it can be placed among the icons or dropped on another group, and
+ /// released anywhere else it simply stays out of the group.
+ fn start_group_drag(&mut self, id: String, point: POINT) -> Result<()> {
+ // Closing the view also releases the mouse it held.
+ self.close_group_view();
+ if !self.roster.ungroup(&id) {
+ return Ok(());
+ }
+ let side = self.stage.as_ref().map_or(48.0, |stage| {
+ (stage.icon * stage.magnifier.max_scale).round()
+ });
+ let brush = self
+ .icons
+ .get(&id, "")
+ .and_then(|visual| {
+ self.gfx
+ .icon_brush(&visual.icon, (side as u32).min(visual.icon.width))
+ .ok()
+ })
+ .or_else(|| self.placeholder.clone());
+ self.ghost = brush.and_then(|brush| {
+ DragGhost::show(&self.gfx, &brush, side, point)
+ .inspect_err(|error| eprintln!("muelle: icono arrastrado: {error:#}"))
+ .ok()
+ });
+ self.press = None;
+ self.drag = Some(Dragging {
+ id,
+ point,
+ removing: false,
+ merge: None,
+ from_group: true,
+ });
+ self.refresh()?;
+ if let Some(stage) = &self.stage {
+ self.cursor = (point.x - stage.dock_origin.x) as f32;
+ }
+ // SAFETY: Capture keeps mouse input while dragging outside the dock.
+ unsafe {
+ SetCapture(self.input);
+ }
+ self.drag_to(point)
+ }
+
+ fn group_view_released(&mut self) -> Result<Option<Outside>> {
+ let Some(view) = &mut self.group_view else {
+ return Ok(None);
+ };
+ Ok(match view.release()? {
+ Released::Item(id) => {
+ self.close_group_view();
+ self.click_app(id)
}
- Role::App if windows.contains(&tracker::foreground_window()) => {
- Some(Outside::Minimize(windows))
+ Released::Dismiss => {
+ self.close_group_view();
+ None
}
- Role::App => self.activating(windows),
- Role::Start => Some(Outside::OpenStart),
- Role::Window => window_of(&id).and_then(|hwnd| self.activating(vec![hwnd])),
- Role::Folder | Role::Trash => Some(Outside::Open(id)),
+ Released::Nothing => None,
})
}
+ /// Right-click on an app in an unfolded group: that app's dock menu.
+ fn group_view_menu(&mut self) -> Result<Option<Outside>> {
+ let Some(view) = &self.group_view else {
+ return Ok(None);
+ };
+ let hit = view.item_at_cursor()?;
+ self.close_group_view();
+ let Some((id, rect)) = hit else {
+ return Ok(None);
+ };
+ let windows = self.windows_of(&id);
+ let items = self.entry_menu(&id, Role::App, &windows);
+ let gap = self
+ .stage
+ .as_ref()
+ .map_or(0, |stage| (stage.gap / 2.0).round() as i32);
+ let anchor = POINT {
+ x: (rect.left + rect.right) / 2,
+ y: rect.top - gap,
+ };
+ self.render()?;
+ Ok(Some(Outside::Menu(MenuRequest {
+ gfx: self.gfx.clone(),
+ target: MenuTarget::Entry {
+ id,
+ role: Role::App,
+ windows,
+ },
+ items,
+ anchor,
+ dark: !uses_light_theme(),
+ })))
+ }
+
/// Middle click on an app opens another window of it, as on the Windows
/// taskbar.
fn on_middle_click(&mut self) -> Result<Option<Outside>> {
self.close_preview();
+ self.close_group_view();
if self.pointer_at_click()?.is_none() {
return Ok(None);
}
@@ -2403,6 +2866,7 @@ impl App {
/// menu when over empty space or a divider.
fn on_right_click(&mut self) -> Result<Option<Outside>> {
self.close_preview();
+ self.close_group_view();
if self.pointer_at_click()?.is_none() {
return Ok(None);
}
@@ -2510,6 +2974,11 @@ impl App {
items.push(MenuItem::action(CMD_QUIT_APP, t.quit_app));
}
}
+ Role::Group => {
+ items.push(MenuItem::action(CMD_OPEN, t.open));
+ items.push(MenuItem::Separator);
+ items.push(MenuItem::action(CMD_UNGROUP, t.ungroup));
+ }
Role::Start => items.push(MenuItem::action(CMD_OPEN, t.open)),
Role::Window => {
items.push(MenuItem::action(CMD_OPEN, t.open));
@@ -2547,6 +3016,18 @@ impl App {
};
};
Ok(match command {
+ CMD_OPEN if role == Role::Group => {
+ self.open_group_view(&id)?;
+ None
+ }
+ // The group's apps go back to the dock, in its place.
+ CMD_UNGROUP => {
+ self.close_group_view();
+ self.roster.dissolve(&id);
+ save_settings(&self.roster, &self.config);
+ self.refresh()?;
+ None
+ }
CMD_OPEN if role == Role::Start => Some(Outside::OpenStart),
CMD_OPEN if role == Role::Window => {
window_of(&id).and_then(|hwnd| self.activating(vec![hwnd]))
@@ -2599,6 +3080,7 @@ impl App {
/// The settings app saved a change: read it and apply what differs.
fn reload_config(&mut self) -> Result<()> {
self.close_preview();
+ self.close_group_view();
let Ok(Some(saved)) = muelle_config::load(&muelle_config::default_path()) else {
return Ok(());
};
@@ -2606,6 +3088,7 @@ impl App {
// changes the rest.
let config = Config {
pinned: self.config.pinned.clone(),
+ groups: self.config.groups.clone(),
recent: self.config.recent.clone(),
taskbar_pins: self.config.taskbar_pins.clone(),
..saved
@@ -2687,14 +3170,14 @@ impl App {
}
/// Unpins apps that were uninstalled, so no broken icon stays behind, as
- /// the Windows taskbar drops them. Returns whether anything changed.
+ /// the Windows taskbar drops them; apps in groups too. Returns whether
+ /// anything changed.
fn prune_missing_pins(&mut self) -> bool {
let missing: Vec<String> = self
.roster
- .pinned()
- .iter()
+ .pinned_apps()
+ .into_iter()
.filter(|id| !app_exists(id))
- .cloned()
.collect();
for id in &missing {
self.roster.unpin(id);
@@ -2957,6 +3440,7 @@ impl App {
if fullscreen {
self.stop_mascot();
self.close_preview();
+ self.close_group_view();
SetTimer(
Some(self.input),
FULLSCREEN_TIMER,
@@ -2981,6 +3465,7 @@ impl App {
self.amount = Spring::at(0.0, HOVER_OMEGA);
self.press = None;
self.drag = None;
+ self.ghost = None;
}
if let Err(error) = self.place_windows() {
self.fullscreen = previous;
@@ -3188,6 +3673,45 @@ pub fn multi_window_view_dismiss() {
});
}
+pub fn group_view_tick() {
+ with_app("grupo", |app| {
+ if let Some(view) = &mut app.group_view
+ && !view.tick()?
+ {
+ app.close_group_view();
+ }
+ Ok(())
+ });
+}
+
+pub fn group_view_press() {
+ with_app("grupo", |app| match &mut app.group_view {
+ Some(view) => view.press(),
+ None => Ok(()),
+ });
+}
+
+pub fn group_view_moved() {
+ with_app("arrastre desde un grupo", App::group_view_moved);
+}
+
+pub fn group_view_release() {
+ with_app_then("abrir desde un grupo", App::group_view_released);
+}
+
+pub fn group_view_menu() {
+ with_app_then("menú de un grupo", App::group_view_menu);
+}
+
+pub fn group_view_press_lost() {
+ with_app("grupo", |app| {
+ if let Some(view) = &mut app.group_view {
+ view.cancel_press();
+ }
+ Ok(())
+ });
+}
+
/// The pointer rested on the top edge with the menu bar hidden.
pub fn menu_bar_edge_rested() {
with_app("barra superior", |app| match &mut app.menubar {
@@ -3726,6 +4250,9 @@ pub fn run() -> Result<()> {
hovered: None,
preview_candidate: None,
preview: None,
+ group_view: None,
+ group_was_open: None,
+ ghost: None,
mascot: None,
// Initial registration notifications establish the baseline after
// the queue starts, without playing a startup charging/saver act.
diff --git a/apps/dock/src/assets.rs b/apps/dock/src/assets.rs
index 1606ae7..6523589 100644
--- a/apps/dock/src/assets.rs
+++ b/apps/dock/src/assets.rs
@@ -135,6 +135,17 @@ impl Visuals {
self.ready.get(&request).and_then(Option::as_ref)
}
+ /// Like `get`, but only reads what is loaded already: several loaded
+ /// visuals can then be borrowed at once (a group's tile).
+ pub fn peek(&self, id: &str, variant: &'static str) -> Option<&AppVisual> {
+ self.ready
+ .get(&Request {
+ id: id.to_owned(),
+ variant,
+ })
+ .and_then(Option::as_ref)
+ }
+
pub fn collect(&mut self) -> Vec<String> {
let mut changed = Vec::new();
for loaded in self.results.try_iter() {
diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rs
index 2b6bed8..9296b39 100644
--- a/apps/dock/src/gfx.rs
+++ b/apps/dock/src/gfx.rs
@@ -42,7 +42,7 @@ use windows::{
DWRITE_MEASURING_MODE_NATURAL, DWRITE_PARAGRAPH_ALIGNMENT_CENTER,
DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_TEXT_METRICS, DWRITE_TRIMMING,
DWRITE_TRIMMING_GRANULARITY_CHARACTER, DWRITE_WORD_WRAPPING_NO_WRAP,
- DWriteCreateFactory, IDWriteFactory,
+ DWriteCreateFactory, IDWriteFactory, IDWriteTextLayout,
},
Dxgi::{Common::DXGI_FORMAT_B8G8R8A8_UNORM, IDXGIDevice},
},
@@ -448,6 +448,218 @@ impl Gfx {
})
}
+ /// A group's icon: a frosted rounded square with a rim, holding the first
+ /// apps' icons in a 2×2 grid, so a group never looks like a single app.
+ /// With more than four apps the last cell counts the others. `icons` are
+ /// the first apps' images (`None` while one is loading); `count` is how
+ /// many apps the group has.
+ pub fn group_brush(
+ &self,
+ side: u32,
+ icons: &[Option<&IconImage>],
+ count: usize,
+ light: bool,
+ ) -> Result<CompositionSurfaceBrush> {
+ let size = side as f32;
+ let inset = size * 0.08;
+ let tile = size - 2.0 * inset;
+ let radius = tile * 0.225;
+ let pad = tile * 0.13;
+ let gap = tile * 0.08;
+ let cell = (tile - 2.0 * pad - gap) / 2.0;
+ let stroke = (size * 0.022).max(1.0);
+ let more = if count > 4 {
+ Some(self.centered_text(&format!("+{}", count - 3), cell * 0.5, cell)?)
+ } else {
+ None
+ };
+ let (fill_color, rim_color, slot_color, ink_color) = if light {
+ (
+ rgb(1.0, 1.0, 1.0, 0.55),
+ rgb(0.0, 0.0, 0.0, 0.22),
+ rgb(0.0, 0.0, 0.0, 0.10),
+ rgb(0.0, 0.0, 0.0, 0.75),
+ )
+ } else {
+ (
+ rgb(0.30, 0.30, 0.33, 0.62),
+ rgb(1.0, 1.0, 1.0, 0.34),
+ rgb(1.0, 1.0, 1.0, 0.12),
+ rgb(1.0, 1.0, 1.0, 0.92),
+ )
+ };
+ self.draw(side, side, |dc| {
+ let half = stroke / 2.0;
+ // SAFETY: Brushes, the text layout and the images stay alive
+ // through the drawing calls.
+ unsafe {
+ let fill = dc.CreateSolidColorBrush(&fill_color, None)?;
+ dc.FillRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: inset,
+ top: inset,
+ right: size - inset,
+ bottom: size - inset,
+ },
+ radiusX: radius,
+ radiusY: radius,
+ },
+ &fill,
+ );
+ let rim = dc.CreateSolidColorBrush(&rim_color, None)?;
+ dc.DrawRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: inset + half,
+ top: inset + half,
+ right: size - inset - half,
+ bottom: size - inset - half,
+ },
+ radiusX: radius - half,
+ radiusY: radius - half,
+ },
+ &rim,
+ stroke,
+ None,
+ );
+ let slot = dc.CreateSolidColorBrush(&slot_color, None)?;
+ let ink = dc.CreateSolidColorBrush(&ink_color, None)?;
+ for index in 0..count.min(4) {
+ let left = inset + pad + (index % 2) as f32 * (cell + gap);
+ let top = inset + pad + (index / 2) as f32 * (cell + gap);
+ let rect = D2D_RECT_F {
+ left,
+ top,
+ right: left + cell,
+ bottom: top + cell,
+ };
+ let rounded = D2D1_ROUNDED_RECT {
+ rect,
+ radiusX: cell * 0.22,
+ radiusY: cell * 0.22,
+ };
+ if index == 3
+ && let Some(more) = &more
+ {
+ dc.FillRoundedRectangle(&rounded, &slot);
+ dc.DrawTextLayout(
+ Vector2 { X: left, Y: top },
+ more,
+ &ink,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+ } else if let Some(Some(icon)) = icons.get(index) {
+ draw_image_in(dc, icon, rect, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC)?;
+ } else {
+ dc.FillRoundedRectangle(&rounded, &slot);
+ }
+ }
+ }
+ Ok(())
+ })
+ }
+
+ /// One line centered in a `side` × `side` square, to draw inside an icon.
+ fn centered_text(&self, text: &str, font_size: f32, side: f32) -> Result<IDWriteTextLayout> {
+ let utf16: Vec<u16> = text.encode_utf16().collect();
+ // SAFETY: The string and the format live through each call.
+ unsafe {
+ let format = self.dwrite.CreateTextFormat(
+ text_font(),
+ None,
+ DWRITE_FONT_WEIGHT_SEMI_BOLD,
+ DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL,
+ font_size.max(1.0),
+ w!(""),
+ )?;
+ format.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)?;
+ format.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)?;
+ Ok(self
+ .dwrite
+ .CreateTextLayout(&utf16, &format, side.max(1.0), side.max(1.0))?)
+ }
+ }
+
+ /// A name on a rounded pill, cut with an ellipsis to fit `max_width`:
+ /// the names beside the apps of an unfolded group.
+ pub fn pill_brush(
+ &self,
+ text: &str,
+ scale: f32,
+ light: bool,
+ max_width: f32,
+ ) -> Result<LabelBrush> {
+ let (pad_x, pad_y) = (10.0 * scale, 4.0 * scale);
+ let (fill_color, ink_color) = if light {
+ (rgb(0.96, 0.96, 0.97, 0.92), rgb(0.0, 0.0, 0.0, 0.88))
+ } else {
+ (rgb(0.13, 0.13, 0.14, 0.86), rgb(1.0, 1.0, 1.0, 0.95))
+ };
+ let room = (max_width - 2.0 * pad_x).max(1.0);
+ let utf16: Vec<u16> = text.encode_utf16().collect();
+ // SAFETY: Strings and structures passed to each call remain alive for its duration.
+ let (layout, metrics) = unsafe {
+ let format = self.dwrite.CreateTextFormat(
+ text_font(),
+ None,
+ DWRITE_FONT_WEIGHT_MEDIUM,
+ DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL,
+ 13.0 * scale,
+ w!(""),
+ )?;
+ let layout = self.dwrite.CreateTextLayout(&utf16, &format, room, 256.0)?;
+ layout.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP)?;
+ let ellipsis = self.dwrite.CreateEllipsisTrimmingSign(&format)?;
+ layout.SetTrimming(
+ &DWRITE_TRIMMING {
+ granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER,
+ ..Default::default()
+ },
+ &ellipsis,
+ )?;
+ let mut metrics = DWRITE_TEXT_METRICS::default();
+ layout.GetMetrics(&mut metrics)?;
+ (layout, metrics)
+ };
+ let width = (metrics.width.ceil().clamp(1.0, room) + 2.0 * pad_x).ceil();
+ let height = (metrics.height + 2.0 * pad_y).ceil();
+ let brush = self.draw(width as u32, height as u32, |dc| {
+ // SAFETY: The brushes and the layout live through the drawing calls.
+ unsafe {
+ let fill = dc.CreateSolidColorBrush(&fill_color, None)?;
+ dc.FillRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: 0.0,
+ top: 0.0,
+ right: width,
+ bottom: height,
+ },
+ radiusX: height / 2.0,
+ radiusY: height / 2.0,
+ },
+ &fill,
+ );
+ let ink = dc.CreateSolidColorBrush(&ink_color, None)?;
+ dc.DrawTextLayout(
+ Vector2 { X: pad_x, Y: pad_y },
+ &layout,
+ &ink,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+ }
+ Ok(())
+ })?;
+ Ok(LabelBrush {
+ brush,
+ width,
+ height,
+ })
+ }
+
/// Shared temporary app tile while a shell icon is loading or unavailable.
pub fn placeholder_brush(&self, side: u32, light: bool) -> Result<CompositionSurfaceBrush> {
let size = side as f32;
@@ -895,6 +1107,22 @@ fn draw_image(
width: f32,
height: f32,
interpolation: D2D1_INTERPOLATION_MODE,
+) -> Result<()> {
+ let dest = D2D_RECT_F {
+ left: 0.0,
+ top: 0.0,
+ right: width,
+ bottom: height,
+ };
+ draw_image_in(dc, image, dest, interpolation)
+}
+
+/// Draws `image` stretched over `dest`.
+fn draw_image_in(
+ dc: &ID2D1DeviceContext,
+ image: &IconImage,
+ dest: D2D_RECT_F,
+ interpolation: D2D1_INTERPOLATION_MODE,
) -> Result<()> {
let properties = D2D1_BITMAP_PROPERTIES1 {
pixelFormat: D2D1_PIXEL_FORMAT {
@@ -906,12 +1134,6 @@ fn draw_image(
bitmapOptions: D2D1_BITMAP_OPTIONS_NONE,
..Default::default()
};
- let dest = D2D_RECT_F {
- left: 0.0,
- top: 0.0,
- right: width,
- bottom: height,
- };
// SAFETY: `image.bgra` contains `width * height * 4` bytes and the stride is `width * 4`.
unsafe {
let bitmap = dc.CreateBitmap(
diff --git a/apps/dock/src/group_view.rs b/apps/dock/src/group_view.rs
new file mode 100644
index 0000000..1ace1f8
--- /dev/null
+++ b/apps/dock/src/group_view.rs
@@ -0,0 +1,900 @@
+//! A dock group unfolded above its icon when it is clicked, as macOS fans
+//! out a Dock stack: a fan of icons with their names going up from the
+//! group or, when they do not fit, a grid on a panel. Clicking an app opens
+//! it as its own dock icon would; dragging one away takes it out of the
+//! group, and the dock carries on with the drag (see `App::start_group_drag`).
+
+use std::time::Instant;
+
+use anyhow::Result;
+use muelle_shell::{system::animations_enabled, tracker};
+use windows::{
+ UI::{
+ Color,
+ Composition::{
+ CompositionSurfaceBrush, ContainerVisual, Desktop::DesktopWindowTarget, SpriteVisual,
+ },
+ },
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
+ Graphics::Dwm::{DWMWA_USE_HOSTBACKDROPBRUSH, DwmSetWindowAttribute},
+ System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},
+ UI::{
+ Input::KeyboardAndMouse::{
+ GetAsyncKeyState, ReleaseCapture, SetCapture, VK_ESCAPE, VK_LBUTTON, VK_MBUTTON,
+ VK_RBUTTON,
+ },
+ WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, GetSystemMetrics,
+ HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MA_NOACTIVATE, PostMessageW,
+ RegisterClassW, SM_CXDRAG, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,
+ WM_APP, WM_CAPTURECHANGED, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEACTIVATE,
+ WM_MOUSEMOVE, WM_RBUTTONUP, WM_TIMER, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE,
+ WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_EX_TRANSPARENT,
+ WS_POPUP, WindowFromPoint,
+ },
+ },
+ },
+ core::{BOOL, Interface, w},
+};
+use windows_numerics::{Vector2, Vector3};
+
+use crate::{
+ app,
+ gfx::{Gfx, Ink},
+ scene::Theme,
+};
+
+const TIMER: usize = 1;
+/// Posted to itself when the window loses the mouse it held for a press.
+const PRESS_LOST: u32 = WM_APP + 1;
+// Dimensions are in logical pixels and are multiplied by the display scale.
+/// Room between the group's icon and what unfolds above it.
+const LIFT: f32 = 12.0;
+const MARGIN: f32 = 12.0;
+/// Fan: room between two apps, widest name, and room between name and icon.
+const FAN_SPACING: f32 = 14.0;
+const FAN_LABEL_MAX: f32 = 220.0;
+const FAN_LABEL_GAP: f32 = 10.0;
+/// How far right the top of the fan bends, in icons.
+const FAN_CURVE: f32 = 0.6;
+/// More apps than this unfold as a grid, as a crowded macOS stack does.
+const FAN_MAX: usize = 10;
+const GRID_PADDING: f32 = 16.0;
+const GRID_CELL_MIN: f32 = 92.0;
+const GRID_ICON_TOP: f32 = 8.0;
+const GRID_TEXT: f32 = 20.0;
+const GRID_FONT: f32 = 12.0;
+/// Room right of an icon for the dot of an open app.
+const DOT_ROOM: f32 = 10.0;
+const DOT_SIZE: f32 = 5.0;
+/// The hover highlight reaches this far around an icon.
+const GLOW: f32 = 6.0;
+const OPEN_SECONDS: f32 = 0.22;
+/// Each app sets off a little after the one below it.
+const STAGGER_SECONDS: f32 = 0.025;
+
+/// One app of the group, as the dock knows it.
+pub struct GroupItem {
+ pub id: String,
+ pub name: String,
+ pub icon: Option<CompositionSurfaceBrush>,
+ pub running: bool,
+}
+
+/// Where and how a group unfolds.
+pub struct Placement {
+ /// The group's icon on screen.
+ pub anchor: RECT,
+ pub screen: RECT,
+ pub scale: f32,
+ /// Side of the apps' icons, in pixels.
+ pub icon: f32,
+ pub theme: Theme,
+ /// The dock's input window: a press there is the dock's business.
+ pub dock: HWND,
+}
+
+/// What releasing the mouse on the view means.
+pub enum Released {
+ /// The app pressed and released on.
+ Item(String),
+ /// A click on the view's empty space: it closes.
+ Dismiss,
+ Nothing,
+}
+
+/// Pure layout, shared by drawing and hit testing. Rectangles are in the
+/// window's coordinates; `bounds` is the window on screen.
+struct GroupLayout {
+ bounds: RECT,
+ fan: bool,
+ icons: Vec<RECT>,
+ /// Grid only: each app's cell, its icon above its name.
+ cells: Vec<RECT>,
+}
+
+impl GroupLayout {
+ fn new(screen: RECT, anchor: RECT, scale: f32, icon: f32, count: usize) -> Self {
+ let center = (anchor.left + anchor.right) as f32 / 2.0;
+ let bottom = anchor.top as f32 - LIFT * scale;
+ let pitch = icon + FAN_SPACING * scale;
+ let room = bottom - screen.top as f32 - MARGIN * scale - icon;
+ let fits = ((room / pitch).floor().max(-1.0) + 1.0) as usize;
+ if count <= FAN_MAX.min(fits) {
+ Self::fan(screen, center, bottom, scale, icon, count)
+ } else {
+ Self::grid(screen, center, bottom, scale, icon, count)
+ }
+ }
+
+ /// The first app sits right above the group; the others go up, the
+ /// column bending right, with their names on the left.
+ fn fan(screen: RECT, center: f32, bottom: f32, scale: f32, icon: f32, count: usize) -> Self {
+ let pitch = icon + FAN_SPACING * scale;
+ let curve = FAN_CURVE * icon;
+ let margin = MARGIN * scale;
+ let left = center - icon / 2.0 - (FAN_LABEL_GAP + FAN_LABEL_MAX) * scale - margin;
+ let right = center + curve + icon / 2.0 + DOT_ROOM * scale + margin;
+ let top = bottom - count.saturating_sub(1) as f32 * pitch - icon - margin;
+ let width = (right - left).ceil();
+ // Near a screen edge the whole fan moves over, names and icons alike.
+ let fitted = left.round().clamp(
+ screen.left as f32,
+ (screen.right as f32 - width).max(screen.left as f32),
+ );
+ let center = center + (fitted - left);
+ let left = fitted;
+ let top = top.round().max(screen.top as f32);
+ let bounds = RECT {
+ left: left as i32,
+ top: top as i32,
+ right: (left + width) as i32,
+ bottom: bottom.ceil() as i32,
+ };
+ let icons = (0..count)
+ .map(|index| {
+ let along = if count > 1 {
+ index as f32 / (count - 1) as f32
+ } else {
+ 0.0
+ };
+ let x = center + curve * along * along - icon / 2.0 - left;
+ let y = bottom - index as f32 * pitch - icon - top;
+ rect(x, y, icon, icon)
+ })
+ .collect();
+ Self {
+ bounds,
+ fan: true,
+ icons,
+ cells: Vec::new(),
+ }
+ }
+
+ /// 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 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 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)
+ .max(count.div_ceil(max_rows))
+ .clamp(1, max_columns);
+ let shown = count.min(columns * max_rows);
+ 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 bounds = RECT {
+ left: left as i32,
+ top: top as i32,
+ right: (left + width).round() as i32,
+ bottom: (top + height).round() as i32,
+ };
+ let cells: Vec<RECT> = (0..shown)
+ .map(|index| {
+ rect(
+ pad + (index % columns) as f32 * cell_width,
+ pad + (index / columns) as f32 * cell_height,
+ cell_width,
+ cell_height,
+ )
+ })
+ .collect();
+ let icons = cells
+ .iter()
+ .map(|cell| {
+ rect(
+ cell.left as f32 + (cell_width - icon) / 2.0,
+ cell.top as f32 + GRID_ICON_TOP * scale,
+ icon,
+ icon,
+ )
+ })
+ .collect();
+ Self {
+ bounds,
+ fan: false,
+ icons,
+ cells,
+ }
+ }
+}
+
+fn rect(x: f32, y: f32, width: f32, height: f32) -> RECT {
+ RECT {
+ left: x.round() as i32,
+ top: y.round() as i32,
+ right: (x + width).round() as i32,
+ bottom: (y + height).round() as i32,
+ }
+}
+
+fn contains(rect: RECT, point: POINT) -> bool {
+ point.x >= rect.left && point.x < rect.right && point.y >= rect.top && point.y < rect.bottom
+}
+
+fn v2(x: f32, y: f32) -> Vector2 {
+ Vector2 { X: x, Y: y }
+}
+
+fn v3(x: f32, y: f32) -> Vector3 {
+ Vector3 { X: x, Y: y, Z: 0.0 }
+}
+
+const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
+ Color {
+ A: a,
+ R: r,
+ G: g,
+ B: b,
+ }
+}
+
+struct ItemVisual {
+ root: ContainerVisual,
+ highlight: SpriteVisual,
+}
+
+pub struct GroupView {
+ pub group_id: String,
+ hwnd: HWND,
+ dock: HWND,
+ target: Option<DesktopWindowTarget>,
+ layout: GroupLayout,
+ /// The group's apps, in its order, when it opened.
+ ids: Vec<String>,
+ visuals: Vec<ItemVisual>,
+ /// Where each app answers the pointer: its icon and its name.
+ targets: Vec<RECT>,
+ panel: Option<ContainerVisual>,
+ anchor: RECT,
+ scale: f32,
+ opened: Instant,
+ animated: bool,
+ /// The app pressed, and where the pointer was on screen.
+ pressed: Option<(usize, POINT)>,
+ mouse_was_down: bool,
+ foreground: isize,
+}
+
+impl GroupView {
+ pub fn show(
+ gfx: &Gfx,
+ group_id: String,
+ items: &[GroupItem],
+ place: &Placement,
+ ) -> Result<Self> {
+ let layout = GroupLayout::new(
+ place.screen,
+ place.anchor,
+ place.scale,
+ place.icon,
+ items.len(),
+ );
+ // SAFETY: Class and window belong to this UI thread. Once created,
+ // `view` owns the HWND even if the graphics setup below fails.
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = w!("MuelleGroupView");
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(group_view_proc),
+ hInstance: instance.into(),
+ hCursor: LoadCursorW(None, IDC_ARROW)?,
+ lpszClassName: class,
+ ..Default::default()
+ });
+ CreateWindowExW(
+ WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+ class,
+ w!("Muelle group"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?
+ };
+ let mut view = Self {
+ group_id,
+ hwnd,
+ dock: place.dock,
+ target: None,
+ layout,
+ ids: items.iter().map(|item| item.id.clone()).collect(),
+ visuals: Vec::new(),
+ targets: Vec::new(),
+ panel: None,
+ anchor: place.anchor,
+ scale: place.scale,
+ opened: Instant::now(),
+ animated: animations_enabled(),
+ pressed: None,
+ mouse_was_down: false,
+ foreground: tracker::foreground_window(),
+ };
+ // The grid's panel is glass, as the dock: same backdrop setup. Older
+ // Windows versions reject it; their theme is opaque anyway.
+ let enable = BOOL::from(true);
+ // SAFETY: Our own window and a live value of the declared size.
+ unsafe {
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_USE_HOSTBACKDROPBRUSH,
+ (&raw const enable).cast(),
+ size_of::<BOOL>() as u32,
+ );
+ }
+ // SAFETY: This process owns the top-level destination window.
+ view.target = Some(unsafe {
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?
+ });
+ view.build(gfx, items, place.theme)?;
+ let bounds = view.layout.bounds;
+ // SAFETY: Shows our window without taking the focus from the app in front.
+ unsafe {
+ SetWindowPos(
+ hwnd,
+ Some(HWND_TOPMOST),
+ bounds.left,
+ bounds.top,
+ bounds.right - bounds.left,
+ bounds.bottom - bounds.top,
+ SWP_NOACTIVATE | SWP_SHOWWINDOW,
+ )?;
+ SetTimer(Some(hwnd), TIMER, 16, None);
+ }
+ view.update()?;
+ Ok(view)
+ }
+
+ /// The group's apps as they were when it opened.
+ pub fn apps(&self) -> &[String] {
+ &self.ids
+ }
+
+ fn build(&mut self, gfx: &Gfx, items: &[GroupItem], theme: Theme) -> Result<()> {
+ let c = &gfx.compositor;
+ let s = self.scale;
+ let root = c.CreateContainerVisual()?;
+ let layers = root.Children()?;
+ if !self.layout.fan {
+ let bounds = self.layout.bounds;
+ let size = v2(
+ (bounds.right - bounds.left) as f32,
+ (bounds.bottom - bounds.top) as f32,
+ );
+ let panel = theme.panel(gfx, size, 18.0 * s, s)?;
+ layers.InsertAtTop(&panel)?;
+ self.panel = Some(panel);
+ }
+ let ink = if theme.light { Ink::Dark } else { Ink::Light };
+ let dot_side = (DOT_SIZE * s).round();
+ let dot = c.CreateEllipseGeometry()?;
+ dot.SetCenter(v2(dot_side / 2.0, dot_side / 2.0))?;
+ dot.SetRadius(v2(dot_side / 2.0, dot_side / 2.0))?;
+ let dot_brush = c.CreateColorBrushWithColor(if theme.light {
+ rgba(0, 0, 0, 170)
+ } else {
+ rgba(255, 255, 255, 215)
+ })?;
+ let glow_brush = c.CreateColorBrushWithColor(rgba(80, 150, 255, 80))?;
+ let glow = (GLOW * s).round();
+ for (index, (item, icon)) in items.iter().zip(&self.layout.icons).enumerate() {
+ let side = (icon.right - icon.left) as f32;
+ // An app's visuals are placed from its icon's top-left corner.
+ let app = c.CreateContainerVisual()?;
+ let children = app.Children()?;
+
+ let around = v2(side + 2.0 * glow, side + 2.0 * glow);
+ let highlight = c.CreateSpriteVisual()?;
+ highlight.SetSize(around)?;
+ highlight.SetOffset(v3(-glow, -glow))?;
+ highlight.SetBrush(&glow_brush)?;
+ let shape = c.CreateRoundedRectangleGeometry()?;
+ shape.SetSize(around)?;
+ shape.SetCornerRadius(v2(around.X * 0.24, around.X * 0.24))?;
+ highlight.SetClip(&c.CreateGeometricClipWithGeometry(&shape)?)?;
+ highlight.SetOpacity(0.0)?;
+ children.InsertAtTop(&highlight)?;
+
+ let picture = c.CreateSpriteVisual()?;
+ picture.SetSize(v2(side, side))?;
+ if let Some(brush) = &item.icon {
+ picture.SetBrush(brush)?;
+ }
+ children.InsertAtTop(&picture)?;
+
+ if item.running {
+ let shape = c.CreateSpriteShapeWithGeometry(&dot)?;
+ shape.SetFillBrush(&dot_brush)?;
+ let marker = c.CreateShapeVisual()?;
+ marker.SetSize(v2(dot_side, dot_side))?;
+ marker.Shapes()?.Append(&shape)?;
+ marker.SetOffset(v3(side + 3.0 * s, ((side - dot_side) / 2.0).round()))?;
+ children.InsertAtTop(&marker)?;
+ }
+
+ let margin = glow as i32;
+ let mut target = RECT {
+ left: icon.left - margin,
+ top: icon.top - margin,
+ right: icon.right + margin,
+ bottom: icon.bottom + margin,
+ };
+ if self.layout.fan {
+ let label = gfx.pill_brush(&item.name, s, theme.light, FAN_LABEL_MAX * s)?;
+ let name = c.CreateSpriteVisual()?;
+ name.SetSize(v2(label.width, label.height))?;
+ name.SetBrush(&label.brush)?;
+ let left = -(FAN_LABEL_GAP * s).round() - label.width;
+ name.SetOffset(v3(left, ((side - label.height) / 2.0).round()))?;
+ children.InsertAtTop(&name)?;
+ target.left = target.left.min(icon.left + left.floor() as i32);
+ } else if let Some(cell) = self.layout.cells.get(index) {
+ let width = (cell.right - cell.left) as f32;
+ let label = gfx.text_brush_fitted(
+ &item.name,
+ s,
+ GRID_FONT,
+ false,
+ ink,
+ (width - 8.0 * s).max(1.0),
+ )?;
+ let name = c.CreateSpriteVisual()?;
+ name.SetSize(v2(label.width, label.height))?;
+ name.SetBrush(&label.brush)?;
+ name.SetOffset(v3(
+ ((width - label.width) / 2.0).round() - (icon.left - cell.left) as f32,
+ side + (GRID_ICON_TOP * s).round(),
+ ))?;
+ children.InsertAtTop(&name)?;
+ target = *cell;
+ }
+ layers.InsertAtTop(&app)?;
+ self.visuals.push(ItemVisual {
+ root: app,
+ highlight,
+ });
+ self.targets.push(target);
+ }
+ if let Some(target) = &self.target {
+ target.SetRoot(&root)?;
+ }
+ Ok(())
+ }
+
+ /// Moves the apps along their opening animation and lights the one
+ /// under the pointer.
+ pub fn update(&mut self) -> Result<()> {
+ let elapsed = self.opened.elapsed().as_secs_f32();
+ let hovered = self.hit(self.local_cursor()?);
+ let lit = self.pressed.map(|(index, _)| index).or(hovered);
+ let start = (
+ ((self.anchor.left + self.anchor.right) / 2 - self.layout.bounds.left) as f32,
+ (self.anchor.top - self.layout.bounds.top) as f32,
+ );
+ let mut moving = false;
+ for (index, (visual, icon)) in self.visuals.iter().zip(&self.layout.icons).enumerate() {
+ let progress = if self.animated {
+ ((elapsed - index as f32 * STAGGER_SECONDS) / OPEN_SECONDS).clamp(0.0, 1.0)
+ } else {
+ 1.0
+ };
+ moving |= progress < 1.0;
+ 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.
+ let (from_x, from_y) = if self.layout.fan {
+ (start.0 - side / 2.0, start.1 - side)
+ } else {
+ (left, top + 24.0 * self.scale)
+ };
+ visual.root.SetOffset(v3(
+ from_x + (left - from_x) * eased,
+ from_y + (top - from_y) * eased,
+ ))?;
+ visual.root.SetOpacity(eased)?;
+ visual
+ .highlight
+ .SetOpacity(if lit == Some(index) { 1.0 } else { 0.0 })?;
+ }
+ if let Some(panel) = &self.panel {
+ let progress = if self.animated {
+ (elapsed / OPEN_SECONDS).min(1.0)
+ } else {
+ 1.0
+ };
+ panel.SetOpacity(1.0 - (1.0 - progress).powi(3))?;
+ }
+ // Quick while unfolding; then just often enough to follow the pointer.
+ // SAFETY: Our own timer; setting it again replaces it.
+ unsafe { SetTimer(Some(self.hwnd), TIMER, if moving { 16 } else { 50 }, None) };
+ Ok(())
+ }
+
+ /// `false` once it should close: Escape, a click elsewhere (a click on
+ /// the dock excepted: the dock handles it), or another window in front.
+ pub fn tick(&mut self) -> Result<bool> {
+ let front = tracker::foreground_window();
+ if front != self.foreground
+ && front != self.dock.0 as isize
+ && front != self.hwnd.0 as isize
+ {
+ return Ok(false);
+ }
+ let mut point = POINT::default();
+ // SAFETY: Read-only pointer, window and key state queries.
+ let (escape, mouse_down, over_dock) = unsafe {
+ GetCursorPos(&mut point)?;
+ (
+ GetAsyncKeyState(i32::from(VK_ESCAPE.0)) < 0,
+ GetAsyncKeyState(i32::from(VK_LBUTTON.0)) < 0
+ || GetAsyncKeyState(i32::from(VK_RBUTTON.0)) < 0
+ || GetAsyncKeyState(i32::from(VK_MBUTTON.0)) < 0,
+ WindowFromPoint(point) == self.dock,
+ )
+ };
+ let inside =
+ over_dock || contains(self.layout.bounds, point) || contains(self.anchor, point);
+ if escape || (mouse_down && !self.mouse_was_down && !inside) {
+ return Ok(false);
+ }
+ self.mouse_was_down = mouse_down;
+ self.update()?;
+ Ok(true)
+ }
+
+ pub fn press(&mut self) -> Result<()> {
+ let mut point = POINT::default();
+ // SAFETY: Valid output buffer for a read-only query.
+ unsafe { GetCursorPos(&mut point)? };
+ self.pressed = self.hit(self.to_local(point)).map(|index| (index, point));
+ if self.pressed.is_some() {
+ // Keep the mouse while the button is down, wherever it goes: the
+ // press may become a drag out of the group.
+ // SAFETY: Our own window, on its thread.
+ unsafe {
+ SetCapture(self.hwnd);
+ }
+ }
+ self.update()
+ }
+
+ /// The app pressed, once the pointer has moved far enough to drag it,
+ /// and where the pointer is.
+ pub fn drag_started(&self) -> Result<Option<(String, POINT)>> {
+ let Some((index, at)) = self.pressed else {
+ return Ok(None);
+ };
+ let mut point = POINT::default();
+ // SAFETY: Read-only queries.
+ let threshold = unsafe {
+ GetCursorPos(&mut point)?;
+ GetSystemMetrics(SM_CXDRAG).max(1)
+ };
+ let moved = (point.x - at.x).abs() > threshold || (point.y - at.y).abs() > threshold;
+ Ok(moved
+ .then(|| self.ids.get(index).cloned())
+ .flatten()
+ .map(|id| (id, point)))
+ }
+
+ pub fn release(&mut self) -> Result<Released> {
+ let point = self.local_cursor()?;
+ let pressed = self.pressed.take();
+ if pressed.is_some() {
+ // SAFETY: Releasing the capture taken in `press`.
+ unsafe {
+ let _ = ReleaseCapture();
+ }
+ }
+ let hit = self.hit(point);
+ Ok(match pressed {
+ Some((index, _)) if hit == Some(index) => self
+ .ids
+ .get(index)
+ .cloned()
+ .map_or(Released::Nothing, Released::Item),
+ Some(_) => Released::Nothing,
+ None if hit.is_none() => Released::Dismiss,
+ None => Released::Nothing,
+ })
+ }
+
+ /// The mouse was taken away mid-press (Alt+Tab, a system dialog).
+ pub fn cancel_press(&mut self) {
+ self.pressed = None;
+ }
+
+ /// The app under the pointer, and its icon on screen.
+ pub fn item_at_cursor(&self) -> Result<Option<(String, RECT)>> {
+ let hit = self.hit(self.local_cursor()?);
+ let bounds = self.layout.bounds;
+ Ok(hit.and_then(|index| {
+ let icon = self.layout.icons.get(index)?;
+ Some((
+ self.ids.get(index)?.clone(),
+ RECT {
+ left: bounds.left + icon.left,
+ top: bounds.top + icon.top,
+ right: bounds.left + icon.right,
+ bottom: bounds.top + icon.bottom,
+ },
+ ))
+ }))
+ }
+
+ fn hit(&self, point: POINT) -> Option<usize> {
+ self.targets.iter().position(|rect| contains(*rect, point))
+ }
+
+ fn to_local(&self, point: POINT) -> POINT {
+ POINT {
+ x: point.x - self.layout.bounds.left,
+ y: point.y - self.layout.bounds.top,
+ }
+ }
+
+ fn local_cursor(&self) -> Result<POINT> {
+ let mut point = POINT::default();
+ // SAFETY: Valid output buffer for a read-only query.
+ unsafe { GetCursorPos(&mut point)? };
+ Ok(self.to_local(point))
+ }
+}
+
+impl Drop for GroupView {
+ fn drop(&mut self) {
+ // Release the composition target before the HWND.
+ self.target = None;
+ // SAFETY: Our own timer and window, on their thread.
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), TIMER);
+ let _ = DestroyWindow(self.hwnd);
+ }
+ }
+}
+
+unsafe extern "system" fn group_view_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ match msg {
+ WM_MOUSEACTIVATE => return LRESULT(MA_NOACTIVATE as isize),
+ WM_TIMER if w.0 == TIMER => app::group_view_tick(),
+ WM_LBUTTONDOWN => app::group_view_press(),
+ WM_MOUSEMOVE => app::group_view_moved(),
+ WM_LBUTTONUP => app::group_view_release(),
+ WM_RBUTTONUP => app::group_view_menu(),
+ // Posted: it also comes while the dock is busy closing this window.
+ // SAFETY: Posting to our own window; dropped if it is gone by then.
+ WM_CAPTURECHANGED => unsafe {
+ let _ = PostMessageW(Some(hwnd), PRESS_LOST, WPARAM(0), LPARAM(0));
+ },
+ PRESS_LOST => app::group_view_press_lost(),
+ _ => return unsafe { DefWindowProcW(hwnd, msg, w, l) },
+ }
+ LRESULT(0)
+}
+
+/// An app's icon following the pointer while it is dragged out of a group:
+/// above everything, and letting clicks through.
+pub struct DragGhost {
+ hwnd: HWND,
+ /// Kept alive with the window; released before it.
+ _target: Option<DesktopWindowTarget>,
+ side: i32,
+}
+
+impl DragGhost {
+ pub fn show(gfx: &Gfx, icon: &CompositionSurfaceBrush, side: f32, at: POINT) -> Result<Self> {
+ // SAFETY: Class and window belong to this UI thread; `ghost` owns
+ // the HWND as soon as it exists.
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = w!("MuelleDragGhost");
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(ghost_proc),
+ hInstance: instance.into(),
+ lpszClassName: class,
+ ..Default::default()
+ });
+ // Layered and transparent, as the dock's visual window: drawn
+ // by the compositor, and clicks go through it.
+ CreateWindowExW(
+ WS_EX_LAYERED
+ | WS_EX_TRANSPARENT
+ | WS_EX_NOREDIRECTIONBITMAP
+ | WS_EX_TOPMOST
+ | WS_EX_TOOLWINDOW
+ | WS_EX_NOACTIVATE,
+ class,
+ w!("Muelle"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?
+ };
+ let mut ghost = Self {
+ hwnd,
+ _target: None,
+ side: side.round().max(1.0) as i32,
+ };
+ let length = ghost.side as f32;
+ // SAFETY: This process owns the top-level destination window.
+ let target = unsafe {
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?
+ };
+ let root = gfx.compositor.CreateContainerVisual()?;
+ let picture = gfx.compositor.CreateSpriteVisual()?;
+ picture.SetSize(v2(length, length))?;
+ picture.SetBrush(icon)?;
+ picture.SetOpacity(0.92)?;
+ root.Children()?.InsertAtTop(&picture)?;
+ target.SetRoot(&root)?;
+ ghost._target = Some(target);
+ ghost.move_to(at);
+ Ok(ghost)
+ }
+
+ /// Centers the icon on `at`, on screen.
+ pub fn move_to(&self, at: POINT) {
+ // SAFETY: Our own window; moving it never activates it.
+ unsafe {
+ let _ = SetWindowPos(
+ self.hwnd,
+ Some(HWND_TOPMOST),
+ at.x - self.side / 2,
+ at.y - self.side / 2,
+ self.side,
+ self.side,
+ SWP_NOACTIVATE | SWP_SHOWWINDOW,
+ );
+ }
+ }
+}
+
+impl Drop for DragGhost {
+ fn drop(&mut self) {
+ self._target = None;
+ // SAFETY: Our own window, on its thread.
+ unsafe {
+ let _ = DestroyWindow(self.hwnd);
+ }
+ }
+}
+
+unsafe extern "system" fn ghost_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ // SAFETY: Default handling for our own window.
+ unsafe { DefWindowProcW(hwnd, msg, w, l) }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SCREEN: RECT = RECT {
+ left: 0,
+ top: 0,
+ right: 1920,
+ bottom: 1080,
+ };
+
+ fn anchor(left: i32) -> RECT {
+ RECT {
+ left,
+ top: 990,
+ right: left + 48,
+ bottom: 1038,
+ }
+ }
+
+ #[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);
+ assert!(layout.fan);
+ assert!(layout.bounds.bottom <= anchor(900).top);
+ let tops: Vec<i32> = layout.icons.iter().map(|icon| icon.top).collect();
+ assert!(tops.windows(2).all(|pair| pair[1] < pair[0]));
+ // The first app sits right above the group.
+ let first = layout.icons[0];
+ let middle = layout.bounds.left + (first.left + first.right) / 2;
+ assert!((middle - 924).abs() <= 1);
+ }
+
+ #[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);
+ let short = RECT {
+ bottom: 400,
+ ..SCREEN
+ };
+ let low = RECT {
+ top: 340,
+ bottom: 388,
+ ..anchor(900)
+ };
+ assert!(!GroupLayout::new(short, low, 1.0, 48.0, 8).fan);
+ }
+
+ #[test]
+ fn group_layout_should_stay_on_screen_at_both_edges_and_high_dpi() {
+ 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 bounds = layout.bounds;
+ assert!(bounds.left >= SCREEN.left && bounds.right <= SCREEN.right);
+ assert!(bounds.top >= SCREEN.top && bounds.bottom <= anchor(left).top);
+ let (width, height) = (bounds.right - bounds.left, bounds.bottom - bounds.top);
+ for icon in &layout.icons {
+ assert!(icon.left >= 0 && icon.right <= width);
+ assert!(icon.top >= 0 && icon.bottom <= height);
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn grid_cells_should_not_overlap() {
+ let layout = GroupLayout::new(SCREEN, anchor(900), 1.0, 48.0, 23);
+ assert_eq!(layout.cells.len(), 23);
+ for (index, cell) in layout.cells.iter().enumerate() {
+ let center = POINT {
+ x: (cell.left + cell.right) / 2,
+ y: (cell.top + cell.bottom) / 2,
+ };
+ let under: Vec<usize> = layout
+ .cells
+ .iter()
+ .enumerate()
+ .filter(|(_, other)| contains(**other, center))
+ .map(|(other, _)| other)
+ .collect();
+ assert_eq!(under, [index]);
+ }
+ }
+}
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index 56b8247..7651616 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -16,6 +16,7 @@ mod assets;
mod drop;
mod flight;
mod gfx;
+mod group_view;
mod guard;
mod mascot;
mod media;
diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rs
index 503a3f1..87a2b5c 100644
--- a/apps/dock/src/scene.rs
+++ b/apps/dock/src/scene.rs
@@ -1,6 +1,8 @@
//! Dock visual tree: shadow, glass, specular border, dividers, icons, indicators,
//! and labels. It is built once per configuration; only its elements move per frame.
+use std::cell::Cell;
+
use anyhow::Result;
use muelle_core::{
layout::{ItemKind, Layout, Rect},
@@ -65,6 +67,15 @@ impl Theme {
}
}
+ /// Inside the frame around the icon a dragged app would join.
+ fn merge_fill(&self) -> Color {
+ if self.light {
+ rgba(255, 255, 255, 120)
+ } else {
+ rgba(255, 255, 255, 46)
+ }
+ }
+
/// Uses the context menu tint with the same rim and sheen as the window picker.
pub(crate) fn for_popup(light: bool, glass: bool) -> Self {
Self {
@@ -166,6 +177,9 @@ impl GlassSurface {
}
}
+/// Outline of the icon a dragged app would join in a group.
+const MERGE_ACCENT: Color = rgba(80, 150, 255, 230);
+
const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
Color {
A: a,
@@ -215,6 +229,10 @@ pub struct Drag {
pub center: (f32, f32),
/// Released here, the icon would leave the dock.
pub removing: bool,
+ /// Taken out of a group: a window of its own follows the pointer (see
+ /// `group_view::DragGhost`), and the slot only shows, faded, where the
+ /// app will land.
+ pub ghost: bool,
}
/// Everything that changes from one frame to the next.
@@ -223,6 +241,8 @@ pub struct Frame<'a> {
pub hovered: Option<usize>,
pub lifts: &'a [f32],
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.
pub slide: f32,
/// Align to whole pixels; only at rest, where sharpness matters.
@@ -260,6 +280,14 @@ pub struct Scene {
frames: [Visual; 3],
outline: CompositionRoundedRectangleGeometry,
rim_geometry: CompositionRoundedRectangleGeometry,
+ content: ContainerVisual,
+ /// Frame drawn around the icon a dragged app would join.
+ merge: ShapeVisual,
+ merge_geometry: CompositionRoundedRectangleGeometry,
+ merge_stroke: f32,
+ /// The slot brought to the front for the current drag, so it passes
+ /// over the icons it is dropped on.
+ raised: Cell<Option<usize>>,
slots: Vec<SpriteVisual>,
badges: Vec<Option<SpriteVisual>>,
indicators: Vec<Option<ShapeVisual>>,
@@ -314,6 +342,19 @@ impl Scene {
dot.SetRadius(v2(indicator_size / 2.0, indicator_size / 2.0))?;
let dot_brush = c.CreateColorBrushWithColor(theme.indicator)?;
+ // Below the icons: it frames the one under the dragged app.
+ let merge_stroke = (2.0 * scale).max(1.0);
+ let merge_geometry = c.CreateRoundedRectangleGeometry()?;
+ merge_geometry.SetOffset(v2(merge_stroke / 2.0, merge_stroke / 2.0))?;
+ let merge_shape = c.CreateSpriteShapeWithGeometry(&merge_geometry)?;
+ merge_shape.SetFillBrush(&c.CreateColorBrushWithColor(theme.merge_fill())?)?;
+ merge_shape.SetStrokeBrush(&c.CreateColorBrushWithColor(MERGE_ACCENT)?)?;
+ merge_shape.SetStrokeThickness(merge_stroke)?;
+ let merge = c.CreateShapeVisual()?;
+ merge.Shapes()?.Append(&merge_shape)?;
+ merge.SetIsVisible(false)?;
+ children.InsertAtTop(&merge)?;
+
let mut slots = Vec::with_capacity(layout.slots.len());
let mut badges = Vec::with_capacity(layout.slots.len());
let mut indicators = Vec::with_capacity(layout.slots.len());
@@ -374,6 +415,11 @@ impl Scene {
frames: [shadow_host.cast()?, glass.cast()?, rim.cast()?],
outline,
rim_geometry,
+ content,
+ merge,
+ merge_geometry,
+ merge_stroke,
+ raised: Cell::new(None),
slots,
badges,
indicators,
@@ -391,11 +437,19 @@ impl Scene {
hovered,
lifts,
drag,
+ target,
slide,
snap,
} = *frame;
let fit = |value: f32| if snap { value.round() } else { value };
self.root.SetOffset(v3(0.0, slide))?;
+ self.raise(drag.map(|drag| drag.index))?;
+ self.place_merge(target.and_then(|index| {
+ Some((
+ *state.rects.get(index)?,
+ lifts.get(index).copied().unwrap_or(0.0),
+ ))
+ }))?;
let size = v2(fit(state.right - state.left), self.height);
let offset = v3(self.origin.0 + fit(state.left), self.origin.1);
@@ -415,7 +469,7 @@ impl Scene {
height,
} = *rect;
let dragged = drag.filter(|drag| drag.index == index);
- let (x, y) = match dragged {
+ let (x, y) = match dragged.filter(|drag| !drag.ghost) {
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)),
};
@@ -423,8 +477,12 @@ impl Scene {
if let Some(visual) = self.slots.get(index) {
visual.SetOffset(v3(fit(x), fit(y)))?;
visual.SetSize(v2(fit(width), fit(height)))?;
- let removing = dragged.is_some_and(|drag| drag.removing);
- visual.SetOpacity(if removing { 0.55 } else { 1.0 })?;
+ let opacity = match dragged {
+ Some(drag) if drag.removing => 0.55,
+ Some(drag) if drag.ghost => 0.35,
+ _ => 1.0,
+ };
+ visual.SetOpacity(opacity)?;
}
if let Some(Some(badge)) = self.badges.get(index) {
let side = width * BADGE_SIZE;
@@ -463,6 +521,41 @@ impl Scene {
Ok(())
}
+ /// Brings the dragged slot above the others, once per drag (the scene
+ /// is rebuilt whenever the order changes).
+ fn raise(&self, index: Option<usize>) -> Result<()> {
+ if index.is_none() || self.raised.get() == index {
+ return Ok(());
+ }
+ if let Some(visual) = index.and_then(|index| self.slots.get(index)) {
+ let children = self.content.Children()?;
+ children.Remove(visual)?;
+ children.InsertAtTop(visual)?;
+ }
+ self.raised.set(index);
+ Ok(())
+ }
+
+ /// Frames `target` (its rectangle and how far it is lifted), or hides
+ /// the frame.
+ fn place_merge(&self, target: Option<(Rect, f32)>) -> Result<()> {
+ let Some((rect, lift)) = target else {
+ self.merge.SetIsVisible(false)?;
+ return Ok(());
+ };
+ 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.SetSize(size)?;
+ self.merge_geometry
+ .SetSize(v2(size.X - self.merge_stroke, size.Y - self.merge_stroke))?;
+ let radius = size.X * 0.26;
+ self.merge_geometry.SetCornerRadius(v2(radius, radius))?;
+ self.merge.SetIsVisible(true)?;
+ 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(),
diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rs
index b8f3941..62a9712 100644
--- a/apps/dock/src/strings.rs
+++ b/apps/dock/src/strings.rs
@@ -20,6 +20,7 @@ pub struct Strings {
pub start: &'static str,
pub remove: &'static str,
pub close_window: &'static str,
+ pub ungroup: &'static str,
pub settings: &'static str,
pub run_as_admin: &'static str,
pub show_desktop: &'static str,
@@ -53,6 +54,7 @@ const ES: Strings = Strings {
start: "Inicio",
remove: "Quitar",
close_window: "&Cerrar",
+ ungroup: "&Desagrupar",
settings: "&Ajustes de Muelle…",
run_as_admin: "Ejecutar como a&dministrador",
show_desktop: "Mostrar &escritorio",
@@ -85,6 +87,7 @@ const EN: Strings = Strings {
start: "Start",
remove: "Remove",
close_window: "&Close",
+ ungroup: "&Ungroup",
settings: "Muelle &Settings…",
run_as_admin: "Run as a&dministrator",
show_desktop: "Show &Desktop",
diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rs
index 2ce5f89..0888945 100644
--- a/apps/settings/src-tauri/src/main.rs
+++ b/apps/settings/src-tauri/src/main.rs
@@ -21,6 +21,7 @@ fn merged_with_disk(config: Config) -> Config {
match muelle_config::load(&muelle_config::default_path()) {
Ok(Some(disk)) => Config {
pinned: disk.pinned,
+ groups: disk.groups,
recent: disk.recent,
taskbar_pins: disk.taskbar_pins,
..config
diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rs
index df40723..0cc7e42 100644
--- a/crates/muelle-config/src/lib.rs
+++ b/crates/muelle-config/src/lib.rs
@@ -36,7 +36,10 @@ pub enum ConfigError {
#[serde(rename_all = "camelCase")]
pub struct Config {
pub version: u32,
+ /// Pinned items in dock order: apps, and the ids of `groups`.
pub pinned: Vec<String>,
+ /// Pinned apps gathered in one dock icon each.
+ pub groups: Vec<DockGroup>,
pub recent: Vec<String>,
/// The apps pinned to the Windows taskbar when the dock last looked, to
/// bring pins and unpins made there (even while Muelle was closed) to the
@@ -79,6 +82,16 @@ pub struct Config {
pub language: Language,
}
+/// Pinned apps the user gathered in one dock icon by dropping one on
+/// another. Its `id` stands for it in `pinned`, in its place.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+#[serde(rename_all = "camelCase")]
+pub struct DockGroup {
+ pub id: String,
+ pub apps: Vec<String>,
+}
+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
@@ -119,6 +132,7 @@ impl Default for Config {
Self {
version: CURRENT_VERSION,
pinned: Vec::new(),
+ groups: Vec::new(),
recent: Vec::new(),
taskbar_pins: None,
auto_hide: false,
@@ -241,6 +255,25 @@ mod tests {
assert!(!config.show_minimized);
}
+ #[test]
+ fn load_should_read_dock_groups() {
+ let path = scratch("groups");
+ save(&path, &Config::default()).ok();
+ fs::write(
+ &path,
+ r#"{"pinned":["a","muelle:group:1"],"groups":[{"id":"muelle:group:1","apps":["b","c"]}]}"#,
+ )
+ .ok();
+ let config = load(&path).ok().flatten().unwrap_or_default();
+ assert_eq!(
+ config.groups,
+ [DockGroup {
+ id: "muelle:group:1".into(),
+ apps: vec!["b".into(), "c".into()],
+ }]
+ );
+ }
+
#[test]
fn load_should_read_show_minimized() {
let path = scratch("show-minimized");
diff --git a/crates/muelle-core/src/roster.rs b/crates/muelle-core/src/roster.rs
index 2635e5b..2f4dc91 100644
--- a/crates/muelle-core/src/roster.rs
+++ b/crates/muelle-core/src/roster.rs
@@ -1,19 +1,36 @@
//! Which apps appear in the dock and in what order:
-//! 1. pinned apps;
+//! 1. pinned apps, some of them gathered in groups;
//! 2. unpinned open apps, in opening order;
//! 3. recently closed unpinned apps, as in macOS.
pub const MAX_RECENT: usize = 3;
+/// Ids of groups start with this, so they never collide with an app's.
+pub const GROUP_PREFIX: &str = "muelle:group:";
+
+#[must_use]
+pub fn is_group_id(id: &str) -> bool {
+ id.starts_with(GROUP_PREFIX)
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DockApp {
pub id: String,
pub running: bool,
}
+/// Pinned apps gathered in one dock icon. The group's id stands in the
+/// pinned list, in the group's place; its apps count as pinned.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Group {
+ pub id: String,
+ pub apps: Vec<String>,
+}
+
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Roster {
pinned: Vec<String>,
+ groups: Vec<Group>,
extra: Vec<String>,
running: Vec<String>,
recent: Vec<String>,
@@ -32,6 +49,52 @@ impl Roster {
roster
}
+ /// Adds the groups saved with the pinned list, mending what a
+ /// hand-edited file could break: a group missing from the pinned list
+ /// gives its apps back to the dock, an app is in one place only, and a
+ /// group with fewer than two apps gives way to its app.
+ #[must_use]
+ pub fn with_groups(mut self, groups: Vec<Group>) -> Self {
+ for group in groups {
+ let mut apps: Vec<String> = Vec::new();
+ for app in group.apps {
+ let taken = is_group_id(&app)
+ || apps.contains(&app)
+ || self.pinned.contains(&app)
+ || self.groups.iter().any(|other| other.apps.contains(&app));
+ if !taken {
+ apps.push(app);
+ }
+ }
+ let placed = is_group_id(&group.id)
+ && self.pinned.contains(&group.id)
+ && !self.is_group(&group.id);
+ if placed {
+ self.groups.push(Group { id: group.id, apps });
+ } else {
+ self.pinned.extend(apps);
+ }
+ }
+ let groups = &self.groups;
+ let mut seen: Vec<String> = Vec::new();
+ self.pinned.retain(|id| {
+ if !is_group_id(id) {
+ return true;
+ }
+ let keep = groups.iter().any(|group| group.id == *id) && !seen.contains(id);
+ seen.push(id.clone());
+ keep
+ });
+ self.tidy_groups();
+ let grouped: Vec<String> = self
+ .groups
+ .iter()
+ .flat_map(|group| group.apps.iter().cloned())
+ .collect();
+ self.recent.retain(|id| !grouped.contains(id));
+ self
+ }
+
/// Updates open apps and returns `true` if the dock's displayed items change.
pub fn sync<'a>(&mut self, running: impl IntoIterator<Item = &'a str>) -> bool {
let before = (self.apps(), self.recent.clone());
@@ -50,7 +113,8 @@ impl Roster {
.collect();
self.extra.retain(|id| now.contains(id));
for id in &now {
- if !self.pinned.contains(id) && !self.extra.contains(id) {
+ // Apps in a group are pinned: they stay in their group.
+ if !self.is_pinned(id) && !self.extra.contains(id) {
self.extra.push(id.clone());
}
}
@@ -69,13 +133,38 @@ impl Roster {
self.running.iter().any(|running| running == id)
}
+ /// `true` for a pinned app, on its own or in a group, and for a group.
#[must_use]
pub fn is_pinned(&self, id: &str) -> bool {
- self.pinned.iter().any(|pinned| pinned == id)
+ self.pinned.iter().any(|pinned| pinned == id) || self.group_of(id).is_some()
+ }
+
+ #[must_use]
+ pub fn is_group(&self, id: &str) -> bool {
+ self.groups.iter().any(|group| group.id == id)
+ }
+
+ #[must_use]
+ pub fn group(&self, id: &str) -> Option<&Group> {
+ self.groups.iter().find(|group| group.id == id)
+ }
+
+ /// The group `app` is in, if any.
+ #[must_use]
+ pub fn group_of(&self, app: &str) -> Option<&Group> {
+ self.groups
+ .iter()
+ .find(|group| group.apps.iter().any(|member| member == app))
+ }
+
+ #[must_use]
+ pub fn groups(&self) -> &[Group] {
+ &self.groups
}
/// Pins an app at the end of the pinned list. If it was open and unpinned,
/// it keeps its screen position as it moves from the open list to the pinned list.
+ /// An app already in a group stays there.
pub fn pin(&mut self, id: &str) {
if self.is_pinned(id) {
return;
@@ -86,7 +175,8 @@ impl Roster {
}
/// Pins `id` (or moves it, if already pinned) right before `before`, or at
- /// the end of the pinned list when `before` is `None` or not pinned.
+ /// the end of the pinned list when `before` is `None` or not pinned. `id`
+ /// may be a group; an app in a group leaves it.
pub fn pin_before(&mut self, id: &str, before: Option<&str>) {
if before == Some(id) {
return;
@@ -94,36 +184,133 @@ impl Roster {
self.pinned.retain(|pinned| pinned != id);
self.extra.retain(|extra| extra != id);
self.recent.retain(|recent| recent != id);
+ self.leave_group(id);
let at = before
.and_then(|before| self.pinned.iter().position(|pinned| pinned == before))
.unwrap_or(self.pinned.len());
self.pinned.insert(at, id.to_owned());
+ self.tidy_groups();
}
/// Unpins an app. If it is open, it remains in the dock as the first unpinned
- /// app until it closes.
+ /// app until it closes. An app in a group leaves it; a whole group leaves
+ /// the dock with its apps.
pub fn unpin(&mut self, id: &str) {
+ if let Some(group) = self.group(id).cloned() {
+ self.pinned.retain(|pinned| pinned != id);
+ self.groups.retain(|other| other.id != id);
+ for app in group.apps.iter().rev() {
+ if self.is_running(app) && !self.extra.contains(app) {
+ self.extra.insert(0, app.clone());
+ }
+ }
+ return;
+ }
if !self.is_pinned(id) {
return;
}
self.pinned.retain(|pinned| pinned != id);
+ self.leave_group(id);
+ self.tidy_groups();
if self.is_running(id) {
self.extra.insert(0, id.to_owned());
}
}
+ /// Puts `app` in a group with `target`, a pinned app or group in the
+ /// dock: into `target` if it is a group, or else into a new group that
+ /// takes `target`'s place, `target` first. Returns the group, or `None`
+ /// (and changes nothing) if they cannot be grouped.
+ pub fn group_with(&mut self, app: &str, target: &str) -> Option<String> {
+ if app == target || self.is_group(app) || !self.pinned.iter().any(|pinned| pinned == target)
+ {
+ return None;
+ }
+ self.pinned.retain(|pinned| pinned != app);
+ self.extra.retain(|extra| extra != app);
+ self.recent.retain(|recent| recent != app);
+ self.leave_group(app);
+ let id = if self.is_group(target) {
+ target.to_owned()
+ } else {
+ let id = self.new_group_id();
+ if let Some(at) = self.pinned.iter().position(|pinned| pinned == target) {
+ self.pinned[at] = id.clone();
+ }
+ self.groups.push(Group {
+ id: id.clone(),
+ apps: vec![target.to_owned()],
+ });
+ id
+ };
+ if let Some(group) = self.groups.iter_mut().find(|group| group.id == id) {
+ group.apps.push(app.to_owned());
+ }
+ self.tidy_groups();
+ Some(id)
+ }
+
+ /// Takes `app` out of its group and pins it right after the group.
+ /// Returns `false` if it was in no group.
+ pub fn ungroup(&mut self, app: &str) -> bool {
+ let Some(group) = self.group_of(app).map(|group| group.id.clone()) else {
+ return false;
+ };
+ self.leave_group(app);
+ let at = self
+ .pinned
+ .iter()
+ .position(|pinned| *pinned == group)
+ .map_or(self.pinned.len(), |at| at + 1);
+ self.pinned.insert(at, app.to_owned());
+ self.tidy_groups();
+ true
+ }
+
+ /// Puts a group's apps back in the dock, in its place and in its order.
+ pub fn dissolve(&mut self, id: &str) {
+ let Some(index) = self.groups.iter().position(|group| group.id == id) else {
+ return;
+ };
+ let group = self.groups.remove(index);
+ match self.pinned.iter().position(|pinned| *pinned == group.id) {
+ Some(at) => {
+ self.pinned.remove(at);
+ for (offset, app) in group.apps.into_iter().enumerate() {
+ self.pinned.insert(at + offset, app);
+ }
+ }
+ None => self.pinned.extend(group.apps),
+ }
+ }
+
+ /// Top-level pinned items in display order: apps and groups.
#[must_use]
pub fn pinned(&self) -> &[String] {
&self.pinned
}
+ /// Every pinned app, on its own or in a group, in display order.
+ #[must_use]
+ pub fn pinned_apps(&self) -> Vec<String> {
+ let mut apps = Vec::new();
+ for id in &self.pinned {
+ match self.group(id) {
+ Some(group) => apps.extend(group.apps.iter().cloned()),
+ None => apps.push(id.clone()),
+ }
+ }
+ apps
+ }
+
/// Recent apps in display order, newest first.
#[must_use]
pub fn recent(&self) -> &[String] {
&self.recent
}
- /// Pinned and open apps in display order, with pinned apps first.
+ /// Pinned items and open apps in display order, with pinned items first.
+ /// A group is running when any of its apps is.
#[must_use]
pub fn apps(&self) -> Vec<DockApp> {
self.pinned
@@ -131,11 +318,56 @@ impl Roster {
.chain(&self.extra)
.map(|id| DockApp {
id: id.clone(),
- running: self.is_running(id),
+ running: match self.group(id) {
+ Some(group) => group.apps.iter().any(|app| self.is_running(app)),
+ None => self.is_running(id),
+ },
})
.collect()
}
+ /// Removes `app` from any group, leaving the group where it is (see
+ /// `tidy_groups`).
+ fn leave_group(&mut self, app: &str) {
+ for group in &mut self.groups {
+ group.apps.retain(|member| member != app);
+ }
+ }
+
+ /// A group left with one app gives its place to that app; an empty one
+ /// disappears.
+ fn tidy_groups(&mut self) {
+ let mut index = 0;
+ while index < self.groups.len() {
+ if self.groups[index].apps.len() > 1 {
+ index += 1;
+ continue;
+ }
+ let group = self.groups.remove(index);
+ let at = self.pinned.iter().position(|pinned| *pinned == group.id);
+ let last = group
+ .apps
+ .into_iter()
+ .next()
+ .filter(|app| !self.pinned.contains(app));
+ match (at, last) {
+ (Some(at), Some(app)) => self.pinned[at] = app,
+ (Some(at), None) => {
+ self.pinned.remove(at);
+ }
+ (None, Some(app)) => self.pinned.push(app),
+ (None, None) => {}
+ }
+ }
+ }
+
+ fn new_group_id(&self) -> String {
+ (1u32..)
+ .map(|number| format!("{GROUP_PREFIX}{number}"))
+ .find(|id| !self.is_group(id) && !self.pinned.contains(id))
+ .unwrap_or_default()
+ }
+
fn remember(&mut self, id: String) {
if self.is_pinned(&id) {
return;
@@ -323,4 +555,154 @@ mod tests {
roster.sync([]);
assert_eq!(roster.recent(), ["browser"]);
}
+
+ /// `a`, `b`, `c` pinned, then `c` dropped on `a`.
+ fn grouped() -> (Roster, String) {
+ let mut roster = Roster::new(vec!["a".into(), "b".into(), "c".into()], Vec::new());
+ let group = roster.group_with("c", "a").unwrap_or_default();
+ (roster, group)
+ }
+
+ fn members(roster: &Roster, group: &str) -> Vec<String> {
+ roster
+ .group(group)
+ .map(|group| group.apps.clone())
+ .unwrap_or_default()
+ }
+
+ #[test]
+ fn group_with_should_put_both_apps_in_one_place_where_the_target_was() {
+ let (roster, group) = grouped();
+ assert!(is_group_id(&group));
+ assert_eq!(roster.pinned(), [group.as_str(), "b"]);
+ assert_eq!(members(&roster, &group), ["a", "c"]);
+ }
+
+ #[test]
+ fn group_with_should_add_to_an_existing_group() {
+ let (mut roster, group) = grouped();
+ assert_eq!(roster.group_with("b", &group), Some(group.clone()));
+ assert_eq!(roster.pinned(), [group.as_str()]);
+ assert_eq!(members(&roster, &group), ["a", "c", "b"]);
+ }
+
+ #[test]
+ fn group_with_should_pin_a_running_app_into_the_group() {
+ let (mut roster, group) = grouped();
+ roster.sync(["editor"]);
+ roster.group_with("editor", &group);
+ assert_eq!(ids(&roster), [group.as_str(), "b"]);
+ assert!(roster.is_pinned("editor"));
+ }
+
+ #[test]
+ fn group_with_should_refuse_a_group_itself_or_an_unpinned_target() {
+ let (mut roster, group) = grouped();
+ roster.sync(["editor"]);
+ let before = roster.clone();
+ assert_eq!(roster.group_with(&group, "b"), None);
+ assert_eq!(roster.group_with("b", "b"), None);
+ assert_eq!(roster.group_with("b", "editor"), None);
+ assert_eq!(roster, before);
+ }
+
+ #[test]
+ fn grouped_apps_should_stay_in_their_group_while_running() {
+ let (mut roster, group) = grouped();
+ roster.sync(["c"]);
+ assert_eq!(ids(&roster), [group.as_str(), "b"]);
+ assert!(roster.apps()[0].running);
+ roster.sync([]);
+ assert!(roster.recent().is_empty());
+ assert!(!roster.apps()[0].running);
+ }
+
+ #[test]
+ fn pin_should_not_duplicate_an_app_in_a_group() {
+ let (mut roster, group) = grouped();
+ roster.pin("c");
+ assert_eq!(roster.pinned(), [group.as_str(), "b"]);
+ }
+
+ #[test]
+ fn ungroup_should_put_the_app_right_after_the_group() {
+ let (mut roster, group) = grouped();
+ roster.group_with("b", &group);
+ assert!(roster.ungroup("c"));
+ assert_eq!(roster.pinned(), [group.as_str(), "c"]);
+ assert_eq!(members(&roster, &group), ["a", "b"]);
+ }
+
+ #[test]
+ fn a_group_left_with_one_app_should_give_its_place_to_it() {
+ let (mut roster, _) = grouped();
+ assert!(roster.ungroup("a"));
+ assert_eq!(roster.pinned(), ["c", "a", "b"]);
+ assert!(roster.groups().is_empty());
+ assert!(!roster.ungroup("a"));
+ }
+
+ #[test]
+ fn dissolve_should_put_the_apps_back_in_the_group_place() {
+ let (mut roster, group) = grouped();
+ roster.pin("d");
+ roster.dissolve(&group);
+ assert_eq!(roster.pinned(), ["a", "c", "b", "d"]);
+ assert!(roster.groups().is_empty());
+ }
+
+ #[test]
+ fn unpin_should_take_an_app_out_of_its_group() {
+ let (mut roster, group) = grouped();
+ roster.group_with("b", &group);
+ roster.sync(["c"]);
+ roster.unpin("c");
+ assert_eq!(members(&roster, &group), ["a", "b"]);
+ assert_eq!(ids(&roster), [group.as_str(), "c"]);
+ }
+
+ #[test]
+ fn pin_before_should_move_a_group_and_take_an_app_out_of_one() {
+ let (mut roster, group) = grouped();
+ roster.pin_before(&group, None);
+ assert_eq!(roster.pinned(), ["b", group.as_str()]);
+ roster.pin_before("c", Some("b"));
+ assert_eq!(roster.pinned(), ["c", "b", "a"]);
+ }
+
+ #[test]
+ fn pinned_apps_should_list_the_apps_inside_groups() {
+ let (roster, _) = grouped();
+ assert_eq!(roster.pinned_apps(), ["a", "c", "b"]);
+ }
+
+ #[test]
+ fn with_groups_should_mend_what_a_hand_edited_file_breaks() {
+ let pinned = vec![
+ "a".to_owned(),
+ "muelle:group:1".to_owned(),
+ "muelle:group:9".to_owned(),
+ "muelle:group:2".to_owned(),
+ ];
+ let roster = Roster::new(pinned, vec!["x".into()]).with_groups(vec![
+ // `a` is pinned already; `x` was recent.
+ Group {
+ id: "muelle:group:1".into(),
+ apps: vec!["a".into(), "x".into(), "y".into(), "y".into()],
+ },
+ // Not in the pinned list: its app comes back to the dock.
+ Group {
+ id: "muelle:group:5".into(),
+ apps: vec!["z".into()],
+ },
+ // One app only: the app takes its place.
+ Group {
+ id: "muelle:group:2".into(),
+ apps: vec!["w".into()],
+ },
+ ]);
+ assert_eq!(roster.pinned(), ["a", "muelle:group:1", "w", "z"]);
+ assert_eq!(members(&roster, "muelle:group:1"), ["x", "y"]);
+ assert!(roster.recent().is_empty());
+ }
}