A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
Fix shortcut handling for pinned apps with arguments; improve popup theme and visuals
CristianOlivera12233d1148b42
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5dfdcf3..5baf35f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,29 @@ copia la sección de la versión que se publica a la release de GitHub.## [Unreleased]+### English++- Fixed (issue #8): apps pinned from a Windows shortcut with arguments, such+ as `wscript.exe "script.vbs"`, a browser profile or a web app, opened the+ program alone. They now open through their shortcut, exactly as from+ Explorer or the taskbar, and show the shortcut's name and icon. A shortcut+ dropped on the dock is kept in `%APPDATA%\Muelle\Pins`, so the pin survives+ deleting the original; shortcuts to scripts or documents can be pinned too.+- Dragging a file over the dock reads a dropped shortcut once, not on every+ mouse move.++### Español++- Corregido (issue #8): las apps fijadas desde un acceso directo de Windows con+ argumentos, como `wscript.exe "script.vbs"`, un perfil de navegador o una+ app web, abrían solo el programa. Ahora se abren a través de su acceso+ directo, igual que desde el Explorador o la barra de tareas, y muestran su+ nombre e icono. Un acceso directo soltado en el dock se guarda en+ `%APPDATA%\Muelle\Pins`, así que la app fijada sigue funcionando aunque se+ borre el original; también se pueden fijar accesos a scripts o documentos.+- Al arrastrar un archivo sobre el dock, un acceso directo se lee una sola vez,+ no en cada movimiento del ratón.+## [0.1.9]### Englishdiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex a5e225a..ac27f95 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -33,7 +33,7 @@ use muelle_core::{use muelle_shell::{appbar::{ABN_FULLSCREENAPP, AppBar, Edge},files, launcher,- pins::{app_exists, link_target, taskbar_pins, taskbar_pins_if_readable},+ pins::{self, app_exists, taskbar_pins, taskbar_pins_if_readable},power,recycle_bin::{self, BinWatch},status,@@ -508,6 +508,8 @@ struct App {drag: Option<Dragging>,/// Files being dragged over the dock from another app.incoming: Vec<String>,+ /// What dropping `incoming` between icons would pin.+ incoming_pin: Option<String>,/// Something (files, text, an image) is being dragged over the dock.drag_over: bool,/// The entry a drag is resting on, which springs open on `SPRING_TIMER`.@@ -1923,19 +1925,7 @@ impl App {/// A single app or shortcut dropped between icons is pinned there.fn pin_action(&self, state: &muelle_core::magnify::Magnified) -> DropAction {- let [file] = self.incoming.as_slice() else {- return DropAction::Nothing;- };- let lower = file.to_lowercase();- let target = if lower.ends_with(".lnk") {- link_target(std::path::Path::new(file))- } else {- Some(file.clone())- };- let Some(id) = target- .map(|target| normalize_id(&target))- .filter(|id| id.ends_with(".exe"))- else {+ let Some(id) = self.incoming_pin.clone() else {return DropAction::Nothing;};let explorer = explorer_id();@@ -1956,6 +1946,14 @@ impl App {fn on_drag_enter(&mut self, incoming: Vec<String>, x: i32) -> 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+ // COM call and a disk read.+ self.incoming_pin = match incoming.as_slice() {+ [file] if tracker::is_shortcut(file) => pins::shortcut_id(std::path::Path::new(file)),+ [file] => Some(normalize_id(file)).filter(|id| id.ends_with(".exe")),+ _ => None,+ };self.incoming = incoming;self.drag_over = true;self.on_drag_over(x)@@ -2056,9 +2054,20 @@ impl App {copy,}),DropAction::Pin { id, before } => {- self.roster.pin_before(&id, before.as_deref());- save_settings(&self.roster, &self.config);- self.refresh()?;+ // A dropped shortcut that is needed to open the app (it has+ // arguments, or opens a script) is kept as Muelle's own copy,+ // so the pin keeps working if the original is deleted.+ let id = match files.first() {+ Some(file) if tracker::is_shortcut(file) => {+ pins::keep_shortcut(std::path::Path::new(file))+ }+ _ => Some(id),+ };+ if let Some(id) = id {+ self.roster.pin_before(&id, before.as_deref());+ save_settings(&self.roster, &self.config);+ self.refresh()?;+ }None}};@@ -2365,6 +2374,7 @@ impl App {let unpinning = self.roster.is_pinned(&id);if unpinning {self.roster.unpin(&id);+ pins::forget_shortcut(&id);} else {self.roster.pin(&id);}@@ -3459,6 +3469,7 @@ pub fn run() -> Result<()> {press: None,drag: None,incoming: Vec::new(),+ incoming_pin: None,drag_over: false,spring: None,switching: false,diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rsindex 248215b..2b6bed8 100644--- a/apps/dock/src/gfx.rs+++ b/apps/dock/src/gfx.rs@@ -203,14 +203,12 @@ impl Gfx {})}- /// Opaque island silhouette. The compact controls meet the screen edge- /// with curved shoulders, while the popovers have rounded corners.+ /// Opaque island silhouette with curved shoulders at the screen edge.pub fn island_mask(&self,width: f32,height: f32,scale: f32,- attached: bool,) -> Result<CompositionSurfaceBrush> {self.draw(width.ceil() as u32, height.ceil() as u32, |dc| {let shoulder = (12.0 * scale).min(width / 5.0).min(height / 2.0);@@ -220,23 +218,6 @@ impl Gfx {// SAFETY: The geometries, sink and brush stay alive through the drawing calls.unsafe {let white = dc.CreateSolidColorBrush(&WHITE, None)?;- if !attached {- let radius = (18.0 * scale).min(width / 2.0).min(height / 2.0);- dc.FillRoundedRectangle(- &D2D1_ROUNDED_RECT {- rect: D2D_RECT_F {- left: 0.0,- top: 0.0,- right: width,- bottom: height,- },- radiusX: radius,- radiusY: radius,- },- &white,- );- return Ok(());- }let shape = dc.GetFactory()?.CreatePathGeometry()?;let sink = shape.Open()?;sink.BeginFigure(Vector2 { X: 0.0, Y: 0.0 }, D2D1_FIGURE_BEGIN_FILLED);diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rsindex f3e140f..cdde63a 100644--- a/apps/dock/src/menu.rs+++ b/apps/dock/src/menu.rs@@ -684,12 +684,7 @@ pub(crate) fn draw_popup_background(width: f32,height: f32,) -> Result<()> {- let tint = match (dark, glass) {- (true, true) => rgba(38, 38, 40, 175),- (false, true) => rgba(246, 246, 248, 215),- (true, false) => rgba(44, 44, 46, 255),- (false, false) => rgba(240, 240, 242, 255),- };+ let tint = popup_tint(dark, glass);let compositor = layers.Compositor()?;if glass {add_sprite(@@ -711,6 +706,15 @@ pub(crate) fn draw_popup_background()}+pub(crate) fn popup_tint(dark: bool, glass: bool) -> Color {+ match (dark, glass) {+ (true, true) => rgba(38, 38, 40, 175),+ (false, true) => rgba(246, 246, 248, 215),+ (true, false) => rgba(44, 44, 46, 255),+ (false, false) => rgba(240, 240, 242, 255),+ }+}+unsafe extern "system" fn menu_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {match msg {WM_ACTIVATE if (w.0 & 0xFFFF) as u32 == WA_INACTIVE => {diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex e3510bc..d3e636b 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -60,6 +60,7 @@ use crate::{app,gfx::{Gfx, Ink, LabelBrush},media::{self, Control as MediaControl, Track},+ scene::Theme,strings,usage::{self, ActiveProviders, Monitor as UsageMonitor, Provider, ProviderUsage, Snapshot, State,@@ -87,7 +88,9 @@ const CLOCK_TIMER: usize = 1;const ISLAND_SINGLE_WIDTH: f32 = 145.0;const ISLAND_EXPANDED_WIDTH: f32 = 440.0;const ISLAND_ROW_HEIGHT: f32 = 118.0;-const ISLAND_CARD_HEIGHT: f32 = 108.0;+const PANEL_GAP: f32 = 5.0;+const PANEL_RADIUS: f32 = 18.0;+const PANEL_SHADOW_MARGIN: f32 = 20.0;const WM_POWERBROADCAST: u32 = 0x0218;const WM_MOUSELEAVE: u32 = 0x02A3;/// AppBar notifications need a message id; the bar ignores them.@@ -188,7 +191,7 @@ struct Look {impl Look {fn panel_height(&self) -> f32 {match self.panel {- Some(Island::Music) => 148.0,+ Some(Island::Music) => 136.0,Some(Island::Usage) => 74.0 + self.active_providers.count() as f32 * ISLAND_ROW_HEIGHT,None => 0.0,}@@ -300,8 +303,8 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -let x = (l.0 & 0xFFFF) as i16 as i32;let y = (l.0 >> 16) as i16 as i32;if y >= BAR_BOTTOM.load(Ordering::Relaxed)- && y < PANEL_BOTTOM.load(Ordering::Relaxed)- && (x < PANEL_LEFT.load(Ordering::Relaxed)+ && (y >= PANEL_BOTTOM.load(Ordering::Relaxed)+ || x < PANEL_LEFT.load(Ordering::Relaxed)|| x >= PANEL_RIGHT.load(Ordering::Relaxed)){return LRESULT(-1);@@ -631,9 +634,9 @@ fn add_panel_text_right(#[expect(clippy::too_many_arguments,- reason = "Each provider card draws its own colors, data and measured rectangle"+ reason = "Each provider row draws its own colors, data and measured rectangle")]-fn draw_usage_card(+fn draw_usage_row(gfx: &Gfx,layers: &VisualCollection,provider: Provider,@@ -651,27 +654,6 @@ fn draw_usage_card(let left = px(23.0);let width = island_width - px(46.0);let right = left + width;- let card_fill = if light {- rgba(32, 52, 77, 13)- } else {- rgba(237, 244, 255, 16)- };- let card_border = if light {- rgba(41, 59, 82, 26)- } else {- rgba(222, 234, 251, 31)- };- add_rounded_box(- c,- layers,- left,- y,- width,- px(ISLAND_CARD_HEIGHT),- px(13.0),- card_fill,- Some(card_border),- )?;add_rounded_box(c,layers,@@ -1390,7 +1372,12 @@ impl MenuBar {let px = |logical: f32| (logical * scale).round();let screen = look.screen;let (width, height) = ((screen.right - screen.left) as f32, px(HEIGHT));- let visual_height = height + px(look.panel_height());+ let panel_bottom = height + px(PANEL_GAP) + px(look.panel_height());+ let visual_height = if look.panel.is_some() {+ panel_bottom + px(PANEL_SHADOW_MARGIN)+ } else {+ height+ };let ink = if look.light { Ink::Dark } else { Ink::Light };let root = c.CreateContainerVisual()?;@@ -1561,7 +1548,12 @@ impl MenuBar {);BAR_TOP.store(screen.top, Ordering::Relaxed);BAR_BOTTOM.store(screen.top + height as i32, Ordering::Relaxed);- PANEL_BOTTOM.store(screen.top + self.visual_height, Ordering::Relaxed);+ let clickable_height = if self.panel_span.width() > 0.0 {+ panel_bottom+ } else {+ height+ };+ PANEL_BOTTOM.store(screen.top + clickable_height as i32, Ordering::Relaxed);self.place()}@@ -1662,9 +1654,10 @@ impl MenuBar {Island::Usage => ISLAND_EXPANDED_WIDTH,}),);- let geometry = IslandGeometry::new(self.panel_span, bar_height, look);+ let geometry = IslandGeometry::new(self.panel_span, bar_height + px(PANEL_GAP), look);let height = px(look.panel_height());- let content = island_surface(gfx, look, layers, geometry, height)?;+ let theme = Theme::for_popup(look.light, look.glass);+ let content = popup_surface(gfx, theme, layers, geometry, height)?;match kind {Island::Music => {if let Some(track) = &look.track {@@ -1724,16 +1717,8 @@ impl MenuBar {button_width,button_height,px(13.5),- if look.light {- rgba(28, 51, 79, 18)- } else {- rgba(235, 242, 252, 26)- },- Some(if look.light {- rgba(41, 62, 86, 36)- } else {- rgba(226, 237, 251, 43)- }),+ geometry.control_fill(),+ Some(geometry.border()),)?;add_visual(c,@@ -1752,7 +1737,18 @@ impl MenuBar {IslandAction::Refresh,));for (index, (provider, usage, accent)) in providers.iter().enumerate() {- draw_usage_card(+ let y = px(48.0 + index as f32 * ISLAND_ROW_HEIGHT);+ let inset = px(23.0);+ add_visual(+ c,+ content,+ &c.CreateColorBrushWithColor(geometry.border())?.cast()?,+ inset,+ y - px(6.0),+ island_width - 2.0 * inset,+ 1.0,+ )?;+ draw_usage_row(gfx,content,*provider,@@ -1761,7 +1757,7 @@ impl MenuBar {scale,look.light,island_width,- px(53.0 + index as f32 * ISLAND_ROW_HEIGHT),+ y,)?;}let newest_age = providers@@ -1825,27 +1821,16 @@ impl MenuBar {px(32.0),IslandAction::Toggle(Island::Music),));- add_rounded_box(- c,- layers,- px(14.0),- px(45.0),- geometry.width - px(28.0),- px(91.0),- px(16.0),- geometry.fill(),- Some(geometry.border()),- )?;let tile = px(34.0);add_rounded_box(c,layers,px(25.0),- px(54.0),+ px(46.0),tile,tile,px(10.0),- geometry.selection(),+ geometry.control_fill(),None,)?;let note = gfx.glyph_brush(&[('\u{E8D6}', 1.0)], geometry.scale, ink)?;@@ -1854,7 +1839,7 @@ impl MenuBar {layers,¬e.brush.cast()?,px(25.0) + (tile - note.width) / 2.0,- px(54.0) + (tile - note.height) / 2.0,+ px(46.0) + (tile - note.height) / 2.0,note.width,note.height,)?;@@ -1868,9 +1853,9 @@ impl MenuBar {available,)?;let title_y = if track.artist.trim().is_empty() {- px(71.0) - title.height / 2.0+ px(63.0) - title.height / 2.0} else {- px(55.0)+ px(47.0)};add_visual(c,@@ -1889,7 +1874,7 @@ impl MenuBar {layers,&artist.brush.cast()?,px(69.0),- px(73.0),+ px(65.0),artist.width,artist.height,)?@@ -1912,7 +1897,7 @@ impl MenuBar {] {let size = px(34.0);let x = center + px(offset) - size / 2.0;- let y = px(96.0);+ let y = px(89.0);let main = matches!(control, MediaControl::PlayPause);if main {add_rounded_box(@@ -1923,7 +1908,7 @@ impl MenuBar {size,size,size / 2.0,- geometry.selection(),+ geometry.control_fill(),Some(geometry.border()),)?;}@@ -1982,11 +1967,11 @@ impl IslandGeometry {fn ink(self) -> Ink {if self.light { Ink::Dark } else { Ink::Light }}- fn fill(self) -> Color {+ fn control_fill(self) -> Color {if self.light {- rgba(35, 63, 96, 15)+ rgba(0, 0, 0, 18)} else {- rgba(223, 237, 255, 17)+ rgba(255, 255, 255, 27)}}fn border(self) -> Color {@@ -1996,13 +1981,6 @@ impl IslandGeometry {rgba(223, 237, 255, 37)}}- fn selection(self) -> Color {- if self.light {- rgba(198, 221, 250, 255)- } else {- rgba(70, 98, 136, 180)- }- }}fn toggle_panel(open: Option<Island>, clicked: Island) -> Option<Island> {@@ -2096,6 +2074,47 @@ fn island_providers(look: &Look) -> Vec<IslandProvider<'_>> {.collect()}+fn popup_surface(+ gfx: &Gfx,+ theme: Theme,+ layers: &VisualCollection,+ geometry: IslandGeometry,+ height: f32,+) -> Result<VisualCollection> {+ let c = &gfx.compositor;+ let size = Vector2::new(geometry.width, height);+ let radius = geometry.px(PANEL_RADIUS);+ let panel = theme.panel(gfx, size, radius, geometry.scale)?;+ let popup = c.CreateContainerVisual()?;+ popup.SetSize(size)?;+ popup.SetOffset(Vector3::new(geometry.left.round(), geometry.top, 0.0))?;+ let children = popup.Children()?;+ let mask = c.CreateNineGridBrush()?;+ mask.SetSource(&gfx.rounded_mask(radius)?)?;+ mask.SetInsets(radius.ceil() + 1.0)?;+ children.InsertAtTop(&island_shadow(c, &mask.cast()?, size, geometry)?)?;+ children.InsertAtTop(&panel)?;+ layers.InsertAtTop(&popup)?;+ Ok(children)+}++fn island_shadow(+ c: &Compositor,+ mask: &CompositionBrush,+ size: Vector2,+ geometry: IslandGeometry,+) -> Result<SpriteVisual> {+ let shadow = c.CreateDropShadow()?;+ shadow.SetMask(mask)?;+ shadow.SetBlurRadius(geometry.px(12.0))?;+ shadow.SetOffset(Vector3::new(0.0, geometry.px(5.0), 0.0))?;+ shadow.SetColor(rgba(0, 0, 0, 92))?;+ let host = c.CreateSpriteVisual()?;+ host.SetSize(size)?;+ host.SetShadow(&shadow)?;+ Ok(host)+}+fn island_surface(gfx: &Gfx,look: &Look,@@ -2108,35 +2127,13 @@ fn island_surface(let island_left = geometry.left;let island_width = geometry.width;let scale = geometry.scale;+ let size = Vector2::new(island_width, island_height);let island = c.CreateContainerVisual()?;- island.SetSize(Vector2 {- X: island_width,- Y: island_height,- })?;- island.SetOffset(Vector3 {- X: island_left.round(),- Y: geometry.top,- Z: 0.0,- })?;+ island.SetSize(size)?;+ island.SetOffset(Vector3::new(island_left.round(), 0.0, 0.0))?;let content = island.Children()?;- let attached = geometry.top == 0.0;- let silhouette = gfx.island_mask(island_width, island_height, scale, attached)?;- let shadow = c.CreateDropShadow()?;- shadow.SetMask(&silhouette)?;- shadow.SetBlurRadius(px(12.0))?;- shadow.SetOffset(Vector3 {- X: 0.0,- Y: px(5.0),- Z: 0.0,- })?;- shadow.SetColor(rgba(0, 0, 0, 92))?;- let shadow_host = c.CreateSpriteVisual()?;- shadow_host.SetSize(Vector2 {- X: island_width,- Y: island_height,- })?;- shadow_host.SetShadow(&shadow)?;- content.InsertAtTop(&shadow_host)?;+ let silhouette = gfx.island_mask(island_width, island_height, scale)?;+ content.InsertAtTop(&island_shadow(c, &silhouette.cast()?, size, geometry)?)?;let tint = match (look.light, look.glass) {(true, true) => rgba(247, 249, 252, 243),@@ -2147,13 +2144,9 @@ fn island_surface(if look.glass {// The backdrop cannot be used as a mask-brush source. Inset its// rounded clip so it stays entirely inside the curved silhouette.- let inset = if attached {- (12.0 * scale)- .min(island_width / 5.0)- .min(island_height / 2.0)- } else {- 0.0- };+ let inset = (12.0 * scale)+ .min(island_width / 5.0)+ .min(island_height / 2.0);let glass_width = island_width - inset * 2.0;let glass = c.CreateContainerVisual()?;glass.SetSize(Vector2 {@@ -2166,17 +2159,13 @@ fn island_surface(Z: 0.0,})?;let outline = c.CreateRoundedRectangleGeometry()?;- let lift = if attached { px(22.0) } else { 0.0 };- let radius = if attached { px(22.0) } else { px(18.0) };+ let lift = px(22.0);outline.SetSize(Vector2 {X: glass_width,Y: island_height + lift,})?;outline.SetOffset(Vector2 { X: 0.0, Y: -lift })?;- outline.SetCornerRadius(Vector2 {- X: radius,- Y: radius,- })?;+ outline.SetCornerRadius(Vector2 { X: lift, Y: lift })?;glass.SetClip(&c.CreateGeometricClipWithGeometry(&outline)?)?;add_visual(c,@@ -2435,4 +2424,36 @@ mod island_tests {assert_eq!(available_panel(Some(Island::Music), false, true), None);assert_eq!(available_panel(Some(Island::Usage), true, false), None);}++ #[test]+ #[ignore = "Requires Windows desktop composition"]+ fn popup_surface_builds_in_both_themes_with_and_without_transparency() -> Result<()> {+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };++ // SAFETY: The controller initializes the test thread's own queue.+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ for (light, glass) in [(true, true), (false, true), (true, false), (false, false)] {+ let root = gfx.compositor.CreateContainerVisual()?;+ let theme = Theme::for_popup(light, glass);+ let geometry = IslandGeometry {+ left: 90.0,+ top: HEIGHT + PANEL_GAP,+ width: 360.0,+ scale: 1.0,+ light,+ };+ popup_surface(&gfx, theme, &root.Children()?, geometry, 136.0)?;+ }+ Ok(())+ }}diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rsindex f877bc8..503a3f1 100644--- a/apps/dock/src/scene.rs+++ b/apps/dock/src/scene.rs@@ -65,6 +65,14 @@ impl Theme {}}+ /// 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 {+ tint: crate::menu::popup_tint(!light, glass),+ ..Self::for_system(light, glass)+ }+ }+/// A fixed-size panel using the dock's backdrop, tint, sheen and rim.pub fn panel(&self,diff --git a/apps/dock/src/shell_work.rs b/apps/dock/src/shell_work.rsindex 6a92d5e..f6e1cb6 100644--- a/apps/dock/src/shell_work.rs+++ b/apps/dock/src/shell_work.rs@@ -80,8 +80,13 @@ impl Action {// the dock their owner would disable its input during long operations.let owner = HWND::default();match self {- Self::Open { id } => launcher::open(&id)?,- Self::OpenAsAdmin { id } => launcher::open_as_admin(&id)?,+ // Through its shortcut when it has one with arguments (issue #8).+ Self::Open { id } => {+ launcher::open(&muelle_shell::pins::launch_target(&id).unwrap_or(id))?+ }+ Self::OpenAsAdmin { id } => {+ launcher::open_as_admin(&muelle_shell::pins::launch_target(&id).unwrap_or(id))?;+ }Self::Reveal { path } => launcher::reveal(&path)?,Self::OpenWith { app, files } => launcher::open_with(&app, &files)?,Self::Recycle { files: paths } => {diff --git a/crates/muelle-shell/src/icon_cache.rs b/crates/muelle-shell/src/icon_cache.rsindex 943d08e..061b69e 100644--- a/crates/muelle-shell/src/icon_cache.rs+++ b/crates/muelle-shell/src/icon_cache.rs@@ -62,15 +62,21 @@ impl IconCache {/// Like [`get`](Self::get), but stores each `variant` separately for items/// whose icon depends on their state, such as an empty or full recycle bin.pub fn get_variant(&self, id: &str, variant: &str, size: u32) -> Result<AppVisual, IconError> {- let path = self.entry_path(&format!("{id}|{variant}"), size);- let stamp = stamp_of(id);+ // A program pinned from a shortcut Muelle keeps shows that shortcut's+ // name and icon ("Launch Hidden", not "Windows Based Script Host"),+ // as the taskbar does. Part of the key, so replacing or removing the+ // shortcut never shows a stale label.+ let kept = crate::pins::kept_shortcut_for(id);+ let source = kept.as_deref().unwrap_or(id);+ let path = self.entry_path(&format!("{source}|{variant}"), size);+ let stamp = stamp_of(source);if let Some(cached) = fs::read(&path).ok().and_then(|bytes| decode(&bytes, stamp)) {return Ok(cached);}let visual = AppVisual {- name: display_name(id),- icon: load_icon(id, size)?,+ name: display_name(source),+ icon: load_icon(source, size)?,};// An unwritable cache only makes the next startup slower.let _ = fs::create_dir_all(&self.folder);diff --git a/crates/muelle-shell/src/pins.rs b/crates/muelle-shell/src/pins.rsindex f771970..5cd3d7f 100644--- a/crates/muelle-shell/src/pins.rs+++ b/crates/muelle-shell/src/pins.rs@@ -71,13 +71,9 @@ pub fn taskbar_pins_if_readable() -> Option<Vec<String>> {// (position in Favorites, id); shortcuts it does not mention go last.let mut found: Vec<(usize, String)> = Vec::new();for link in &links {- let Some(target) = link_target(link) else {+ let Some(id) = shortcut_id(link) else {continue;};- let id = normalize_id(&target);- if !id.ends_with(".exe") || !Path::new(&id).exists() {- continue;- }let position = link.file_name().and_then(|name| name.to_str())@@ -232,7 +228,7 @@ pub fn unpin_from_taskbar(id: &str) -> bool {/// What Explorer pinned for `id`: the Store app itself, or the shortcut in/// `User Pinned\TaskBar` that opens the program.fn pinned_item(id: &str) -> Option<String> {- if id.starts_with("shell:AppsFolder\\") {+ if id.starts_with("shell:AppsFolder\\") || crate::tracker::is_shortcut(id) {return Some(id.to_owned());}let folder = PathBuf::from(env::var("APPDATA").ok()?)@@ -325,7 +321,183 @@ pub fn app_exists(id: &str) -> bool {!fixed || path.exists()}-pub fn link_target(link: &std::path::Path) -> Option<String> {+pub fn link_target(link: &Path) -> Option<String> {+ read_link(link)?.0+}++/// What the dock pins for the shortcut `link`, as the Windows taskbar does:+/// the program it opens, whatever its arguments, so the program's windows+/// gather under one icon (the arguments still apply when it is opened, see+/// [`launch_target`]); or the shortcut itself when it opens something that+/// is not a program (a script, a document). `None` for shortcuts to no file+/// (File Explorer, Control Panel items) or to a file that no longer exists.+///+/// Requires COM to be initialized on the calling thread.+#[must_use]+pub fn shortcut_id(link: &Path) -> Option<String> {+ let (target, _) = read_link(link)?;+ let target = target.filter(|target| Path::new(target).exists())?;+ Some(if is_program(&target) {+ normalize_id(&target)+ } else {+ normalize_id(&link.to_string_lossy())+ })+}++/// The shortcut to open `id` with, when one carries more than the program:+/// `wscript.exe "script.vbs"`, a browser profile, a web app. Searched among+/// the shortcuts Muelle keeps and those pinned to the Windows taskbar, only+/// when the app is opened, never on the dock's thread.+///+/// Requires COM to be initialized on the calling thread.+#[must_use]+pub fn launch_target(id: &str) -> Option<String> {+ if crate::tracker::is_shortcut(id) || id.starts_with("shell:") {+ return None;+ }+ [kept_folder(), taskbar_folder()]+ .into_iter()+ .flatten()+ .filter_map(|folder| fs::read_dir(folder).ok())+ .flatten()+ .filter_map(|entry| Some(entry.ok()?.path()))+ .filter(|link| crate::tracker::is_shortcut(&link.to_string_lossy()))+ .find(|link| {+ read_link(link).is_some_and(|(target, arguments)| {+ !arguments.is_empty() && target.is_some_and(|target| normalize_id(&target) == id)+ })+ })+ .map(|link| link.to_string_lossy().into_owned())+}++/// The shortcut Muelle keeps for the program `id` (see [`keep_shortcut`]),+/// which gives its pin its name and icon. Only Muelle's own folder, which+/// is usually empty: cheap enough for every icon lookup.+///+/// Requires COM to be initialized on the calling thread.+#[must_use]+pub fn kept_shortcut_for(id: &str) -> Option<String> {+ if crate::tracker::is_shortcut(id) || id.starts_with("shell:") {+ return None;+ }+ fs::read_dir(kept_folder()?)+ .ok()?+ .filter_map(|entry| Some(entry.ok()?.path()))+ .find(|link| {+ read_link(link)+ .and_then(|(target, _)| target)+ .is_some_and(|target| normalize_id(&target) == id)+ })+ .map(|link| link.to_string_lossy().into_owned())+}++fn is_program(path: &str) -> bool {+ path.len() > 4 && path[path.len() - 4..].eq_ignore_ascii_case(".exe")+}++/// The folder where Muelle keeps its own copy of shortcuts pinned from+/// elsewhere (the desktop, Downloads), as the taskbar keeps `User Pinned`:+/// the pin keeps working if the original is moved or deleted.+fn kept_folder() -> Option<PathBuf> {+ Some(PathBuf::from(env::var_os("APPDATA")?).join("Muelle\\Pins"))+}++fn taskbar_folder() -> Option<PathBuf> {+ Some(+ PathBuf::from(env::var_os("APPDATA")?)+ .join("Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar"),+ )+}++/// Pins the shortcut `link`, dropped on the dock, and returns the pin id+/// ([`shortcut_id`]). When the shortcut is needed to open it (it is the pin+/// itself, or it carries arguments), Muelle keeps a copy: the pin keeps+/// working if the original is moved or deleted. One kept shortcut per+/// program, as on the taskbar: the newest replaces the older one.+#[must_use]+pub fn keep_shortcut(link: &Path) -> Option<String> {+ let id = shortcut_id(link)?;+ let (_, arguments) = read_link(link)?;+ let is_link = crate::tracker::is_shortcut(&id);+ if !is_link && arguments.is_empty() {+ return Some(id);+ }+ let folder = kept_folder()?;+ let parent = link.parent()?;+ if [Some(&folder), taskbar_folder().as_ref()]+ .into_iter()+ .flatten()+ .any(|managed| same_path(parent, managed))+ {+ return Some(id);+ }+ let contents = fs::read(link).ok()?;+ fs::create_dir_all(&folder).ok()?;+ if !is_link {+ forget_shortcut(&id);+ }+ let stem = link.file_stem()?.to_string_lossy().into_owned();+ for attempt in 1..100 {+ let name = if attempt == 1 {+ format!("{stem}.lnk")+ } else {+ format!("{stem} ({attempt}).lnk")+ };+ let kept = folder.join(name);+ match fs::read(&kept) {+ Ok(existing) if existing == contents => {}+ Ok(_) => continue,+ Err(_) => fs::write(&kept, &contents).ok()?,+ }+ return Some(if is_link {+ normalize_id(&kept.to_string_lossy())+ } else {+ id+ });+ }+ None+}++/// Deletes what Muelle kept to open `id` once it is no longer pinned: the+/// kept shortcut itself, or the kept shortcuts that open that program. The+/// taskbar's and the user's own shortcuts are never touched.+///+/// Requires COM to be initialized on the calling thread.+pub fn forget_shortcut(id: &str) {+ let Some(folder) = kept_folder() else {+ return;+ };+ if crate::tracker::is_shortcut(id) {+ let path = Path::new(id);+ if path+ .parent()+ .is_some_and(|parent| same_path(parent, &folder))+ {+ let _ = fs::remove_file(path);+ }+ return;+ }+ for link in fs::read_dir(&folder)+ .into_iter()+ .flatten()+ .filter_map(|entry| Some(entry.ok()?.path()))+ {+ let opens_id = read_link(&link)+ .and_then(|(target, _)| target)+ .is_some_and(|target| normalize_id(&target) == id);+ if opens_id {+ let _ = fs::remove_file(link);+ }+ }+}++fn same_path(a: &Path, b: &Path) -> bool {+ a.as_os_str().eq_ignore_ascii_case(b.as_os_str())+}++/// The program a shortcut opens (`None` when it points at no file, such as+/// a Control Panel item) and its arguments.+fn read_link(link: &Path) -> Option<(Option<String>, String)> {// SAFETY: COM calls use buffers and strings that remain alive for the duration of each call.unsafe {let shell_link: IShellLinkW =@@ -335,12 +507,22 @@ pub fn link_target(link: &std::path::Path) -> Option<String> {.ok()?.Load(&HSTRING::from(link.as_os_str()), STGM_READ).ok()?;- let mut buffer = [0u16; 1024];- shell_link- .GetPath(&mut buffer, std::ptr::null_mut(), 0)- .ok()?;- let len = buffer.iter().position(|&unit| unit == 0)?;- (len > 0).then(|| String::from_utf16_lossy(&buffer[..len]))+ let text = |buffer: &[u16]| {+ let len = buffer.iter().position(|&unit| unit == 0).unwrap_or(0);+ String::from_utf16_lossy(&buffer[..len])+ };+ let mut path = [0u16; 1024];+ let target = shell_link+ .GetPath(&mut path, std::ptr::null_mut(), 0)+ .ok()+ .map(|()| text(&path))+ .filter(|target| !target.is_empty());+ // Up to 32 767 characters, the longest command line Windows takes.+ let mut arguments = vec![0u16; 32_768];+ let arguments = shell_link+ .GetArguments(&mut arguments)+ .map_or_else(|_| String::new(), |()| text(&arguments));+ Some((target, arguments.trim().to_owned()))}}diff --git a/crates/muelle-shell/src/tracker.rs b/crates/muelle-shell/src/tracker.rsindex 1508712..ce99512 100644--- a/crates/muelle-shell/src/tracker.rs+++ b/crates/muelle-shell/src/tracker.rs@@ -43,7 +43,9 @@ pub struct TrackedWindow {#[must_use]pub fn normalize_id(id: &str) -> String {- if id.starts_with(APPS_FOLDER) {+ // Shortcuts kept as pins (see `pins::shortcut_id`) keep their case: the+ // shell shows their file name as the label.+ if id.starts_with(APPS_FOLDER) || is_shortcut(id) {id.to_owned()} else {id.to_lowercase()@@ -447,6 +449,12 @@ fn app_id(hwnd: HWND) -> Option<String> {}}+/// `true` for the path of a Windows shortcut (`.lnk`).+#[must_use]+pub fn is_shortcut(id: &str) -> bool {+ id.len() > 4 && id[id.len() - 4..].eq_ignore_ascii_case(".lnk")+}+fn class_name(hwnd: HWND) -> String {let mut buffer = [0u16; 128];// SAFETY: The buffer remains alive during the call, which returns the number of characters written.diff --git a/spikes/src/bin/spike_shortcut.rs b/spikes/src/bin/spike_shortcut.rsnew file mode 100644index 0000000..d5fda68--- /dev/null+++ b/spikes/src/bin/spike_shortcut.rs@@ -0,0 +1,98 @@+//! End-to-end check of issue #8 (shortcuts with arguments): builds a+//! `wscript.exe "script.vbs"` shortcut in a scratch folder, pins it the way+//! the dock does (with %APPDATA% pointed at the scratch folder) and opens+//! it, then checks that the script really ran. Usage: `spike_shortcut <dir>`.++#![allow(clippy::unwrap_used, clippy::expect_used)]++use std::{+ fs,+ path::Path,+ thread::sleep,+ time::{Duration, Instant},+};++use muelle_shell::{launcher, pins};+use windows::{+ Win32::{+ System::Com::{+ CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx,+ IPersistFile,+ },+ UI::Shell::{IShellLinkW, ShellLink},+ },+ core::{HSTRING, Interface},+};++fn make_link(path: &Path, target: &str, arguments: &str) {+ unsafe {+ let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).unwrap();+ link.SetPath(&HSTRING::from(target)).unwrap();+ link.SetArguments(&HSTRING::from(arguments)).unwrap();+ link.cast::<IPersistFile>()+ .unwrap()+ .Save(&HSTRING::from(path.as_os_str()), true)+ .unwrap();+ }+}++fn main() {+ let dir = std::path::PathBuf::from(std::env::args().nth(1).expect("dir"));+ fs::create_dir_all(&dir).unwrap();+ unsafe {+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ // Only this process: the kept copy goes to the scratch folder.+ std::env::set_var("APPDATA", dir.join("appdata"));+ }+ let marker = dir.join("ran.txt");+ let _ = fs::remove_file(&marker);+ let script = dir.join("Launch-Hidden.vbs");+ fs::write(&script, format!(+ "Set f = CreateObject(\"Scripting.FileSystemObject\").CreateTextFile(\"{}\", True)\r\nf.WriteLine \"ok\"\r\nf.Close\r\n",+ marker.display()+ )).unwrap();+ let wscript = r"C:\Windows\System32\wscript.exe";+ let with_args = dir.join("Launch Hidden.lnk");+ let plain = dir.join("Plain wscript.lnk");+ make_link(&with_args, wscript, &format!("\"{}\"", script.display()));+ make_link(&plain, wscript, "");++ let to_script = dir.join("Script itself.lnk");+ make_link(&to_script, &script.to_string_lossy(), "");+ println!("with arguments -> {:?}", pins::shortcut_id(&with_args));+ println!("no arguments -> {:?}", pins::shortcut_id(&plain));+ println!("to a .vbs file -> {:?}", pins::shortcut_id(&to_script));++ let pinned = pins::keep_shortcut(&with_args).expect("pinned");+ let kept_dir = dir.join("appdata").join("Muelle").join("Pins");+ let kept: Vec<_> = fs::read_dir(&kept_dir)+ .map(|d| d.flatten().map(|e| e.file_name()).collect())+ .unwrap_or_default();+ println!("pin id -> {pinned} (kept copies: {kept:?})");+ println!(+ "plain pin -> {:?} (no copy needed)",+ pins::keep_shortcut(&plain)+ );+ let target = pins::launch_target(&pinned);+ println!("opens through -> {target:?}");+ let cache = muelle_shell::icon_cache::IconCache::new(dir.join("cache"));+ let visual = cache.get(&pinned, 48).expect("visual");+ println!(+ "dock label -> {:?} (icon {}x{})",+ visual.name, visual.icon.width, visual.icon.height+ );++ let started = Instant::now();+ launcher::open(&target.unwrap_or(pinned.clone())).expect("open");+ while !marker.exists() && started.elapsed() < Duration::from_secs(10) {+ sleep(Duration::from_millis(50));+ }+ println!(+ "script ran -> {} ({} ms)",+ marker.exists(),+ started.elapsed().as_millis()+ );+ pins::forget_shortcut(&pinned);+ let left = fs::read_dir(&kept_dir).map(|d| d.count()).unwrap_or(0);+ println!("unpinned -> kept copies left: {left}");+}