A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat: add a shortcuts folder that opens as a menu
AzureAD\davidlamad1d21041cf71
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 139ab10..0107ab5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,11 @@ copia la sección de la versión que se publica a la release de GitHub.its apps out above it (a grid when there are many); drag one out of thefan to take it out of the group, into the dock where it is dropped.Right-click a group to ungroup it.+- Shortcuts folder: choose a folder in Settings → Dock and it shows at the+ right of the dock. Clicking it opens its contents as a menu, as a Windows 10+ taskbar toolbar did: folders first, each one a submenu, then files, with+ Explorer's names and icons; choosing an item opens it. Right-click it to+ open the folder, change it or remove it.- French: the dock, Settings and the installer are now also in French. Chooseit in Settings → System, or leave Automatic to follow Windows. A languageMuelle does not know in the settings file now reads as Automatic instead of@@ -37,6 +42,12 @@ copia la sección de la versión que se publica a la release de GitHub.puntero. Al hacer clic se despliegan en abanico encima (en cuadrícula si sonmuchas); arrastra una fuera del abanico para sacarla del grupo, al lugar deldock donde la sueltes. Clic derecho en un grupo para desagruparlo.+- Carpeta de accesos directos: elige una carpeta en Ajustes → Dock y aparece+ a la derecha del dock. Al hacer clic, su contenido se abre como un menú,+ como una barra de herramientas de la barra de tareas de Windows 10: primero+ las carpetas, cada una un submenú, luego los archivos, con los nombres e+ iconos del Explorador; al elegir un elemento se abre. Clic derecho para+ abrir la carpeta, cambiarla o quitarla.- Francés: el dock, Ajustes y el instalador también están en francés.Elígelo en Ajustes → Sistema, o deja Automático para seguir a Windows. Unidioma que Muelle no conoce en el archivo de ajustes ahora se lee comodiff --git a/README.md b/README.mdindex 213d851..05989e9 100644--- a/README.md+++ b/README.md@@ -34,6 +34,8 @@ Smooth magnification, live window previews, and an optional Genie-style minimizeon the right side of the dock instead.- Click the app already in front to minimize it, as on the Windows taskbar.- Drag and drop files onto apps, Downloads, or the Recycle Bin.+- A shortcuts folder at the right of the dock: its contents open as a menu,+ with a submenu for each folder inside, like a Windows 10 taskbar toolbar.- Optional auto-hide.- A top menu bar with the app in front, clock, network, volume and battery, theinput language, microphone/camera in use, the hidden tray icons, plusdiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex d54f0e0..0fbea7b 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -72,16 +72,17 @@ use windows::{CreateWindowExW, DefWindowProcW, DispatchMessageW, EVENT_OBJECT_CLOAKED,EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_MINIMIZEEND,EVENT_SYSTEM_MINIMIZESTART, FindWindowW, GetCursorPos, GetMessageW,- GetSystemMetrics, HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MA_ACTIVATE,- MA_NOACTIVATE, MSG, OBJID_WINDOW, PM_REMOVE, PeekMessageW, PostMessageW,- PostQuitMessage, RegisterClassW, RegisterShellHookWindow, RegisterWindowMessageW,- SM_CXDRAG, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,- WINDOW_EX_STYLE, WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS, WM_APP,- WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED,- WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEACTIVATE,- WM_MOUSEMOVE, WM_QUIT, WM_RBUTTONUP, WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW,- WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW,- WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP,+ GetSystemMetrics, HMENU, HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW,+ MA_ACTIVATE, MA_NOACTIVATE, MSG, OBJID_WINDOW, PM_REMOVE, PeekMessageW,+ PostMessageW, PostQuitMessage, RegisterClassW, RegisterShellHookWindow,+ RegisterWindowMessageW, SM_CXDRAG, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW,+ SetTimer, SetWindowPos, WINDOW_EX_STYLE, WINEVENT_OUTOFCONTEXT,+ WINEVENT_SKIPOWNPROCESS, WM_APP, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,+ WM_DISPLAYCHANGE, WM_DPICHANGED, WM_INITMENUPOPUP, WM_LBUTTONDOWN, WM_LBUTTONUP,+ WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEACTIVATE, WM_MOUSEMOVE, WM_QUIT,+ WM_RBUTTONUP, WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW, WS_EX_LAYERED,+ WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST,+ WS_EX_TRANSPARENT, WS_POPUP,},},},@@ -92,6 +93,7 @@ use crate::{assets::{Visuals, fallback_name},drop::DropTarget,flight::{Flight, Snapshot},+ folder_menu,gfx::{Gfx, LabelBrush},group_view::{DragGhost, GroupItem, GroupView, Placement, Released},mascot,@@ -256,6 +258,7 @@ 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_REMOVE_FOLDER: u32 = 16;const CMD_WINDOW: u32 = 100;const MENU_WINDOWS: usize = 12;const MENU_TITLE_CHARS: usize = 60;@@ -332,6 +335,8 @@ enum Role {/// A minimized window, shown as a live thumbnail.Window,Folder,+ /// The shortcuts folder: a click opens its contents as a menu.+ Shortcuts,Trash,}@@ -361,6 +366,12 @@ enum Outside {copy: bool,},Menu(MenuRequest),+ /// The shortcuts folder's contents, as a menu above its icon.+ FolderMenu {+ folder: String,+ anchor: POINT,+ dark: bool,+ },QuitDock,OpenSettings,OpenAsAdmin(String),@@ -798,6 +809,9 @@ impl App {.map(|&hwnd| icon(&window_id(hwnd), Role::Window, false)),);}+ if let Some(folder) = &self.config.shortcuts_folder {+ entries.push(icon(folder, Role::Shortcuts, false));+ }if let Some(downloads) = &self.downloads {entries.push(icon(downloads, Role::Folder, false));}@@ -2340,7 +2354,10 @@ impl App {.all(|file| files::same_volume(file, &id)),folder: id,},- Role::App | Role::Group | Role::Start | Role::Window => DropAction::Nothing,+ // The user arranges the shortcuts folder in Explorer.+ Role::App | Role::Group | Role::Start | Role::Window | Role::Shortcuts => {+ DropAction::Nothing+ }}}@@ -2608,10 +2625,46 @@ impl App {}Role::Start => Some(Outside::OpenStart),Role::Window => window_of(&id).and_then(|hwnd| self.activating(vec![hwnd])),+ Role::Shortcuts => self.folder_menu(id)?,Role::Folder | Role::Trash => Some(Outside::Open(id)),})}+ /// The shortcuts folder's menu, above its icon. The label hides while+ /// the menu is open, as for the context menu.+ fn folder_menu(&mut self, folder: String) -> Result<Option<Outside>> {+ let Some(anchor) = self.hovered.and_then(|index| self.anchor_above(index)) else {+ return Ok(None);+ };+ self.close_preview();+ self.close_group_view();+ self.hovered = None;+ self.hovering = false;+ self.render()?;+ Ok(Some(Outside::FolderMenu {+ folder,+ anchor,+ dark: !uses_light_theme(),+ }))+ }++ /// Where a menu for the icon at `index` opens: centered just above it.+ fn anchor_above(&self, index: usize) -> Option<POINT> {+ let stage = self.stage.as_ref()?;+ let state = magnify(+ &stage.layout,+ self.cursor,+ self.amount.value,+ &stage.magnifier,+ );+ let rect = state.rects.get(index)?;+ let gap = (stage.gap / 2.0).round() as i32;+ Some(POINT {+ x: stage.dock_origin.x + (rect.x + rect.width / 2.0).round() as i32,+ y: stage.dock_origin.y + rect.y.round() as i32 - gap,+ })+ }+/// 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.@@ -2989,6 +3042,13 @@ impl App {items.push(MenuItem::action(CMD_OPEN, t.open));items.push(MenuItem::action(CMD_REVEAL, t.show_in_explorer));}+ // The folder is chosen in Settings, so changing it opens them.+ Role::Shortcuts => {+ items.push(MenuItem::action(CMD_OPEN, t.open));+ items.push(MenuItem::action(CMD_SETTINGS, t.change_folder));+ items.push(MenuItem::Separator);+ items.push(MenuItem::action(CMD_REMOVE_FOLDER, t.remove_from_dock));+ }Role::Trash => {items.push(MenuItem::action(CMD_OPEN, t.open));items.push(MenuItem::Separator);@@ -3036,6 +3096,13 @@ impl App {launcher::close(&window_of(&id).into_iter().collect::<Vec<_>>());None}+ CMD_SETTINGS => Some(Outside::OpenSettings),+ CMD_REMOVE_FOLDER => {+ self.config.shortcuts_folder = None;+ save_settings(&self.roster, &self.config);+ self.refresh()?;+ None+ }CMD_OPEN => {if role == Role::App {self.start_bounce(id.clone(), None);@@ -3888,6 +3955,17 @@ fn run_outside(outside: Outside) {});}}+ Outside::FolderMenu {+ folder,+ anchor,+ dark,+ } => {+ let chosen = folder_menu::show(main_window(), &folder, anchor, dark);+ with_app("menú cerrado", App::after_menu);+ if let Some(path) = chosen {+ submit(ShellAction::Open { id: path });+ }+ }}}@@ -4050,6 +4128,8 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->// SAFETY: `hwnd` is this live window on its owning UI thread.unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };}+ // A folder's submenu in the shortcuts folder's menu is about to open.+ WM_INITMENUPOPUP if folder_menu::init_popup(HMENU(w.0 as *mut _)) => {}WM_DESTROY => unsafe { PostQuitMessage(0) },_ if SHELL_HOOK.get() == Some(&msg) => match w.0 {// Changing the foreground window does not change the app list; itdiff --git a/apps/dock/src/folder_menu.rs b/apps/dock/src/folder_menu.rsnew file mode 100644index 0000000..7da5d0b--- /dev/null+++ b/apps/dock/src/folder_menu.rs@@ -0,0 +1,260 @@+//! The shortcuts folder's menu: the folder's contents as a native Windows+//! menu, with a submenu for each folder inside, like a Windows 10 taskbar+//! toolbar. Each submenu is listed only when it opens, so nesting costs+//! nothing; names and icons come from the shell, as in Explorer.++use std::{cell::RefCell, ffi::c_void, ptr};++use muelle_shell::{+ folder::{self, FolderItem},+ icons::IconImage,+};+use windows::{+ Win32::{+ Foundation::{HWND, LPARAM, POINT, WPARAM},+ Graphics::Gdi::{+ BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS, DeleteObject,+ HBITMAP,+ },+ UI::WindowsAndMessaging::{+ CreatePopupMenu, DestroyMenu, GetForegroundWindow, GetMenuItemCount, HMENU,+ InsertMenuItemW, MENUITEMINFOW, MFS_DISABLED, MIIM_BITMAP, MIIM_ID, MIIM_STATE,+ MIIM_STRING, MIIM_SUBMENU, PostMessageW, SetForegroundWindow, TPM_BOTTOMALIGN,+ TPM_CENTERALIGN, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx, WM_NULL,+ },+ },+ core::{HSTRING, PWSTR},+};++use crate::strings::text;++/// Items listed per folder; past this, a huge folder would make its menu+/// slow to open and too long to use.+const MAX_ITEMS: usize = 500;+/// Longest name shown; longer ones end in "…".+const NAME_CHARS: usize = 64;++/// The menu being shown.+#[derive(Default)]+struct Open {+ /// Submenus not listed yet, with their folder.+ pending: Vec<(isize, String)>,+ /// What each item opens, by command id minus one.+ commands: Vec<String>,+ /// The items' icons, freed when the menu closes.+ bitmaps: Vec<HBITMAP>,+}++impl Drop for Open {+ fn drop(&mut self) {+ for bitmap in &self.bitmaps {+ // SAFETY: Our own bitmaps; the menu that drew them is destroyed.+ unsafe {+ let _ = DeleteObject((*bitmap).into());+ }+ }+ }+}++thread_local! {+ static OPEN: RefCell<Option<Open>> = const { RefCell::new(None) };+}++/// Shows the contents of `folder` as a menu whose bottom edge is centered+/// at `anchor`, and returns the path of the item chosen (`None` if+/// dismissed). Folders inside are submenus and are never returned.+///+/// Runs a modal loop that keeps dispatching messages to the dock, whose+/// window procedure hands `WM_INITMENUPOPUP` to [`init_popup`]. The caller+/// must not hold the app state meanwhile.+pub fn show(owner: HWND, folder: &str, anchor: POINT, dark: bool) -> Option<String> {+ crate::menu::apply_theme(dark);+ // SAFETY: The menu is destroyed below, with its submenus.+ let root = unsafe { CreatePopupMenu() }.ok()?;+ OPEN.with_borrow_mut(|open| *open = Some(Open::default()));+ fill(root, folder);++ // SAFETY: Calls on our own menu and window; as for the dock's native+ // menu, the owner must be in front for a click outside to close it.+ let chosen = unsafe {+ let previous = GetForegroundWindow();+ let _ = SetForegroundWindow(owner);+ let chosen = TrackPopupMenuEx(+ root,+ (TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_BOTTOMALIGN | TPM_CENTERALIGN).0,+ anchor.x,+ anchor.y,+ owner,+ None,+ );+ let _ = PostMessageW(Some(owner), WM_NULL, WPARAM(0), LPARAM(0));+ let _ = DestroyMenu(root);+ if chosen.0 == 0 {+ // Dismissing gives the focus back, as the dock's own menu does.+ let _ = SetForegroundWindow(previous);+ }+ chosen.0+ };+ let open = OPEN.with_borrow_mut(Option::take)?;+ usize::try_from(chosen)+ .ok()?+ .checked_sub(1)+ .and_then(|index| open.commands.get(index).cloned())+}++/// Lists a folder's submenu as it opens. `false` for any other menu (the+/// dock's native menu), which is left alone.+pub fn init_popup(menu: HMENU) -> bool {+ let folder = OPEN.with_borrow_mut(|open| {+ let open = open.as_mut()?;+ let index = open+ .pending+ .iter()+ .position(|(pending, _)| *pending == menu.0 as isize)?;+ Some(open.pending.swap_remove(index).1)+ });+ let Some(folder) = folder else {+ return false;+ };+ fill(menu, &folder);+ true+}++fn fill(menu: HMENU, folder: &str) {+ // Listing asks the shell for names and icons, which may dispatch+ // messages: the menu state is not borrowed meanwhile.+ match folder::list(folder) {+ Err(_) => add_note(menu, text().folder_unavailable),+ Ok(items) if items.is_empty() => add_note(menu, text().folder_empty),+ Ok(items) => {+ for item in items.into_iter().take(MAX_ITEMS) {+ add_item(menu, item);+ }+ }+ }+}++fn add_item(menu: HMENU, item: FolderItem) {+ let label = HSTRING::from(label_of(&item.name));+ let mut info = MENUITEMINFOW {+ cbSize: size_of::<MENUITEMINFOW>() as u32,+ fMask: MIIM_STRING | MIIM_ID,+ dwTypeData: PWSTR(label.as_ptr().cast_mut()),+ ..Default::default()+ };+ if let Some(bitmap) = item.icon.as_ref().and_then(bitmap_of) {+ info.fMask |= MIIM_BITMAP;+ info.hbmpItem = bitmap;+ OPEN.with_borrow_mut(|open| {+ if let Some(open) = open {+ open.bitmaps.push(bitmap);+ }+ });+ }+ if item.is_folder {+ // SAFETY: Destroyed with the menu it is attached to below.+ let Ok(submenu) = (unsafe { CreatePopupMenu() }) else {+ return;+ };+ info.fMask |= MIIM_SUBMENU;+ info.hSubMenu = submenu;+ OPEN.with_borrow_mut(|open| {+ if let Some(open) = open {+ open.pending.push((submenu.0 as isize, item.path));+ }+ });+ } else {+ info.wID = OPEN.with_borrow_mut(|open| {+ open.as_mut().map_or(0, |open| {+ open.commands.push(item.path);+ open.commands.len() as u32+ })+ });+ }+ append(menu, &info);+}++/// A line that cannot be chosen: the folder is empty or unavailable.+fn add_note(menu: HMENU, note: &str) {+ let label = HSTRING::from(note);+ append(+ menu,+ &MENUITEMINFOW {+ cbSize: size_of::<MENUITEMINFOW>() as u32,+ fMask: MIIM_STRING | MIIM_STATE,+ fState: MFS_DISABLED,+ dwTypeData: PWSTR(label.as_ptr().cast_mut()),+ ..Default::default()+ },+ );+}++fn append(menu: HMENU, info: &MENUITEMINFOW) {+ // SAFETY: `info` and the strings it points to live for the call, which+ // copies them into the menu.+ unsafe {+ let end = GetMenuItemCount(Some(menu)).max(0) as u32;+ let _ = InsertMenuItemW(menu, end, true, info);+ }+}++/// The name as a menu shows it: `&` is the access key marker, so it is+/// doubled, and a very long name is shortened.+fn label_of(name: &str) -> String {+ let shown: String = if name.chars().count() > NAME_CHARS {+ let mut short: String = name.chars().take(NAME_CHARS - 1).collect();+ short.push('…');+ short+ } else {+ name.to_owned()+ };+ shown.replace('&', "&&")+}++/// A menu draws a 32-bit top-down bitmap with premultiplied alpha blended,+/// which is what the icon already is.+fn bitmap_of(icon: &IconImage) -> Option<HBITMAP> {+ let info = BITMAPINFO {+ bmiHeader: BITMAPINFOHEADER {+ biSize: size_of::<BITMAPINFOHEADER>() as u32,+ biWidth: icon.width as i32,+ // A negative height specifies top-down rows.+ biHeight: -(icon.height as i32),+ biPlanes: 1,+ biBitCount: 32,+ biCompression: BI_RGB.0,+ ..Default::default()+ },+ ..Default::default()+ };+ let mut bits: *mut c_void = ptr::null_mut();+ // SAFETY: The section is created for exactly these dimensions; the copy+ // writes `width * height * 4` bytes, the size of both buffers.+ unsafe {+ let bitmap = CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0).ok()?;+ let size = icon.width as usize * icon.height as usize * 4;+ if bits.is_null() || icon.bgra.len() != size {+ let _ = DeleteObject(bitmap.into());+ return None;+ }+ ptr::copy_nonoverlapping(icon.bgra.as_ptr(), bits.cast::<u8>(), size);+ Some(bitmap)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn label_of_should_double_ampersands() {+ assert_eq!(label_of("Tom & Jerry"), "Tom && Jerry");+ }++ #[test]+ fn label_of_should_shorten_very_long_names() {+ let label = label_of(&"x".repeat(NAME_CHARS + 10));+ assert_eq!(label.chars().count(), NAME_CHARS);+ assert!(label.ends_with('…'));+ }+}diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex 7651616..0edbf99 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -15,6 +15,7 @@ mod app;mod assets;mod drop;mod flight;+mod folder_menu;mod gfx;mod group_view;mod guard;diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rsindex cdde63a..210ed1e 100644--- a/apps/dock/src/menu.rs+++ b/apps/dock/src/menu.rs@@ -851,7 +851,7 @@ fn show_native(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Op/// Windows has no public API for dark Win32 menus, so this uses `uxtheme.dll`/// functions by ordinal, as Windows Terminal and Notepad++ do. If unavailable/// on another Windows version, the menu remains light.-fn apply_theme(dark: bool) {+pub fn apply_theme(dark: bool) {type SetPreferredAppMode = unsafe extern "system" fn(i32) -> i32;type FlushMenuThemes = unsafe extern "system" fn();const FORCE_DARK: i32 = 2;diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rsindex db51be9..8155a95 100644--- a/apps/dock/src/strings.rs+++ b/apps/dock/src/strings.rs@@ -37,6 +37,10 @@ pub struct Strings {pub usage_updated: &'static str,pub usage_used: &'static str,pub media_title: &'static str,+ pub folder_empty: &'static str,+ pub folder_unavailable: &'static str,+ pub change_folder: &'static str,+ pub remove_from_dock: &'static str,pub shell_operation_failed: &'static str,}@@ -71,6 +75,10 @@ const ES: Strings = Strings {usage_updated: "Actualizado hace",usage_used: "usado",media_title: "Reproducción",+ folder_empty: "(vacía)",+ folder_unavailable: "Carpeta no disponible",+ change_folder: "&Cambiar de carpeta…",+ remove_from_dock: "&Quitar del Dock",};const EN: Strings = Strings {@@ -104,6 +112,10 @@ const EN: Strings = Strings {usage_updated: "Updated",usage_used: "used",media_title: "Now playing",+ folder_empty: "(empty)",+ folder_unavailable: "Folder unavailable",+ change_folder: "&Change Folder…",+ remove_from_dock: "&Remove from Dock",};const FR: Strings = Strings {@@ -137,6 +149,10 @@ const FR: Strings = Strings {usage_updated: "Actualisé il y a",usage_used: "utilisé",media_title: "En cours de lecture",+ folder_empty: "(vide)",+ folder_unavailable: "Dossier introuvable",+ change_folder: "&Changer de dossier…",+ remove_from_dock: "&Retirer du Dock",};/// 0 = not chosen yet (follow Windows), 1 = Spanish, 2 = English, 3 = French.diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rsindex 0888945..8ca324e 100644--- a/apps/settings/src-tauri/src/main.rs+++ b/apps/settings/src-tauri/src/main.rs@@ -77,6 +77,25 @@ fn open_animation_settings() -> Result<(), String> {launcher::open(page).map_err(|error| error.to_string())}+/// Asks for the folder the dock shows as a menu, opened at `current`;+/// `None` if the user cancels. The dialog runs on its own thread, so the+/// window keeps drawing behind it.+#[tauri::command]+async fn pick_folder(+ window: tauri::WebviewWindow,+ current: Option<String>,+) -> Result<Option<String>, String> {+ let owner = window+ .hwnd()+ .map(|hwnd| hwnd.0 as isize)+ .unwrap_or_default();+ tauri::async_runtime::spawn_blocking(move || {+ muelle_shell::folder::pick(owner, current.as_deref())+ })+ .await+ .map_err(|error| error.to_string())+}+#[tauri::command]fn get_autostart() -> bool {autostart::is_enabled()@@ -262,6 +281,7 @@ fn main() {set_autostart,windows_animations,open_animation_settings,+ pick_folder,check_update,install_update,open_release_notesdiff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex 5b82c1b..ccca3d4 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -16,6 +16,7 @@ import {installUpdate,loadConfig,openReleaseNotes,+ pickFolder,saveConfig,setAutostart,} from "./config";@@ -182,12 +183,19 @@ export function App() {}setConfirmingReset(false);defaultConfig()- .then(({ pinned: _pinned, recent: _recent, ...defaults }) => update(defaults))+ .then(({ pinned: _pinned, recent: _recent, shortcutsFolder: _folder, ...defaults }) =>+ update(defaults),+ ).catch(() => setFailed(true));}, [confirmingReset, update]);if (!config) return <div className="window" />;const t = textsFor(config.language);+ const chooseFolder = () => {+ pickFolder(config.shortcutsFolder)+ .then((folder) => folder && update({ shortcutsFolder: folder }))+ .catch(() => setFailed(true));+ };const appWindow = getCurrentWindow();const waiting = pendingUpdate(updateState);// An update the user asked for keeps its banner even after "Later".@@ -319,6 +327,20 @@ export function App() {/></Row></Card>+ <Card>+ <Row label={t.shortcutsFolder} hint={config.shortcutsFolder ?? t.shortcutsFolderHint}>+ <div className="push-group">+ {config.shortcutsFolder ? (+ <button type="button" className="push" onClick={() => update({ shortcutsFolder: null })}>+ {t.shortcutsFolderRemove}+ </button>+ ) : null}+ <button type="button" className="push" onClick={chooseFolder}>+ {t.shortcutsFolderChoose}+ </button>+ </div>+ </Row>+ </Card></>) : section === "windows" ? (<>diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex ded35c6..03b5c16 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -23,6 +23,8 @@ export interface Config {checkUpdates: boolean;autoUpdate: boolean;language: Language;+ /** The folder shown at the right of the dock, whose contents open as a menu. */+ shortcutsFolder: string | null;}export const ICON_SIZE = { min: 32, max: 96 } as const;@@ -36,6 +38,9 @@ export const getAutostart = () => invoke<boolean>("get_autostart");export const windowsAnimations = () => invoke<boolean>("windows_animations");export const openAnimationSettings = () => invoke<void>("open_animation_settings");export const setAutostart = (enabled: boolean) => invoke<void>("set_autostart", { enabled });+/** The folder the user picks, or null if they cancel. */+export const pickFolder = (current: string | null) =>+ invoke<string | null>("pick_folder", { current });export interface UpdateInfo {version: string;/** Release page with the notes, if the manifest has one. */diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonindex 9c32b32..1173d8c 100644--- a/apps/settings/src/i18n/en.json+++ b/apps/settings/src/i18n/en.json@@ -67,5 +67,9 @@"groupBehavior": "Behavior","groupMinimize": "Minimizing","zoom": "Zoom",- "updatesNow": "This version"+ "updatesNow": "This version",+ "shortcutsFolder": "Shortcuts folder",+ "shortcutsFolderHint": "A folder at the right of the Dock: its contents open as a menu, with a submenu for each folder inside.",+ "shortcutsFolderChoose": "Choose…",+ "shortcutsFolderRemove": "Remove"}diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.jsonindex d1d0b12..3c66f1e 100644--- a/apps/settings/src/i18n/es.json+++ b/apps/settings/src/i18n/es.json@@ -67,5 +67,9 @@"groupBehavior": "Comportamiento","groupMinimize": "Al minimizar","zoom": "Ampliar",- "updatesNow": "Esta versión"+ "updatesNow": "Esta versión",+ "shortcutsFolder": "Carpeta de accesos directos",+ "shortcutsFolderHint": "Una carpeta a la derecha del Dock: su contenido se abre como un menú, con un submenú por cada carpeta que contiene.",+ "shortcutsFolderChoose": "Elegir…",+ "shortcutsFolderRemove": "Quitar"}diff --git a/apps/settings/src/i18n/fr.json b/apps/settings/src/i18n/fr.jsonindex 957e972..48ebce3 100644--- a/apps/settings/src/i18n/fr.json+++ b/apps/settings/src/i18n/fr.json@@ -67,5 +67,9 @@"groupBehavior": "Comportement","groupMinimize": "Réduction","zoom": "Agrandir",- "updatesNow": "Cette version"+ "updatesNow": "Cette version",+ "shortcutsFolder": "Dossier de raccourcis",+ "shortcutsFolderHint": "Un dossier à droite du Dock : son contenu s'ouvre en menu, avec un sous-menu pour chaque dossier qu'il contient.",+ "shortcutsFolderChoose": "Choisir…",+ "shortcutsFolderRemove": "Retirer"}diff --git a/apps/settings/src/styles.css b/apps/settings/src/styles.cssindex 34e9112..0a34406 100644--- a/apps/settings/src/styles.css+++ b/apps/settings/src/styles.css@@ -338,6 +338,8 @@ input:focus-visible {color: var(--text-dim);font-size: 11.5px;line-height: 1.35;+ /* A folder path has no spaces to wrap at. */+ overflow-wrap: anywhere;}.row-control {@@ -435,6 +437,11 @@ input:focus-visible {opacity: 0.5;}+.push-group {+ display: flex;+ gap: 6px;+}+.push-danger {background: #ff453a;color: #fff;diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsindex 0607829..1bc23e7 100644--- a/crates/muelle-config/src/lib.rs+++ b/crates/muelle-config/src/lib.rs@@ -80,6 +80,10 @@ pub struct Config {/// computer, new versions are downloaded and installed without asking.pub auto_update: bool,pub language: Language,+ /// A folder shown at the right of the dock whose contents open as a+ /// menu, with a submenu for each folder inside, like a Windows 10 taskbar+ /// toolbar. Only one: the user arranges the folder as they like.+ pub shortcuts_folder: Option<String>,}/// Pinned apps the user gathered in one dock icon by dropping one on@@ -117,6 +121,10 @@ impl Config {self.magnified_size = self.magnified_size.clamp(self.icon_size, MAX_MAGNIFIED_SIZE);+ self.shortcuts_folder = self+ .shortcuts_folder+ .map(|folder| folder.trim().to_owned())+ .filter(|folder| !folder.is_empty());self}@@ -155,6 +163,7 @@ impl Default for Config {check_updates: true,auto_update: true,language: Language::Auto,+ shortcuts_folder: None,}}}@@ -330,6 +339,24 @@ mod tests {);}+ #[test]+ fn load_should_read_the_shortcuts_folder() {+ let path = scratch("shortcuts-folder");+ save(&path, &Config::default()).ok();+ fs::write(&path, r#"{"shortcutsFolder":"D:\\Racc"}"#).ok();+ let config = load(&path).ok().flatten().unwrap_or_default();+ assert_eq!(config.shortcuts_folder.as_deref(), Some(r"D:\Racc"));+ }++ #[test]+ fn sanitized_should_forget_a_blank_shortcuts_folder() {+ let config = Config {+ shortcuts_folder: Some(" ".into()),+ ..Config::default()+ };+ assert_eq!(config.sanitized().shortcuts_folder, None);+ }+#[test]fn load_should_fail_on_invalid_json() {let path = scratch("invalid");diff --git a/crates/muelle-shell/src/folder.rs b/crates/muelle-shell/src/folder.rsnew file mode 100644index 0000000..66b602d--- /dev/null+++ b/crates/muelle-shell/src/folder.rs@@ -0,0 +1,205 @@+//! A folder's contents as Explorer lists them, for the dock's folder menu,+//! and the standard dialog to choose that folder.++use std::{cmp::Ordering, fs, io, os::windows::fs::MetadataExt};++use windows::{+ Win32::{+ Foundation::{E_FAIL, HWND},+ Storage::FileSystem::FILE_FLAGS_AND_ATTRIBUTES,+ System::Com::{+ CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx,+ CoTaskMemFree, CoUninitialize,+ },+ UI::{+ Shell::{+ FOS_FORCEFILESYSTEM, FOS_PICKFOLDERS, FileOpenDialog, IFileOpenDialog, IShellItem,+ SHCreateItemFromParsingName, SHFILEINFOW, SHGFI_DISPLAYNAME, SHGFI_ICON,+ SHGFI_SMALLICON, SHGetFileInfoW, SIGDN_FILESYSPATH, StrCmpLogicalW,+ },+ WindowsAndMessaging::DestroyIcon,+ },+ },+ core::HSTRING,+};++use crate::icons::{IconImage, icon_image};++const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;+const FILE_ATTRIBUTE_SYSTEM: u32 = 0x4;++/// An item of a folder, as Explorer shows it.+#[derive(Clone, Debug)]+pub struct FolderItem {+ pub path: String,+ /// The name Explorer shows: without `.lnk`, and without the extension+ /// when Explorer hides extensions.+ pub name: String,+ pub is_folder: bool,+ /// Explorer's small icon, `None` if the shell has none.+ pub icon: Option<IconImage>,+}++/// The items of `folder`: folders first, then files, each in Explorer's+/// order ("2" before "10"). Hidden and system items are left out, as in+/// Explorer by default (`desktop.ini`).+///+/// Requires COM to be initialized on the calling thread.+pub fn list(folder: &str) -> io::Result<Vec<FolderItem>> {+ let mut items: Vec<FolderItem> = fs::read_dir(folder)?+ .filter_map(Result::ok)+ .filter(|entry| {+ entry.metadata().is_ok_and(|meta| {+ meta.file_attributes() & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM) == 0+ })+ })+ .map(|entry| {+ let path = entry.path();+ // Through links too: a junction to a folder opens like one.+ let is_folder = fs::metadata(&path).is_ok_and(|meta| meta.is_dir());+ let path = path.to_string_lossy().into_owned();+ let (name, icon) = shell_info(&path);+ FolderItem {+ name: name.unwrap_or_else(|| entry.file_name().to_string_lossy().into_owned()),+ path,+ is_folder,+ icon,+ }+ })+ .collect();+ items.sort_by(explorer_order);+ Ok(items)+}++fn explorer_order(a: &FolderItem, b: &FolderItem) -> Ordering {+ b.is_folder.cmp(&a.is_folder).then_with(|| {+ // SAFETY: Both strings live for the call.+ unsafe { StrCmpLogicalW(&HSTRING::from(&a.name), &HSTRING::from(&b.name)) }.cmp(&0)+ })+}++/// The display name and small icon the shell gives `path`.+fn shell_info(path: &str) -> (Option<String>, Option<IconImage>) {+ let mut info = SHFILEINFOW::default();+ // SAFETY: `info` is a buffer of the declared size; the icon written to it+ // is ours and destroyed below.+ let found = unsafe {+ SHGetFileInfoW(+ &HSTRING::from(path),+ FILE_FLAGS_AND_ATTRIBUTES(0),+ Some(&raw mut info),+ size_of::<SHFILEINFOW>() as u32,+ SHGFI_ICON | SHGFI_SMALLICON | SHGFI_DISPLAYNAME,+ )+ };+ if found == 0 {+ return (None, None);+ }+ let icon = (!info.hIcon.is_invalid()).then(|| {+ let image = icon_image(info.hIcon);+ // SAFETY: SHGetFileInfo gave us this icon; it is not used afterward.+ unsafe {+ let _ = DestroyIcon(info.hIcon);+ }+ image+ });+ let length = info+ .szDisplayName+ .iter()+ .position(|&unit| unit == 0)+ .unwrap_or(info.szDisplayName.len());+ let name = String::from_utf16_lossy(&info.szDisplayName[..length]);+ ((!name.is_empty()).then_some(name), icon.flatten())+}++/// Asks for a folder with the standard Windows dialog, opened at `initial`;+/// `None` if the user cancels. `owner` is the window the dialog belongs to.+///+/// Initializes COM on the calling thread for the duration of the call.+#[must_use]+pub fn pick(owner: isize, initial: Option<&str>) -> Option<String> {+ // SAFETY: Balanced below, once every COM object is released.+ let com = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };+ let picked = pick_in_apartment(owner, initial);+ if com.is_ok() {+ // SAFETY: Balances the successful initialization above.+ unsafe { CoUninitialize() };+ }+ picked.ok()+}++fn pick_in_apartment(owner: isize, initial: Option<&str>) -> windows::core::Result<String> {+ // SAFETY: COM calls with arguments that live for each call; the path the+ // dialog returns is freed once copied.+ unsafe {+ let dialog: IFileOpenDialog =+ CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER)?;+ dialog.SetOptions(dialog.GetOptions()? | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM)?;+ if let Some(start) = initial.and_then(|path| {+ SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(path), None).ok()+ }) {+ let _ = dialog.SetFolder(&start);+ }+ // Cancelling is an error here, and ends the pick.+ dialog.Show(Some(HWND(owner as *mut _)))?;+ let raw = dialog.GetResult()?.GetDisplayName(SIGDN_FILESYSPATH)?;+ let path = raw.to_string();+ CoTaskMemFree(Some(raw.0.cast()));+ path.map_err(|_| E_FAIL.into())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn item(name: &str, is_folder: bool) -> FolderItem {+ FolderItem {+ path: name.into(),+ name: name.into(),+ is_folder,+ icon: None,+ }+ }++ #[test]+ fn explorer_order_should_put_folders_first_then_sort_numbers_by_value() {+ let mut items = [+ item("file10", false),+ item("Zeta", true),+ item("file2", false),+ item("alpha", true),+ item("Beta", false),+ ];+ items.sort_by(explorer_order);+ let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();+ assert_eq!(names, ["alpha", "Zeta", "Beta", "file2", "file10"]);+ }++ #[test]+ fn list_should_leave_out_hidden_items_and_mark_folders() -> io::Result<()> {+ // SAFETY: The shell needs COM on this test thread.+ let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };+ let root = std::env::temp_dir().join(format!("muelle-folder-{}", std::process::id()));+ let _ = fs::remove_dir_all(&root);+ fs::create_dir_all(root.join("Sub"))?;+ fs::write(root.join("note.txt"), b"x")?;+ fs::write(root.join("hidden.txt"), b"x")?;+ let hidden = HSTRING::from(root.join("hidden.txt").to_string_lossy().as_ref());+ // SAFETY: The path lives for the call.+ unsafe {+ windows::Win32::Storage::FileSystem::SetFileAttributesW(+ &hidden,+ FILE_FLAGS_AND_ATTRIBUTES(FILE_ATTRIBUTE_HIDDEN),+ )?;+ }+ let items = list(&root.to_string_lossy())?;+ let _ = fs::remove_dir_all(&root);+ let found: Vec<(bool, bool)> = items+ .iter()+ .map(|item| (item.is_folder, item.path.ends_with("note.txt")))+ .collect();+ assert_eq!(found, [(true, false), (false, true)]);+ Ok(())+ }+}diff --git a/crates/muelle-shell/src/icons.rs b/crates/muelle-shell/src/icons.rsindex a93d653..bf80a95 100644--- a/crates/muelle-shell/src/icons.rs+++ b/crates/muelle-shell/src/icons.rs@@ -104,9 +104,17 @@ fn program_icon(path: &str, size: u32) -> Option<IconImage> {return None;}let icon = OwnedIcon(icon);+ icon_image(icon.0)+}++/// The pixels of `icon`, premultiplied; `None` for a monochrome icon. The+/// caller keeps the icon and destroys it.+#[must_use]+pub fn icon_image(icon: HICON) -> Option<IconImage> {let mut info = ICONINFO::default();- // SAFETY: `icon` is valid; GetIconInfo creates two bitmaps, owned below.- unsafe { GetIconInfo(icon.0, &mut info) }.ok()?;+ // SAFETY: The caller passes a valid icon; GetIconInfo creates two+ // bitmaps, owned below.+ unsafe { GetIconInfo(icon, &mut info) }.ok()?;let (color, mask) = (OwnedBitmap(info.hbmColor), OwnedBitmap(info.hbmMask));// A monochrome icon has no color bitmap: left to the shell.if color.0.is_invalid() {diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rsindex 2cd3098..03dc26a 100644--- a/crates/muelle-shell/src/lib.rs+++ b/crates/muelle-shell/src/lib.rs@@ -2,6 +2,7 @@ pub mod appbar;pub mod autostart;pub mod dock_link;pub mod files;+pub mod folder;pub mod icon_cache;pub mod icons;pub mod launcher;