From 7f42e869f58292d10c87f0abb49b0d4796071695 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 13:55:17 -0500 Subject: [PATCH 01/44] desktop: cap the playing-row bars to 30 fps instead of repainting every display frame Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/main.rs | 51 ++++++++++++++++++++++++++++++++ crates/echo-desktop/src/views.rs | 14 +++------ 2 files changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 1772918..653b26b 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -233,6 +233,7 @@ pub(crate) struct EchoApp { /// from a list edge. The ticking task ends itself when this clears or the drag ends. pub(crate) drag_scroll: Option<(DragList, f32)>, pub(crate) drag_scroll_ticking: bool, + playing_bars: Cell, pub(crate) playlist_modal_scroll: ScrollHandle, pub(crate) device_modal_scroll: ScrollHandle, pub(crate) theme_modal_scroll: ScrollHandle, @@ -334,6 +335,25 @@ fn is_paste_chord(modifiers: &gpui::Modifiers) -> bool { modifiers.secondary() || modifiers.control } +/// The animation of the playing row's bars. A render that draws them moves this to `Drawn` +/// and each tick of the animation's task moves it one step back, so the task ends itself one +/// tick after the row leaves the screen. +#[derive(Clone, Copy, PartialEq, Eq)] +enum PlayingBars { + /// Not on screen; no task is running. + Hidden, + /// Drawn since the last tick. + Drawn, + /// Not drawn since the last tick; the next one ends the task. + Stale, +} + +/// One bounce of the playing row's bars. +const PLAYING_BARS_LOOP: Duration = Duration::from_millis(900); +/// How often the bars repaint. Every frame re-renders the whole window, so this stays well +/// under the display's refresh rate. +const PLAYING_BARS_FRAME: Duration = Duration::from_millis(33); + /// The lists a drag can scroll by hovering near their edges. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum DragList { @@ -594,6 +614,7 @@ impl EchoApp { right_panel, drag_scroll: None, drag_scroll_ticking: false, + playing_bars: Cell::new(PlayingBars::Hidden), playlist_modal_scroll: ScrollHandle::new(), device_modal_scroll: ScrollHandle::new(), theme_modal_scroll: ScrollHandle::new(), @@ -1702,6 +1723,36 @@ impl EchoApp { echo_core::intent::has_multi_selection(&self.state) } + /// The phase, in `0..1`, to draw the playing row's bars at. Calling this from a render + /// keeps the window repainting every [`PLAYING_BARS_FRAME`] for as long as renders keep + /// calling it. + pub(crate) fn animate_playing_bars(&self, cx: &mut Context) -> f32 { + if self.playing_bars.replace(PlayingBars::Drawn) == PlayingBars::Hidden { + cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(PLAYING_BARS_FRAME).await; + let keep_going = this.update(cx, |app, cx| match app.playing_bars.get() { + PlayingBars::Drawn => { + app.playing_bars.set(PlayingBars::Stale); + cx.notify(); + true + } + PlayingBars::Stale | PlayingBars::Hidden => { + app.playing_bars.set(PlayingBars::Hidden); + false + } + }); + if !matches!(keep_going, Ok(true)) { + break; + } + } + }) + .detach(); + } + let elapsed = self.started_at.elapsed().as_secs_f32(); + (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() + } + /// Called on every drag move over a list: within [`DRAG_EDGE`] of its top or bottom edge /// the list scrolls toward that edge, faster the closer the pointer gets, on a frame tick /// that runs only while a drag is alive and the pointer stays near an edge. diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 426e52a..8ae3647 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -2208,18 +2208,12 @@ fn track_index_cell( ) -> impl IntoElement { let number = row_number(&app.state, ix, selected); let animate = playing && app.state.playback.is_playing && !cx.reduce_motion(); - let bars = if animate { - div() - .size(px(18.0)) - .with_animation( - ("playing-bars", ix), - Animation::new(std::time::Duration::from_millis(900)).repeat(), - move |el, phase| el.child(playing_bars(phase, accent)), - ) - .into_any_element() + let phase = if animate { + app.animate_playing_bars(cx) } else { - playing_bars(0.25, accent).into_any_element() + 0.25 }; + let bars = playing_bars(phase, accent).into_any_element(); div() .id(("track-index", ix)) .relative() From 434adc09edcc708ddad4f3b38a19e20ddc56c303 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:11:42 -0500 Subject: [PATCH 02/44] desktop: render the sidebar, main area, right panel and playback bar as cached views and redraw only the bar on playback ticks Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/main.rs | 55 +++++++++--- crates/echo-desktop/src/regions.rs | 132 +++++++++++++++++++++++++++++ 2 files changed, 174 insertions(+), 13 deletions(-) create mode 100644 crates/echo-desktop/src/regions.rs diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 653b26b..118ec2d 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -15,6 +15,7 @@ mod backdrop; mod dock_icon; mod images; mod playlist_ui; +mod regions; mod single_instance; mod theme; mod tray; @@ -234,6 +235,8 @@ pub(crate) struct EchoApp { pub(crate) drag_scroll: Option<(DragList, f32)>, pub(crate) drag_scroll_ticking: bool, playing_bars: Cell, + regions: regions::Regions, + _regions_follow_app: gpui::Subscription, pub(crate) playlist_modal_scroll: ScrollHandle, pub(crate) device_modal_scroll: ScrollHandle, pub(crate) theme_modal_scroll: ScrollHandle, @@ -350,7 +353,7 @@ enum PlayingBars { /// One bounce of the playing row's bars. const PLAYING_BARS_LOOP: Duration = Duration::from_millis(900); -/// How often the bars repaint. Every frame re-renders the whole window, so this stays well +/// How often the bars repaint. Every frame re-renders the track list, so this stays well /// under the display's refresh rate. const PLAYING_BARS_FRAME: Duration = Duration::from_millis(33); @@ -507,11 +510,19 @@ impl EchoApp { &event, echo_core::events::WorkerEvent::AuthenticationComplete ); + // Arrives ten times a second during playback and only moves the position. + let position_only = matches!(&event, echo_core::events::WorkerEvent::Tick); apply_worker_event(event, &mut app.state, &app.app_tx, &app.worker_tx); if signed_in { app.open_home(cx); } - cx.notify(); + // A tick that reaches the end of the track stops playback, which every + // pane shows. + if position_only && app.state.playback.is_playing { + app.notify_playback_position(cx); + } else { + cx.notify(); + } }); if applied.is_err() { break; // entity dropped — app is shutting down @@ -529,8 +540,10 @@ impl EchoApp { let interval = this.update(cx, |app: &mut EchoApp, cx| { app.maybe_auto_update(cx); let animating = app.immersive && !cx.reduce_motion(); - if app.state.playback.is_playing || animating { + if animating { cx.notify(); + } else if app.state.playback.is_playing { + app.notify_playback_position(cx); } // Status messages carry an expiry; the periodic tick retires them. if app @@ -615,6 +628,8 @@ impl EchoApp { drag_scroll: None, drag_scroll_ticking: false, playing_bars: Cell::new(PlayingBars::Hidden), + regions: regions::Regions::new(cx), + _regions_follow_app: cx.observe_self(|app, cx| app.regions.notify_all(cx)), playlist_modal_scroll: ScrollHandle::new(), device_modal_scroll: ScrollHandle::new(), theme_modal_scroll: ScrollHandle::new(), @@ -1723,8 +1738,21 @@ impl EchoApp { echo_core::intent::has_multi_selection(&self.state) } + /// Redraws only what shows the playback position or the volume: the playback bar, the + /// lyrics panel, and the immersive view, which is drawn by the app itself. + fn notify_playback_position(&mut self, cx: &mut Context) { + if self.immersive { + cx.notify(); + return; + } + self.regions.notify(regions::Region::PlaybackBar, cx); + if self.right_panel == Some(RightPanel::Lyrics) { + self.regions.notify(regions::Region::RightPanel, cx); + } + } + /// The phase, in `0..1`, to draw the playing row's bars at. Calling this from a render - /// keeps the window repainting every [`PLAYING_BARS_FRAME`] for as long as renders keep + /// keeps the track list repainting every [`PLAYING_BARS_FRAME`] for as long as renders keep /// calling it. pub(crate) fn animate_playing_bars(&self, cx: &mut Context) -> f32 { if self.playing_bars.replace(PlayingBars::Drawn) == PlayingBars::Hidden { @@ -1734,7 +1762,7 @@ impl EchoApp { let keep_going = this.update(cx, |app, cx| match app.playing_bars.get() { PlayingBars::Drawn => { app.playing_bars.set(PlayingBars::Stale); - cx.notify(); + app.regions.notify(regions::Region::Main, cx); true } PlayingBars::Stale | PlayingBars::Hidden => { @@ -2840,7 +2868,7 @@ impl EchoApp { self.state.playback.volume = (fraction * 100.0).round() as u32; } } - cx.notify(); + self.notify_playback_position(cx); } fn finish_scrub(&mut self, x: Pixels, cx: &mut Context) { @@ -3027,7 +3055,7 @@ impl EchoApp { let _ = self.app_tx.send(event); } - fn render_playback_bar(&mut self, cx: &mut Context) -> impl IntoElement { + pub(crate) fn render_playback_bar(&mut self, cx: &mut Context) -> impl IntoElement { let theme = &self.state.ui.active_theme; let palette = DesktopPalette::resolve(theme); let fg = theme.text.gpui(WINDOW_FG()); @@ -3158,7 +3186,7 @@ impl EchoApp { .flex_col() .justify_center() .gap_1() - .h(px(108.0)) + .h(px(regions::PLAYBACK_BAR_HEIGHT)) .px_4() .border_t_1() .border_color(palette.border) @@ -4190,11 +4218,12 @@ impl Render for EchoApp { .flex_row() .overflow_hidden() .when(!self.sidebar_collapsed, |el| { - el.child(views::sidebar(self, cx)) + el.child(self.regions.sidebar(self.sidebar_width)) }) - .child(views::main_area(self, window, cx)) - .when_some(self.right_panel, |el, panel| { - el.child(views::right_panel(self, panel, window, cx)) + .child(self.regions.main()) + .when(self.right_panel.is_some(), |el| { + let width = self.effective_right_panel_width(window); + el.child(self.regions.right_panel(width)) }), ) .when_some(status_line, |el, line| el.child(line)) @@ -4203,7 +4232,7 @@ impl Render for EchoApp { .when_some(command_bar, |el, bar| el.child(bar)) .when_some(audio_banner, |el, banner| el.child(banner)) .when_some(update_banner, |el, banner| el.child(banner)) - .when(!self.immersive, |el| el.child(self.render_playback_bar(cx))) + .when(!self.immersive, |el| el.child(self.regions.playback_bar())) .when_some(theme_modal, |el, modal| el.child(modal)) .when_some(device_modal, |el, modal| el.child(modal)) .when_some(playlist_add_modal, |el, modal| el.child(modal)) diff --git a/crates/echo-desktop/src/regions.rs b/crates/echo-desktop/src/regions.rs new file mode 100644 index 0000000..222bccf --- /dev/null +++ b/crates/echo-desktop/src/regions.rs @@ -0,0 +1,132 @@ +//! The window's large panes as their own views, so gpui can reuse a pane's last frame while +//! another one repaints. +//! +//! A cached view is redrawn only when it is notified itself: gpui does not redraw it because +//! an entity it read has changed. Every pane reads [`EchoApp`], so a notify on the app redraws +//! all of them, and [`Regions::notify`] redraws one pane for changes that are known to stay +//! inside it. + +use gpui::{ + AnyElement, App, AppContext, Context, Empty, Entity, IntoElement, ParentElement, Render, + StyleRefinement, Styled, WeakEntity, Window, div, px, +}; + +use crate::{EchoApp, views}; + +/// Height of the playback bar. Cached views are laid out from a style rather than measured, so +/// the bar and the slot holding it both size themselves from this. +pub(crate) const PLAYBACK_BAR_HEIGHT: f32 = 108.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Region { + Sidebar, + Main, + RightPanel, + PlaybackBar, +} + +pub(crate) struct RegionView { + app: WeakEntity, + region: Region, +} + +impl Render for RegionView { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let region = self.region; + let content = self + .app + .update(cx, |app, cx| -> AnyElement { + match region { + Region::Sidebar => views::sidebar(app, cx).into_any_element(), + Region::Main => views::main_area(app, window, cx).into_any_element(), + Region::RightPanel => match app.right_panel { + Some(panel) => views::right_panel(app, panel, window, cx), + None => Empty.into_any_element(), + }, + Region::PlaybackBar => app.render_playback_bar(cx).into_any_element(), + } + }) + .unwrap_or_else(|_| Empty.into_any_element()); + // A cached view's content is laid out as a root, which shrinks to fit; the column makes + // it fill the slot the parent gave it instead. + div().size_full().flex().flex_col().child(content) + } +} + +pub(crate) struct Regions { + sidebar: Entity, + main: Entity, + right_panel: Entity, + playback_bar: Entity, +} + +impl Regions { + pub(crate) fn new(cx: &mut Context) -> Self { + let app = cx.weak_entity(); + let mut view = |region| { + let app = app.clone(); + cx.new(|_| RegionView { app, region }) + }; + Self { + sidebar: view(Region::Sidebar), + main: view(Region::Main), + right_panel: view(Region::RightPanel), + playback_bar: view(Region::PlaybackBar), + } + } + + fn view(&self, region: Region) -> &Entity { + match region { + Region::Sidebar => &self.sidebar, + Region::Main => &self.main, + Region::RightPanel => &self.right_panel, + Region::PlaybackBar => &self.playback_bar, + } + } + + /// Redraws one pane and leaves the others' cached frames alone. + pub(crate) fn notify(&self, region: Region, cx: &mut Context) { + App::notify(cx, self.view(region).entity_id()); + } + + pub(crate) fn notify_all(&self, cx: &mut Context) { + for region in [ + Region::Sidebar, + Region::Main, + Region::RightPanel, + Region::PlaybackBar, + ] { + self.notify(region, cx); + } + } + + pub(crate) fn sidebar(&self, width: f32) -> impl IntoElement + use<> { + self.sidebar + .clone() + .cached(StyleRefinement::default().flex_none().w(px(width)).h_full()) + } + + pub(crate) fn main(&self) -> impl IntoElement + use<> { + self.main.clone().cached( + StyleRefinement::default() + .flex_grow(1.0) + .h_full() + .overflow_hidden(), + ) + } + + pub(crate) fn right_panel(&self, width: f32) -> impl IntoElement + use<> { + self.right_panel + .clone() + .cached(StyleRefinement::default().flex_none().w(px(width)).h_full()) + } + + pub(crate) fn playback_bar(&self) -> impl IntoElement + use<> { + self.playback_bar.clone().cached( + StyleRefinement::default() + .flex_none() + .w_full() + .h(px(PLAYBACK_BAR_HEIGHT)), + ) + } +} From 6f44387707ecd00cc3c9c1a801e647b560de4947 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:22:30 -0500 Subject: [PATCH 03/44] desktop: move the titlebar and window frame into views/chrome.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 432 +---------------------- crates/echo-desktop/src/views/chrome.rs | 439 ++++++++++++++++++++++++ 2 files changed, 441 insertions(+), 430 deletions(-) create mode 100644 crates/echo-desktop/src/views/chrome.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 8ae3647..9f9ca07 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -13,10 +13,12 @@ use echo_core::app::{ActiveView, AppMode, LibraryTab, QueueRow, QueueTab, Search use echo_core::config::RightPanel; use echo_core::models::{ActionMenuAction, ActionMenuContext, LibraryNode}; use echo_core::thumbnails::{ThumbState, ThumbTier, tier_for_edge}; +mod chrome; mod menu_placement; pub(crate) mod panel_layout; mod playlist_edit; mod search; +pub(crate) use chrome::*; use gpui::{ Animation, AnimationExt, AnyElement, App, Context, Div, Entity, Hsla, MouseButton, MouseDownEvent, SharedString, Stateful, Window, canvas, div, ease_out_quint, prelude::*, px, @@ -34,14 +36,6 @@ pub(crate) const SIDEBAR_WIDTH: f32 = 240.0; const SUBMENU_WIDTH: f32 = 190.0; const SUBMENU_MAX_H: f32 = 270.0; const THUMB_EDGE: f32 = 26.0; -// Native caption metrics: Windows titlebars are a fixed 32px, macOS gets a touch more. -const TITLEBAR_HEIGHT: f32 = if cfg!(target_os = "windows") { - 32.0 -} else { - 34.0 -}; -// Zed's measured inset for the macOS traffic lights (71px, +1px window border). -const TRAFFIC_LIGHT_PADDING: f32 = 71.0; /// The shape of a selectable list row: the fixed height `uniform_list` measures and the /// shorter pill drawn inside it. Hover strength comes from the palette slot the caller @@ -349,428 +343,6 @@ fn is_fixed_library_row(id: &str) -> bool { id == "LIKED_SONGS" || id == "local-library" } -/// The custom titlebar: themed like the rest of the window, draggable, with caption buttons -/// on Windows and Linux. macOS keeps its native traffic lights (the bar just insets past them) -/// and only needs the drag/double-click plumbing done in Rust; Windows gets drag, double-click -/// and snap layouts for free from the `HTCAPTION`/`HTMAXBUTTON` hit-tests. -/// -/// Linux needs every one of those by hand. gpui's Linux backends leave -/// `on_hit_test_window_control` unimplemented, so `window_control_area` does nothing there and -/// the caption buttons have to call `minimize_window`/`zoom_window`/`remove_window` themselves. -/// Dragging uses the same mouse-down latch as macOS. This used to be skipped on Linux on the -/// assumption the window manager would draw its own bar, but GNOME/Mutter does not implement -/// xdg-decoration and forces client-side decorations, which left the window with no titlebar -/// and no way to move or resize it. See [`window_frame`] for the resize edges. -/// -/// `immersive` swaps the bar's own colors for the backdrop's: no fill, so the backdrop shows -/// through, and its text and hover wash. -pub fn titlebar( - app: &mut EchoApp, - immersive: Option<&ImmersiveColors>, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let (fg, surface, hover) = match immersive { - Some(colors) => (colors.text, gpui::transparent_black(), colors.wash), - None => ( - theme.text.gpui(WINDOW_FG()), - theme.surface.gpui(crate::theme::PANEL_BG()), - DesktopPalette::resolve(theme).menu_hover, - ), - }; - let fullscreen = window.is_fullscreen(); - let maximized = window.is_maximized(); - let corners = client_corners(window); - // The close button's hover fill reaches the window's top-right corner, so it rounds - // itself too — DWM's radius on Windows 11, ours on a client-decorated Linux window. - let close_radius = match corners { - Some(tiling) => (!tiling.top && !tiling.right).then(|| px(CLIENT_CONTENT_RADIUS)), - None => (cfg!(target_os = "windows") && !maximized).then(|| px(WIN_CORNER_RADIUS)), - }; - - div() - .id("titlebar") - .window_control_area(gpui::WindowControlArea::Drag) - .flex_none() - .w_full() - .h(px(TITLEBAR_HEIGHT)) - // The bar's own surface fill reaches the window's top corners, so it has to round them - // itself — see `round_client_corners`. - .map(|el| round_client_corners(el, corners, ClientCorners::Top)) - .flex() - .flex_row() - .items_center() - .justify_between() - .bg(surface) - .map(|el| { - if fullscreen { - el.pl_3() - } else if cfg!(target_os = "macos") { - el.pl(px(TRAFFIC_LIGHT_PADDING)) - } else { - el.pl_3() - } - }) - // AppKit neither drags nor double-click-zooms a transparent titlebar for us - // (`app_owns_titlebar_drag`), and Linux has no titlebar hit-testing at all, so both do - // it by hand — the Zed latch pattern: arm on mouse-down, and the first real move starts - // the native window drag. - .when(cfg!(any(target_os = "macos", target_os = "linux")), |el| { - el.on_mouse_down( - MouseButton::Left, - cx.listener(|this, _, _window, _cx| this.titlebar_should_move = true), - ) - .on_mouse_up( - MouseButton::Left, - cx.listener(|this, _, _window, _cx| this.titlebar_should_move = false), - ) - .on_mouse_move(cx.listener(|this, _, window, _cx| { - if this.titlebar_should_move { - this.titlebar_should_move = false; - window.start_window_move(); - } - })) - .on_click(|event, window, _cx| { - if event.click_count() == 2 { - window.titlebar_double_click(); - } - }) - }) - // The window manager's own menu (Move, Resize, Always on Top, …), which a server-side - // titlebar would have offered on right-click. - .when(cfg!(target_os = "linux"), |el| { - el.on_mouse_down(MouseButton::Right, |event, window, _cx| { - window.show_window_menu(event.position); - }) - }) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap_2() - .child( - svg() - .path("icons/music-note.svg") - .size(px(14.0)) - .text_color(fg), - ) - .child(div().text_xs().text_color(fg).child("echo")), - ) - .when(CAPTION_BUTTONS && !fullscreen, |el| { - el.child( - div() - .flex() - .flex_row() - .h_full() - .child(caption_button( - "caption-min", - "icons/win-minimize.svg", - gpui::WindowControlArea::Min, - fg, - hover, - None, - )) - .child(caption_button( - "caption-max", - if maximized { - "icons/win-restore.svg" - } else { - "icons/win-maximize.svg" - }, - gpui::WindowControlArea::Max, - fg, - hover, - None, - )) - .child(caption_button( - "caption-close", - "icons/win-close.svg", - gpui::WindowControlArea::Close, - fg, - hover, - close_radius, - )), - ) - }) -} - -/// Windows and Linux draw their own caption buttons; macOS uses the native traffic lights. -const CAPTION_BUTTONS: bool = cfg!(any(target_os = "windows", target_os = "linux")); - -/// A caption button. On Windows there is no click handler: the `window_control_area` tag routes -/// the click through `WM_NCHITTEST`, and gpui + `DefWindowProc` do the minimize/maximize/close. -/// Linux ignores that tag (gpui's backends leave `on_hit_test_window_control` unimplemented), -/// so there the button drives the window directly. `occlude` is load-bearing on both — without -/// it the surrounding Drag hitbox wins the hit-test and the button is dead. -fn caption_button( - id: &'static str, - icon: &'static str, - area: gpui::WindowControlArea, - fg: gpui::Hsla, - hover: gpui::Hsla, - top_right_radius: Option, -) -> impl IntoElement { - let close = matches!(area, gpui::WindowControlArea::Close); - // The close button hovers Windows-red with a white glyph; the rest get a faint wash. - let hover_bg: gpui::Hsla = if close { - crate::theme::CLOSE_RED() - } else { - hover - }; - div() - .id(id) - .group(id) - .occlude() - .window_control_area(area) - .when(cfg!(target_os = "linux"), |el| { - el.on_click(move |_event, window, cx| match area { - gpui::WindowControlArea::Min => window.minimize_window(), - gpui::WindowControlArea::Max => window.zoom_window(), - // Not `remove_window` directly: that skips `on_window_should_close`, so the - // action persists the rectangle and decides tray-or-quit first. - gpui::WindowControlArea::Close => { - window.dispatch_action(Box::new(crate::CloseWindow), cx) - } - gpui::WindowControlArea::Drag => {} - }) - }) - .w(px(46.0)) - .h_full() - .flex() - .items_center() - .justify_center() - .when_some(top_right_radius, |el, r| el.rounded_tr(r)) - .hover(|style| style.bg(hover_bg)) - .active(|style| style.bg(hover_bg)) - .child( - svg() - .path(icon) - .size(px(10.0)) - .text_color(fg) - .when(close, |el| { - el.group_hover(id, |style| style.text_color(gpui::white())) - }), - ) -} - -/// Corner radius and drop-shadow depth for a client-decorated window, matching what GNOME and -/// Zed use so echo sits alongside them without looking off. -const CLIENT_CORNER_RADIUS: f32 = 10.0; -const CLIENT_BORDER_WIDTH: f32 = 1.0; -// Content sits inside the frame border: reduce its radius by the same inset so both -// arcs share a center instead of leaving a sliver between their antialiased edges. -const CLIENT_CONTENT_RADIUS: f32 = CLIENT_CORNER_RADIUS - CLIENT_BORDER_WIDTH; -/// The radius DWM clips an unmaximized window to on Windows 11. -const WIN_CORNER_RADIUS: f32 = 8.0; -const CLIENT_SHADOW: f32 = 10.0; -/// Grab bands, sized to the transparent shadow margin so they sit beside the visible window -/// rather than over its content. The corners reach a little further in, as window managers' do. -const RESIZE_BAND: f32 = CLIENT_SHADOW; -const RESIZE_CORNER: f32 = CLIENT_SHADOW * 2.0; - -/// Which corners of an element sit against the window's own, for [`round_client_corners`]. -#[derive(Clone, Copy)] -pub(crate) enum ClientCorners { - All, - Top, -} - -/// The window's tiling state when the app is drawing its own frame, `None` when the compositor -/// draws it and the corners are not ours to round. Resolve this once per render and hand it to -/// [`round_client_corners`] — the alternative is borrowing the window inside a style closure. -pub(crate) fn client_corners(window: &Window) -> Option { - match window.window_decorations() { - gpui::Decorations::Client { tiling } => Some(tiling), - gpui::Decorations::Server => None, - } -} - -/// Width of the visible app, excluding client-drawn shadow/resize margins. -pub(crate) fn client_content_width(window: &Window) -> f32 { - let inset = client_corners(window).map_or(0.0, |tiling| { - f32::from(!tiling.left) * CLIENT_SHADOW + f32::from(!tiling.right) * CLIENT_SHADOW - }); - (f32::from(window.viewport_size().width) - inset).max(0.0) -} - -/// Rounds the corners an element shares with the window's. -/// -/// gpui's content mask is a plain rectangle, so rounding a container does **not** clip what is -/// inside it: any child that paints an opaque background into a corner squares it off again. -/// That makes this a per-element job rather than one wrapper — here the root's background and -/// the titlebar's, which are the only two surfaces reaching a corner. An edge that is tiled is -/// flush against a screen or a neighbour, and stays square, as every other app's does. -pub(crate) fn round_client_corners( - el: E, - corners: Option, - which: ClientCorners, -) -> E { - let radii = client_corner_radii(corners, which); - el.rounded_tl(radii.top_left) - .rounded_tr(radii.top_right) - .rounded_bl(radii.bottom_left) - .rounded_br(radii.bottom_right) -} - -/// The radii [`round_client_corners`] applies, for painting that bypasses styles. -pub(crate) fn client_corner_radii( - corners: Option, - which: ClientCorners, -) -> gpui::Corners { - corner_radii(corners, which, CLIENT_CONTENT_RADIUS) -} - -fn corner_radii( - corners: Option, - which: ClientCorners, - radius: f32, -) -> gpui::Corners { - let Some(tiling) = corners else { - return gpui::Corners::default(); - }; - let all = matches!(which, ClientCorners::All); - let radius = |rounded: bool| { - if rounded { px(radius) } else { px(0.0) } - }; - gpui::Corners { - top_left: radius(!tiling.top && !tiling.left), - top_right: radius(!tiling.top && !tiling.right), - bottom_left: radius(all && !tiling.bottom && !tiling.left), - bottom_right: radius(all && !tiling.bottom && !tiling.right), - } -} - -/// Wraps the whole app in the frame a window manager would normally provide. -/// -/// A compositor that does not implement xdg-decoration — GNOME/Mutter, notably, which is the -/// Ubuntu default — hands the window back as [`Decorations::Client`] and draws nothing itself: -/// no titlebar, no border, no shadow, and crucially no resize handles, leaving the window stuck -/// at its opening size with square edges. [`titlebar`] covers moving and the caption buttons; -/// this covers the frame, as a transparent margin around the app carrying the drop shadow, with -/// the resize strips laid into that margin so they grab beside the window rather than over its -/// content. Requesting client decorations already makes the surface transparent, so the rounded -/// corners show what is behind the window rather than a black notch. -/// -/// A pass-through everywhere else: Windows, macOS, and any Linux WM that does draw its own -/// decorations all report [`Decorations::Server`], and then the real frame already works. -pub fn window_frame( - root: impl IntoElement, - window: &mut Window, - palette: DesktopPalette, -) -> AnyElement { - let Some(tiling) = client_corners(window) else { - return root.into_any_element(); - }; - let shadow = px(CLIENT_SHADOW); - // Tells the compositor the visible window is inset from the surface by the shadow margin, so - // snapping and edge detection use the frame the user sees rather than the transparent one. - window.set_client_inset(shadow); - let resizable = window.is_resizable(); - - // Edges are laid down first and corners on top, so the corners win where they overlap. - let edges: [(&'static str, gpui::ResizeEdge, bool); 8] = [ - ("resize-top", gpui::ResizeEdge::Top, tiling.top), - ("resize-bottom", gpui::ResizeEdge::Bottom, tiling.bottom), - ("resize-left", gpui::ResizeEdge::Left, tiling.left), - ("resize-right", gpui::ResizeEdge::Right, tiling.right), - ( - "resize-top-left", - gpui::ResizeEdge::TopLeft, - tiling.top || tiling.left, - ), - ( - "resize-top-right", - gpui::ResizeEdge::TopRight, - tiling.top || tiling.right, - ), - ( - "resize-bottom-left", - gpui::ResizeEdge::BottomLeft, - tiling.bottom || tiling.left, - ), - ( - "resize-bottom-right", - gpui::ResizeEdge::BottomRight, - tiling.bottom || tiling.right, - ), - ]; - - div() - .relative() - .size_full() - // The transparent margin: room for the shadow to fall into, and where the grab strips - // live. A tiled edge has neither, so the window still meets the screen edge exactly. - .when(!tiling.top, |el| el.pt(shadow)) - .when(!tiling.bottom, |el| el.pb(shadow)) - .when(!tiling.left, |el| el.pl(shadow)) - .when(!tiling.right, |el| el.pr(shadow)) - .child( - div() - .size_full() - .map(|el| { - let radii = - corner_radii(Some(tiling), ClientCorners::All, CLIENT_CORNER_RADIUS); - el.rounded_tl(radii.top_left) - .rounded_tr(radii.top_right) - .rounded_bl(radii.bottom_left) - .rounded_br(radii.bottom_right) - }) - // A hairline outline stands in for the frame the compositor is not drawing, so - // the window still reads as one against a same-coloured background behind it. - .border(px(CLIENT_BORDER_WIDTH)) - .border_color(palette.border) - .when(!tiling.is_tiled(), |el| { - el.shadow(vec![ - gpui::BoxShadow::new(px(0.0), px(2.0), gpui::hsla(0.0, 0.0, 0.0, 0.36)) - .blur_radius(shadow / 2.0), - ]) - }) - .child(root), - ) - .children( - edges - .into_iter() - .filter(|&(_id, _edge, tiled)| resizable && !tiled) - .map(|(id, edge, _tiled)| resize_handle(id, edge)), - ) - .into_any_element() -} - -/// One transparent grab strip, positioned against the outer edge of the shadow margin. `occlude` -/// keeps it above the app's own hitboxes, which matters at the corners, where the square reaches -/// past the margin into the window. -fn resize_handle(id: &'static str, edge: gpui::ResizeEdge) -> impl IntoElement { - use gpui::ResizeEdge as E; - let band = px(RESIZE_BAND); - let corner = px(RESIZE_CORNER); - - div() - .id(id) - .occlude() - .absolute() - .cursor(match edge { - E::Top | E::Bottom => gpui::CursorStyle::ResizeUpDown, - E::Left | E::Right => gpui::CursorStyle::ResizeLeftRight, - E::TopLeft | E::BottomRight => gpui::CursorStyle::ResizeUpLeftDownRight, - E::TopRight | E::BottomLeft => gpui::CursorStyle::ResizeUpRightDownLeft, - }) - .map(|el| match edge { - E::Top => el.top_0().left_0().w_full().h(band), - E::Bottom => el.bottom_0().left_0().w_full().h(band), - E::Left => el.top_0().left_0().h_full().w(band), - E::Right => el.top_0().right_0().h_full().w(band), - E::TopLeft => el.top_0().left_0().w(corner).h(corner), - E::TopRight => el.top_0().right_0().w(corner).h(corner), - E::BottomLeft => el.bottom_0().left_0().w(corner).h(corner), - E::BottomRight => el.bottom_0().right_0().w(corner).h(corner), - }) - .on_mouse_down(MouseButton::Left, move |_event, window, _cx| { - window.start_window_resize(edge); - }) -} - fn nav_button_cluster(app: &EchoApp, cx: &mut Context) -> impl IntoElement { let theme = &app.state.ui.active_theme; let palette = DesktopPalette::resolve(theme); diff --git a/crates/echo-desktop/src/views/chrome.rs b/crates/echo-desktop/src/views/chrome.rs new file mode 100644 index 0000000..b7f3c0e --- /dev/null +++ b/crates/echo-desktop/src/views/chrome.rs @@ -0,0 +1,439 @@ +use super::*; + +// Native caption metrics: Windows titlebars are a fixed 32px, macOS gets a touch more. +pub(super) const TITLEBAR_HEIGHT: f32 = if cfg!(target_os = "windows") { + 32.0 +} else { + 34.0 +}; + +// Zed's measured inset for the macOS traffic lights (71px, +1px window border). +const TRAFFIC_LIGHT_PADDING: f32 = 71.0; + +/// The custom titlebar: themed like the rest of the window, draggable, with caption buttons +/// on Windows and Linux. macOS keeps its native traffic lights (the bar just insets past them) +/// and only needs the drag/double-click plumbing done in Rust; Windows gets drag, double-click +/// and snap layouts for free from the `HTCAPTION`/`HTMAXBUTTON` hit-tests. +/// +/// Linux needs every one of those by hand. gpui's Linux backends leave +/// `on_hit_test_window_control` unimplemented, so `window_control_area` does nothing there and +/// the caption buttons have to call `minimize_window`/`zoom_window`/`remove_window` themselves. +/// Dragging uses the same mouse-down latch as macOS. This used to be skipped on Linux on the +/// assumption the window manager would draw its own bar, but GNOME/Mutter does not implement +/// xdg-decoration and forces client-side decorations, which left the window with no titlebar +/// and no way to move or resize it. See [`window_frame`] for the resize edges. +/// +/// `immersive` swaps the bar's own colors for the backdrop's: no fill, so the backdrop shows +/// through, and its text and hover wash. +pub fn titlebar( + app: &mut EchoApp, + immersive: Option<&ImmersiveColors>, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let (fg, surface, hover) = match immersive { + Some(colors) => (colors.text, gpui::transparent_black(), colors.wash), + None => ( + theme.text.gpui(WINDOW_FG()), + theme.surface.gpui(crate::theme::PANEL_BG()), + DesktopPalette::resolve(theme).menu_hover, + ), + }; + let fullscreen = window.is_fullscreen(); + let maximized = window.is_maximized(); + let corners = client_corners(window); + // The close button's hover fill reaches the window's top-right corner, so it rounds + // itself too — DWM's radius on Windows 11, ours on a client-decorated Linux window. + let close_radius = match corners { + Some(tiling) => (!tiling.top && !tiling.right).then(|| px(CLIENT_CONTENT_RADIUS)), + None => (cfg!(target_os = "windows") && !maximized).then(|| px(WIN_CORNER_RADIUS)), + }; + + div() + .id("titlebar") + .window_control_area(gpui::WindowControlArea::Drag) + .flex_none() + .w_full() + .h(px(TITLEBAR_HEIGHT)) + // The bar's own surface fill reaches the window's top corners, so it has to round them + // itself — see `round_client_corners`. + .map(|el| round_client_corners(el, corners, ClientCorners::Top)) + .flex() + .flex_row() + .items_center() + .justify_between() + .bg(surface) + .map(|el| { + if fullscreen { + el.pl_3() + } else if cfg!(target_os = "macos") { + el.pl(px(TRAFFIC_LIGHT_PADDING)) + } else { + el.pl_3() + } + }) + // AppKit neither drags nor double-click-zooms a transparent titlebar for us + // (`app_owns_titlebar_drag`), and Linux has no titlebar hit-testing at all, so both do + // it by hand — the Zed latch pattern: arm on mouse-down, and the first real move starts + // the native window drag. + .when(cfg!(any(target_os = "macos", target_os = "linux")), |el| { + el.on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, _window, _cx| this.titlebar_should_move = true), + ) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _, _window, _cx| this.titlebar_should_move = false), + ) + .on_mouse_move(cx.listener(|this, _, window, _cx| { + if this.titlebar_should_move { + this.titlebar_should_move = false; + window.start_window_move(); + } + })) + .on_click(|event, window, _cx| { + if event.click_count() == 2 { + window.titlebar_double_click(); + } + }) + }) + // The window manager's own menu (Move, Resize, Always on Top, …), which a server-side + // titlebar would have offered on right-click. + .when(cfg!(target_os = "linux"), |el| { + el.on_mouse_down(MouseButton::Right, |event, window, _cx| { + window.show_window_menu(event.position); + }) + }) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_2() + .child( + svg() + .path("icons/music-note.svg") + .size(px(14.0)) + .text_color(fg), + ) + .child(div().text_xs().text_color(fg).child("echo")), + ) + .when(CAPTION_BUTTONS && !fullscreen, |el| { + el.child( + div() + .flex() + .flex_row() + .h_full() + .child(caption_button( + "caption-min", + "icons/win-minimize.svg", + gpui::WindowControlArea::Min, + fg, + hover, + None, + )) + .child(caption_button( + "caption-max", + if maximized { + "icons/win-restore.svg" + } else { + "icons/win-maximize.svg" + }, + gpui::WindowControlArea::Max, + fg, + hover, + None, + )) + .child(caption_button( + "caption-close", + "icons/win-close.svg", + gpui::WindowControlArea::Close, + fg, + hover, + close_radius, + )), + ) + }) +} + +/// Windows and Linux draw their own caption buttons; macOS uses the native traffic lights. +const CAPTION_BUTTONS: bool = cfg!(any(target_os = "windows", target_os = "linux")); + +/// A caption button. On Windows there is no click handler: the `window_control_area` tag routes +/// the click through `WM_NCHITTEST`, and gpui + `DefWindowProc` do the minimize/maximize/close. +/// Linux ignores that tag (gpui's backends leave `on_hit_test_window_control` unimplemented), +/// so there the button drives the window directly. `occlude` is load-bearing on both — without +/// it the surrounding Drag hitbox wins the hit-test and the button is dead. +fn caption_button( + id: &'static str, + icon: &'static str, + area: gpui::WindowControlArea, + fg: gpui::Hsla, + hover: gpui::Hsla, + top_right_radius: Option, +) -> impl IntoElement { + let close = matches!(area, gpui::WindowControlArea::Close); + // The close button hovers Windows-red with a white glyph; the rest get a faint wash. + let hover_bg: gpui::Hsla = if close { + crate::theme::CLOSE_RED() + } else { + hover + }; + div() + .id(id) + .group(id) + .occlude() + .window_control_area(area) + .when(cfg!(target_os = "linux"), |el| { + el.on_click(move |_event, window, cx| match area { + gpui::WindowControlArea::Min => window.minimize_window(), + gpui::WindowControlArea::Max => window.zoom_window(), + // Not `remove_window` directly: that skips `on_window_should_close`, so the + // action persists the rectangle and decides tray-or-quit first. + gpui::WindowControlArea::Close => { + window.dispatch_action(Box::new(crate::CloseWindow), cx) + } + gpui::WindowControlArea::Drag => {} + }) + }) + .w(px(46.0)) + .h_full() + .flex() + .items_center() + .justify_center() + .when_some(top_right_radius, |el, r| el.rounded_tr(r)) + .hover(|style| style.bg(hover_bg)) + .active(|style| style.bg(hover_bg)) + .child( + svg() + .path(icon) + .size(px(10.0)) + .text_color(fg) + .when(close, |el| { + el.group_hover(id, |style| style.text_color(gpui::white())) + }), + ) +} + +/// Corner radius and drop-shadow depth for a client-decorated window, matching what GNOME and +/// Zed use so echo sits alongside them without looking off. +const CLIENT_CORNER_RADIUS: f32 = 10.0; + +const CLIENT_BORDER_WIDTH: f32 = 1.0; + +// Content sits inside the frame border: reduce its radius by the same inset so both +// arcs share a center instead of leaving a sliver between their antialiased edges. +const CLIENT_CONTENT_RADIUS: f32 = CLIENT_CORNER_RADIUS - CLIENT_BORDER_WIDTH; + +/// The radius DWM clips an unmaximized window to on Windows 11. +const WIN_CORNER_RADIUS: f32 = 8.0; + +pub(super) const CLIENT_SHADOW: f32 = 10.0; + +/// Grab bands, sized to the transparent shadow margin so they sit beside the visible window +/// rather than over its content. The corners reach a little further in, as window managers' do. +const RESIZE_BAND: f32 = CLIENT_SHADOW; + +const RESIZE_CORNER: f32 = CLIENT_SHADOW * 2.0; + +/// Which corners of an element sit against the window's own, for [`round_client_corners`]. +#[derive(Clone, Copy)] +pub(crate) enum ClientCorners { + All, + Top, +} + +/// The window's tiling state when the app is drawing its own frame, `None` when the compositor +/// draws it and the corners are not ours to round. Resolve this once per render and hand it to +/// [`round_client_corners`] — the alternative is borrowing the window inside a style closure. +pub(crate) fn client_corners(window: &Window) -> Option { + match window.window_decorations() { + gpui::Decorations::Client { tiling } => Some(tiling), + gpui::Decorations::Server => None, + } +} + +/// Width of the visible app, excluding client-drawn shadow/resize margins. +pub(crate) fn client_content_width(window: &Window) -> f32 { + let inset = client_corners(window).map_or(0.0, |tiling| { + f32::from(!tiling.left) * CLIENT_SHADOW + f32::from(!tiling.right) * CLIENT_SHADOW + }); + (f32::from(window.viewport_size().width) - inset).max(0.0) +} + +/// Rounds the corners an element shares with the window's. +/// +/// gpui's content mask is a plain rectangle, so rounding a container does **not** clip what is +/// inside it: any child that paints an opaque background into a corner squares it off again. +/// That makes this a per-element job rather than one wrapper — here the root's background and +/// the titlebar's, which are the only two surfaces reaching a corner. An edge that is tiled is +/// flush against a screen or a neighbour, and stays square, as every other app's does. +pub(crate) fn round_client_corners( + el: E, + corners: Option, + which: ClientCorners, +) -> E { + let radii = client_corner_radii(corners, which); + el.rounded_tl(radii.top_left) + .rounded_tr(radii.top_right) + .rounded_bl(radii.bottom_left) + .rounded_br(radii.bottom_right) +} + +/// The radii [`round_client_corners`] applies, for painting that bypasses styles. +pub(crate) fn client_corner_radii( + corners: Option, + which: ClientCorners, +) -> gpui::Corners { + corner_radii(corners, which, CLIENT_CONTENT_RADIUS) +} + +fn corner_radii( + corners: Option, + which: ClientCorners, + radius: f32, +) -> gpui::Corners { + let Some(tiling) = corners else { + return gpui::Corners::default(); + }; + let all = matches!(which, ClientCorners::All); + let radius = |rounded: bool| { + if rounded { px(radius) } else { px(0.0) } + }; + gpui::Corners { + top_left: radius(!tiling.top && !tiling.left), + top_right: radius(!tiling.top && !tiling.right), + bottom_left: radius(all && !tiling.bottom && !tiling.left), + bottom_right: radius(all && !tiling.bottom && !tiling.right), + } +} + +/// Wraps the whole app in the frame a window manager would normally provide. +/// +/// A compositor that does not implement xdg-decoration — GNOME/Mutter, notably, which is the +/// Ubuntu default — hands the window back as [`Decorations::Client`] and draws nothing itself: +/// no titlebar, no border, no shadow, and crucially no resize handles, leaving the window stuck +/// at its opening size with square edges. [`titlebar`] covers moving and the caption buttons; +/// this covers the frame, as a transparent margin around the app carrying the drop shadow, with +/// the resize strips laid into that margin so they grab beside the window rather than over its +/// content. Requesting client decorations already makes the surface transparent, so the rounded +/// corners show what is behind the window rather than a black notch. +/// +/// A pass-through everywhere else: Windows, macOS, and any Linux WM that does draw its own +/// decorations all report [`Decorations::Server`], and then the real frame already works. +pub fn window_frame( + root: impl IntoElement, + window: &mut Window, + palette: DesktopPalette, +) -> AnyElement { + let Some(tiling) = client_corners(window) else { + return root.into_any_element(); + }; + let shadow = px(CLIENT_SHADOW); + // Tells the compositor the visible window is inset from the surface by the shadow margin, so + // snapping and edge detection use the frame the user sees rather than the transparent one. + window.set_client_inset(shadow); + let resizable = window.is_resizable(); + + // Edges are laid down first and corners on top, so the corners win where they overlap. + let edges: [(&'static str, gpui::ResizeEdge, bool); 8] = [ + ("resize-top", gpui::ResizeEdge::Top, tiling.top), + ("resize-bottom", gpui::ResizeEdge::Bottom, tiling.bottom), + ("resize-left", gpui::ResizeEdge::Left, tiling.left), + ("resize-right", gpui::ResizeEdge::Right, tiling.right), + ( + "resize-top-left", + gpui::ResizeEdge::TopLeft, + tiling.top || tiling.left, + ), + ( + "resize-top-right", + gpui::ResizeEdge::TopRight, + tiling.top || tiling.right, + ), + ( + "resize-bottom-left", + gpui::ResizeEdge::BottomLeft, + tiling.bottom || tiling.left, + ), + ( + "resize-bottom-right", + gpui::ResizeEdge::BottomRight, + tiling.bottom || tiling.right, + ), + ]; + + div() + .relative() + .size_full() + // The transparent margin: room for the shadow to fall into, and where the grab strips + // live. A tiled edge has neither, so the window still meets the screen edge exactly. + .when(!tiling.top, |el| el.pt(shadow)) + .when(!tiling.bottom, |el| el.pb(shadow)) + .when(!tiling.left, |el| el.pl(shadow)) + .when(!tiling.right, |el| el.pr(shadow)) + .child( + div() + .size_full() + .map(|el| { + let radii = + corner_radii(Some(tiling), ClientCorners::All, CLIENT_CORNER_RADIUS); + el.rounded_tl(radii.top_left) + .rounded_tr(radii.top_right) + .rounded_bl(radii.bottom_left) + .rounded_br(radii.bottom_right) + }) + // A hairline outline stands in for the frame the compositor is not drawing, so + // the window still reads as one against a same-coloured background behind it. + .border(px(CLIENT_BORDER_WIDTH)) + .border_color(palette.border) + .when(!tiling.is_tiled(), |el| { + el.shadow(vec![ + gpui::BoxShadow::new(px(0.0), px(2.0), gpui::hsla(0.0, 0.0, 0.0, 0.36)) + .blur_radius(shadow / 2.0), + ]) + }) + .child(root), + ) + .children( + edges + .into_iter() + .filter(|&(_id, _edge, tiled)| resizable && !tiled) + .map(|(id, edge, _tiled)| resize_handle(id, edge)), + ) + .into_any_element() +} + +/// One transparent grab strip, positioned against the outer edge of the shadow margin. `occlude` +/// keeps it above the app's own hitboxes, which matters at the corners, where the square reaches +/// past the margin into the window. +fn resize_handle(id: &'static str, edge: gpui::ResizeEdge) -> impl IntoElement { + use gpui::ResizeEdge as E; + let band = px(RESIZE_BAND); + let corner = px(RESIZE_CORNER); + + div() + .id(id) + .occlude() + .absolute() + .cursor(match edge { + E::Top | E::Bottom => gpui::CursorStyle::ResizeUpDown, + E::Left | E::Right => gpui::CursorStyle::ResizeLeftRight, + E::TopLeft | E::BottomRight => gpui::CursorStyle::ResizeUpLeftDownRight, + E::TopRight | E::BottomLeft => gpui::CursorStyle::ResizeUpRightDownLeft, + }) + .map(|el| match edge { + E::Top => el.top_0().left_0().w_full().h(band), + E::Bottom => el.bottom_0().left_0().w_full().h(band), + E::Left => el.top_0().left_0().h_full().w(band), + E::Right => el.top_0().right_0().h_full().w(band), + E::TopLeft => el.top_0().left_0().w(corner).h(corner), + E::TopRight => el.top_0().right_0().w(corner).h(corner), + E::BottomLeft => el.bottom_0().left_0().w(corner).h(corner), + E::BottomRight => el.bottom_0().right_0().w(corner).h(corner), + }) + .on_mouse_down(MouseButton::Left, move |_event, window, _cx| { + window.start_window_resize(edge); + }) +} From 01a2a3f6848e81778ae98ab89a706ecd6cd7fbbe Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:22:43 -0500 Subject: [PATCH 04/44] desktop: move the library sidebar into views/sidebar.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 552 +--------------------- crates/echo-desktop/src/views/sidebar.rs | 554 +++++++++++++++++++++++ 2 files changed, 556 insertions(+), 550 deletions(-) create mode 100644 crates/echo-desktop/src/views/sidebar.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 9f9ca07..441ab00 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -18,6 +18,7 @@ mod menu_placement; pub(crate) mod panel_layout; mod playlist_edit; mod search; +mod sidebar; pub(crate) use chrome::*; use gpui::{ Animation, AnimationExt, AnyElement, App, Context, Div, Entity, Hsla, MouseButton, @@ -26,16 +27,15 @@ use gpui::{ }; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; +pub(crate) use sidebar::*; use crate::backdrop::{Backdrop, ImmersiveColors}; use crate::theme::{DesktopPalette, ToGpui, WINDOW_FG}; use crate::{ControlColors, EchoApp, MenuAction, TrackMenuItem, UpdateState, format_time}; -pub(crate) const SIDEBAR_WIDTH: f32 = 240.0; /// The add-to-playlist flyout's preferred dimensions. const SUBMENU_WIDTH: f32 = 190.0; const SUBMENU_MAX_H: f32 = 270.0; -const THUMB_EDGE: f32 = 26.0; /// The shape of a selectable list row: the fixed height `uniform_list` measures and the /// shorter pill drawn inside it. Hover strength comes from the palette slot the caller @@ -47,11 +47,6 @@ pub(crate) struct PillMetrics { pill_height: f32, } -/// Sidebar rows, which hover a touch stronger than the main area. -const SIDEBAR_PILL: PillMetrics = PillMetrics { - row_height: 34.0, - pill_height: 30.0, -}; /// Main-area lists carrying a thumbnail column. const LIST_PILL: PillMetrics = PillMetrics { row_height: 34.0, @@ -337,12 +332,6 @@ impl gpui::Render for DragPreview { } } -/// True for the sidebar rows drag-and-drop must not move (their position is fixed, mirroring -/// `echo_core::intent`'s own check). -fn is_fixed_library_row(id: &str) -> bool { - id == "LIKED_SONGS" || id == "local-library" -} - fn nav_button_cluster(app: &EchoApp, cx: &mut Context) -> impl IntoElement { let theme = &app.state.ui.active_theme; let palette = DesktopPalette::resolve(theme); @@ -404,543 +393,6 @@ fn nav_button_cluster(app: &EchoApp, cx: &mut Context) -> impl IntoElem )) } -pub fn sidebar(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let tab = app.state.ui.active_library_tab; - let count = match tab { - LibraryTab::Albums => app.state.data.saved_albums.len(), - LibraryTab::Artists => app.state.data.followed_artists.len(), - _ => app.state.data.library_view.len(), - }; - - let nav_row = div() - .flex() - .flex_row() - .items_center() - .px_2() - .pt_2() - .child(nav_button_cluster(app, cx)); - - let tab_button = |id: &'static str, label: SharedString, target: LibraryTab, active: bool| { - div() - .id(id) - .px_2() - .py_1() - .rounded_md() - .text_sm() - .text_color(if active { accent } else { muted }) - .hover(move |style| style.bg(palette.row_hover)) - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.state.ui.active_library_tab = target; - this.state.ui.selected_playlist_index = 0; - if target == LibraryTab::Artists && this.state.data.followed_artists.is_empty() { - this.dispatch(echo_core::events::AppEvent::FetchFollowedArtists); - } - cx.notify(); - })) - .child(label) - }; - - div() - .relative() - .flex_none() - .w(px(app.sidebar_width)) - .h_full() - .flex() - .flex_col() - .child(nav_row) - .child(div().id("home-link").mx_2().mt_2().px_2().py_2().rounded_md().flex().items_center().gap_2().text_sm().text_color(if app.state.ui.active_view == ActiveView::Home { accent } else { muted }).when(app.state.ui.active_view == ActiveView::Home, |el| el.bg(palette.row_selected)).hover(move |style| style.bg(palette.row_hover)).cursor_pointer().on_click(cx.listener(|this: &mut EchoApp, _, window, cx| { this.open_home(cx); window.focus(&this.focus_handle, cx); })).child(svg().path("icons/home.svg").size(px(18.0)).text_color(muted)).child(tr(&app.state, "desktop.home"))) - .child( - div() - .flex() - .flex_row() - .gap_1() - .p_2() - .child(tab_button( - "Playlists", - tr(&app.state, "ui.playlists"), - LibraryTab::Playlists, - tab == LibraryTab::Playlists, - )) - .child(tab_button( - "Albums", - tr(&app.state, "ui.albums"), - LibraryTab::Albums, - tab == LibraryTab::Albums, - )) - .child(tab_button( - "Artists", - tr(&app.state, "ui.artists"), - LibraryTab::Artists, - tab == LibraryTab::Artists, - )), - ) - .child({ - // Browse nodes presented as quick links. - let browse_link = |id: &'static str, - icon: &'static str, - label: SharedString, - open: fn(&mut echo_core::app::AppState) - -> Option| { - div() - .id(id) - .mx_2() - .px_2() - .py_1() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_2() - .text_sm() - .text_color(muted) - .hover(move |style| style.bg(palette.row_hover)) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = open(&mut this.state) { - this.dispatch(event); - } - cx.notify(); - })) - .child( - svg() - .path(icon) - .flex_none() - .w(px(14.0)) - .h(px(14.0)) - .text_color(muted), - ) - .child(label) - }; - div() - .flex_none() - .flex() - .flex_col() - .pb_1() - .child(browse_link( - "top-tracks", - "icons/star.svg", - tr(&app.state, "desktop.top_tracks"), - echo_core::intent::open_top_tracks, - )) - .child(browse_link( - "recently-played", - "icons/clock.svg", - tr(&app.state, "desktop.recently_played"), - echo_core::intent::open_recently_played, - )) - .child(browse_link( - "top-artists", - "icons/mic.svg", - tr(&app.state, "desktop.top_artists"), - echo_core::intent::open_top_artists, - )) - .child(browse_link( - "whats-new", - "icons/sparkles.svg", - tr(&app.state, "desktop.whats_new"), - echo_core::intent::open_whats_new, - )) - }) - .child( - uniform_list( - "library-rows", - count, - cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = if this.state.ui.active_view == ActiveView::Library { - palette.row_selected - } else { - palette.row_hover - }; - let drag_colors = DragColors::resolve(theme); - let tab = this.state.ui.active_library_tab; - let selected = this.state.ui.selected_playlist_index; - let visual = visual_range_in(&this.state, ActiveView::Library); - - let rows: Vec<_> = range - .map(|ix| { - // Folders carry no cover; playlists, albums and artists get a - // thumb box even while (or if never) loaded, so the text column - // stays aligned. Folders get a chevron icon, pinned playlists a - // pin icon; artist thumbs are circular. - let (label, label_color, indent_px, thumb_url, has_thumb, chevron, pinned, round_thumb): ( - SharedString, - _, - f32, - Option, - bool, - Option<&'static str>, - bool, - bool, - ) = if tab == LibraryTab::Albums { - let album = &this.state.data.saved_albums[ix]; - let url = album - .thumb_url - .clone() - .or_else(|| album.image_url.clone()); - (album.name.clone().into(), fg, 0.0, url, true, None, false, false) - } else if tab == LibraryTab::Artists { - let artist = &this.state.data.followed_artists[ix]; - ( - artist.name.clone().into(), - fg, - 0.0, - artist.image_url.clone(), - true, - None, - false, - true, - ) - } else { - match &this.state.data.library_view[ix] { - LibraryNode::Folder(f) => ( - f.name.clone().into(), - accent, - 0.0, - None, - false, - Some(if f.is_open { - "icons/arrow-down.svg" - } else { - "icons/arrow-right.svg" - }), - false, - false, - ), - LibraryNode::SpotifyFolder { name, is_open, indent, .. } => ( - name.clone().into(), - accent, - *indent as f32 * 14.0, - None, - false, - Some(if *is_open { - "icons/arrow-down.svg" - } else { - "icons/arrow-right.svg" - }), - false, - false, - ), - LibraryNode::Playlist { playlist, indent } => { - let pinned = this - .state - .ui - .library_config - .pinned - .contains(&playlist.id); - let url = playlist - .thumb_url - .clone() - .or_else(|| playlist.image_url.clone()); - ( - playlist.name.clone().into(), - fg, - *indent as f32 * 14.0, - url, - true, - None, - pinned, - false, - ) - } - } - }; - - // Liked Songs has no cover, so its box holds the heart icon, which - // takes the theme's accent. (An emoji in the name would not: macOS - // draws those in full colour.) - let liked_row = tab == LibraryTab::Playlists - && matches!( - &this.state.data.library_view[ix], - LibraryNode::Playlist { playlist, .. } - if playlist.id == "LIKED_SONGS" - ); - let thumb: Option = has_thumb.then(|| { - let artwork = thumb_url.as_deref().and_then(|url| { - this.state.ui.thumbnails.request(url, ThumbTier::Small); - match this.state.ui.thumbnails.get(url, ThumbTier::Small) { - Some(ThumbState::Ready { artwork }) => { - Some(artwork.clone()) - } - _ => None, - } - }); - match artwork.and_then(|artwork| this.images.get(&artwork)) { - Some(image) => { - let radius = if round_thumb { THUMB_EDGE / 2.0 } else { 4.0 }; - cover_image(image, THUMB_EDGE, radius).into_any_element() - } - None => { - let el = div() - .flex_none() - .w(px(THUMB_EDGE)) - .h(px(THUMB_EDGE)) - .bg(palette.wash) - .flex() - .items_center() - .justify_center() - .child( - svg() - .path(if liked_row { - "icons/heart.svg" - } else { - "icons/music-note.svg" - }) - .w(px(12.0)) - .h(px(12.0)) - .text_color(if liked_row { accent } else { muted }), - ); - if round_thumb { el.rounded_full() } else { el.rounded_sm() } - .into_any_element() - } - } - }); - - // Local playlists and echo's own folders look like Spotify's in the - // sidebar, so they are tagged to keep the distinction visible. - let local_badge: Option = (tab - == LibraryTab::Playlists - && match &this.state.data.library_view[ix] { - LibraryNode::Playlist { playlist, .. } => { - playlist.id.starts_with("local-playlist:") - } - LibraryNode::Folder(_) => true, - LibraryNode::SpotifyFolder { .. } => false, - }) - .then(|| tr(&this.state, "desktop.local_badge")); - - // Playlists can be dragged between folders, the pinned block and the - // loose list, and folders among themselves; every playlist-tab row - // is a drop target (the intent rejects invalid ones). - let drag_source: Option<(String, SharedString)> = - if tab == LibraryTab::Playlists { - match &this.state.data.library_view[ix] { - LibraryNode::Playlist { playlist, .. } - if !is_fixed_library_row(&playlist.id) => - { - Some(( - playlist.id.clone(), - playlist.name.clone().into(), - )) - } - LibraryNode::Playlist { .. } => None, - LibraryNode::Folder(folder) => Some(( - echo_core::models::echo_folder_key(&folder.name), - folder.name.clone().into(), - )), - LibraryNode::SpotifyFolder { id, name, .. } => Some(( - echo_core::models::spotify_folder_key(id), - name.clone().into(), - )), - } - } else { - None - }; - - pill_row(ix, SIDEBAR_PILL, row_selected(ix, selected, visual), selected_bg, palette.row_hover, |row| { - row.pl(px(8.0 + indent_px)) - .gap_2() - .text_color(label_color) - .when(tab != LibraryTab::Artists, |el| { - // Artists have no row actions, so no context menu. - el.on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_playlist_index = ix; - this.track_menu = None; - this.state.ui.playlist_add_filter.clear(); - // Spotify's folders are read-only, so they have no - // row actions to offer. - if this.state.ui.active_library_tab - == LibraryTab::Playlists - && matches!( - this.state.data.library_view.get(ix), - Some(LibraryNode::SpotifyFolder { .. }) - ) - { - this.context_menu = None; - cx.notify(); - return; - } - this.context_menu = Some(crate::ContextMenuState { - index: ix, - position: event.position, - }); - cx.notify(); - }), - ) - }) - .when_some(drag_source, |el, (id, name)| { - el.on_drag( - DraggedPlaylist { id, name }, - move |drag, _offset, _window, cx| { - let name = drag.name.clone(); - cx.new(|_| DragPreview::label(name, drag_colors)) - }, - ) - }) - .when(tab == LibraryTab::Playlists, |el| { - el.drag_over::(move |style, _, _, _| { - style.bg(palette.drag_target) - }) - .on_drop(cx.listener( - move |this: &mut EchoApp, drag: &DraggedPlaylist, _window, cx| { - if echo_core::intent::move_library_row( - &mut this.state, - &drag.id, - ix, - ) { - cx.notify(); - } - }, - )) - .drag_over::(move |style, _, _, _| { - style.bg(palette.drag_target) - }) - .on_drop(cx.listener( - move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { - for event in echo_core::intent::drop_tracks_on_library_row( - &mut this.state, - ix, - drag.tracks.clone(), - ) { - this.dispatch(event); - } - cx.notify(); - }, - )) - }) - .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { - this.state.ui.selected_playlist_index = ix; - let tab = this.state.ui.active_library_tab; - // The first click of a double-click already opened the - // entry; the second one starts it playing. - if event.click_count() >= 2 { - let play = match tab { - LibraryTab::Albums => { - echo_core::intent::play_album_at(&mut this.state, ix) - } - LibraryTab::Artists => None, - _ => echo_core::intent::play_library_entry( - &mut this.state, - ix, - ), - }; - if let Some(event) = play { - this.dispatch(event); - } - cx.notify(); - return; - } - let event = match tab { - LibraryTab::Albums => { - echo_core::intent::open_album(&mut this.state, ix) - } - LibraryTab::Artists => { - echo_core::intent::open_followed_artist( - &mut this.state, - ix, - ) - } - _ => echo_core::intent::open_library_entry( - &mut this.state, - ix, - ), - }; - if let Some(event) = event { - this.dispatch(event); - } - cx.notify(); - })) - .when_some(chevron, |el, icon| { - el.child( - svg() - .path(icon) - .flex_none() - .w(px(12.0)) - .h(px(12.0)) - .text_color(accent), - ) - }) - .when_some(thumb, |el, thumb| el.child(thumb)) - .when(pinned, |el| { - el.child( - svg() - .path("icons/pin.svg") - .flex_none() - .w(px(12.0)) - .h(px(12.0)) - .text_color(muted), - ) - }) - .child( - div() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .child(label), - ) - .when_some(local_badge, |el, badge| { - el.child( - div() - .ml_auto() - .flex_none() - .text_xs() - .text_color(muted) - .child(badge), - ) - }) - }) - }) - .collect(); - - // Kick off fetches for whatever the rows above just requested. - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - - rows - }), - ) - .track_scroll(&app.library_scroll) - .on_drag_move(cx.listener( - |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { - this.drag_autoscroll(crate::DragList::Library, event.event.position.y, event.bounds, cx); - }, - )) - .on_drag_move(cx.listener( - |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { - this.drag_autoscroll(crate::DragList::Library, event.event.position.y, event.bounds, cx); - }, - )) - .flex_grow(1.0), - ) - .child( - div() - .absolute() - .right_0() - .top_0() - .bottom_0() - .w(px(5.0)) - .cursor_col_resize() - .hover(move |style| style.bg(palette.drag_target)) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.begin_sidebar_resize(event.position.x, cx); - cx.stop_propagation(); - }), - ), - ) -} - pub fn main_area( app: &mut EchoApp, window: &mut Window, diff --git a/crates/echo-desktop/src/views/sidebar.rs b/crates/echo-desktop/src/views/sidebar.rs new file mode 100644 index 0000000..3874206 --- /dev/null +++ b/crates/echo-desktop/src/views/sidebar.rs @@ -0,0 +1,554 @@ +use super::*; + +pub(crate) const SIDEBAR_WIDTH: f32 = 240.0; + +const THUMB_EDGE: f32 = 26.0; + +/// Sidebar rows, which hover a touch stronger than the main area. +const SIDEBAR_PILL: PillMetrics = PillMetrics { + row_height: 34.0, + pill_height: 30.0, +}; + +/// True for the sidebar rows drag-and-drop must not move (their position is fixed, mirroring +/// `echo_core::intent`'s own check). +fn is_fixed_library_row(id: &str) -> bool { + id == "LIKED_SONGS" || id == "local-library" +} + +pub fn sidebar(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let tab = app.state.ui.active_library_tab; + let count = match tab { + LibraryTab::Albums => app.state.data.saved_albums.len(), + LibraryTab::Artists => app.state.data.followed_artists.len(), + _ => app.state.data.library_view.len(), + }; + + let nav_row = div() + .flex() + .flex_row() + .items_center() + .px_2() + .pt_2() + .child(nav_button_cluster(app, cx)); + + let tab_button = |id: &'static str, label: SharedString, target: LibraryTab, active: bool| { + div() + .id(id) + .px_2() + .py_1() + .rounded_md() + .text_sm() + .text_color(if active { accent } else { muted }) + .hover(move |style| style.bg(palette.row_hover)) + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.state.ui.active_library_tab = target; + this.state.ui.selected_playlist_index = 0; + if target == LibraryTab::Artists && this.state.data.followed_artists.is_empty() { + this.dispatch(echo_core::events::AppEvent::FetchFollowedArtists); + } + cx.notify(); + })) + .child(label) + }; + + div() + .relative() + .flex_none() + .w(px(app.sidebar_width)) + .h_full() + .flex() + .flex_col() + .child(nav_row) + .child(div().id("home-link").mx_2().mt_2().px_2().py_2().rounded_md().flex().items_center().gap_2().text_sm().text_color(if app.state.ui.active_view == ActiveView::Home { accent } else { muted }).when(app.state.ui.active_view == ActiveView::Home, |el| el.bg(palette.row_selected)).hover(move |style| style.bg(palette.row_hover)).cursor_pointer().on_click(cx.listener(|this: &mut EchoApp, _, window, cx| { this.open_home(cx); window.focus(&this.focus_handle, cx); })).child(svg().path("icons/home.svg").size(px(18.0)).text_color(muted)).child(tr(&app.state, "desktop.home"))) + .child( + div() + .flex() + .flex_row() + .gap_1() + .p_2() + .child(tab_button( + "Playlists", + tr(&app.state, "ui.playlists"), + LibraryTab::Playlists, + tab == LibraryTab::Playlists, + )) + .child(tab_button( + "Albums", + tr(&app.state, "ui.albums"), + LibraryTab::Albums, + tab == LibraryTab::Albums, + )) + .child(tab_button( + "Artists", + tr(&app.state, "ui.artists"), + LibraryTab::Artists, + tab == LibraryTab::Artists, + )), + ) + .child({ + // Browse nodes presented as quick links. + let browse_link = |id: &'static str, + icon: &'static str, + label: SharedString, + open: fn(&mut echo_core::app::AppState) + -> Option| { + div() + .id(id) + .mx_2() + .px_2() + .py_1() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_2() + .text_sm() + .text_color(muted) + .hover(move |style| style.bg(palette.row_hover)) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = open(&mut this.state) { + this.dispatch(event); + } + cx.notify(); + })) + .child( + svg() + .path(icon) + .flex_none() + .w(px(14.0)) + .h(px(14.0)) + .text_color(muted), + ) + .child(label) + }; + div() + .flex_none() + .flex() + .flex_col() + .pb_1() + .child(browse_link( + "top-tracks", + "icons/star.svg", + tr(&app.state, "desktop.top_tracks"), + echo_core::intent::open_top_tracks, + )) + .child(browse_link( + "recently-played", + "icons/clock.svg", + tr(&app.state, "desktop.recently_played"), + echo_core::intent::open_recently_played, + )) + .child(browse_link( + "top-artists", + "icons/mic.svg", + tr(&app.state, "desktop.top_artists"), + echo_core::intent::open_top_artists, + )) + .child(browse_link( + "whats-new", + "icons/sparkles.svg", + tr(&app.state, "desktop.whats_new"), + echo_core::intent::open_whats_new, + )) + }) + .child( + uniform_list( + "library-rows", + count, + cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = if this.state.ui.active_view == ActiveView::Library { + palette.row_selected + } else { + palette.row_hover + }; + let drag_colors = DragColors::resolve(theme); + let tab = this.state.ui.active_library_tab; + let selected = this.state.ui.selected_playlist_index; + let visual = visual_range_in(&this.state, ActiveView::Library); + + let rows: Vec<_> = range + .map(|ix| { + // Folders carry no cover; playlists, albums and artists get a + // thumb box even while (or if never) loaded, so the text column + // stays aligned. Folders get a chevron icon, pinned playlists a + // pin icon; artist thumbs are circular. + let (label, label_color, indent_px, thumb_url, has_thumb, chevron, pinned, round_thumb): ( + SharedString, + _, + f32, + Option, + bool, + Option<&'static str>, + bool, + bool, + ) = if tab == LibraryTab::Albums { + let album = &this.state.data.saved_albums[ix]; + let url = album + .thumb_url + .clone() + .or_else(|| album.image_url.clone()); + (album.name.clone().into(), fg, 0.0, url, true, None, false, false) + } else if tab == LibraryTab::Artists { + let artist = &this.state.data.followed_artists[ix]; + ( + artist.name.clone().into(), + fg, + 0.0, + artist.image_url.clone(), + true, + None, + false, + true, + ) + } else { + match &this.state.data.library_view[ix] { + LibraryNode::Folder(f) => ( + f.name.clone().into(), + accent, + 0.0, + None, + false, + Some(if f.is_open { + "icons/arrow-down.svg" + } else { + "icons/arrow-right.svg" + }), + false, + false, + ), + LibraryNode::SpotifyFolder { name, is_open, indent, .. } => ( + name.clone().into(), + accent, + *indent as f32 * 14.0, + None, + false, + Some(if *is_open { + "icons/arrow-down.svg" + } else { + "icons/arrow-right.svg" + }), + false, + false, + ), + LibraryNode::Playlist { playlist, indent } => { + let pinned = this + .state + .ui + .library_config + .pinned + .contains(&playlist.id); + let url = playlist + .thumb_url + .clone() + .or_else(|| playlist.image_url.clone()); + ( + playlist.name.clone().into(), + fg, + *indent as f32 * 14.0, + url, + true, + None, + pinned, + false, + ) + } + } + }; + + // Liked Songs has no cover, so its box holds the heart icon, which + // takes the theme's accent. (An emoji in the name would not: macOS + // draws those in full colour.) + let liked_row = tab == LibraryTab::Playlists + && matches!( + &this.state.data.library_view[ix], + LibraryNode::Playlist { playlist, .. } + if playlist.id == "LIKED_SONGS" + ); + let thumb: Option = has_thumb.then(|| { + let artwork = thumb_url.as_deref().and_then(|url| { + this.state.ui.thumbnails.request(url, ThumbTier::Small); + match this.state.ui.thumbnails.get(url, ThumbTier::Small) { + Some(ThumbState::Ready { artwork }) => { + Some(artwork.clone()) + } + _ => None, + } + }); + match artwork.and_then(|artwork| this.images.get(&artwork)) { + Some(image) => { + let radius = if round_thumb { THUMB_EDGE / 2.0 } else { 4.0 }; + cover_image(image, THUMB_EDGE, radius).into_any_element() + } + None => { + let el = div() + .flex_none() + .w(px(THUMB_EDGE)) + .h(px(THUMB_EDGE)) + .bg(palette.wash) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path(if liked_row { + "icons/heart.svg" + } else { + "icons/music-note.svg" + }) + .w(px(12.0)) + .h(px(12.0)) + .text_color(if liked_row { accent } else { muted }), + ); + if round_thumb { el.rounded_full() } else { el.rounded_sm() } + .into_any_element() + } + } + }); + + // Local playlists and echo's own folders look like Spotify's in the + // sidebar, so they are tagged to keep the distinction visible. + let local_badge: Option = (tab + == LibraryTab::Playlists + && match &this.state.data.library_view[ix] { + LibraryNode::Playlist { playlist, .. } => { + playlist.id.starts_with("local-playlist:") + } + LibraryNode::Folder(_) => true, + LibraryNode::SpotifyFolder { .. } => false, + }) + .then(|| tr(&this.state, "desktop.local_badge")); + + // Playlists can be dragged between folders, the pinned block and the + // loose list, and folders among themselves; every playlist-tab row + // is a drop target (the intent rejects invalid ones). + let drag_source: Option<(String, SharedString)> = + if tab == LibraryTab::Playlists { + match &this.state.data.library_view[ix] { + LibraryNode::Playlist { playlist, .. } + if !is_fixed_library_row(&playlist.id) => + { + Some(( + playlist.id.clone(), + playlist.name.clone().into(), + )) + } + LibraryNode::Playlist { .. } => None, + LibraryNode::Folder(folder) => Some(( + echo_core::models::echo_folder_key(&folder.name), + folder.name.clone().into(), + )), + LibraryNode::SpotifyFolder { id, name, .. } => Some(( + echo_core::models::spotify_folder_key(id), + name.clone().into(), + )), + } + } else { + None + }; + + pill_row(ix, SIDEBAR_PILL, row_selected(ix, selected, visual), selected_bg, palette.row_hover, |row| { + row.pl(px(8.0 + indent_px)) + .gap_2() + .text_color(label_color) + .when(tab != LibraryTab::Artists, |el| { + // Artists have no row actions, so no context menu. + el.on_mouse_down( + MouseButton::Right, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.selected_playlist_index = ix; + this.track_menu = None; + this.state.ui.playlist_add_filter.clear(); + // Spotify's folders are read-only, so they have no + // row actions to offer. + if this.state.ui.active_library_tab + == LibraryTab::Playlists + && matches!( + this.state.data.library_view.get(ix), + Some(LibraryNode::SpotifyFolder { .. }) + ) + { + this.context_menu = None; + cx.notify(); + return; + } + this.context_menu = Some(crate::ContextMenuState { + index: ix, + position: event.position, + }); + cx.notify(); + }), + ) + }) + .when_some(drag_source, |el, (id, name)| { + el.on_drag( + DraggedPlaylist { id, name }, + move |drag, _offset, _window, cx| { + let name = drag.name.clone(); + cx.new(|_| DragPreview::label(name, drag_colors)) + }, + ) + }) + .when(tab == LibraryTab::Playlists, |el| { + el.drag_over::(move |style, _, _, _| { + style.bg(palette.drag_target) + }) + .on_drop(cx.listener( + move |this: &mut EchoApp, drag: &DraggedPlaylist, _window, cx| { + if echo_core::intent::move_library_row( + &mut this.state, + &drag.id, + ix, + ) { + cx.notify(); + } + }, + )) + .drag_over::(move |style, _, _, _| { + style.bg(palette.drag_target) + }) + .on_drop(cx.listener( + move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { + for event in echo_core::intent::drop_tracks_on_library_row( + &mut this.state, + ix, + drag.tracks.clone(), + ) { + this.dispatch(event); + } + cx.notify(); + }, + )) + }) + .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + this.state.ui.selected_playlist_index = ix; + let tab = this.state.ui.active_library_tab; + // The first click of a double-click already opened the + // entry; the second one starts it playing. + if event.click_count() >= 2 { + let play = match tab { + LibraryTab::Albums => { + echo_core::intent::play_album_at(&mut this.state, ix) + } + LibraryTab::Artists => None, + _ => echo_core::intent::play_library_entry( + &mut this.state, + ix, + ), + }; + if let Some(event) = play { + this.dispatch(event); + } + cx.notify(); + return; + } + let event = match tab { + LibraryTab::Albums => { + echo_core::intent::open_album(&mut this.state, ix) + } + LibraryTab::Artists => { + echo_core::intent::open_followed_artist( + &mut this.state, + ix, + ) + } + _ => echo_core::intent::open_library_entry( + &mut this.state, + ix, + ), + }; + if let Some(event) = event { + this.dispatch(event); + } + cx.notify(); + })) + .when_some(chevron, |el, icon| { + el.child( + svg() + .path(icon) + .flex_none() + .w(px(12.0)) + .h(px(12.0)) + .text_color(accent), + ) + }) + .when_some(thumb, |el, thumb| el.child(thumb)) + .when(pinned, |el| { + el.child( + svg() + .path("icons/pin.svg") + .flex_none() + .w(px(12.0)) + .h(px(12.0)) + .text_color(muted), + ) + }) + .child( + div() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .child(label), + ) + .when_some(local_badge, |el, badge| { + el.child( + div() + .ml_auto() + .flex_none() + .text_xs() + .text_color(muted) + .child(badge), + ) + }) + }) + }) + .collect(); + + // Kick off fetches for whatever the rows above just requested. + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + + rows + }), + ) + .track_scroll(&app.library_scroll) + .on_drag_move(cx.listener( + |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { + this.drag_autoscroll(crate::DragList::Library, event.event.position.y, event.bounds, cx); + }, + )) + .on_drag_move(cx.listener( + |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { + this.drag_autoscroll(crate::DragList::Library, event.event.position.y, event.bounds, cx); + }, + )) + .flex_grow(1.0), + ) + .child( + div() + .absolute() + .right_0() + .top_0() + .bottom_0() + .w(px(5.0)) + .cursor_col_resize() + .hover(move |style| style.bg(palette.drag_target)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.begin_sidebar_resize(event.position.x, cx); + cx.stop_propagation(); + }), + ), + ) +} From f9360d20a2f490178e9000d22a69026257ee43ab Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:22:51 -0500 Subject: [PATCH 05/44] desktop: move drag payloads and the drag preview into views/drag.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 170 +------------------------- crates/echo-desktop/src/views/drag.rs | 170 ++++++++++++++++++++++++++ 2 files changed, 172 insertions(+), 168 deletions(-) create mode 100644 crates/echo-desktop/src/views/drag.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 441ab00..2f90837 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -14,12 +14,14 @@ use echo_core::config::RightPanel; use echo_core::models::{ActionMenuAction, ActionMenuContext, LibraryNode}; use echo_core::thumbnails::{ThumbState, ThumbTier, tier_for_edge}; mod chrome; +mod drag; mod menu_placement; pub(crate) mod panel_layout; mod playlist_edit; mod search; mod sidebar; pub(crate) use chrome::*; +pub(crate) use drag::*; use gpui::{ Animation, AnimationExt, AnyElement, App, Context, Div, Entity, Hsla, MouseButton, MouseDownEvent, SharedString, Stateful, Window, canvas, div, ease_out_quint, prelude::*, px, @@ -144,78 +146,6 @@ const ECHO_LOGO: [&str; 6] = [ "╚══════╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝", ]; -/// Drag payload for a sidebar playlist or folder row. `id` is the row's key: a playlist id, or -/// a folder key. -pub(crate) struct DraggedPlaylist { - pub id: String, - pub name: SharedString, -} - -/// Drag payload for track rows: the whole selection when the dragged row is part of it, else -/// that one row. `source_context` names the tracklist the rows came from, so a drop back into -/// the same list reorders instead of copying. `name`, `artist` and `cover` feed the preview -/// chip: the dragged row's cover with the track's title and artist, or the song count. -pub(crate) struct DraggedTracks { - pub tracks: Vec, - pub from_row: usize, - pub source_context: Option, - pub name: SharedString, - pub artist: SharedString, - pub cover: Option>, -} - -/// The payload for dragging one `track` from outside any track list (the playback bar, an -/// artist's Popular rows). -pub(crate) fn single_drag_payload( - track: &echo_core::models::Track, - cover: Option>, -) -> DraggedTracks { - DraggedTracks { - tracks: vec![track.clone()], - from_row: 0, - source_context: None, - name: SharedString::from(track.name.clone()), - artist: SharedString::from(track.artist.clone()), - cover, - } -} - -/// The payload for dragging row `ix` of `view`: every selected track in display order when the -/// row is one of them, otherwise just `track`. -fn drag_payload( - this: &mut EchoApp, - view: ActiveView, - ix: usize, - track: &echo_core::models::Track, -) -> DraggedTracks { - let cover = thumb_image(this, track.image_url.as_deref(), DRAG_COVER_EDGE); - let mut payload = single_drag_payload(track, cover); - let state = &this.state; - let rows = if state.ui.active_view == view { - echo_core::intent::selected_rows(state) - } else { - Vec::new() - }; - if rows.len() > 1 && rows.contains(&ix) { - payload.tracks = echo_core::intent::selected_tracks(state); - payload.name = tr(state, "desktop.drag_songs") - .replace("{}", &payload.tracks.len().to_string()) - .into(); - payload.artist = SharedString::default(); - } - payload.from_row = ix; - payload.source_context = (view == ActiveView::TrackList) - .then(|| { - state - .data - .active_tracklist_context - .as_ref() - .map(|c| c.id.clone()) - }) - .flatten(); - payload -} - /// A queue row cloned out of the state: its row index and either a header or `(track index, track)`. type OwnedQueueRow = (usize, Result<(usize, echo_core::models::Track), String>); @@ -236,102 +166,6 @@ fn is_pick_click(event: &gpui::ClickEvent) -> bool { modifiers.secondary() || modifiers.control } -const DRAG_COVER_EDGE: f32 = 32.0; -const DRAG_CHIP_MAX_WIDTH: f32 = 320.0; - -/// The colours of the chip that follows the cursor during a drag. -#[derive(Clone, Copy)] -pub(crate) struct DragColors { - fg: gpui::Hsla, - muted: gpui::Hsla, - bg: gpui::Hsla, - border: gpui::Hsla, -} - -impl DragColors { - pub(crate) fn resolve(theme: &echo_core::theme::ResolvedTheme) -> Self { - Self { - fg: theme.text.gpui(WINDOW_FG()), - muted: theme.text_muted.gpui(WINDOW_FG()), - bg: theme.surface.gpui(crate::theme::PANEL_BG()), - border: DesktopPalette::resolve(theme).menu_border, - } - } -} - -/// The chip that follows the cursor while something is dragged: a name, or for tracks the -/// cover with title and artist like a shortened track row. -pub(crate) struct DragPreview { - name: SharedString, - artist: SharedString, - cover: Option>, - colors: DragColors, -} - -impl DragPreview { - fn label(name: SharedString, colors: DragColors) -> Self { - Self { - name, - artist: SharedString::default(), - cover: None, - colors, - } - } -} - -/// The preview entity for a track drag, for `on_drag`. -pub(crate) fn track_drag_preview( - drag: &DraggedTracks, - colors: DragColors, - cx: &mut App, -) -> Entity { - let preview = DragPreview { - name: drag.name.clone(), - artist: drag.artist.clone(), - cover: drag.cover.clone(), - colors, - }; - cx.new(|_| preview) -} - -impl gpui::Render for DragPreview { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - let colors = self.colors; - let line = |text: SharedString| { - div() - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(text) - }; - div() - .max_w(px(DRAG_CHIP_MAX_WIDTH)) - .px_2() - .py_1() - .rounded_md() - .bg(colors.bg) - .border_1() - .border_color(colors.border) - .flex() - .flex_row() - .items_center() - .gap_3() - .when_some(self.cover.clone(), |el, image| { - el.child(cover_image(image, DRAG_COVER_EDGE, 4.0)) - }) - .child( - div() - .min_w_0() - .flex() - .flex_col() - .child(line(self.name.clone()).text_sm().text_color(colors.fg)) - .when(!self.artist.is_empty(), |el| { - el.child(line(self.artist.clone()).text_xs().text_color(colors.muted)) - }), - ) - } -} - fn nav_button_cluster(app: &EchoApp, cx: &mut Context) -> impl IntoElement { let theme = &app.state.ui.active_theme; let palette = DesktopPalette::resolve(theme); diff --git a/crates/echo-desktop/src/views/drag.rs b/crates/echo-desktop/src/views/drag.rs new file mode 100644 index 0000000..6acad0d --- /dev/null +++ b/crates/echo-desktop/src/views/drag.rs @@ -0,0 +1,170 @@ +use super::*; + +/// Drag payload for a sidebar playlist or folder row. `id` is the row's key: a playlist id, or +/// a folder key. +pub(crate) struct DraggedPlaylist { + pub id: String, + pub name: SharedString, +} + +/// Drag payload for track rows: the whole selection when the dragged row is part of it, else +/// that one row. `source_context` names the tracklist the rows came from, so a drop back into +/// the same list reorders instead of copying. `name`, `artist` and `cover` feed the preview +/// chip: the dragged row's cover with the track's title and artist, or the song count. +pub(crate) struct DraggedTracks { + pub tracks: Vec, + pub from_row: usize, + pub source_context: Option, + pub name: SharedString, + pub artist: SharedString, + pub cover: Option>, +} + +/// The payload for dragging one `track` from outside any track list (the playback bar, an +/// artist's Popular rows). +pub(crate) fn single_drag_payload( + track: &echo_core::models::Track, + cover: Option>, +) -> DraggedTracks { + DraggedTracks { + tracks: vec![track.clone()], + from_row: 0, + source_context: None, + name: SharedString::from(track.name.clone()), + artist: SharedString::from(track.artist.clone()), + cover, + } +} + +/// The payload for dragging row `ix` of `view`: every selected track in display order when the +/// row is one of them, otherwise just `track`. +pub(super) fn drag_payload( + this: &mut EchoApp, + view: ActiveView, + ix: usize, + track: &echo_core::models::Track, +) -> DraggedTracks { + let cover = thumb_image(this, track.image_url.as_deref(), DRAG_COVER_EDGE); + let mut payload = single_drag_payload(track, cover); + let state = &this.state; + let rows = if state.ui.active_view == view { + echo_core::intent::selected_rows(state) + } else { + Vec::new() + }; + if rows.len() > 1 && rows.contains(&ix) { + payload.tracks = echo_core::intent::selected_tracks(state); + payload.name = tr(state, "desktop.drag_songs") + .replace("{}", &payload.tracks.len().to_string()) + .into(); + payload.artist = SharedString::default(); + } + payload.from_row = ix; + payload.source_context = (view == ActiveView::TrackList) + .then(|| { + state + .data + .active_tracklist_context + .as_ref() + .map(|c| c.id.clone()) + }) + .flatten(); + payload +} + +pub(super) const DRAG_COVER_EDGE: f32 = 32.0; + +const DRAG_CHIP_MAX_WIDTH: f32 = 320.0; + +/// The colours of the chip that follows the cursor during a drag. +#[derive(Clone, Copy)] +pub(crate) struct DragColors { + fg: gpui::Hsla, + muted: gpui::Hsla, + bg: gpui::Hsla, + border: gpui::Hsla, +} + +impl DragColors { + pub(crate) fn resolve(theme: &echo_core::theme::ResolvedTheme) -> Self { + Self { + fg: theme.text.gpui(WINDOW_FG()), + muted: theme.text_muted.gpui(WINDOW_FG()), + bg: theme.surface.gpui(crate::theme::PANEL_BG()), + border: DesktopPalette::resolve(theme).menu_border, + } + } +} + +/// The chip that follows the cursor while something is dragged: a name, or for tracks the +/// cover with title and artist like a shortened track row. +pub(crate) struct DragPreview { + name: SharedString, + artist: SharedString, + cover: Option>, + colors: DragColors, +} + +impl DragPreview { + pub(super) fn label(name: SharedString, colors: DragColors) -> Self { + Self { + name, + artist: SharedString::default(), + cover: None, + colors, + } + } +} + +/// The preview entity for a track drag, for `on_drag`. +pub(crate) fn track_drag_preview( + drag: &DraggedTracks, + colors: DragColors, + cx: &mut App, +) -> Entity { + let preview = DragPreview { + name: drag.name.clone(), + artist: drag.artist.clone(), + cover: drag.cover.clone(), + colors, + }; + cx.new(|_| preview) +} + +impl gpui::Render for DragPreview { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let colors = self.colors; + let line = |text: SharedString| { + div() + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(text) + }; + div() + .max_w(px(DRAG_CHIP_MAX_WIDTH)) + .px_2() + .py_1() + .rounded_md() + .bg(colors.bg) + .border_1() + .border_color(colors.border) + .flex() + .flex_row() + .items_center() + .gap_3() + .when_some(self.cover.clone(), |el, image| { + el.child(cover_image(image, DRAG_COVER_EDGE, 4.0)) + }) + .child( + div() + .min_w_0() + .flex() + .flex_col() + .child(line(self.name.clone()).text_sm().text_color(colors.fg)) + .when(!self.artist.is_empty(), |el| { + el.child(line(self.artist.clone()).text_xs().text_color(colors.muted)) + }), + ) + } +} From cff98ba1a6885c70be8c2eb621713604500e3b01 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:22:57 -0500 Subject: [PATCH 06/44] desktop: move the track list, its header and the sort menu into views/track_list.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 820 +------------------- crates/echo-desktop/src/views/track_list.rs | 819 +++++++++++++++++++ 2 files changed, 821 insertions(+), 818 deletions(-) create mode 100644 crates/echo-desktop/src/views/track_list.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 2f90837..11c4f9f 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -20,6 +20,7 @@ pub(crate) mod panel_layout; mod playlist_edit; mod search; mod sidebar; +mod track_list; pub(crate) use chrome::*; pub(crate) use drag::*; use gpui::{ @@ -30,6 +31,7 @@ use gpui::{ use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; pub(crate) use sidebar::*; +pub(crate) use track_list::*; use crate::backdrop::{Backdrop, ImmersiveColors}; use crate::theme::{DesktopPalette, ToGpui, WINDOW_FG}; @@ -672,824 +674,6 @@ fn search_bar( )) } -pub const SORT_OPTIONS: &[(&str, &str)] = &[ - ("desktop.sort.original", "original"), - ("desktop.sort.title", "title"), - ("ui.artist", "artist"), - ("ui.album", "album"), - ("ui.duration", "duration"), - ("desktop.sort.added", "added"), - ("desktop.context.added_by", "addedby"), - ("desktop.sort.reverse", "reverse"), -]; - -fn sort_button(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let muted = theme.text_muted.gpui(WINDOW_FG()); - div() - .on_mouse_down( - MouseButton::Left, - cx.listener(|this: &mut EchoApp, event: &MouseDownEvent, window, _cx| { - this.sort_menu_top = (f32::from(event.position.y) + 16.0) - .min((f32::from(window.viewport_size().height) - 230.0).max(0.0)); - }), - ) - .child(crate::icon_button( - "track-sort", - "icons/arrow-down.svg", - muted, - palette.wash, - cx, - |this, cx| { - this.sort_menu_open = !this.sort_menu_open; - cx.notify(); - }, - )) -} - -/// The sort picker, anchored under the track-list header's sort button. -pub fn sort_menu(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let active = app.state.ui.track_sort; - let selected = app.sort_menu_index; - - div() - .id("sort-backdrop") - .absolute() - .inset_0() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.sort_menu_open = false; - cx.notify(); - })) - .child( - div() - .id("sort-menu") - .absolute() - .right(px(16.0)) - .top(px(app.sort_menu_top)) - .w(px(180.0)) - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .py_1() - .flex() - .flex_col() - .overflow_hidden() - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .children( - SORT_OPTIONS - .iter() - .enumerate() - .map(|(ix, (label_key, arg))| { - let label = tr(&app.state, label_key); - // `reverse` flips the current order rather than naming one, so it never - // shows the active marker. - let is_active = *arg != "reverse" && crate::sort_arg(active) == *arg; - let is_selected = ix == selected; - div() - .id(*arg) - .mx_1() - .px_2() - .py_1() - .rounded_md() - .flex() - .flex_row() - .items_center() - .justify_between() - .text_sm() - .text_color(if is_active { accent } else { fg }) - .when(is_selected, |el| el.bg(palette.menu_selected)) - .when(!is_selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - this.apply_sort(arg, cx); - }, - )) - .child(label) - .when(is_active, |el| { - el.child(div().flex_none().text_color(accent).child("●")) - }) - }), - ), - ) -} - -#[derive(Clone, Copy)] -struct TrackColumns { - album: bool, - added_by: bool, - date: bool, - heart: bool, -} - -fn track_columns(state: &echo_core::app::AppState) -> TrackColumns { - let context = state.data.active_tracklist_context.as_ref(); - TrackColumns { - album: context.is_none_or(|context| !context.is_album()), - added_by: context.is_some_and(|context| { - context.kind == echo_core::models::TrackListContextKind::Playlist - }) && state - .data - .active_context_details - .as_ref() - .is_some_and(|details| !details.collaborators.is_empty()), - date: context.is_some_and(|context| { - context.kind == echo_core::models::TrackListContextKind::Playlist - }), - heart: context.is_none_or(|context| context.id != "LIKED_SONGS"), - } -} - -fn context_hero(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - use echo_core::context_details::header_summary; - let state = &app.state; - let context = state.data.active_tracklist_context.as_ref().unwrap(); - let details = state - .data - .active_context_details - .clone() - .unwrap_or_default(); - let theme = &state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let background = theme.background.gpui(crate::theme::WINDOW_BG()); - let label = tr(state, details.label_key(context)); - let title = SharedString::from(context.title.clone()); - let summary = SharedString::from(header_summary( - context, - &details, - &state.data.tracks, - &|key| tr(state, key).to_string(), - )); - let playing = echo_core::intent::active_context_is_playing(state) && state.playback.is_playing; - let shuffled = - echo_core::intent::active_context_is_playing(state) && state.playback.is_shuffled; - let cover = state - .ui - .active_library_header_image - .clone() - .and_then(|artwork| app.images.get(&artwork)); - let image_url = context.image_url.clone(); - let cover = match cover { - Some(image) => cover_image(image, 160.0, 6.0).into_any_element(), - None => thumb_element(app, image_url.as_deref(), 160.0, false, muted), - }; - div() - .flex_none() - .px_4() - .pt_4() - .flex() - .flex_col() - .gap_3() - .child( - div().flex().items_end().gap_4().child(cover).child( - div() - .min_w_0() - .flex_1() - .flex() - .flex_col() - .gap_2() - .child( - div() - .text_xs() - .text_color(muted) - .child(SharedString::from(label.to_uppercase())), - ) - .child( - div() - .text_size(px(32.0)) - .font_weight(gpui::FontWeight::BOLD) - .line_clamp(2) - .text_color(fg) - .child(title), - ) - .when_some(details.description, |el, description| { - el.child( - div() - .text_sm() - .text_color(muted) - .truncate() - .child(SharedString::from(description)), - ) - }) - .child(div().text_xs().text_color(muted).truncate().child(summary)), - ), - ) - .child( - div() - .flex() - .items_center() - .gap_3() - .pb_3() - .child( - div() - .id("context-play") - .size(px(48.0)) - .rounded_full() - .bg(accent) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .on_click(cx.listener(|this: &mut EchoApp, _, _, cx| { - if let Some(event) = - echo_core::intent::play_context_from_header(&mut this.state) - { - this.dispatch(event); - } - cx.notify(); - })) - .child( - svg() - .path(if playing { - "icons/pause.svg" - } else { - "icons/play.svg" - }) - .size(px(24.0)) - .text_color(background), - ), - ) - .child(crate::icon_button( - "context-shuffle", - "icons/shuffle.svg", - if shuffled { accent } else { muted }, - palette.wash, - cx, - |this, cx| { - for event in echo_core::intent::toggle_context_shuffle(&mut this.state) { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child(playlist_edit::page_buttons(app, cx)) - .child(div().flex_1()) - .child(sort_button(app, cx)), - ) -} - -fn track_column_headers( - app: &EchoApp, - columns: TrackColumns, - cx: &mut Context, -) -> impl IntoElement { - use echo_core::app::TrackSort; - let palette = DesktopPalette::resolve(&app.state.ui.active_theme); - let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); - let cell = |sort, label: SharedString, width: Option, grow: f32| { - div() - .id(SharedString::from(format!("column-{sort:?}"))) - .flex() - .items_center() - .gap_1() - .min_w_0() - .cursor_pointer() - .when_some(width, |el, width| el.flex_none().w(px(width))) - .when(width.is_none(), |el| el.flex_grow(grow).flex_basis(px(0.0))) - .on_click(cx.listener(move |this: &mut EchoApp, _, _, cx| { - echo_core::intent::sort_by_column(&mut this.state, sort); - cx.notify(); - })) - .child(div().truncate().child(label)) - .when(sort == TrackSort::Duration, |el| { - el.child( - svg() - .path("icons/clock.svg") - .size(px(14.0)) - .text_color(muted), - ) - }) - .when(sort == app.state.ui.track_sort, |el| { - el.child( - svg() - .path(if app.state.ui.track_sort_ascending { - "icons/arrow-up.svg" - } else { - "icons/arrow-down.svg" - }) - .size(px(10.0)) - .text_color(muted), - ) - }) - }; - div() - .flex_none() - .mx_4() - .h(px(32.0)) - .flex() - .items_center() - .gap_3() - .text_xs() - .text_color(muted) - .border_b_1() - .border_color(palette.border) - .child(cell(TrackSort::Original, "#".into(), Some(32.0), 0.0)) - .child(cell( - TrackSort::Title, - tr(&app.state, "desktop.context.title"), - None, - 2.0, - )) - .when(columns.album, |el| { - el.child(cell( - TrackSort::Album, - tr(&app.state, "desktop.context.album_column"), - None, - 1.5, - )) - }) - .when(columns.added_by, |el| { - el.child(cell( - TrackSort::AddedBy, - tr(&app.state, "desktop.context.added_by"), - None, - 1.0, - )) - }) - .when(columns.date, |el| { - el.child(cell( - TrackSort::Added, - tr(&app.state, "desktop.context.date_added"), - None, - 1.0, - )) - }) - .when(columns.heart, |el| el.child(div().flex_none().w(px(14.0)))) - .child(cell(TrackSort::Duration, "".into(), Some(48.0), 0.0)) -} - -fn playing_bars(phase: f32, accent: Hsla) -> impl IntoElement { - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - for bar in 0..3 { - let height = 4.0 - + 12.0 - * (phase * std::f32::consts::TAU + bar as f32 * 1.8) - .sin() - .abs(); - window.paint_quad(gpui::fill( - gpui::Bounds::new( - bounds.origin - + gpui::point(px(bar as f32 * 6.0), bounds.size.height - px(height)), - gpui::size(px(3.0), px(height)), - ), - accent, - )); - } - }, - ) - .size(px(18.0)) -} - -fn track_index_cell( - app: &EchoApp, - ix: usize, - selected: usize, - playing: bool, - accent: Hsla, - muted: Hsla, - cx: &mut Context, -) -> impl IntoElement { - let number = row_number(&app.state, ix, selected); - let animate = playing && app.state.playback.is_playing && !cx.reduce_motion(); - let phase = if animate { - app.animate_playing_bars(cx) - } else { - 0.25 - }; - let bars = playing_bars(phase, accent).into_any_element(); - div() - .id(("track-index", ix)) - .relative() - .flex_none() - .w(px(32.0)) - .h(px(24.0)) - .flex() - .items_center() - .on_click(cx.listener(move |this: &mut EchoApp, _, _, cx| { - cx.stop_propagation(); - if let Some(event) = echo_core::intent::play_track_at(&mut this.state, ix) { - this.dispatch(event); - } - cx.notify(); - })) - .child( - div() - .group_hover("track-row", |style| style.invisible()) - .text_color(muted) - .child(if playing { - bars - } else { - div().child(number).into_any_element() - }), - ) - .child( - svg() - .absolute() - .path("icons/play.svg") - .size(px(16.0)) - .text_color(muted) - .invisible() - .group_hover("track-row", |style| style.visible()), - ) -} - -fn track_list( - app: &mut EchoApp, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let wide = app.main_content_width(window) >= 640.0; - let hero = wide - && app - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.requires_worker_load()); - let columns = track_columns(&app.state); - - let (context_title, context_author) = app - .state - .data - .active_tracklist_context - .as_ref() - .map(|context| (context.title.clone(), context.subtitle.clone())) - .unwrap_or_default(); - - let header_image = app - .state - .ui - .active_library_header_image - .clone() - .and_then(|artwork| app.images.get(&artwork)); - - let count = app.state.data.tracks.len(); - let loading = count == 0 && app.state.data.active_context_details.is_none(); - let is_top_tracks = app - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.id == "TOP_TRACKS"); - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child(if hero { - context_hero(app, cx).into_any_element() - } else { - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_row() - .items_center() - .gap_3() - .when_some(header_image.filter(|_| wide), |el, image| { - el.child( - cover_image(image, 72.0, 6.0), - ) - }) - .child( - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .text_lg() - .text_color(fg) - .truncate() - .child(SharedString::from(context_title)), - ) - .when(wide, |el| el.child( - div() - .text_xs() - .text_color(muted) - .truncate() - .child(SharedString::from(context_author)), - )), - ) - .when(is_top_tracks, |el| el.child(range_switcher(app, cx))) - .child(playlist_edit::page_buttons(app, cx)) - .child(sort_button(app, cx)) - .into_any_element() - }) - .child(track_column_headers(app, columns, cx)) - .child(if loading { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.loading")) - .into_any_element() - } else { - uniform_list( - "track-rows", - count, - cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = if this.state.ui.active_view == ActiveView::TrackList { - palette.row_selected - } else { - palette.row_hover - }; - let selected = this.state.ui.selected_track_index; - let visual = visual_range_in(&this.state, ActiveView::TrackList); - let picked = picked_in(&this.state, ActiveView::TrackList); - let context_id = this - .state - .data - .active_tracklist_context - .as_ref() - .map(|context| context.id.clone()); - let playing_id = this.state.playback.playing_track_id.clone(); - let secondary = theme.secondary.gpui(WINDOW_FG()); - // On an album page every row shares the album in the header, so the - // column carries no information. - let in_album = this - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.is_album()); - // Inside Liked Songs every track is liked, so the hearts say nothing. - let in_liked_songs = this - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.id == "LIKED_SONGS"); - // Rows are drag-reorderable only where a reorder can be applied: a - // playlist the user can modify, shown in original order. - let reorderable = this.state.ui.track_sort - == echo_core::app::TrackSort::Original - && this.state.ui.track_sort_ascending - && this - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| { - context.can_modify_playlist(this.state.data.user_id.as_ref()) - }); - let drag_colors = DragColors::resolve(theme); - - let rows = range - .map(|ix| { - let track = this.state.data.tracks[ix].clone(); - let thumb = thumb_element(this, track.image_url.as_deref(), 32.0, false, muted); - let is_liked = this.state.data.liked_tracks.contains(&track.id); - let is_playing = playing_id.as_deref() == Some(track.id.as_str()); - let title_color = if is_playing { accent } else { fg }; - let payload = drag_payload(this, ActiveView::TrackList, ix, &track); - let over_context = context_id.clone(); - let drop_context = context_id.clone(); - - pill_row(ix, TRACK_PILL, row_marked(ix, selected, visual, &picked), selected_bg, palette.row_hover, |row| { - row.gap_3().group("track-row") - .on_drag(payload, move |drag, _offset, _window, cx| { - track_drag_preview(drag, drag_colors, cx) - }) - .when(reorderable, |row| { - row.drag_over::(move |style, drag, _, _| { - if drag.source_context == over_context { - style.bg(palette.drag_target) - } else { - style.border_t_2().border_color(accent) - } - }) - .on_drop(cx.listener( - move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { - let same_list = drag.source_context == drop_context; - if same_list && drag.tracks.len() > 1 { - return; - } - if let Some(event) = - echo_core::intent::drop_tracks_in_tracklist( - &mut this.state, - drag.tracks.clone(), - same_list.then_some(drag.from_row), - Some(ix), - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - }) - .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { - // Shift-click selects from the previously focused row to - // this one — the desktop's version of `v` plus motion. - if event.modifiers().shift { - this.extend_selection_to(ix, cx); - return; - } - this.state.ui.active_view = ActiveView::TrackList; - if is_pick_click(event) { - echo_core::intent::toggle_picked_row(&mut this.state, ix); - cx.notify(); - return; - } - this.state.ui.selected_track_index = ix; - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_track_at(&mut this.state, ix) - { - this.dispatch(event); - } - cx.notify(); - })) - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_track_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }), - ) - .child(track_index_cell(this, ix, selected, is_playing, accent, muted, cx)) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .min_w_0() - .flex().items_center().gap_2() - .child(thumb) - .child(div().min_w_0().flex_1().flex().flex_col() - .child(div() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(title_color) - .child(SharedString::from(track.name.clone()))) - .child(div().flex().items_center().gap_1().text_xs().overflow_hidden() - .when(track.explicit, |el| el.child(div().flex_none().rounded_sm().border_1().border_color(muted).px(px(2.0)).text_size(px(10.0)).text_color(muted).child(tr(&this.state, "desktop.context.explicit")))) - .child({ - let base = div() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_color(muted); - if track.artists.is_empty() { - // Local files and pre-credit caches carry only the - // joined string: one span, go-to-artist fallback. - base.id(("track-artist", ix)) - .text_ellipsis() - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { - cx.stop_propagation(); - if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { - this.go_to(ctx, ActionMenuAction::GoToArtist, cx); - } - })) - .child(SharedString::from(track.artist.clone())) - .into_any_element() - } else { - let mut cell = base.flex().flex_row().items_center(); - for (k, credit) in track.artists.iter().enumerate() { - if k > 0 { - cell = cell.child(div().flex_none().child(SharedString::from(", "))); - } - let name = SharedString::from(credit.name.clone()); - cell = cell.child(match credit.id.clone() { - Some(id) => { - let artist_name = credit.name.clone(); - div() - .id(SharedString::from(format!("track-artist-{ix}-{k}"))) - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { - cx.stop_propagation(); - this.open_artist(id.clone(), artist_name.clone(), cx); - })) - .child(name) - .into_any_element() - } - None => div().child(name).into_any_element(), - }); - } - cell.into_any_element() - } - }))), - ) - .when(!in_album, |row| { - row.child( - div() - .id(("track-album", ix)) - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { - cx.stop_propagation(); - if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { - this.go_to(ctx, ActionMenuAction::GoToAlbum, cx); - } - })) - .child(SharedString::from(track.album.clone())), - ) - }) - .when(columns.added_by, |row| row.child(div().flex_grow(1.0).flex_basis(px(0.0)).min_w_0().truncate().text_color(muted).child(SharedString::from(track.added_by.clone().unwrap_or_default())))) - .when(columns.date, |row| row.child(div().flex_grow(1.0).flex_basis(px(0.0)).min_w_0().truncate().text_color(muted).child(SharedString::from(echo_core::context_details::format_added_at_with(std::time::SystemTime::now().into(), track.added_at.as_deref().unwrap_or_default(), &|key| tr(&this.state, key).to_string()))))) - .when(!in_liked_songs, |row| { - row.child(liked_cell( - "tracks", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - }) - .child( - div() - .flex_none() - .w(px(48.0)) - .text_color(muted) - .child(SharedString::from(format_time(track.duration_ms))), - ) - }) - }) - .collect(); - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }), - ) - .track_scroll(&app.tracks_scroll) - .on_drag_move(cx.listener( - |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { - this.drag_autoscroll(crate::DragList::Tracks, event.event.position.y, event.bounds, cx); - }, - )) - .on_drop(cx.listener( - |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { - // A drop past the last row appends; drops on rows never reach here. - let same_list = drag.source_context.is_some() - && drag.source_context - == this.state.data.active_tracklist_context.as_ref().map(|c| c.id.clone()); - if same_list && drag.tracks.len() > 1 { - return; - } - if let Some(event) = echo_core::intent::drop_tracks_in_tracklist( - &mut this.state, - drag.tracks.clone(), - same_list.then_some(drag.from_row), - None, - ) { - this.dispatch(event); - } - cx.notify(); - }, - )) - .flex_grow(1.0) - .into_any_element() - }) -} - fn queue_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { let theme = &app.state.ui.active_theme; let fg = theme.text.gpui(WINDOW_FG()); diff --git a/crates/echo-desktop/src/views/track_list.rs b/crates/echo-desktop/src/views/track_list.rs new file mode 100644 index 0000000..bc769fd --- /dev/null +++ b/crates/echo-desktop/src/views/track_list.rs @@ -0,0 +1,819 @@ +use super::*; + +pub const SORT_OPTIONS: &[(&str, &str)] = &[ + ("desktop.sort.original", "original"), + ("desktop.sort.title", "title"), + ("ui.artist", "artist"), + ("ui.album", "album"), + ("ui.duration", "duration"), + ("desktop.sort.added", "added"), + ("desktop.context.added_by", "addedby"), + ("desktop.sort.reverse", "reverse"), +]; + +fn sort_button(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + div() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this: &mut EchoApp, event: &MouseDownEvent, window, _cx| { + this.sort_menu_top = (f32::from(event.position.y) + 16.0) + .min((f32::from(window.viewport_size().height) - 230.0).max(0.0)); + }), + ) + .child(crate::icon_button( + "track-sort", + "icons/arrow-down.svg", + muted, + palette.wash, + cx, + |this, cx| { + this.sort_menu_open = !this.sort_menu_open; + cx.notify(); + }, + )) +} + +/// The sort picker, anchored under the track-list header's sort button. +pub fn sort_menu(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let active = app.state.ui.track_sort; + let selected = app.sort_menu_index; + + div() + .id("sort-backdrop") + .absolute() + .inset_0() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.sort_menu_open = false; + cx.notify(); + })) + .child( + div() + .id("sort-menu") + .absolute() + .right(px(16.0)) + .top(px(app.sort_menu_top)) + .w(px(180.0)) + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .py_1() + .flex() + .flex_col() + .overflow_hidden() + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .children( + SORT_OPTIONS + .iter() + .enumerate() + .map(|(ix, (label_key, arg))| { + let label = tr(&app.state, label_key); + // `reverse` flips the current order rather than naming one, so it never + // shows the active marker. + let is_active = *arg != "reverse" && crate::sort_arg(active) == *arg; + let is_selected = ix == selected; + div() + .id(*arg) + .mx_1() + .px_2() + .py_1() + .rounded_md() + .flex() + .flex_row() + .items_center() + .justify_between() + .text_sm() + .text_color(if is_active { accent } else { fg }) + .when(is_selected, |el| el.bg(palette.menu_selected)) + .when(!is_selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + this.apply_sort(arg, cx); + }, + )) + .child(label) + .when(is_active, |el| { + el.child(div().flex_none().text_color(accent).child("●")) + }) + }), + ), + ) +} + +#[derive(Clone, Copy)] +struct TrackColumns { + album: bool, + added_by: bool, + date: bool, + heart: bool, +} + +fn track_columns(state: &echo_core::app::AppState) -> TrackColumns { + let context = state.data.active_tracklist_context.as_ref(); + TrackColumns { + album: context.is_none_or(|context| !context.is_album()), + added_by: context.is_some_and(|context| { + context.kind == echo_core::models::TrackListContextKind::Playlist + }) && state + .data + .active_context_details + .as_ref() + .is_some_and(|details| !details.collaborators.is_empty()), + date: context.is_some_and(|context| { + context.kind == echo_core::models::TrackListContextKind::Playlist + }), + heart: context.is_none_or(|context| context.id != "LIKED_SONGS"), + } +} + +fn context_hero(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + use echo_core::context_details::header_summary; + let state = &app.state; + let context = state.data.active_tracklist_context.as_ref().unwrap(); + let details = state + .data + .active_context_details + .clone() + .unwrap_or_default(); + let theme = &state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let background = theme.background.gpui(crate::theme::WINDOW_BG()); + let label = tr(state, details.label_key(context)); + let title = SharedString::from(context.title.clone()); + let summary = SharedString::from(header_summary( + context, + &details, + &state.data.tracks, + &|key| tr(state, key).to_string(), + )); + let playing = echo_core::intent::active_context_is_playing(state) && state.playback.is_playing; + let shuffled = + echo_core::intent::active_context_is_playing(state) && state.playback.is_shuffled; + let cover = state + .ui + .active_library_header_image + .clone() + .and_then(|artwork| app.images.get(&artwork)); + let image_url = context.image_url.clone(); + let cover = match cover { + Some(image) => cover_image(image, 160.0, 6.0).into_any_element(), + None => thumb_element(app, image_url.as_deref(), 160.0, false, muted), + }; + div() + .flex_none() + .px_4() + .pt_4() + .flex() + .flex_col() + .gap_3() + .child( + div().flex().items_end().gap_4().child(cover).child( + div() + .min_w_0() + .flex_1() + .flex() + .flex_col() + .gap_2() + .child( + div() + .text_xs() + .text_color(muted) + .child(SharedString::from(label.to_uppercase())), + ) + .child( + div() + .text_size(px(32.0)) + .font_weight(gpui::FontWeight::BOLD) + .line_clamp(2) + .text_color(fg) + .child(title), + ) + .when_some(details.description, |el, description| { + el.child( + div() + .text_sm() + .text_color(muted) + .truncate() + .child(SharedString::from(description)), + ) + }) + .child(div().text_xs().text_color(muted).truncate().child(summary)), + ), + ) + .child( + div() + .flex() + .items_center() + .gap_3() + .pb_3() + .child( + div() + .id("context-play") + .size(px(48.0)) + .rounded_full() + .bg(accent) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .on_click(cx.listener(|this: &mut EchoApp, _, _, cx| { + if let Some(event) = + echo_core::intent::play_context_from_header(&mut this.state) + { + this.dispatch(event); + } + cx.notify(); + })) + .child( + svg() + .path(if playing { + "icons/pause.svg" + } else { + "icons/play.svg" + }) + .size(px(24.0)) + .text_color(background), + ), + ) + .child(crate::icon_button( + "context-shuffle", + "icons/shuffle.svg", + if shuffled { accent } else { muted }, + palette.wash, + cx, + |this, cx| { + for event in echo_core::intent::toggle_context_shuffle(&mut this.state) { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child(playlist_edit::page_buttons(app, cx)) + .child(div().flex_1()) + .child(sort_button(app, cx)), + ) +} + +fn track_column_headers( + app: &EchoApp, + columns: TrackColumns, + cx: &mut Context, +) -> impl IntoElement { + use echo_core::app::TrackSort; + let palette = DesktopPalette::resolve(&app.state.ui.active_theme); + let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); + let cell = |sort, label: SharedString, width: Option, grow: f32| { + div() + .id(SharedString::from(format!("column-{sort:?}"))) + .flex() + .items_center() + .gap_1() + .min_w_0() + .cursor_pointer() + .when_some(width, |el, width| el.flex_none().w(px(width))) + .when(width.is_none(), |el| el.flex_grow(grow).flex_basis(px(0.0))) + .on_click(cx.listener(move |this: &mut EchoApp, _, _, cx| { + echo_core::intent::sort_by_column(&mut this.state, sort); + cx.notify(); + })) + .child(div().truncate().child(label)) + .when(sort == TrackSort::Duration, |el| { + el.child( + svg() + .path("icons/clock.svg") + .size(px(14.0)) + .text_color(muted), + ) + }) + .when(sort == app.state.ui.track_sort, |el| { + el.child( + svg() + .path(if app.state.ui.track_sort_ascending { + "icons/arrow-up.svg" + } else { + "icons/arrow-down.svg" + }) + .size(px(10.0)) + .text_color(muted), + ) + }) + }; + div() + .flex_none() + .mx_4() + .h(px(32.0)) + .flex() + .items_center() + .gap_3() + .text_xs() + .text_color(muted) + .border_b_1() + .border_color(palette.border) + .child(cell(TrackSort::Original, "#".into(), Some(32.0), 0.0)) + .child(cell( + TrackSort::Title, + tr(&app.state, "desktop.context.title"), + None, + 2.0, + )) + .when(columns.album, |el| { + el.child(cell( + TrackSort::Album, + tr(&app.state, "desktop.context.album_column"), + None, + 1.5, + )) + }) + .when(columns.added_by, |el| { + el.child(cell( + TrackSort::AddedBy, + tr(&app.state, "desktop.context.added_by"), + None, + 1.0, + )) + }) + .when(columns.date, |el| { + el.child(cell( + TrackSort::Added, + tr(&app.state, "desktop.context.date_added"), + None, + 1.0, + )) + }) + .when(columns.heart, |el| el.child(div().flex_none().w(px(14.0)))) + .child(cell(TrackSort::Duration, "".into(), Some(48.0), 0.0)) +} + +pub(super) fn playing_bars(phase: f32, accent: Hsla) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + for bar in 0..3 { + let height = 4.0 + + 12.0 + * (phase * std::f32::consts::TAU + bar as f32 * 1.8) + .sin() + .abs(); + window.paint_quad(gpui::fill( + gpui::Bounds::new( + bounds.origin + + gpui::point(px(bar as f32 * 6.0), bounds.size.height - px(height)), + gpui::size(px(3.0), px(height)), + ), + accent, + )); + } + }, + ) + .size(px(18.0)) +} + +fn track_index_cell( + app: &EchoApp, + ix: usize, + selected: usize, + playing: bool, + accent: Hsla, + muted: Hsla, + cx: &mut Context, +) -> impl IntoElement { + let number = row_number(&app.state, ix, selected); + let animate = playing && app.state.playback.is_playing && !cx.reduce_motion(); + let phase = if animate { + app.animate_playing_bars(cx) + } else { + 0.25 + }; + let bars = playing_bars(phase, accent).into_any_element(); + div() + .id(("track-index", ix)) + .relative() + .flex_none() + .w(px(32.0)) + .h(px(24.0)) + .flex() + .items_center() + .on_click(cx.listener(move |this: &mut EchoApp, _, _, cx| { + cx.stop_propagation(); + if let Some(event) = echo_core::intent::play_track_at(&mut this.state, ix) { + this.dispatch(event); + } + cx.notify(); + })) + .child( + div() + .group_hover("track-row", |style| style.invisible()) + .text_color(muted) + .child(if playing { + bars + } else { + div().child(number).into_any_element() + }), + ) + .child( + svg() + .absolute() + .path("icons/play.svg") + .size(px(16.0)) + .text_color(muted) + .invisible() + .group_hover("track-row", |style| style.visible()), + ) +} + +pub(super) fn track_list( + app: &mut EchoApp, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let wide = app.main_content_width(window) >= 640.0; + let hero = wide + && app + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.requires_worker_load()); + let columns = track_columns(&app.state); + + let (context_title, context_author) = app + .state + .data + .active_tracklist_context + .as_ref() + .map(|context| (context.title.clone(), context.subtitle.clone())) + .unwrap_or_default(); + + let header_image = app + .state + .ui + .active_library_header_image + .clone() + .and_then(|artwork| app.images.get(&artwork)); + + let count = app.state.data.tracks.len(); + let loading = count == 0 && app.state.data.active_context_details.is_none(); + let is_top_tracks = app + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.id == "TOP_TRACKS"); + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child(if hero { + context_hero(app, cx).into_any_element() + } else { + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_row() + .items_center() + .gap_3() + .when_some(header_image.filter(|_| wide), |el, image| { + el.child( + cover_image(image, 72.0, 6.0), + ) + }) + .child( + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .text_lg() + .text_color(fg) + .truncate() + .child(SharedString::from(context_title)), + ) + .when(wide, |el| el.child( + div() + .text_xs() + .text_color(muted) + .truncate() + .child(SharedString::from(context_author)), + )), + ) + .when(is_top_tracks, |el| el.child(range_switcher(app, cx))) + .child(playlist_edit::page_buttons(app, cx)) + .child(sort_button(app, cx)) + .into_any_element() + }) + .child(track_column_headers(app, columns, cx)) + .child(if loading { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.loading")) + .into_any_element() + } else { + uniform_list( + "track-rows", + count, + cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = if this.state.ui.active_view == ActiveView::TrackList { + palette.row_selected + } else { + palette.row_hover + }; + let selected = this.state.ui.selected_track_index; + let visual = visual_range_in(&this.state, ActiveView::TrackList); + let picked = picked_in(&this.state, ActiveView::TrackList); + let context_id = this + .state + .data + .active_tracklist_context + .as_ref() + .map(|context| context.id.clone()); + let playing_id = this.state.playback.playing_track_id.clone(); + let secondary = theme.secondary.gpui(WINDOW_FG()); + // On an album page every row shares the album in the header, so the + // column carries no information. + let in_album = this + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.is_album()); + // Inside Liked Songs every track is liked, so the hearts say nothing. + let in_liked_songs = this + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.id == "LIKED_SONGS"); + // Rows are drag-reorderable only where a reorder can be applied: a + // playlist the user can modify, shown in original order. + let reorderable = this.state.ui.track_sort + == echo_core::app::TrackSort::Original + && this.state.ui.track_sort_ascending + && this + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| { + context.can_modify_playlist(this.state.data.user_id.as_ref()) + }); + let drag_colors = DragColors::resolve(theme); + + let rows = range + .map(|ix| { + let track = this.state.data.tracks[ix].clone(); + let thumb = thumb_element(this, track.image_url.as_deref(), 32.0, false, muted); + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let is_playing = playing_id.as_deref() == Some(track.id.as_str()); + let title_color = if is_playing { accent } else { fg }; + let payload = drag_payload(this, ActiveView::TrackList, ix, &track); + let over_context = context_id.clone(); + let drop_context = context_id.clone(); + + pill_row(ix, TRACK_PILL, row_marked(ix, selected, visual, &picked), selected_bg, palette.row_hover, |row| { + row.gap_3().group("track-row") + .on_drag(payload, move |drag, _offset, _window, cx| { + track_drag_preview(drag, drag_colors, cx) + }) + .when(reorderable, |row| { + row.drag_over::(move |style, drag, _, _| { + if drag.source_context == over_context { + style.bg(palette.drag_target) + } else { + style.border_t_2().border_color(accent) + } + }) + .on_drop(cx.listener( + move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { + let same_list = drag.source_context == drop_context; + if same_list && drag.tracks.len() > 1 { + return; + } + if let Some(event) = + echo_core::intent::drop_tracks_in_tracklist( + &mut this.state, + drag.tracks.clone(), + same_list.then_some(drag.from_row), + Some(ix), + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + }) + .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + // Shift-click selects from the previously focused row to + // this one — the desktop's version of `v` plus motion. + if event.modifiers().shift { + this.extend_selection_to(ix, cx); + return; + } + this.state.ui.active_view = ActiveView::TrackList; + if is_pick_click(event) { + echo_core::intent::toggle_picked_row(&mut this.state, ix); + cx.notify(); + return; + } + this.state.ui.selected_track_index = ix; + if event.click_count() >= 2 + && let Some(event) = + echo_core::intent::play_track_at(&mut this.state, ix) + { + this.dispatch(event); + } + cx.notify(); + })) + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.selected_track_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }), + ) + .child(track_index_cell(this, ix, selected, is_playing, accent, muted, cx)) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .min_w_0() + .flex().items_center().gap_2() + .child(thumb) + .child(div().min_w_0().flex_1().flex().flex_col() + .child(div() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(title_color) + .child(SharedString::from(track.name.clone()))) + .child(div().flex().items_center().gap_1().text_xs().overflow_hidden() + .when(track.explicit, |el| el.child(div().flex_none().rounded_sm().border_1().border_color(muted).px(px(2.0)).text_size(px(10.0)).text_color(muted).child(tr(&this.state, "desktop.context.explicit")))) + .child({ + let base = div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_color(muted); + if track.artists.is_empty() { + // Local files and pre-credit caches carry only the + // joined string: one span, go-to-artist fallback. + base.id(("track-artist", ix)) + .text_ellipsis() + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { + cx.stop_propagation(); + if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { + this.go_to(ctx, ActionMenuAction::GoToArtist, cx); + } + })) + .child(SharedString::from(track.artist.clone())) + .into_any_element() + } else { + let mut cell = base.flex().flex_row().items_center(); + for (k, credit) in track.artists.iter().enumerate() { + if k > 0 { + cell = cell.child(div().flex_none().child(SharedString::from(", "))); + } + let name = SharedString::from(credit.name.clone()); + cell = cell.child(match credit.id.clone() { + Some(id) => { + let artist_name = credit.name.clone(); + div() + .id(SharedString::from(format!("track-artist-{ix}-{k}"))) + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { + cx.stop_propagation(); + this.open_artist(id.clone(), artist_name.clone(), cx); + })) + .child(name) + .into_any_element() + } + None => div().child(name).into_any_element(), + }); + } + cell.into_any_element() + } + }))), + ) + .when(!in_album, |row| { + row.child( + div() + .id(("track-album", ix)) + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { + cx.stop_propagation(); + if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { + this.go_to(ctx, ActionMenuAction::GoToAlbum, cx); + } + })) + .child(SharedString::from(track.album.clone())), + ) + }) + .when(columns.added_by, |row| row.child(div().flex_grow(1.0).flex_basis(px(0.0)).min_w_0().truncate().text_color(muted).child(SharedString::from(track.added_by.clone().unwrap_or_default())))) + .when(columns.date, |row| row.child(div().flex_grow(1.0).flex_basis(px(0.0)).min_w_0().truncate().text_color(muted).child(SharedString::from(echo_core::context_details::format_added_at_with(std::time::SystemTime::now().into(), track.added_at.as_deref().unwrap_or_default(), &|key| tr(&this.state, key).to_string()))))) + .when(!in_liked_songs, |row| { + row.child(liked_cell( + "tracks", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + }) + .child( + div() + .flex_none() + .w(px(48.0)) + .text_color(muted) + .child(SharedString::from(format_time(track.duration_ms))), + ) + }) + }) + .collect(); + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows + }), + ) + .track_scroll(&app.tracks_scroll) + .on_drag_move(cx.listener( + |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { + this.drag_autoscroll(crate::DragList::Tracks, event.event.position.y, event.bounds, cx); + }, + )) + .on_drop(cx.listener( + |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { + // A drop past the last row appends; drops on rows never reach here. + let same_list = drag.source_context.is_some() + && drag.source_context + == this.state.data.active_tracklist_context.as_ref().map(|c| c.id.clone()); + if same_list && drag.tracks.len() > 1 { + return; + } + if let Some(event) = echo_core::intent::drop_tracks_in_tracklist( + &mut this.state, + drag.tracks.clone(), + same_list.then_some(drag.from_row), + None, + ) { + this.dispatch(event); + } + cx.notify(); + }, + )) + .flex_grow(1.0) + .into_any_element() + }) +} From 7101e6b5792a6a5b4049c754cac11285f800eb23 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:07 -0500 Subject: [PATCH 07/44] desktop: move the queue and recently played lists into views/queue.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 665 +----------------------- crates/echo-desktop/src/views/queue.rs | 668 +++++++++++++++++++++++++ 2 files changed, 670 insertions(+), 663 deletions(-) create mode 100644 crates/echo-desktop/src/views/queue.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 11c4f9f..30c65b5 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -18,6 +18,7 @@ mod drag; mod menu_placement; pub(crate) mod panel_layout; mod playlist_edit; +mod queue; mod search; mod sidebar; mod track_list; @@ -30,6 +31,7 @@ use gpui::{ }; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; +use queue::*; pub(crate) use sidebar::*; pub(crate) use track_list::*; @@ -148,9 +150,6 @@ const ECHO_LOGO: [&str; 6] = [ "╚══════╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝", ]; -/// A queue row cloned out of the state: its row index and either a header or `(track index, track)`. -type OwnedQueueRow = (usize, Result<(usize, echo_core::models::Track), String>); - /// The picked rows of `view`, when it is the one on screen. fn picked_in( state: &echo_core::app::AppState, @@ -674,462 +673,6 @@ fn search_bar( )) } -fn queue_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - - let count = app.state.data.queue.len(); - let row_count = app.state.queue_rows().len(); - let recent = app.state.ui.queue_tab == QueueTab::Recent; - let subtitle = if recent { - tr(&app.state, "ui.recently_played").to_string() - } else { - tr(&app.state, "desktop.queue_upcoming").replace("{}", &count.to_string()) - }; - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_col() - .child(div().text_lg().text_color(fg).child(tr(&app.state, "ui.queue"))) - .child( - div() - .text_xs() - .text_color(muted) - .child(SharedString::from(subtitle)), - ) - .child(queue_tab_strip(app, cx)), - ) - .child(if recent { - recent_list(app, cx).into_any_element() - } else if count == 0 { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.queue_empty")) - .into_any_element() - } else { - uniform_list( - "queue-rows", - row_count, - cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - let secondary = theme.secondary.gpui(WINDOW_FG()); - let selected = this.state.ui.selected_queue_index; - let visual = visual_range_in(&this.state, ActiveView::Queue); - let picked = picked_in(&this.state, ActiveView::Queue); - let has_manual = !this.state.data.manual_queue.is_empty(); - let drag_colors = DragColors::resolve(theme); - // Cloned out first: the rows borrow the state the drag payload below mutates. - let rows: Vec = { - let rows = this.state.queue_rows(); - range - .map(|row_ix| { - let row = match &rows[row_ix] { - QueueRow::Header(text) => Err(text.clone()), - QueueRow::Track(ix, track) => Ok((*ix, (*track).clone())), - }; - (row_ix, row) - }) - .collect() - }; - - rows.into_iter() - .map(|(row_ix, row)| match row { - Err(text) => queue_header( - text, - (row_ix == 0 && has_manual).then(|| tr(&this.state, "actions.clear_queue")), - COMPACT_PILL, - fg, - muted, - cx, - ), - Ok((ix, track)) => { - let is_liked = this.state.data.liked_tracks.contains(&track.id); - let payload = drag_payload(this, ActiveView::Queue, ix, &track); - - pill_row(ix, COMPACT_PILL, row_marked(ix, selected, visual, &picked), selected_bg, palette.row_hover, |row| { - row.gap_3() - .on_drag(payload, move |drag, _offset, _window, cx| { - track_drag_preview(drag, drag_colors, cx) - }) - .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { - if event.modifiers().shift { - this.extend_selection_to(ix, cx); - return; - } - if is_pick_click(event) { - echo_core::intent::toggle_picked_row(&mut this.state, ix); - cx.notify(); - return; - } - this.state.ui.selected_queue_index = ix; - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_queue_track_at(&mut this.state, ix) - { - this.dispatch(event); - } - cx.notify(); - })) - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_queue_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }), - ) - .child(div() - .flex_none() - .w(px(32.0)) - .text_color(muted) - .child(row_number(&this.state, ix, selected)),) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(track.name.clone())), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from(track.artist.clone())), - ) - .child(liked_cell( - "queue", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - .child( - div() - .flex_none() - .w(px(48.0)) - .text_color(muted) - .child(SharedString::from(format_time(track.duration_ms))), - ) - }) - .into_any_element() - } - }) - .collect() - }), - ) - .track_scroll(&app.queue_scroll) - .flex_grow(1.0) - .into_any_element() - }) -} - -fn queue_tab_strip(app: &EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let active = app.state.ui.queue_tab; - let tabs = [ - ( - QueueTab::Queue, - "queue-tab-queue", - tr(&app.state, "ui.queue"), - ), - ( - QueueTab::Recent, - "queue-tab-recent", - tr(&app.state, "ui.recent"), - ), - ]; - div() - .mt_2() - .flex() - .gap_2() - .children(tabs.into_iter().map(|(tab, id, label)| { - let is_active = tab == active; - div() - .id(id) - .cursor_pointer() - .px_3() - .py_1() - .rounded_md() - .text_sm() - .text_color(if is_active { fg } else { muted }) - .when(is_active, |el| el.bg(palette.row_selected)) - .when(!is_active, |el| { - el.hover(move |style| style.bg(palette.row_hover)) - }) - .child(label) - .on_click(cx.listener( - move |this: &mut EchoApp, _: &gpui::ClickEvent, _window, cx| { - if this.state.ui.queue_tab != tab { - echo_core::intent::cycle_queue_tab(&mut this.state); - } - cx.notify(); - }, - )) - })) -} - -fn recent_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); - let row_count = app.state.data.recent_plays.len(); - if row_count == 0 { - return div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.recent_empty")) - .into_any_element(); - } - uniform_list( - "recent-rows", - row_count, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let secondary = theme.secondary.gpui(WINDOW_FG()); - let selected = this.state.ui.selected_queue_index; - let visual = visual_range_in(&this.state, ActiveView::Queue); - let picked = picked_in(&this.state, ActiveView::Queue); - let drag_colors = DragColors::resolve(theme); - let now = std::time::SystemTime::now().into(); - // Cloned out first: the records borrow the state the drag payload below mutates. - let rows: Vec<(usize, echo_core::models::Track, String)> = range - .filter_map(|ix| { - let record = this.state.data.recent_plays.get(ix)?; - let played = echo_core::context_details::format_added_at_with( - now, - &record.played_at, - &|key| tr(&this.state, key).to_string(), - ); - Some((ix, record.track.clone(), played)) - }) - .collect(); - - rows.into_iter() - .map(|(ix, track, played)| { - let is_liked = this.state.data.liked_tracks.contains(&track.id); - let payload = drag_payload(this, ActiveView::Queue, ix, &track); - - pill_row( - ix, - COMPACT_PILL, - row_marked(ix, selected, visual, &picked), - palette.row_selected, - palette.row_hover, - |row| { - row.gap_3() - .on_drag(payload, move |drag, _offset, _window, cx| { - track_drag_preview(drag, drag_colors, cx) - }) - .on_click(cx.listener( - move |this: &mut EchoApp, - event: &gpui::ClickEvent, - _window, - cx| { - if event.modifiers().shift { - this.extend_selection_to(ix, cx); - return; - } - if is_pick_click(event) { - echo_core::intent::toggle_picked_row( - &mut this.state, - ix, - ); - cx.notify(); - return; - } - this.state.ui.selected_queue_index = ix; - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_queue_track_at( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .on_mouse_down( - MouseButton::Right, - cx.listener( - move |this: &mut EchoApp, - event: &MouseDownEvent, - _window, - cx| { - this.state.ui.selected_queue_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }, - ), - ) - .child( - div() - .flex_none() - .w(px(32.0)) - .text_color(muted) - .child(row_number(&this.state, ix, selected)), - ) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(track.name.clone())), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from(track.artist.clone())), - ) - .child(liked_cell( - "recent", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - .child( - div() - .flex_none() - .w(px(112.0)) - .text_xs() - .text_color(muted) - .child(SharedString::from(played)), - ) - }, - ) - .into_any_element() - }) - .collect() - }, - ), - ) - .track_scroll(&app.queue_scroll) - .flex_grow(1.0) - .into_any_element() -} - -/// A section label inside a queue list. `uniform_list` takes its row pitch from row 0, which is -/// always a header, so the header has to be as tall as the track rows of the list it sits in: -/// `metrics` is that list's. In rows taller than the compact ones the label drops to the bottom -/// edge, next to the tracks it names. -fn queue_header( - text: String, - clear_label: Option, - metrics: PillMetrics, - fg: Hsla, - muted: Hsla, - cx: &mut Context, -) -> gpui::AnyElement { - div() - .w_full() - .h(px(metrics.row_height)) - .px_4() - .flex() - .map(|el| { - if metrics.row_height > COMPACT_PILL.row_height { - el.items_end().pb_1() - } else { - el.items_center() - } - }) - .justify_between() - .gap_2() - .text_xs() - .text_color(muted) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(SharedString::from(text)), - ) - .when_some(clear_label, |el, label| { - el.child( - div() - .id("clear-queue") - .flex_none() - .max_w(relative(0.6)) - .truncate() - .cursor_pointer() - .text_color(fg) - .hover(move |style| style.text_color(muted)) - .child(label) - .on_click(cx.listener( - |this: &mut EchoApp, _: &gpui::ClickEvent, _window, cx| { - if let Some(event) = echo_core::intent::clear_queue(&mut this.state) { - this.dispatch(event); - } - cx.notify(); - }, - )), - ) - }) - .into_any_element() -} - /// "Playing from {}" label for the playback bar, resolving the playing context id to a /// name from whatever state already holds it (loaded track list, library lists, artist /// page, What's New). Falls back to a generic "a playlist"/"an album" when the id is not @@ -2804,210 +2347,6 @@ pub fn right_panel( .into_any_element() } -/// The queue panel: the playing track on top, then the same rows as the full queue view in a -/// narrower two-line layout. Double-click plays a row, right-click opens its track menu; the -/// keyboard-driven selection stays with the full view. -fn queue_panel_body(app: &mut EchoApp, width: f32, cx: &mut Context) -> AnyElement { - let show_duration = panel_layout::show_queue_duration(width); - let theme = &app.state.ui.active_theme; - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let playback = &app.state.playback; - let now_playing = playback.playing_track_id.is_some().then(|| { - ( - SharedString::from(playback.playing_track_title.clone()), - SharedString::from(playback.playing_track_artist.clone()), - playback - .playing_track_image - .as_ref() - .or(playback.previous_track_image.as_ref()) - .cloned() - .and_then(|artwork| app.images.get(&artwork)), - ) - }); - let row_count = app.state.queue_rows().len(); - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .when_some(now_playing, |el, (title, artist, cover)| { - el.child( - div() - .flex_none() - .px_4() - .pb_1() - .text_xs() - .text_color(muted) - .child(tr(&app.state, "desktop.now_playing")), - ) - .child( - div() - .flex_none() - .mx_2() - .px_2() - .h(px(TRACK_PILL.pill_height)) - .flex() - .flex_row() - .items_center() - .gap_3() - .child(match cover { - Some(image) => cover_image(image, 32.0, 4.0).into_any_element(), - None => div() - .flex_none() - .size(px(32.0)) - .rounded_sm() - .bg(palette.wash) - .into_any_element(), - }) - .child( - div() - .min_w_0() - .flex_grow(1.0) - .flex() - .flex_col() - .child( - div() - .text_sm() - .text_color(accent) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(title), - ) - .child( - div() - .text_xs() - .text_color(muted) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(artist), - ), - ), - ) - }) - .child(if row_count == 0 { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.queue_empty")) - .into_any_element() - } else { - uniform_list( - "queue-panel-rows", - row_count, - cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let has_manual = !this.state.data.manual_queue.is_empty(); - // Cloned out first: the rows borrow the state the thumbnails below mutate. - let rows: Vec<(usize, Option, Option)> = { - let rows = this.state.queue_rows(); - range - .map(|row_ix| match &rows[row_ix] { - QueueRow::Header(text) => (row_ix, Some(text.clone()), None), - QueueRow::Track(ix, track) => (*ix, None, Some((*track).clone())), - }) - .collect() - }; - - rows.into_iter() - .map(|(ix, header, track)| { - if let Some(text) = header { - return queue_header( - text, - (ix == 0 && has_manual).then(|| tr(&this.state, "actions.clear_queue")), - TRACK_PILL, - fg, - muted, - cx, - ); - } - let Some(track) = track else { - return div().into_any_element(); - }; - let thumb = thumb_element(this, track.image_url.as_deref(), 32.0, false, muted); - let ctx = ActionMenuContext::from(&track); - pill_row(ix, TRACK_PILL, false, palette.row_selected, palette.row_hover, |row| { - row.gap_3() - .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_queue_track_at(&mut this.state, ix) - { - this.dispatch(event); - } - cx.notify(); - })) - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.context_menu = None; - this.track_menu = Some(crate::TrackMenuState { - ctx: ctx.clone(), - position: Some(event.position), - selected: 0, - submenu: None, - }); - cx.notify(); - }), - ) - .child(thumb) - .child( - div() - .min_w_0() - .flex_grow(1.0) - .flex() - .flex_col() - .child( - div() - .text_sm() - .text_color(fg) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(SharedString::from(track.name.clone())), - ) - .child( - div() - .text_xs() - .text_color(muted) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(SharedString::from(track.artist.clone())), - ), - ) - .when(show_duration, |row| { - row.child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(format_time(track.duration_ms))), - ) - }) - }) - .into_any_element() - }) - .collect() - }), - ) - .track_scroll(&app.queue_panel_scroll) - .flex_grow(1.0) - .into_any_element() - }) - .into_any_element() -} - /// The backdrop's picture over the whole window, under everything else: the keyframe before /// `phase` with the one after it crossfaded on top. Painted straight from the texture as a fill /// (its guard border just outside the window) rather than through `img`, which takes the diff --git a/crates/echo-desktop/src/views/queue.rs b/crates/echo-desktop/src/views/queue.rs new file mode 100644 index 0000000..a9cdeba --- /dev/null +++ b/crates/echo-desktop/src/views/queue.rs @@ -0,0 +1,668 @@ +use super::*; + +/// A queue row cloned out of the state: its row index and either a header or `(track index, track)`. +type OwnedQueueRow = (usize, Result<(usize, echo_core::models::Track), String>); + +pub(super) fn queue_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + + let count = app.state.data.queue.len(); + let row_count = app.state.queue_rows().len(); + let recent = app.state.ui.queue_tab == QueueTab::Recent; + let subtitle = if recent { + tr(&app.state, "ui.recently_played").to_string() + } else { + tr(&app.state, "desktop.queue_upcoming").replace("{}", &count.to_string()) + }; + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_col() + .child(div().text_lg().text_color(fg).child(tr(&app.state, "ui.queue"))) + .child( + div() + .text_xs() + .text_color(muted) + .child(SharedString::from(subtitle)), + ) + .child(queue_tab_strip(app, cx)), + ) + .child(if recent { + recent_list(app, cx).into_any_element() + } else if count == 0 { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.queue_empty")) + .into_any_element() + } else { + uniform_list( + "queue-rows", + row_count, + cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + let secondary = theme.secondary.gpui(WINDOW_FG()); + let selected = this.state.ui.selected_queue_index; + let visual = visual_range_in(&this.state, ActiveView::Queue); + let picked = picked_in(&this.state, ActiveView::Queue); + let has_manual = !this.state.data.manual_queue.is_empty(); + let drag_colors = DragColors::resolve(theme); + // Cloned out first: the rows borrow the state the drag payload below mutates. + let rows: Vec = { + let rows = this.state.queue_rows(); + range + .map(|row_ix| { + let row = match &rows[row_ix] { + QueueRow::Header(text) => Err(text.clone()), + QueueRow::Track(ix, track) => Ok((*ix, (*track).clone())), + }; + (row_ix, row) + }) + .collect() + }; + + rows.into_iter() + .map(|(row_ix, row)| match row { + Err(text) => queue_header( + text, + (row_ix == 0 && has_manual).then(|| tr(&this.state, "actions.clear_queue")), + COMPACT_PILL, + fg, + muted, + cx, + ), + Ok((ix, track)) => { + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let payload = drag_payload(this, ActiveView::Queue, ix, &track); + + pill_row(ix, COMPACT_PILL, row_marked(ix, selected, visual, &picked), selected_bg, palette.row_hover, |row| { + row.gap_3() + .on_drag(payload, move |drag, _offset, _window, cx| { + track_drag_preview(drag, drag_colors, cx) + }) + .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + if event.modifiers().shift { + this.extend_selection_to(ix, cx); + return; + } + if is_pick_click(event) { + echo_core::intent::toggle_picked_row(&mut this.state, ix); + cx.notify(); + return; + } + this.state.ui.selected_queue_index = ix; + if event.click_count() >= 2 + && let Some(event) = + echo_core::intent::play_queue_track_at(&mut this.state, ix) + { + this.dispatch(event); + } + cx.notify(); + })) + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.selected_queue_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }), + ) + .child(div() + .flex_none() + .w(px(32.0)) + .text_color(muted) + .child(row_number(&this.state, ix, selected)),) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(track.name.clone())), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(track.artist.clone())), + ) + .child(liked_cell( + "queue", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + .child( + div() + .flex_none() + .w(px(48.0)) + .text_color(muted) + .child(SharedString::from(format_time(track.duration_ms))), + ) + }) + .into_any_element() + } + }) + .collect() + }), + ) + .track_scroll(&app.queue_scroll) + .flex_grow(1.0) + .into_any_element() + }) +} + +fn queue_tab_strip(app: &EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let active = app.state.ui.queue_tab; + let tabs = [ + ( + QueueTab::Queue, + "queue-tab-queue", + tr(&app.state, "ui.queue"), + ), + ( + QueueTab::Recent, + "queue-tab-recent", + tr(&app.state, "ui.recent"), + ), + ]; + div() + .mt_2() + .flex() + .gap_2() + .children(tabs.into_iter().map(|(tab, id, label)| { + let is_active = tab == active; + div() + .id(id) + .cursor_pointer() + .px_3() + .py_1() + .rounded_md() + .text_sm() + .text_color(if is_active { fg } else { muted }) + .when(is_active, |el| el.bg(palette.row_selected)) + .when(!is_active, |el| { + el.hover(move |style| style.bg(palette.row_hover)) + }) + .child(label) + .on_click(cx.listener( + move |this: &mut EchoApp, _: &gpui::ClickEvent, _window, cx| { + if this.state.ui.queue_tab != tab { + echo_core::intent::cycle_queue_tab(&mut this.state); + } + cx.notify(); + }, + )) + })) +} + +fn recent_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); + let row_count = app.state.data.recent_plays.len(); + if row_count == 0 { + return div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.recent_empty")) + .into_any_element(); + } + uniform_list( + "recent-rows", + row_count, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let secondary = theme.secondary.gpui(WINDOW_FG()); + let selected = this.state.ui.selected_queue_index; + let visual = visual_range_in(&this.state, ActiveView::Queue); + let picked = picked_in(&this.state, ActiveView::Queue); + let drag_colors = DragColors::resolve(theme); + let now = std::time::SystemTime::now().into(); + // Cloned out first: the records borrow the state the drag payload below mutates. + let rows: Vec<(usize, echo_core::models::Track, String)> = range + .filter_map(|ix| { + let record = this.state.data.recent_plays.get(ix)?; + let played = echo_core::context_details::format_added_at_with( + now, + &record.played_at, + &|key| tr(&this.state, key).to_string(), + ); + Some((ix, record.track.clone(), played)) + }) + .collect(); + + rows.into_iter() + .map(|(ix, track, played)| { + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let payload = drag_payload(this, ActiveView::Queue, ix, &track); + + pill_row( + ix, + COMPACT_PILL, + row_marked(ix, selected, visual, &picked), + palette.row_selected, + palette.row_hover, + |row| { + row.gap_3() + .on_drag(payload, move |drag, _offset, _window, cx| { + track_drag_preview(drag, drag_colors, cx) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, + event: &gpui::ClickEvent, + _window, + cx| { + if event.modifiers().shift { + this.extend_selection_to(ix, cx); + return; + } + if is_pick_click(event) { + echo_core::intent::toggle_picked_row( + &mut this.state, + ix, + ); + cx.notify(); + return; + } + this.state.ui.selected_queue_index = ix; + if event.click_count() >= 2 + && let Some(event) = + echo_core::intent::play_queue_track_at( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .on_mouse_down( + MouseButton::Right, + cx.listener( + move |this: &mut EchoApp, + event: &MouseDownEvent, + _window, + cx| { + this.state.ui.selected_queue_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }, + ), + ) + .child( + div() + .flex_none() + .w(px(32.0)) + .text_color(muted) + .child(row_number(&this.state, ix, selected)), + ) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(track.name.clone())), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(track.artist.clone())), + ) + .child(liked_cell( + "recent", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + .child( + div() + .flex_none() + .w(px(112.0)) + .text_xs() + .text_color(muted) + .child(SharedString::from(played)), + ) + }, + ) + .into_any_element() + }) + .collect() + }, + ), + ) + .track_scroll(&app.queue_scroll) + .flex_grow(1.0) + .into_any_element() +} + +/// A section label inside a queue list. `uniform_list` takes its row pitch from row 0, which is +/// always a header, so the header has to be as tall as the track rows of the list it sits in: +/// `metrics` is that list's. In rows taller than the compact ones the label drops to the bottom +/// edge, next to the tracks it names. +fn queue_header( + text: String, + clear_label: Option, + metrics: PillMetrics, + fg: Hsla, + muted: Hsla, + cx: &mut Context, +) -> gpui::AnyElement { + div() + .w_full() + .h(px(metrics.row_height)) + .px_4() + .flex() + .map(|el| { + if metrics.row_height > COMPACT_PILL.row_height { + el.items_end().pb_1() + } else { + el.items_center() + } + }) + .justify_between() + .gap_2() + .text_xs() + .text_color(muted) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .child(SharedString::from(text)), + ) + .when_some(clear_label, |el, label| { + el.child( + div() + .id("clear-queue") + .flex_none() + .max_w(relative(0.6)) + .truncate() + .cursor_pointer() + .text_color(fg) + .hover(move |style| style.text_color(muted)) + .child(label) + .on_click(cx.listener( + |this: &mut EchoApp, _: &gpui::ClickEvent, _window, cx| { + if let Some(event) = echo_core::intent::clear_queue(&mut this.state) { + this.dispatch(event); + } + cx.notify(); + }, + )), + ) + }) + .into_any_element() +} + +/// The queue panel: the playing track on top, then the same rows as the full queue view in a +/// narrower two-line layout. Double-click plays a row, right-click opens its track menu; the +/// keyboard-driven selection stays with the full view. +pub(super) fn queue_panel_body( + app: &mut EchoApp, + width: f32, + cx: &mut Context, +) -> AnyElement { + let show_duration = panel_layout::show_queue_duration(width); + let theme = &app.state.ui.active_theme; + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let playback = &app.state.playback; + let now_playing = playback.playing_track_id.is_some().then(|| { + ( + SharedString::from(playback.playing_track_title.clone()), + SharedString::from(playback.playing_track_artist.clone()), + playback + .playing_track_image + .as_ref() + .or(playback.previous_track_image.as_ref()) + .cloned() + .and_then(|artwork| app.images.get(&artwork)), + ) + }); + let row_count = app.state.queue_rows().len(); + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .when_some(now_playing, |el, (title, artist, cover)| { + el.child( + div() + .flex_none() + .px_4() + .pb_1() + .text_xs() + .text_color(muted) + .child(tr(&app.state, "desktop.now_playing")), + ) + .child( + div() + .flex_none() + .mx_2() + .px_2() + .h(px(TRACK_PILL.pill_height)) + .flex() + .flex_row() + .items_center() + .gap_3() + .child(match cover { + Some(image) => cover_image(image, 32.0, 4.0).into_any_element(), + None => div() + .flex_none() + .size(px(32.0)) + .rounded_sm() + .bg(palette.wash) + .into_any_element(), + }) + .child( + div() + .min_w_0() + .flex_grow(1.0) + .flex() + .flex_col() + .child( + div() + .text_sm() + .text_color(accent) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(title), + ) + .child( + div() + .text_xs() + .text_color(muted) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(artist), + ), + ), + ) + }) + .child(if row_count == 0 { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.queue_empty")) + .into_any_element() + } else { + uniform_list( + "queue-panel-rows", + row_count, + cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let has_manual = !this.state.data.manual_queue.is_empty(); + // Cloned out first: the rows borrow the state the thumbnails below mutate. + let rows: Vec<(usize, Option, Option)> = { + let rows = this.state.queue_rows(); + range + .map(|row_ix| match &rows[row_ix] { + QueueRow::Header(text) => (row_ix, Some(text.clone()), None), + QueueRow::Track(ix, track) => (*ix, None, Some((*track).clone())), + }) + .collect() + }; + + rows.into_iter() + .map(|(ix, header, track)| { + if let Some(text) = header { + return queue_header( + text, + (ix == 0 && has_manual).then(|| tr(&this.state, "actions.clear_queue")), + TRACK_PILL, + fg, + muted, + cx, + ); + } + let Some(track) = track else { + return div().into_any_element(); + }; + let thumb = thumb_element(this, track.image_url.as_deref(), 32.0, false, muted); + let ctx = ActionMenuContext::from(&track); + pill_row(ix, TRACK_PILL, false, palette.row_selected, palette.row_hover, |row| { + row.gap_3() + .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + if event.click_count() >= 2 + && let Some(event) = + echo_core::intent::play_queue_track_at(&mut this.state, ix) + { + this.dispatch(event); + } + cx.notify(); + })) + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.context_menu = None; + this.track_menu = Some(crate::TrackMenuState { + ctx: ctx.clone(), + position: Some(event.position), + selected: 0, + submenu: None, + }); + cx.notify(); + }), + ) + .child(thumb) + .child( + div() + .min_w_0() + .flex_grow(1.0) + .flex() + .flex_col() + .child( + div() + .text_sm() + .text_color(fg) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(SharedString::from(track.name.clone())), + ) + .child( + div() + .text_xs() + .text_color(muted) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(SharedString::from(track.artist.clone())), + ), + ) + .when(show_duration, |row| { + row.child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(format_time(track.duration_ms))), + ) + }) + }) + .into_any_element() + }) + .collect() + }), + ) + .track_scroll(&app.queue_panel_scroll) + .flex_grow(1.0) + .into_any_element() + }) + .into_any_element() +} From e175b07853979b525a75bea0cb106f791c0c73f5 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:09 -0500 Subject: [PATCH 08/44] desktop: move the artist views into views/artist.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 772 +----------------------- crates/echo-desktop/src/views/artist.rs | 771 +++++++++++++++++++++++ 2 files changed, 773 insertions(+), 770 deletions(-) create mode 100644 crates/echo-desktop/src/views/artist.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 30c65b5..7560cf0 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -13,6 +13,7 @@ use echo_core::app::{ActiveView, AppMode, LibraryTab, QueueRow, QueueTab, Search use echo_core::config::RightPanel; use echo_core::models::{ActionMenuAction, ActionMenuContext, LibraryNode}; use echo_core::thumbnails::{ThumbState, ThumbTier, tier_for_edge}; +mod artist; mod chrome; mod drag; mod menu_placement; @@ -22,6 +23,7 @@ mod queue; mod search; mod sidebar; mod track_list; +use artist::*; pub(crate) use chrome::*; pub(crate) use drag::*; use gpui::{ @@ -1277,776 +1279,6 @@ fn range_switcher(app: &EchoApp, cx: &mut Context) -> Div { row } -/// The artist page's discography chips, styled like [`range_switcher`]. -fn discography_switcher(app: &EchoApp, cx: &mut Context) -> Div { - use echo_core::models::DiscographyFilter; - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let active = app.state.ui.artist_discography_filter; - - let mut row = div().flex().flex_row().items_center().gap_1(); - for filter in DiscographyFilter::ALL { - let is_active = filter == active; - row = row.child( - div() - .id(SharedString::from(format!("discography-{:?}", filter))) - .px_2() - .py_1() - .rounded_full() - .border_1() - .text_xs() - .when(is_active, |el| el.border_color(accent).text_color(accent)) - .when(!is_active, |el| { - el.border_color(palette.border).text_color(muted) - }) - .hover(move |style| style.bg(palette.row_hover)) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.set_discography_filter(filter); - cx.notify(); - })) - .child(tr(&app.state, filter.label_key())), - ); - } - row -} - -/// Follow / Following toggle in the artist header: filled while the artist is in the -/// followed list, outlined otherwise. -fn follow_button(app: &EchoApp, artist_id: &str, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let accent = theme.primary.gpui(WINDOW_FG()); - let following = app - .state - .data - .followed_artists - .iter() - .any(|artist| artist.id == artist_id); - let label = if following { - tr(&app.state, "desktop.following") - } else { - tr(&app.state, "desktop.follow") - }; - div() - .id("artist-follow") - .flex_none() - .px_3() - .py_1() - .rounded_full() - .border_1() - .text_xs() - .border_color(accent) - .text_color(accent) - .when(following, |el| el.bg(palette.wash)) - .hover(move |style| style.bg(palette.row_hover)) - .cursor_pointer() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = echo_core::intent::toggle_follow_artist(&mut this.state) { - this.dispatch(event); - } - cx.notify(); - })) - .child(label) -} - -/// Full-page artist list: reached through the "Top Artists" browse link (the sidebar's -/// Artists tab still covers followed artists) and by back-navigation. -fn artist_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let is_top = app.state.ui.artist_list_source == echo_core::app::ArtistListSource::Top; - let title = if is_top { - tr(&app.state, "desktop.top_artists") - } else { - tr(&app.state, "ui.artists") - }; - let count = app.state.artist_list().len(); - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_row() - .items_center() - .gap_3() - .child(div().flex_grow(1.0).text_lg().text_color(fg).child(title)) - .when(is_top, |el| el.child(range_switcher(app, cx))), - ) - .child(if count == 0 { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.loading")) - .into_any_element() - } else { - uniform_list( - "artist-rows", - count, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - let selected = this.state.ui.selected_artist_index; - let visual = visual_range_in(&this.state, ActiveView::ArtistList); - - let rows: Vec = range - .map(|ix| { - let Some(artist) = this.state.artist_list().get(ix).cloned() else { - return div().id(ix).into_any_element(); - }; - let thumb = thumb_element( - this, - artist.image_url.as_deref(), - 26.0, - true, - muted, - ); - pill_row( - ix, - LIST_PILL, - row_selected(ix, selected, visual), - selected_bg, - palette.row_hover, - |row| { - row.gap_3() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::intent::open_artist_at( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child( - div() - .flex_none() - .w(px(24.0)) - .text_xs() - .text_color(muted) - .child(row_number(&this.state, ix, selected)), - ) - .child(thumb) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(artist.name)), - ) - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }, - ), - ) - .track_scroll(&app.artist_list_scroll) - .flex_grow(1.0) - .into_any_element() - }) -} - -/// What's New: recent releases from followed artists, reached through the sidebar -/// browse link. Renders live from state, filling in as the background scan reports. -fn whats_new(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let count = app.state.data.whats_new.len(); - let progress = app.state.data.whats_new_progress; - let scanning = progress.is_some(); - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_row() - .items_center() - .gap_3() - .child( - div() - .flex_grow(1.0) - .text_lg() - .text_color(fg) - .child(tr(&app.state, "desktop.whats_new")), - ) - .when_some(progress, |el, (done, total)| { - el.child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from( - tr(&app.state, "desktop.whats_new_checking") - .replace("{done}", &done.to_string()) - .replace("{total}", &total.to_string()), - )), - ) - }), - ) - .child(if count == 0 { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(if scanning { - tr(&app.state, "desktop.loading") - } else { - tr(&app.state, "desktop.whats_new_empty") - }) - .into_any_element() - } else { - uniform_list( - "whats-new-rows", - count, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - let selected = this.state.ui.selected_whats_new_index; - let visual = visual_range_in(&this.state, ActiveView::WhatsNew); - - let rows: Vec = range - .map(|ix| { - let Some(album) = this.state.data.whats_new.get(ix).cloned() else { - return div().id(ix).into_any_element(); - }; - let thumb = thumb_element( - this, - album.thumb_url.as_deref().or(album.image_url.as_deref()), - 26.0, - false, - muted, - ); - let released = album - .release_date - .clone() - .unwrap_or_else(|| album.release_year.clone()); - pill_row( - ix, - LIST_PILL, - row_selected(ix, selected, visual), - selected_bg, - palette.row_hover, - |row| { - row.gap_3() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::intent::open_whats_new_album( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child(thumb) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(album.name)), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_sm() - .text_color(muted) - .child(SharedString::from(album.artists)), - ) - .child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(released)), - ) - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }, - ), - ) - .track_scroll(&app.whats_new_scroll) - .flex_grow(1.0) - .into_any_element() - }) -} - -fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyElement { - let theme = &app.state.ui.active_theme; - let outer_palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - - let Some(data) = app.state.data.artist_page_data.clone() else { - return div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.loading_artist")) - .into_any_element(); - }; - - let header_image = app - .state - .ui - .active_library_header_image - .clone() - .and_then(|artwork| app.images.get(&artwork)); - let filter = app.state.ui.artist_discography_filter; - let count = data - .chips - .get(&echo_core::models::DiscographyFilter::All) - .map_or(data.albums.len(), |page| page.total); - let loading = app.state.data.artist_albums_loading && data.albums.is_empty(); - let row_count = data.album_row_count(filter); - let top_len = data.top_tracks.len(); - let top_loading = app.state.data.artist_top_tracks_loading; - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_row() - .items_center() - .gap_3() - .child( - div() - .id("artist-back") - .flex_none() - .w(px(28.0)) - .h(px(28.0)) - .flex() - .items_center() - .justify_center() - .rounded_full() - .text_color(muted) - .hover(move |style| style.bg(outer_palette.wash)) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.close_artist_page(cx); - })) - .child( - svg() - .path("icons/arrow-left.svg") - .w(px(16.0)) - .h(px(16.0)) - .text_color(muted), - ), - ) - .when_some(header_image, |el, image| { - el.child( - cover_image(image, 72.0, 36.0), - ) - }) - .child( - div() - .flex() - .flex_col() - .flex_grow(1.0) - .overflow_hidden() - .child( - div() - .text_lg() - .text_color(fg) - .child(SharedString::from(data.artist_name.clone())), - ) - .child( - div() - .text_xs() - .text_color(muted) - .child(SharedString::from(format!("{count} albums"))), - ), - ) - .child(follow_button(app, &data.artist_id, cx)), - ) - .when(top_len > 0 || top_loading, |el| { - el.child( - div() - .flex_none() - .px_4() - .pt_2() - .pb_1() - .text_xs() - .text_color(muted) - .child(tr(&app.state, "desktop.popular")), - ) - .child(if top_len == 0 { - div() - .flex_none() - .px_4() - .py_2() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.loading")) - .into_any_element() - } else { - uniform_list( - "artist-top-track-rows", - top_len, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let drag_colors = DragColors::resolve(theme); - let selected_bg = palette.row_selected; - // Combined index space: Popular rows come first, so `ix` compares - // against the page cursor directly. - let selected = this.state.ui.artist_page_album_index; - let playing_id = this.state.playback.playing_track_id.clone(); - - let rows: Vec = range - .map(|ix| { - let Some(track) = this - .state - .data - .artist_page_data - .as_ref() - .and_then(|data| data.top_tracks.get(ix)) - .cloned() - else { - return div().id(ix).into_any_element(); - }; - let is_playing = - playing_id.as_deref() == Some(track.id.as_str()); - let is_liked = this.state.data.liked_tracks.contains(&track.id); - let secondary = - this.state.ui.active_theme.secondary.gpui(WINDOW_FG()); - let title_color = if is_playing { accent } else { fg }; - let thumb = thumb_element( - this, - track.image_url.as_deref(), - 26.0, - false, - muted, - ); - let cover = thumb_image(this, track.image_url.as_deref(), DRAG_COVER_EDGE); - let payload = single_drag_payload(&track, cover); - pill_row( - ix, - LIST_PILL, - ix == selected, - selected_bg, - palette.row_hover, - |row| { - row.gap_3() - .on_drag(payload, move |drag, _offset, _window, cx| { - track_drag_preview(drag, drag_colors, cx) - }) - .on_click(cx.listener( - move |this: &mut EchoApp, - event: &gpui::ClickEvent, - _window, - cx| { - this.state.ui.artist_page_album_index = ix; - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_artist_top_track( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.artist_page_album_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }), - ) - .child(div() - .flex_none() - .w(px(24.0)) - .text_xs() - .text_color(muted) - .child(row_number(&this.state, ix, selected)),) - .child(thumb) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(title_color) - .child(SharedString::from(track.name.clone())), - ) - .child(liked_cell( - "popular", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - .child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(format_time( - track.duration_ms, - ))), - ) - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }, - ), - ) - .track_scroll(&app.artist_top_tracks_scroll) - .flex_none() - .h(px(top_len.min(10) as f32 * LIST_PILL.row_height)) - .max_h(relative(0.4)) - .into_any_element() - }) - }) - .child( - div() - .flex_none() - .px_4() - .pt_2() - .pb_1() - .flex() - .flex_row() - .items_center() - .gap_3() - .child( - div() - .text_xs() - .text_color(muted) - .child(tr(&app.state, "desktop.albums_section")), - ) - .child(discography_switcher(app, cx)), - ) - .child(if loading { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.loading_albums")) - .into_any_element() - } else { - uniform_list( - "artist-album-rows", - row_count, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - // Album rows sit after the Popular rows in the page's combined index space. - let selected = this.state.ui.artist_page_album_index; - let top_len = this.artist_page_top_len(); - let more_label = tr( - &this.state, - if this.state.data.artist_albums_loading { - "desktop.loading" - } else { - "desktop.load_more" - }, - ); - - let rows: Vec = range - .map(|ix| { - let Some(album) = this - .state - .data - .artist_page_data - .as_ref() - .and_then(|data| data.albums.get(ix)) - .cloned() - else { - // The Load more row after the last album. - return pill_row( - ix, - LIST_PILL, - ix + top_len == selected, - selected_bg, - palette.row_hover, - |row| { - row.justify_center() - .text_color(muted) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::intent::load_more_artist_albums( - &mut this.state, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child(more_label.clone()) - }, - ) - .into_any_element(); - }; - let thumb_url = - album.thumb_url.clone().or_else(|| album.image_url.clone()); - let thumb = - thumb_element(this, thumb_url.as_deref(), 26.0, false, muted); - let tracks_label = album - .track_count - .map(|n| format!("{n} tracks")) - .unwrap_or_default(); - pill_row( - ix, - LIST_PILL, - ix + top_len == selected, - selected_bg, - palette.row_hover, - |row| { - row.gap_3() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - let index = ix + this.artist_page_top_len(); - if let Some(event) = - echo_core::intent::activate_artist_page_row( - &mut this.state, - index, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child(thumb) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(album.name)), - ) - .child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(album.release_year)), - ) - .child( - div() - .flex_none() - .w(px(70.0)) - .text_xs() - .text_color(muted) - .child(SharedString::from(tracks_label)), - ) - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }, - ), - ) - .track_scroll(&app.artist_albums_scroll) - .flex_grow(1.0) - .into_any_element() - }) - .into_any_element() -} - /// Index of the lyric line playing at `progress_ms`: the last line that has started, or the /// first before any has. pub(crate) fn current_lyric_index( diff --git a/crates/echo-desktop/src/views/artist.rs b/crates/echo-desktop/src/views/artist.rs new file mode 100644 index 0000000..201aa1a --- /dev/null +++ b/crates/echo-desktop/src/views/artist.rs @@ -0,0 +1,771 @@ +use super::*; + +/// The artist page's discography chips, styled like [`range_switcher`]. +fn discography_switcher(app: &EchoApp, cx: &mut Context) -> Div { + use echo_core::models::DiscographyFilter; + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let active = app.state.ui.artist_discography_filter; + + let mut row = div().flex().flex_row().items_center().gap_1(); + for filter in DiscographyFilter::ALL { + let is_active = filter == active; + row = row.child( + div() + .id(SharedString::from(format!("discography-{:?}", filter))) + .px_2() + .py_1() + .rounded_full() + .border_1() + .text_xs() + .when(is_active, |el| el.border_color(accent).text_color(accent)) + .when(!is_active, |el| { + el.border_color(palette.border).text_color(muted) + }) + .hover(move |style| style.bg(palette.row_hover)) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.set_discography_filter(filter); + cx.notify(); + })) + .child(tr(&app.state, filter.label_key())), + ); + } + row +} + +/// Follow / Following toggle in the artist header: filled while the artist is in the +/// followed list, outlined otherwise. +fn follow_button(app: &EchoApp, artist_id: &str, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let accent = theme.primary.gpui(WINDOW_FG()); + let following = app + .state + .data + .followed_artists + .iter() + .any(|artist| artist.id == artist_id); + let label = if following { + tr(&app.state, "desktop.following") + } else { + tr(&app.state, "desktop.follow") + }; + div() + .id("artist-follow") + .flex_none() + .px_3() + .py_1() + .rounded_full() + .border_1() + .text_xs() + .border_color(accent) + .text_color(accent) + .when(following, |el| el.bg(palette.wash)) + .hover(move |style| style.bg(palette.row_hover)) + .cursor_pointer() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = echo_core::intent::toggle_follow_artist(&mut this.state) { + this.dispatch(event); + } + cx.notify(); + })) + .child(label) +} + +/// Full-page artist list: reached through the "Top Artists" browse link (the sidebar's +/// Artists tab still covers followed artists) and by back-navigation. +pub(super) fn artist_list(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let is_top = app.state.ui.artist_list_source == echo_core::app::ArtistListSource::Top; + let title = if is_top { + tr(&app.state, "desktop.top_artists") + } else { + tr(&app.state, "ui.artists") + }; + let count = app.state.artist_list().len(); + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_row() + .items_center() + .gap_3() + .child(div().flex_grow(1.0).text_lg().text_color(fg).child(title)) + .when(is_top, |el| el.child(range_switcher(app, cx))), + ) + .child(if count == 0 { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.loading")) + .into_any_element() + } else { + uniform_list( + "artist-rows", + count, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + let selected = this.state.ui.selected_artist_index; + let visual = visual_range_in(&this.state, ActiveView::ArtistList); + + let rows: Vec = range + .map(|ix| { + let Some(artist) = this.state.artist_list().get(ix).cloned() else { + return div().id(ix).into_any_element(); + }; + let thumb = thumb_element( + this, + artist.image_url.as_deref(), + 26.0, + true, + muted, + ); + pill_row( + ix, + LIST_PILL, + row_selected(ix, selected, visual), + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::intent::open_artist_at( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child( + div() + .flex_none() + .w(px(24.0)) + .text_xs() + .text_color(muted) + .child(row_number(&this.state, ix, selected)), + ) + .child(thumb) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(artist.name)), + ) + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows + }, + ), + ) + .track_scroll(&app.artist_list_scroll) + .flex_grow(1.0) + .into_any_element() + }) +} + +/// What's New: recent releases from followed artists, reached through the sidebar +/// browse link. Renders live from state, filling in as the background scan reports. +pub(super) fn whats_new(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let count = app.state.data.whats_new.len(); + let progress = app.state.data.whats_new_progress; + let scanning = progress.is_some(); + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_row() + .items_center() + .gap_3() + .child( + div() + .flex_grow(1.0) + .text_lg() + .text_color(fg) + .child(tr(&app.state, "desktop.whats_new")), + ) + .when_some(progress, |el, (done, total)| { + el.child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from( + tr(&app.state, "desktop.whats_new_checking") + .replace("{done}", &done.to_string()) + .replace("{total}", &total.to_string()), + )), + ) + }), + ) + .child(if count == 0 { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(if scanning { + tr(&app.state, "desktop.loading") + } else { + tr(&app.state, "desktop.whats_new_empty") + }) + .into_any_element() + } else { + uniform_list( + "whats-new-rows", + count, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + let selected = this.state.ui.selected_whats_new_index; + let visual = visual_range_in(&this.state, ActiveView::WhatsNew); + + let rows: Vec = range + .map(|ix| { + let Some(album) = this.state.data.whats_new.get(ix).cloned() else { + return div().id(ix).into_any_element(); + }; + let thumb = thumb_element( + this, + album.thumb_url.as_deref().or(album.image_url.as_deref()), + 26.0, + false, + muted, + ); + let released = album + .release_date + .clone() + .unwrap_or_else(|| album.release_year.clone()); + pill_row( + ix, + LIST_PILL, + row_selected(ix, selected, visual), + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::intent::open_whats_new_album( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child(thumb) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(album.name)), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_sm() + .text_color(muted) + .child(SharedString::from(album.artists)), + ) + .child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(released)), + ) + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows + }, + ), + ) + .track_scroll(&app.whats_new_scroll) + .flex_grow(1.0) + .into_any_element() + }) +} + +pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyElement { + let theme = &app.state.ui.active_theme; + let outer_palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + + let Some(data) = app.state.data.artist_page_data.clone() else { + return div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.loading_artist")) + .into_any_element(); + }; + + let header_image = app + .state + .ui + .active_library_header_image + .clone() + .and_then(|artwork| app.images.get(&artwork)); + let filter = app.state.ui.artist_discography_filter; + let count = data + .chips + .get(&echo_core::models::DiscographyFilter::All) + .map_or(data.albums.len(), |page| page.total); + let loading = app.state.data.artist_albums_loading && data.albums.is_empty(); + let row_count = data.album_row_count(filter); + let top_len = data.top_tracks.len(); + let top_loading = app.state.data.artist_top_tracks_loading; + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_row() + .items_center() + .gap_3() + .child( + div() + .id("artist-back") + .flex_none() + .w(px(28.0)) + .h(px(28.0)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .text_color(muted) + .hover(move |style| style.bg(outer_palette.wash)) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.close_artist_page(cx); + })) + .child( + svg() + .path("icons/arrow-left.svg") + .w(px(16.0)) + .h(px(16.0)) + .text_color(muted), + ), + ) + .when_some(header_image, |el, image| { + el.child( + cover_image(image, 72.0, 36.0), + ) + }) + .child( + div() + .flex() + .flex_col() + .flex_grow(1.0) + .overflow_hidden() + .child( + div() + .text_lg() + .text_color(fg) + .child(SharedString::from(data.artist_name.clone())), + ) + .child( + div() + .text_xs() + .text_color(muted) + .child(SharedString::from(format!("{count} albums"))), + ), + ) + .child(follow_button(app, &data.artist_id, cx)), + ) + .when(top_len > 0 || top_loading, |el| { + el.child( + div() + .flex_none() + .px_4() + .pt_2() + .pb_1() + .text_xs() + .text_color(muted) + .child(tr(&app.state, "desktop.popular")), + ) + .child(if top_len == 0 { + div() + .flex_none() + .px_4() + .py_2() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.loading")) + .into_any_element() + } else { + uniform_list( + "artist-top-track-rows", + top_len, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let drag_colors = DragColors::resolve(theme); + let selected_bg = palette.row_selected; + // Combined index space: Popular rows come first, so `ix` compares + // against the page cursor directly. + let selected = this.state.ui.artist_page_album_index; + let playing_id = this.state.playback.playing_track_id.clone(); + + let rows: Vec = range + .map(|ix| { + let Some(track) = this + .state + .data + .artist_page_data + .as_ref() + .and_then(|data| data.top_tracks.get(ix)) + .cloned() + else { + return div().id(ix).into_any_element(); + }; + let is_playing = + playing_id.as_deref() == Some(track.id.as_str()); + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let secondary = + this.state.ui.active_theme.secondary.gpui(WINDOW_FG()); + let title_color = if is_playing { accent } else { fg }; + let thumb = thumb_element( + this, + track.image_url.as_deref(), + 26.0, + false, + muted, + ); + let cover = thumb_image(this, track.image_url.as_deref(), DRAG_COVER_EDGE); + let payload = single_drag_payload(&track, cover); + pill_row( + ix, + LIST_PILL, + ix == selected, + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .on_drag(payload, move |drag, _offset, _window, cx| { + track_drag_preview(drag, drag_colors, cx) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, + event: &gpui::ClickEvent, + _window, + cx| { + this.state.ui.artist_page_album_index = ix; + if event.click_count() >= 2 + && let Some(event) = + echo_core::intent::play_artist_top_track( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.artist_page_album_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }), + ) + .child(div() + .flex_none() + .w(px(24.0)) + .text_xs() + .text_color(muted) + .child(row_number(&this.state, ix, selected)),) + .child(thumb) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(title_color) + .child(SharedString::from(track.name.clone())), + ) + .child(liked_cell( + "popular", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + .child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(format_time( + track.duration_ms, + ))), + ) + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows + }, + ), + ) + .track_scroll(&app.artist_top_tracks_scroll) + .flex_none() + .h(px(top_len.min(10) as f32 * LIST_PILL.row_height)) + .max_h(relative(0.4)) + .into_any_element() + }) + }) + .child( + div() + .flex_none() + .px_4() + .pt_2() + .pb_1() + .flex() + .flex_row() + .items_center() + .gap_3() + .child( + div() + .text_xs() + .text_color(muted) + .child(tr(&app.state, "desktop.albums_section")), + ) + .child(discography_switcher(app, cx)), + ) + .child(if loading { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.loading_albums")) + .into_any_element() + } else { + uniform_list( + "artist-album-rows", + row_count, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + // Album rows sit after the Popular rows in the page's combined index space. + let selected = this.state.ui.artist_page_album_index; + let top_len = this.artist_page_top_len(); + let more_label = tr( + &this.state, + if this.state.data.artist_albums_loading { + "desktop.loading" + } else { + "desktop.load_more" + }, + ); + + let rows: Vec = range + .map(|ix| { + let Some(album) = this + .state + .data + .artist_page_data + .as_ref() + .and_then(|data| data.albums.get(ix)) + .cloned() + else { + // The Load more row after the last album. + return pill_row( + ix, + LIST_PILL, + ix + top_len == selected, + selected_bg, + palette.row_hover, + |row| { + row.justify_center() + .text_color(muted) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::intent::load_more_artist_albums( + &mut this.state, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child(more_label.clone()) + }, + ) + .into_any_element(); + }; + let thumb_url = + album.thumb_url.clone().or_else(|| album.image_url.clone()); + let thumb = + thumb_element(this, thumb_url.as_deref(), 26.0, false, muted); + let tracks_label = album + .track_count + .map(|n| format!("{n} tracks")) + .unwrap_or_default(); + pill_row( + ix, + LIST_PILL, + ix + top_len == selected, + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + let index = ix + this.artist_page_top_len(); + if let Some(event) = + echo_core::intent::activate_artist_page_row( + &mut this.state, + index, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child(thumb) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(album.name)), + ) + .child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(album.release_year)), + ) + .child( + div() + .flex_none() + .w(px(70.0)) + .text_xs() + .text_color(muted) + .child(SharedString::from(tracks_label)), + ) + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows + }, + ), + ) + .track_scroll(&app.artist_albums_scroll) + .flex_grow(1.0) + .into_any_element() + }) + .into_any_element() +} From 76a829a2b802e279c59270c7a458167d54e22a2e Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:17 -0500 Subject: [PATCH 09/44] desktop: move lyric rendering into views/lyrics.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 197 +---------------------- crates/echo-desktop/src/views/lyrics.rs | 202 ++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 195 deletions(-) create mode 100644 crates/echo-desktop/src/views/lyrics.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 7560cf0..e9e642d 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -16,6 +16,7 @@ use echo_core::thumbnails::{ThumbState, ThumbTier, tier_for_edge}; mod artist; mod chrome; mod drag; +mod lyrics; mod menu_placement; pub(crate) mod panel_layout; mod playlist_edit; @@ -31,6 +32,7 @@ use gpui::{ MouseDownEvent, SharedString, Stateful, Window, canvas, div, ease_out_quint, prelude::*, px, relative, svg, uniform_list, }; +pub(crate) use lyrics::*; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; use queue::*; @@ -1279,201 +1281,6 @@ fn range_switcher(app: &EchoApp, cx: &mut Context) -> Div { row } -/// Index of the lyric line playing at `progress_ms`: the last line that has started, or the -/// first before any has. -pub(crate) fn current_lyric_index( - lines: &[echo_core::models::LyricLine], - progress_ms: u32, -) -> usize { - lines - .iter() - .take_while(|line| line.start_ms <= progress_ms) - .count() - .saturating_sub(1) -} - -/// The colors a lyric line takes by its place in the song: the current line accented, lines -/// already sung in the text color, upcoming ones muted. -struct LyricColors { - fg: Hsla, - muted: Hsla, - accent: Hsla, -} - -impl LyricColors { - fn resolve(app: &EchoApp) -> Self { - let theme = &app.state.ui.active_theme; - Self { - fg: theme.text.gpui(WINDOW_FG()), - muted: theme.text_muted.gpui(WINDOW_FG()), - accent: theme.primary.gpui(WINDOW_FG()), - } - } - - fn immersive(colors: &ImmersiveColors) -> Self { - Self { - fg: colors.text, - muted: colors.text_muted, - accent: colors.accent, - } - } - - fn line(&self, ix: usize, current: usize) -> Hsla { - match ix.cmp(¤t) { - std::cmp::Ordering::Equal => self.accent, - std::cmp::Ordering::Greater => self.muted, - std::cmp::Ordering::Less => self.fg, - } - } -} - -/// One lyric line on a single row of `height` pixels, ellipsized if it is too long. A block -/// with the line height set to the row, not a flex row: a flex item is measured at its -/// max-content width, which defeats the ellipsis. -fn lyric_row(text: SharedString, color: Hsla, height: f32, large: bool) -> Div { - div() - .w_full() - .h(px(height)) - .px_4() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .map(|el| { - if large { - el.text_xl().text_center() - } else { - el.text_sm() - } - }) - .line_height(px(height)) - .text_color(color) - .child(text) -} - -/// What stands in for the lyrics while they load or when the track has none; `None` once there -/// are lines to show. -fn lyric_status(app: &EchoApp, muted: Hsla) -> Option { - let playback = &app.state.playback; - let key = if playback.is_fetching_lyrics { - "desktop.loading_lyrics" - } else if playback.current_lyrics.is_none() { - "desktop.no_lyrics" - } else { - return None; - }; - Some( - div() - .py_8() - .flex() - .justify_center() - .text_color(muted) - .child(tr(&app.state, key)) - .into_any_element(), - ) -} - -/// The panel's lyric list: every line, scrolled so the current one (by playback position) sits -/// at the center whenever the list is long enough to allow it. -fn lyric_list(app: &mut EchoApp, cx: &mut Context) -> AnyElement { - let lines = app - .state - .playback - .current_lyrics - .as_ref() - .map(|lyrics| lyrics.lines.as_slice()) - .unwrap_or_default(); - let current = current_lyric_index(lines, app.state.playback.display_progress_ms()); - app.lyrics_scroll - .scroll_to_item(current, gpui::ScrollStrategy::Center); - - uniform_list( - "lyric-lines", - lines.len(), - cx.processor( - |this: &mut EchoApp, range: std::ops::Range, _window, _cx| { - let colors = LyricColors::resolve(this); - let lines = this - .state - .playback - .current_lyrics - .as_ref() - .map(|lyrics| lyrics.lines.as_slice()) - .unwrap_or_default(); - let current = current_lyric_index(lines, this.state.playback.display_progress_ms()); - - range - .map(|ix| { - let text = lines - .get(ix) - .map(|line| line.text.clone()) - .unwrap_or_default(); - lyric_row( - text.into(), - colors.line(ix, current), - PANEL_LYRIC_ROW, - false, - ) - .id(ix) - }) - .collect() - }, - ), - ) - .track_scroll(&app.lyrics_scroll) - .flex_grow(1.0) - .into_any_element() -} - -/// The immersive lyrics: a fixed window of `rows` (odd) whole lines with the current line -/// pinned to the center row, so nothing is ever clipped and the first and last lines of a song -/// sit exactly where the middle ones do. When the line advances the column glides up one row -/// over [`LYRIC_GLIDE`]; the extra row above the window carries the line on its way out. Rows -/// fade toward the edges (see [`lyric_opacity`]), the outermost still faintly legible. -fn lyric_window(app: &EchoApp, colors: LyricColors, rows: usize, row_height: f32) -> AnyElement { - let lines = app - .state - .playback - .current_lyrics - .as_ref() - .map(|lyrics| lyrics.lines.as_slice()) - .unwrap_or_default(); - let current = current_lyric_index(lines, app.state.playback.display_progress_ms()); - let half = (rows / 2) as isize; - let reach = (half + 1) as f32; - let column: Vec<(isize, SharedString, Hsla)> = (-half - 1..=half) - .map(|offset| { - let ix = current.checked_add_signed(offset); - let text = ix - .and_then(|ix| lines.get(ix)) - .map(|line| SharedString::from(line.text.clone())) - .unwrap_or_default(); - (offset, text, colors.line(ix.unwrap_or(current), current)) - }) - .collect(); - - div() - .relative() - .w_full() - .h(px(rows as f32 * row_height)) - .overflow_hidden() - .child(div().absolute().w_full().with_animation( - ("lyric-glide", current), - Animation::new(LYRIC_GLIDE).with_easing(ease_out_quint()), - move |el, t| { - el.top(px(-row_height * t)) - .children(column.iter().map(|(offset, text, color)| { - let distance = (*offset as f32 + 1.0 - t).abs(); - lyric_row(text.clone(), *color, row_height, true) - .opacity(lyric_opacity(distance, reach)) - })) - }, - )) - .into_any_element() -} - -const PANEL_LYRIC_ROW: f32 = 26.0; -const LYRIC_GLIDE: std::time::Duration = std::time::Duration::from_millis(240); - /// The docked column to the right of the main area: the queue or the lyrics, whichever the /// playback bar's buttons (or `shift-L`) opened. Persistent UI rather than an overlay, so /// escape leaves it alone and it comes back on the next launch. diff --git a/crates/echo-desktop/src/views/lyrics.rs b/crates/echo-desktop/src/views/lyrics.rs new file mode 100644 index 0000000..d2a8674 --- /dev/null +++ b/crates/echo-desktop/src/views/lyrics.rs @@ -0,0 +1,202 @@ +use super::*; + +/// Index of the lyric line playing at `progress_ms`: the last line that has started, or the +/// first before any has. +pub(crate) fn current_lyric_index( + lines: &[echo_core::models::LyricLine], + progress_ms: u32, +) -> usize { + lines + .iter() + .take_while(|line| line.start_ms <= progress_ms) + .count() + .saturating_sub(1) +} + +/// The colors a lyric line takes by its place in the song: the current line accented, lines +/// already sung in the text color, upcoming ones muted. +pub(super) struct LyricColors { + fg: Hsla, + muted: Hsla, + accent: Hsla, +} + +impl LyricColors { + fn resolve(app: &EchoApp) -> Self { + let theme = &app.state.ui.active_theme; + Self { + fg: theme.text.gpui(WINDOW_FG()), + muted: theme.text_muted.gpui(WINDOW_FG()), + accent: theme.primary.gpui(WINDOW_FG()), + } + } + + pub(super) fn immersive(colors: &ImmersiveColors) -> Self { + Self { + fg: colors.text, + muted: colors.text_muted, + accent: colors.accent, + } + } + + fn line(&self, ix: usize, current: usize) -> Hsla { + match ix.cmp(¤t) { + std::cmp::Ordering::Equal => self.accent, + std::cmp::Ordering::Greater => self.muted, + std::cmp::Ordering::Less => self.fg, + } + } +} + +/// One lyric line on a single row of `height` pixels, ellipsized if it is too long. A block +/// with the line height set to the row, not a flex row: a flex item is measured at its +/// max-content width, which defeats the ellipsis. +fn lyric_row(text: SharedString, color: Hsla, height: f32, large: bool) -> Div { + div() + .w_full() + .h(px(height)) + .px_4() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .map(|el| { + if large { + el.text_xl().text_center() + } else { + el.text_sm() + } + }) + .line_height(px(height)) + .text_color(color) + .child(text) +} + +/// What stands in for the lyrics while they load or when the track has none; `None` once there +/// are lines to show. +pub(super) fn lyric_status(app: &EchoApp, muted: Hsla) -> Option { + let playback = &app.state.playback; + let key = if playback.is_fetching_lyrics { + "desktop.loading_lyrics" + } else if playback.current_lyrics.is_none() { + "desktop.no_lyrics" + } else { + return None; + }; + Some( + div() + .py_8() + .flex() + .justify_center() + .text_color(muted) + .child(tr(&app.state, key)) + .into_any_element(), + ) +} + +/// The panel's lyric list: every line, scrolled so the current one (by playback position) sits +/// at the center whenever the list is long enough to allow it. +pub(super) fn lyric_list(app: &mut EchoApp, cx: &mut Context) -> AnyElement { + let lines = app + .state + .playback + .current_lyrics + .as_ref() + .map(|lyrics| lyrics.lines.as_slice()) + .unwrap_or_default(); + let current = current_lyric_index(lines, app.state.playback.display_progress_ms()); + app.lyrics_scroll + .scroll_to_item(current, gpui::ScrollStrategy::Center); + + uniform_list( + "lyric-lines", + lines.len(), + cx.processor( + |this: &mut EchoApp, range: std::ops::Range, _window, _cx| { + let colors = LyricColors::resolve(this); + let lines = this + .state + .playback + .current_lyrics + .as_ref() + .map(|lyrics| lyrics.lines.as_slice()) + .unwrap_or_default(); + let current = current_lyric_index(lines, this.state.playback.display_progress_ms()); + + range + .map(|ix| { + let text = lines + .get(ix) + .map(|line| line.text.clone()) + .unwrap_or_default(); + lyric_row( + text.into(), + colors.line(ix, current), + PANEL_LYRIC_ROW, + false, + ) + .id(ix) + }) + .collect() + }, + ), + ) + .track_scroll(&app.lyrics_scroll) + .flex_grow(1.0) + .into_any_element() +} + +/// The immersive lyrics: a fixed window of `rows` (odd) whole lines with the current line +/// pinned to the center row, so nothing is ever clipped and the first and last lines of a song +/// sit exactly where the middle ones do. When the line advances the column glides up one row +/// over [`LYRIC_GLIDE`]; the extra row above the window carries the line on its way out. Rows +/// fade toward the edges (see [`lyric_opacity`]), the outermost still faintly legible. +pub(super) fn lyric_window( + app: &EchoApp, + colors: LyricColors, + rows: usize, + row_height: f32, +) -> AnyElement { + let lines = app + .state + .playback + .current_lyrics + .as_ref() + .map(|lyrics| lyrics.lines.as_slice()) + .unwrap_or_default(); + let current = current_lyric_index(lines, app.state.playback.display_progress_ms()); + let half = (rows / 2) as isize; + let reach = (half + 1) as f32; + let column: Vec<(isize, SharedString, Hsla)> = (-half - 1..=half) + .map(|offset| { + let ix = current.checked_add_signed(offset); + let text = ix + .and_then(|ix| lines.get(ix)) + .map(|line| SharedString::from(line.text.clone())) + .unwrap_or_default(); + (offset, text, colors.line(ix.unwrap_or(current), current)) + }) + .collect(); + + div() + .relative() + .w_full() + .h(px(rows as f32 * row_height)) + .overflow_hidden() + .child(div().absolute().w_full().with_animation( + ("lyric-glide", current), + Animation::new(LYRIC_GLIDE).with_easing(ease_out_quint()), + move |el, t| { + el.top(px(-row_height * t)) + .children(column.iter().map(|(offset, text, color)| { + let distance = (*offset as f32 + 1.0 - t).abs(); + lyric_row(text.clone(), *color, row_height, true) + .opacity(lyric_opacity(distance, reach)) + })) + }, + )) + .into_any_element() +} + +const PANEL_LYRIC_ROW: f32 = 26.0; + +const LYRIC_GLIDE: std::time::Duration = std::time::Duration::from_millis(240); From 5d8b5517510cdced06da48e448192c84e6637c0c Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:19 -0500 Subject: [PATCH 10/44] desktop: move the immersive view into views/immersive.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 344 +------------------- crates/echo-desktop/src/views/immersive.rs | 356 +++++++++++++++++++++ 2 files changed, 358 insertions(+), 342 deletions(-) create mode 100644 crates/echo-desktop/src/views/immersive.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index e9e642d..2a07056 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -16,6 +16,7 @@ use echo_core::thumbnails::{ThumbState, ThumbTier, tier_for_edge}; mod artist; mod chrome; mod drag; +mod immersive; mod lyrics; mod menu_placement; pub(crate) mod panel_layout; @@ -32,6 +33,7 @@ use gpui::{ MouseDownEvent, SharedString, Stateful, Window, canvas, div, ease_out_quint, prelude::*, px, relative, svg, uniform_list, }; +pub(crate) use immersive::*; pub(crate) use lyrics::*; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; @@ -1386,287 +1388,6 @@ pub fn right_panel( .into_any_element() } -/// The backdrop's picture over the whole window, under everything else: the keyframe before -/// `phase` with the one after it crossfaded on top. Painted straight from the texture as a fill -/// (its guard border just outside the window) rather than through `img`, which takes the -/// texture's aspect ratio as the box's and would paint a square. -pub fn backdrop_layer( - backdrop: std::sync::Arc, - phase: f32, - corners: Option, -) -> impl IntoElement { - let radii = client_corner_radii(corners, ClientCorners::All); - let (first, second, blend) = backdrop.frame(phase); - let layer = |image: std::sync::Arc| { - let backdrop = backdrop.clone(); - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let image_bounds = backdrop.image_bounds(bounds); - window - .paint_image(bounds, image_bounds, radii, image, 0, false) - .ok(); - }, - ) - .absolute() - .inset_0() - }; - div() - .absolute() - .inset_0() - .child(layer(first)) - .when(blend > 0.0, |el| { - el.child( - div() - .absolute() - .inset_0() - .opacity(blend) - .child(layer(second)), - ) - }) -} - -/// The immersive toggle. Callers pick its colors: the search bar paints it muted in the theme, -/// the immersive view accented in the cover's colors. It is the one control the immersive view -/// keeps, so it lives here rather than inline in the search bar. -fn immersive_button(color: Hsla, hover: Hsla, cx: &mut Context) -> impl IntoElement { - crate::icon_button( - "immersive", - "icons/full-screen.svg", - color, - hover, - cx, - |this, cx| this.toggle_immersive(cx), - ) -} - -/// Edge of the immersive cover, in pixels, for a body of `width` x `height`: the largest square -/// that, with the caption under it, fits the height inside the margins, bounded by the -/// half-width; then scaled down to leave air around it, and capped for very tall windows. -pub(crate) fn immersive_cover_edge(width: f32, height: f32) -> f32 { - let by_width = width * 0.5 - 2.0 * IMMERSIVE_MARGIN; - let by_height = height - 2.0 * IMMERSIVE_MARGIN - IMMERSIVE_CAPTION_HEIGHT; - (by_width.min(by_height) * IMMERSIVE_COVER_SCALE).clamp(0.0, IMMERSIVE_COVER_MAX) -} - -/// Rows in the immersive lyric window for a panel `panel_height` tall: as many whole rows as -/// fit, made odd so one row is the exact center, and at least one. -pub(crate) fn lyric_window_rows(panel_height: f32, row_height: f32) -> usize { - let rows = (panel_height / row_height).max(1.0) as usize; - if rows.is_multiple_of(2) { - rows - 1 - } else { - rows - } -} - -/// Opacity of a lyric row `distance` rows from the center when the row just past the window's -/// edge is `reach` rows away: full at the center, easing out so the neighbors stay readable and -/// reaching transparent one row beyond the edge — the Apple Music fade. `distance` is -/// fractional mid-glide. -pub(crate) fn lyric_opacity(distance: f32, reach: f32) -> f32 { - let t = (distance / reach).min(1.0); - 1.0 - t * t -} - -const IMMERSIVE_MARGIN: f32 = 48.0; -/// Both halves stack a cover-high box, a gap and a caption-high block, centered; so the -/// right's lyrics box centers on the cover and its controls block tops out with the title. -/// The caption block is the title's 32px text_2xl line, gap_1, the artist's 28px text_lg line; -/// the controls block is the seek row, gap_1, the transport row, the same 64. -const IMMERSIVE_CAPTION_HEIGHT: f32 = IMMERSIVE_GAP + IMMERSIVE_CAPTION_BLOCK; -const IMMERSIVE_CAPTION_BLOCK: f32 = 32.0 + 4.0 + 28.0; -const IMMERSIVE_GAP: f32 = 24.0; -const IMMERSIVE_SEEK_ROW: f32 = 24.0; -const IMMERSIVE_TRANSPORT_ROW: f32 = IMMERSIVE_CAPTION_BLOCK - 4.0 - IMMERSIVE_SEEK_ROW; -const IMMERSIVE_COVER_SCALE: f32 = 0.75; -const IMMERSIVE_COVER_MAX: f32 = 480.0; -/// The lyric window fills up to this share of the body height, and never more than the cover. -const IMMERSIVE_LYRICS_SHARE: f32 = 0.5; -const IMMERSIVE_LYRIC_ROW: f32 = 40.0; - -/// The immersive view: the cover with the track's title and artist under it, that whole block -/// centered in the left half; on the right the synced lyrics, centered on the cover, with the -/// seek bar and transport under them level with the caption; and top right, in the search -/// bar's slots, the toggle, the queue (where the theme picker sits otherwise) and settings. -/// Everything else — sidebar, navigation, search, playback bar — is gone until it is toggled -/// off. Lyric lines are centered so each shares its axis with the seek bar and play button. Every color comes from `backdrop`, derived from the cover -/// (see [`crate::backdrop`]); the backdrop's picture and window fill are the root's, so they -/// reach under the titlebar too. -pub fn immersive_view( - app: &mut EchoApp, - backdrop: &Backdrop, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - let colors = backdrop.colors; - let (fg, muted) = (colors.text, colors.text_muted); - let controls = ControlColors { - fg, - muted, - accent: colors.accent, - hover: colors.wash, - track: colors.wash, - }; - let playback = &app.state.playback; - let has_track = playback.playing_track_id.is_some(); - let title: SharedString = if playback.playing_track_title.is_empty() { - tr(&app.state, "desktop.nothing_playing") - } else { - playback.playing_track_title.clone().into() - }; - let artist: SharedString = playback.playing_track_artist.clone().into(); - let viewport = window.viewport_size(); - let body_height = f32::from(viewport.height) - TITLEBAR_HEIGHT; - let edge = immersive_cover_edge(f32::from(viewport.width), body_height); - let rows = lyric_window_rows( - edge.min(body_height * IMMERSIVE_LYRICS_SHARE), - IMMERSIVE_LYRIC_ROW, - ); - let cover = playback - .playing_track_image - .as_ref() - .or(playback.previous_track_image.as_ref()) - .cloned() - .and_then(|artwork| app.images.get(&artwork)); - let cover = match cover { - Some(image) => cover_image(image, edge, 8.0).into_any_element(), - None => div() - .flex_none() - .w(px(edge)) - .h(px(edge)) - .rounded_lg() - .bg(colors.wash) - .flex() - .items_center() - .justify_center() - .child( - svg() - .path("icons/music-note.svg") - .w(px(edge * 0.25)) - .h(px(edge * 0.25)) - .text_color(muted), - ) - .into_any_element(), - }; - let lyrics = lyric_status(app, muted).unwrap_or_else(|| { - lyric_window( - app, - LyricColors::immersive(&colors), - rows, - IMMERSIVE_LYRIC_ROW, - ) - }); - - div() - .id("immersive") - .relative() - .flex_grow(1.0) - .flex() - .flex_row() - .overflow_hidden() - .child( - div() - .w(relative(0.5)) - .h_full() - .flex() - .flex_col() - .items_center() - .justify_center() - .gap(px(IMMERSIVE_GAP)) - .child(cover) - .child( - div() - .w(px(edge)) - .flex() - .flex_col() - .gap_1() - .child( - crate::playing_track_link( - "immersive-title", - title, - fg, - has_track, - ActionMenuAction::GoToAlbum, - cx, - ) - .text_2xl(), - ) - .child( - crate::playing_track_link( - "immersive-artist", - artist, - muted, - has_track, - ActionMenuAction::GoToArtist, - cx, - ) - .text_lg(), - ), - ), - ) - .child( - div() - .w(relative(0.5)) - .h_full() - .pr(px(IMMERSIVE_MARGIN)) - .flex() - .flex_col() - .justify_center() - .gap(px(IMMERSIVE_GAP)) - .child( - div() - .h(px(edge)) - .flex() - .flex_col() - .justify_center() - .child(lyrics), - ) - .child( - div() - .h(px(IMMERSIVE_CAPTION_BLOCK)) - .px_4() - .flex() - .flex_col() - .gap_1() - .child(app.seek_bar(controls, cx).h(px(IMMERSIVE_SEEK_ROW))) - .child( - app.transport_controls(controls, cx) - .h(px(IMMERSIVE_TRANSPORT_ROW)) - .justify_center(), - ), - ), - ) - // The exact pixels the search bar gives its three buttons (pr_4 from the edge), so the - // toggle and settings never move out from under the pointer. The queue takes the theme - // picker's slot; opening it leaves the view. - .child( - div() - .absolute() - .top_2() - .right(px(16.0)) - .flex() - .flex_row() - .child(immersive_button(colors.accent, colors.wash, cx)) - .child(crate::icon_button( - "queue", - "icons/playlist.svg", - muted, - colors.wash, - cx, - |this, cx| this.toggle_queue_view(cx), - )) - .child(crate::icon_button( - "settings", - "icons/settings.svg", - muted, - colors.wash, - cx, - |this, cx| this.toggle_settings(cx), - )), - ) -} - /// The theme picker: every loaded theme by name, the active one accented. /// Theme names in the order the picker lists them. `EchoApp::theme_modal_index` indexes into /// this, so keyboard selection and rendering must both go through here or the two drift. @@ -4428,64 +4149,3 @@ pub fn prompt_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoEl ), ) } - -#[cfg(test)] -mod immersive_tests { - use super::*; - use echo_core::models::LyricLine; - - fn line(start_ms: u32) -> LyricLine { - LyricLine { - start_ms, - text: String::new(), - } - } - - #[test] - fn current_lyric_is_last_started_line() { - let lines = [line(0), line(1_000), line(2_000)]; - assert_eq!(current_lyric_index(&lines, 0), 0); - assert_eq!(current_lyric_index(&lines, 1_500), 1); - assert_eq!(current_lyric_index(&lines, 9_000), 2); - } - - #[test] - fn current_lyric_before_first_line_is_first() { - let lines = [line(500), line(1_000)]; - assert_eq!(current_lyric_index(&lines, 100), 0); - assert_eq!(current_lyric_index(&[], 100), 0); - } - - #[test] - fn cover_edge_fits_the_narrower_axis() { - // Wide body: the half-width minus margins bounds the square (504), scaled to 378. - assert_eq!(immersive_cover_edge(1200.0, 900.0), 378.0); - // Short body: the height minus margins and the caption bounds it (316), scaled to 237. - assert_eq!(immersive_cover_edge(1600.0, 500.0), 237.0); - } - - #[test] - fn lyric_opacity_eases_to_transparent_past_the_edge() { - assert_eq!(lyric_opacity(0.0, 5.0), 1.0); - assert!(lyric_opacity(1.0, 5.0) > 0.9); - assert!(lyric_opacity(4.0, 5.0) < 0.4); - assert!(lyric_opacity(4.0, 5.0) > 0.3); - assert_eq!(lyric_opacity(5.0, 5.0), 0.0); - assert_eq!(lyric_opacity(9.0, 5.0), 0.0); - } - - #[test] - fn lyric_window_holds_an_odd_number_of_whole_rows() { - assert_eq!(lyric_window_rows(360.0, 40.0), 9); - assert_eq!(lyric_window_rows(434.0, 40.0), 9); - assert_eq!(lyric_window_rows(479.0, 40.0), 11); - assert_eq!(lyric_window_rows(0.0, 40.0), 1); - assert_eq!(lyric_window_rows(80.0, 40.0), 1); - } - - #[test] - fn cover_edge_is_capped_and_never_negative() { - assert_eq!(immersive_cover_edge(4000.0, 3000.0), IMMERSIVE_COVER_MAX); - assert_eq!(immersive_cover_edge(50.0, 50.0), 0.0); - } -} diff --git a/crates/echo-desktop/src/views/immersive.rs b/crates/echo-desktop/src/views/immersive.rs new file mode 100644 index 0000000..2432203 --- /dev/null +++ b/crates/echo-desktop/src/views/immersive.rs @@ -0,0 +1,356 @@ +use super::*; + +/// The backdrop's picture over the whole window, under everything else: the keyframe before +/// `phase` with the one after it crossfaded on top. Painted straight from the texture as a fill +/// (its guard border just outside the window) rather than through `img`, which takes the +/// texture's aspect ratio as the box's and would paint a square. +pub fn backdrop_layer( + backdrop: std::sync::Arc, + phase: f32, + corners: Option, +) -> impl IntoElement { + let radii = client_corner_radii(corners, ClientCorners::All); + let (first, second, blend) = backdrop.frame(phase); + let layer = |image: std::sync::Arc| { + let backdrop = backdrop.clone(); + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let image_bounds = backdrop.image_bounds(bounds); + window + .paint_image(bounds, image_bounds, radii, image, 0, false) + .ok(); + }, + ) + .absolute() + .inset_0() + }; + div() + .absolute() + .inset_0() + .child(layer(first)) + .when(blend > 0.0, |el| { + el.child( + div() + .absolute() + .inset_0() + .opacity(blend) + .child(layer(second)), + ) + }) +} + +/// The immersive toggle. Callers pick its colors: the search bar paints it muted in the theme, +/// the immersive view accented in the cover's colors. It is the one control the immersive view +/// keeps, so it lives here rather than inline in the search bar. +pub(super) fn immersive_button( + color: Hsla, + hover: Hsla, + cx: &mut Context, +) -> impl IntoElement { + crate::icon_button( + "immersive", + "icons/full-screen.svg", + color, + hover, + cx, + |this, cx| this.toggle_immersive(cx), + ) +} + +/// Edge of the immersive cover, in pixels, for a body of `width` x `height`: the largest square +/// that, with the caption under it, fits the height inside the margins, bounded by the +/// half-width; then scaled down to leave air around it, and capped for very tall windows. +pub(crate) fn immersive_cover_edge(width: f32, height: f32) -> f32 { + let by_width = width * 0.5 - 2.0 * IMMERSIVE_MARGIN; + let by_height = height - 2.0 * IMMERSIVE_MARGIN - IMMERSIVE_CAPTION_HEIGHT; + (by_width.min(by_height) * IMMERSIVE_COVER_SCALE).clamp(0.0, IMMERSIVE_COVER_MAX) +} + +/// Rows in the immersive lyric window for a panel `panel_height` tall: as many whole rows as +/// fit, made odd so one row is the exact center, and at least one. +pub(crate) fn lyric_window_rows(panel_height: f32, row_height: f32) -> usize { + let rows = (panel_height / row_height).max(1.0) as usize; + if rows.is_multiple_of(2) { + rows - 1 + } else { + rows + } +} + +/// Opacity of a lyric row `distance` rows from the center when the row just past the window's +/// edge is `reach` rows away: full at the center, easing out so the neighbors stay readable and +/// reaching transparent one row beyond the edge — the Apple Music fade. `distance` is +/// fractional mid-glide. +pub(crate) fn lyric_opacity(distance: f32, reach: f32) -> f32 { + let t = (distance / reach).min(1.0); + 1.0 - t * t +} + +const IMMERSIVE_MARGIN: f32 = 48.0; + +/// Both halves stack a cover-high box, a gap and a caption-high block, centered; so the +/// right's lyrics box centers on the cover and its controls block tops out with the title. +/// The caption block is the title's 32px text_2xl line, gap_1, the artist's 28px text_lg line; +/// the controls block is the seek row, gap_1, the transport row, the same 64. +const IMMERSIVE_CAPTION_HEIGHT: f32 = IMMERSIVE_GAP + IMMERSIVE_CAPTION_BLOCK; + +const IMMERSIVE_CAPTION_BLOCK: f32 = 32.0 + 4.0 + 28.0; + +const IMMERSIVE_GAP: f32 = 24.0; + +const IMMERSIVE_SEEK_ROW: f32 = 24.0; + +const IMMERSIVE_TRANSPORT_ROW: f32 = IMMERSIVE_CAPTION_BLOCK - 4.0 - IMMERSIVE_SEEK_ROW; + +const IMMERSIVE_COVER_SCALE: f32 = 0.75; + +const IMMERSIVE_COVER_MAX: f32 = 480.0; + +/// The lyric window fills up to this share of the body height, and never more than the cover. +const IMMERSIVE_LYRICS_SHARE: f32 = 0.5; + +const IMMERSIVE_LYRIC_ROW: f32 = 40.0; + +/// The immersive view: the cover with the track's title and artist under it, that whole block +/// centered in the left half; on the right the synced lyrics, centered on the cover, with the +/// seek bar and transport under them level with the caption; and top right, in the search +/// bar's slots, the toggle, the queue (where the theme picker sits otherwise) and settings. +/// Everything else — sidebar, navigation, search, playback bar — is gone until it is toggled +/// off. Lyric lines are centered so each shares its axis with the seek bar and play button. Every color comes from `backdrop`, derived from the cover +/// (see [`crate::backdrop`]); the backdrop's picture and window fill are the root's, so they +/// reach under the titlebar too. +pub fn immersive_view( + app: &mut EchoApp, + backdrop: &Backdrop, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + let colors = backdrop.colors; + let (fg, muted) = (colors.text, colors.text_muted); + let controls = ControlColors { + fg, + muted, + accent: colors.accent, + hover: colors.wash, + track: colors.wash, + }; + let playback = &app.state.playback; + let has_track = playback.playing_track_id.is_some(); + let title: SharedString = if playback.playing_track_title.is_empty() { + tr(&app.state, "desktop.nothing_playing") + } else { + playback.playing_track_title.clone().into() + }; + let artist: SharedString = playback.playing_track_artist.clone().into(); + let viewport = window.viewport_size(); + let body_height = f32::from(viewport.height) - TITLEBAR_HEIGHT; + let edge = immersive_cover_edge(f32::from(viewport.width), body_height); + let rows = lyric_window_rows( + edge.min(body_height * IMMERSIVE_LYRICS_SHARE), + IMMERSIVE_LYRIC_ROW, + ); + let cover = playback + .playing_track_image + .as_ref() + .or(playback.previous_track_image.as_ref()) + .cloned() + .and_then(|artwork| app.images.get(&artwork)); + let cover = match cover { + Some(image) => cover_image(image, edge, 8.0).into_any_element(), + None => div() + .flex_none() + .w(px(edge)) + .h(px(edge)) + .rounded_lg() + .bg(colors.wash) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path("icons/music-note.svg") + .w(px(edge * 0.25)) + .h(px(edge * 0.25)) + .text_color(muted), + ) + .into_any_element(), + }; + let lyrics = lyric_status(app, muted).unwrap_or_else(|| { + lyric_window( + app, + LyricColors::immersive(&colors), + rows, + IMMERSIVE_LYRIC_ROW, + ) + }); + + div() + .id("immersive") + .relative() + .flex_grow(1.0) + .flex() + .flex_row() + .overflow_hidden() + .child( + div() + .w(relative(0.5)) + .h_full() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(px(IMMERSIVE_GAP)) + .child(cover) + .child( + div() + .w(px(edge)) + .flex() + .flex_col() + .gap_1() + .child( + crate::playing_track_link( + "immersive-title", + title, + fg, + has_track, + ActionMenuAction::GoToAlbum, + cx, + ) + .text_2xl(), + ) + .child( + crate::playing_track_link( + "immersive-artist", + artist, + muted, + has_track, + ActionMenuAction::GoToArtist, + cx, + ) + .text_lg(), + ), + ), + ) + .child( + div() + .w(relative(0.5)) + .h_full() + .pr(px(IMMERSIVE_MARGIN)) + .flex() + .flex_col() + .justify_center() + .gap(px(IMMERSIVE_GAP)) + .child( + div() + .h(px(edge)) + .flex() + .flex_col() + .justify_center() + .child(lyrics), + ) + .child( + div() + .h(px(IMMERSIVE_CAPTION_BLOCK)) + .px_4() + .flex() + .flex_col() + .gap_1() + .child(app.seek_bar(controls, cx).h(px(IMMERSIVE_SEEK_ROW))) + .child( + app.transport_controls(controls, cx) + .h(px(IMMERSIVE_TRANSPORT_ROW)) + .justify_center(), + ), + ), + ) + // The exact pixels the search bar gives its three buttons (pr_4 from the edge), so the + // toggle and settings never move out from under the pointer. The queue takes the theme + // picker's slot; opening it leaves the view. + .child( + div() + .absolute() + .top_2() + .right(px(16.0)) + .flex() + .flex_row() + .child(immersive_button(colors.accent, colors.wash, cx)) + .child(crate::icon_button( + "queue", + "icons/playlist.svg", + muted, + colors.wash, + cx, + |this, cx| this.toggle_queue_view(cx), + )) + .child(crate::icon_button( + "settings", + "icons/settings.svg", + muted, + colors.wash, + cx, + |this, cx| this.toggle_settings(cx), + )), + ) +} + +#[cfg(test)] +mod immersive_tests { + use super::*; + use echo_core::models::LyricLine; + + fn line(start_ms: u32) -> LyricLine { + LyricLine { + start_ms, + text: String::new(), + } + } + + #[test] + fn current_lyric_is_last_started_line() { + let lines = [line(0), line(1_000), line(2_000)]; + assert_eq!(current_lyric_index(&lines, 0), 0); + assert_eq!(current_lyric_index(&lines, 1_500), 1); + assert_eq!(current_lyric_index(&lines, 9_000), 2); + } + + #[test] + fn current_lyric_before_first_line_is_first() { + let lines = [line(500), line(1_000)]; + assert_eq!(current_lyric_index(&lines, 100), 0); + assert_eq!(current_lyric_index(&[], 100), 0); + } + + #[test] + fn cover_edge_fits_the_narrower_axis() { + // Wide body: the half-width minus margins bounds the square (504), scaled to 378. + assert_eq!(immersive_cover_edge(1200.0, 900.0), 378.0); + // Short body: the height minus margins and the caption bounds it (316), scaled to 237. + assert_eq!(immersive_cover_edge(1600.0, 500.0), 237.0); + } + + #[test] + fn lyric_opacity_eases_to_transparent_past_the_edge() { + assert_eq!(lyric_opacity(0.0, 5.0), 1.0); + assert!(lyric_opacity(1.0, 5.0) > 0.9); + assert!(lyric_opacity(4.0, 5.0) < 0.4); + assert!(lyric_opacity(4.0, 5.0) > 0.3); + assert_eq!(lyric_opacity(5.0, 5.0), 0.0); + assert_eq!(lyric_opacity(9.0, 5.0), 0.0); + } + + #[test] + fn lyric_window_holds_an_odd_number_of_whole_rows() { + assert_eq!(lyric_window_rows(360.0, 40.0), 9); + assert_eq!(lyric_window_rows(434.0, 40.0), 9); + assert_eq!(lyric_window_rows(479.0, 40.0), 11); + assert_eq!(lyric_window_rows(0.0, 40.0), 1); + assert_eq!(lyric_window_rows(80.0, 40.0), 1); + } + + #[test] + fn cover_edge_is_capped_and_never_negative() { + assert_eq!(immersive_cover_edge(4000.0, 3000.0), IMMERSIVE_COVER_MAX); + assert_eq!(immersive_cover_edge(50.0, 50.0), 0.0); + } +} From 0f47457445fe2169c52787745a137abe40b15468 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:22 -0500 Subject: [PATCH 11/44] desktop: move the home view into views/home.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 403 +------------------------- crates/echo-desktop/src/views/home.rs | 402 +++++++++++++++++++++++++ 2 files changed, 404 insertions(+), 401 deletions(-) create mode 100644 crates/echo-desktop/src/views/home.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 2a07056..c44e800 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -16,6 +16,7 @@ use echo_core::thumbnails::{ThumbState, ThumbTier, tier_for_edge}; mod artist; mod chrome; mod drag; +mod home; mod immersive; mod lyrics; mod menu_placement; @@ -33,6 +34,7 @@ use gpui::{ MouseDownEvent, SharedString, Stateful, Window, canvas, div, ease_out_quint, prelude::*, px, relative, svg, uniform_list, }; +use home::*; pub(crate) use immersive::*; pub(crate) use lyrics::*; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; @@ -3066,407 +3068,6 @@ fn library_placeholder(app: &EchoApp) -> AnyElement { .into_any_element() } -fn home_item_title( - state: &echo_core::app::AppState, - item: &echo_core::home::HomeItem, -) -> SharedString { - if item.id == "LIKED_SONGS" { - tr(state, "desktop.home_liked_songs") - } else { - item.title.clone().into() - } -} - -fn home_play_button( - item: echo_core::home::HomeItem, - search_row: Option, - accent: Hsla, - fg: Hsla, - cx: &mut Context, -) -> impl IntoElement { - div() - .id("home-play") - .absolute() - .right(px(8.0)) - .bottom(px(8.0)) - .size(px(36.0)) - .rounded_full() - .bg(accent) - .flex() - .items_center() - .justify_center() - .invisible() - .group_hover("home-item", |style| style.visible()) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _, window, cx| { - cx.stop_propagation(); - window.focus(&this.focus_handle, cx); - let event = if let Some(row) = search_row { - echo_core::intent::play_search_row(&mut this.state, row) - } else { - echo_core::intent::play_home_item(&mut this.state, item.clone()) - }; - if let Some(event) = event { - this.dispatch(event); - } - cx.notify(); - })) - .child(svg().path("icons/play.svg").size(px(18.0)).text_color(fg)) -} - -fn home_card( - app: &mut EchoApp, - item: echo_core::home::HomeItem, - index: usize, - quick: bool, - search_row: Option, - cx: &mut Context, -) -> AnyElement { - use echo_core::home::HomeItemKind; - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let background = theme.background.gpui(crate::theme::WINDOW_BG()); - let title = home_item_title(&app.state, &item); - let subtitle = if item.kind == HomeItemKind::Artist { - tr(&app.state, "desktop.home_artist") - } else if let Some(year) = &item.release_year { - year.clone().into() - } else { - item.subtitle.clone().into() - }; - let selected = if search_row.is_some() { - app.state.ui.selected_search_index == index - } else { - app.state.ui.active_view == ActiveView::Home && app.state.ui.selected_home_index == index - }; - let edge = if quick { 56.0 } else { 160.0 }; - let cover = if item.id == "LIKED_SONGS" { - div() - .size(px(edge)) - .flex_none() - .rounded(px(8.0)) - .bg(palette.wash) - .flex() - .items_center() - .justify_center() - .child( - svg() - .path("icons/heart.svg") - .size(px(edge * 0.45)) - .text_color(accent), - ) - .into_any_element() - } else { - thumb_element( - app, - item.image_url.as_deref(), - edge, - item.kind == HomeItemKind::Artist, - muted, - ) - }; - let play = if search_row.is_none() || !item.id.starts_with("local-") { - home_play_button(item.clone(), search_row, accent, background, cx).into_any_element() - } else { - div().absolute().into_any_element() - }; - let base = div() - .id(("home-item", index)) - .group("home-item") - .relative() - .min_w_0() - .cursor_pointer() - .rounded(px(8.0)) - .text_color(fg) - .when(selected, |el| el.bg(palette.row_selected)) - .hover(move |style| style.bg(palette.row_hover)) - .on_click(cx.listener(move |this: &mut EchoApp, _, window, cx| { - window.focus(&this.focus_handle, cx); - let event = if search_row.is_some() { - echo_core::intent::activate_search_result(&mut this.state, index) - } else { - this.state.ui.selected_home_index = index; - echo_core::intent::open_home_item(&mut this.state, item.clone()) - }; - if let Some(event) = event { - this.dispatch(event); - } - cx.notify(); - })); - if quick { - base.flex_1() - .h(px(56.0)) - .flex() - .items_center() - .gap_2() - .overflow_hidden() - .border_1() - .border_color(palette.border) - .when(!selected, |el| el.bg(palette.wash)) - .child(cover) - .child( - div() - .min_w_0() - .flex_1() - .pr_2() - .text_sm() - .font_weight(gpui::FontWeight::BOLD) - .line_clamp(2) - .child(title), - ) - .child(play) - .into_any_element() - } else { - base.flex_none() - .w(px(160.0)) - .flex() - .flex_col() - .gap_2() - .child(div().relative().size(px(160.0)).child(cover).child(play)) - .child( - div() - .px_1() - .h(px(40.0)) - .text_sm() - .font_weight(gpui::FontWeight::BOLD) - .line_clamp(2) - .child(title), - ) - .child( - div() - .px_1() - .pb_2() - .text_xs() - .text_color(muted) - .truncate() - .child(subtitle), - ) - .into_any_element() - } -} - -/// Horizontal scrollbar under a Home shelf, colored like the seek bar: `border` track, -/// `accent` thumb. -fn home_scrollbar( - scroll: gpui::ScrollHandle, - palette: DesktopPalette, - accent: Hsla, - cx: &mut Context, -) -> impl IntoElement { - let paint_scroll = scroll.clone(); - div() - .id("home-scrollbar") - .h(px(12.0)) - .w_full() - .cursor_pointer() - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _, cx| { - this.begin_shelf_scrub(scroll.clone(), event.position.x); - cx.stop_propagation(); - cx.notify(); - }), - ) - .child( - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let max = f32::from(paint_scroll.max_offset().x); - if max <= 0.0 { - return; - } - let width = f32::from(bounds.size.width); - let thumb = (width * width / (width + max)).max(24.0).min(width); - let left = -f32::from(paint_scroll.offset().x) / max * (width - thumb); - window.paint_quad(gpui::fill( - gpui::Bounds::new( - bounds.origin + gpui::point(px(0.0), px(4.0)), - gpui::size(bounds.size.width, px(4.0)), - ), - palette.border, - )); - window.paint_quad(gpui::fill( - gpui::Bounds::new( - bounds.origin + gpui::point(px(left), px(4.0)), - gpui::size(px(thumb), px(4.0)), - ), - accent, - )); - }, - ) - .size_full(), - ) -} - -fn home_view( - app: &mut EchoApp, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - use echo_core::home::{HomeShelfKind, home_shelves, pending_shelves}; - let palette = DesktopPalette::resolve(&app.state.ui.active_theme); - let fg = app.state.ui.active_theme.text.gpui(WINDOW_FG()); - let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); - let accent = app.state.ui.active_theme.primary.gpui(WINDOW_FG()); - let mut shelves = home_shelves(&app.state); - let width = app.main_content_width(window); - let columns = if width >= 640.0 { - 4 - } else if width >= 320.0 { - 2 - } else { - 1 - }; - let pending = pending_shelves(&app.state.data.home_fetches); - let empty = shelves - .iter() - .all(|shelf| shelf.kind == HomeShelfKind::QuickPicks); - let mut content = div() - .id("home-scroll") - .flex_1() - .min_h_0() - .w_full() - .overflow_y_scroll() - .track_scroll(&app.home_scroll) - // Shelves clip at the main area's edge; only non-scrolling content is inset. - .py_4() - .flex() - .flex_col() - .gap_6() - .child( - div() - .flex_none() - .px_4() - .flex() - .flex_col() - .gap_2() - .child( - div() - .text_size(px(28.0)) - .font_weight(gpui::FontWeight::BOLD) - .text_color(fg) - .child(tr(&app.state, echo_core::home::local_greeting_key())), - ) - .when(empty, |el| { - el.child( - div() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.home_empty")), - ) - }), - ); - let mut index = 0; - let mut section = 1; - app.home_section_indices.clear(); - for kind in HomeShelfKind::ALL { - let Some(position) = shelves.iter().position(|shelf| shelf.kind == kind) else { - if pending.contains(&kind) { - content = content.child( - div() - .flex_none() - .px_4() - .flex() - .flex_col() - .gap_2() - .child( - div() - .text_size(px(18.0)) - .font_weight(gpui::FontWeight::BOLD) - .text_color(fg) - .child(tr(&app.state, kind.title_key())), - ) - .child( - div() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.home_loading")), - ), - ); - section += 1; - } - continue; - }; - let shelf = shelves.remove(position); - app.home_section_indices.insert(kind, section); - section += 1; - if shelf.kind == HomeShelfKind::QuickPicks { - let mut grid = div().flex_none().px_4().flex().flex_col().gap_2(); - for chunk in shelf.items.chunks(columns) { - let mut row = div().flex().gap_2().w_full(); - for item in chunk { - row = row.child(home_card(app, item.clone(), index, true, None, cx)); - index += 1; - } - for _ in chunk.len()..columns { - row = row.child(div().flex_1().min_w_0()); - } - grid = grid.child(row); - } - content = content.child(grid); - continue; - } - let scroll = app - .home_shelf_scrolls - .entry(shelf.kind) - .or_default() - .clone(); - let wheel_scroll = scroll.clone(); - let mut row = div() - .id(SharedString::from(format!("home-shelf-{:?}", shelf.kind))) - .flex() - .gap_3() - // Scroll the end spacing with the cards instead of clipping before the gutter. - .px_4() - .overflow_x_scroll() - .restrict_scroll_to_axis() - .track_scroll(&scroll) - .on_scroll_wheel(cx.listener( - move |_: &mut EchoApp, event: &gpui::ScrollWheelEvent, window, cx| { - if event.modifiers.shift { - let delta = event.delta.pixel_delta(window.line_height()); - let x = wheel_scroll.offset().x - + if delta.x != px(0.0) { delta.x } else { delta.y }; - wheel_scroll.set_offset(gpui::point( - x.clamp(-wheel_scroll.max_offset().x, px(0.0)), - px(0.0), - )); - cx.stop_propagation(); - cx.notify(); - } - }, - )); - for item in shelf.items { - row = row.child(home_card(app, item, index, false, None, cx)); - index += 1; - } - content = content.child( - div() - .id(SharedString::from(format!("home-section-{:?}", shelf.kind))) - .flex_none() - .min_w_0() - .flex() - .flex_col() - .gap_3() - .child( - div() - .text_size(px(18.0)) - .font_weight(gpui::FontWeight::BOLD) - .text_color(fg) - .px_4() - .child(tr(&app.state, shelf.kind.title_key())), - ) - .child(row) - .child(home_scrollbar(scroll, palette, accent, cx)), - ); - } - echo_core::thumbnails::drain_pending(&mut app.state, &app.worker_tx); - content -} - fn lerp_hsla(a: gpui::Hsla, b: gpui::Hsla, t: f32) -> gpui::Hsla { let a: gpui::Rgba = a.into(); let b: gpui::Rgba = b.into(); diff --git a/crates/echo-desktop/src/views/home.rs b/crates/echo-desktop/src/views/home.rs new file mode 100644 index 0000000..4cf97e5 --- /dev/null +++ b/crates/echo-desktop/src/views/home.rs @@ -0,0 +1,402 @@ +use super::*; + +fn home_item_title( + state: &echo_core::app::AppState, + item: &echo_core::home::HomeItem, +) -> SharedString { + if item.id == "LIKED_SONGS" { + tr(state, "desktop.home_liked_songs") + } else { + item.title.clone().into() + } +} + +fn home_play_button( + item: echo_core::home::HomeItem, + search_row: Option, + accent: Hsla, + fg: Hsla, + cx: &mut Context, +) -> impl IntoElement { + div() + .id("home-play") + .absolute() + .right(px(8.0)) + .bottom(px(8.0)) + .size(px(36.0)) + .rounded_full() + .bg(accent) + .flex() + .items_center() + .justify_center() + .invisible() + .group_hover("home-item", |style| style.visible()) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _, window, cx| { + cx.stop_propagation(); + window.focus(&this.focus_handle, cx); + let event = if let Some(row) = search_row { + echo_core::intent::play_search_row(&mut this.state, row) + } else { + echo_core::intent::play_home_item(&mut this.state, item.clone()) + }; + if let Some(event) = event { + this.dispatch(event); + } + cx.notify(); + })) + .child(svg().path("icons/play.svg").size(px(18.0)).text_color(fg)) +} + +pub(super) fn home_card( + app: &mut EchoApp, + item: echo_core::home::HomeItem, + index: usize, + quick: bool, + search_row: Option, + cx: &mut Context, +) -> AnyElement { + use echo_core::home::HomeItemKind; + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let background = theme.background.gpui(crate::theme::WINDOW_BG()); + let title = home_item_title(&app.state, &item); + let subtitle = if item.kind == HomeItemKind::Artist { + tr(&app.state, "desktop.home_artist") + } else if let Some(year) = &item.release_year { + year.clone().into() + } else { + item.subtitle.clone().into() + }; + let selected = if search_row.is_some() { + app.state.ui.selected_search_index == index + } else { + app.state.ui.active_view == ActiveView::Home && app.state.ui.selected_home_index == index + }; + let edge = if quick { 56.0 } else { 160.0 }; + let cover = if item.id == "LIKED_SONGS" { + div() + .size(px(edge)) + .flex_none() + .rounded(px(8.0)) + .bg(palette.wash) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path("icons/heart.svg") + .size(px(edge * 0.45)) + .text_color(accent), + ) + .into_any_element() + } else { + thumb_element( + app, + item.image_url.as_deref(), + edge, + item.kind == HomeItemKind::Artist, + muted, + ) + }; + let play = if search_row.is_none() || !item.id.starts_with("local-") { + home_play_button(item.clone(), search_row, accent, background, cx).into_any_element() + } else { + div().absolute().into_any_element() + }; + let base = div() + .id(("home-item", index)) + .group("home-item") + .relative() + .min_w_0() + .cursor_pointer() + .rounded(px(8.0)) + .text_color(fg) + .when(selected, |el| el.bg(palette.row_selected)) + .hover(move |style| style.bg(palette.row_hover)) + .on_click(cx.listener(move |this: &mut EchoApp, _, window, cx| { + window.focus(&this.focus_handle, cx); + let event = if search_row.is_some() { + echo_core::intent::activate_search_result(&mut this.state, index) + } else { + this.state.ui.selected_home_index = index; + echo_core::intent::open_home_item(&mut this.state, item.clone()) + }; + if let Some(event) = event { + this.dispatch(event); + } + cx.notify(); + })); + if quick { + base.flex_1() + .h(px(56.0)) + .flex() + .items_center() + .gap_2() + .overflow_hidden() + .border_1() + .border_color(palette.border) + .when(!selected, |el| el.bg(palette.wash)) + .child(cover) + .child( + div() + .min_w_0() + .flex_1() + .pr_2() + .text_sm() + .font_weight(gpui::FontWeight::BOLD) + .line_clamp(2) + .child(title), + ) + .child(play) + .into_any_element() + } else { + base.flex_none() + .w(px(160.0)) + .flex() + .flex_col() + .gap_2() + .child(div().relative().size(px(160.0)).child(cover).child(play)) + .child( + div() + .px_1() + .h(px(40.0)) + .text_sm() + .font_weight(gpui::FontWeight::BOLD) + .line_clamp(2) + .child(title), + ) + .child( + div() + .px_1() + .pb_2() + .text_xs() + .text_color(muted) + .truncate() + .child(subtitle), + ) + .into_any_element() + } +} + +/// Horizontal scrollbar under a Home shelf, colored like the seek bar: `border` track, +/// `accent` thumb. +fn home_scrollbar( + scroll: gpui::ScrollHandle, + palette: DesktopPalette, + accent: Hsla, + cx: &mut Context, +) -> impl IntoElement { + let paint_scroll = scroll.clone(); + div() + .id("home-scrollbar") + .h(px(12.0)) + .w_full() + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _, cx| { + this.begin_shelf_scrub(scroll.clone(), event.position.x); + cx.stop_propagation(); + cx.notify(); + }), + ) + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let max = f32::from(paint_scroll.max_offset().x); + if max <= 0.0 { + return; + } + let width = f32::from(bounds.size.width); + let thumb = (width * width / (width + max)).max(24.0).min(width); + let left = -f32::from(paint_scroll.offset().x) / max * (width - thumb); + window.paint_quad(gpui::fill( + gpui::Bounds::new( + bounds.origin + gpui::point(px(0.0), px(4.0)), + gpui::size(bounds.size.width, px(4.0)), + ), + palette.border, + )); + window.paint_quad(gpui::fill( + gpui::Bounds::new( + bounds.origin + gpui::point(px(left), px(4.0)), + gpui::size(px(thumb), px(4.0)), + ), + accent, + )); + }, + ) + .size_full(), + ) +} + +pub(super) fn home_view( + app: &mut EchoApp, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + use echo_core::home::{HomeShelfKind, home_shelves, pending_shelves}; + let palette = DesktopPalette::resolve(&app.state.ui.active_theme); + let fg = app.state.ui.active_theme.text.gpui(WINDOW_FG()); + let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); + let accent = app.state.ui.active_theme.primary.gpui(WINDOW_FG()); + let mut shelves = home_shelves(&app.state); + let width = app.main_content_width(window); + let columns = if width >= 640.0 { + 4 + } else if width >= 320.0 { + 2 + } else { + 1 + }; + let pending = pending_shelves(&app.state.data.home_fetches); + let empty = shelves + .iter() + .all(|shelf| shelf.kind == HomeShelfKind::QuickPicks); + let mut content = div() + .id("home-scroll") + .flex_1() + .min_h_0() + .w_full() + .overflow_y_scroll() + .track_scroll(&app.home_scroll) + // Shelves clip at the main area's edge; only non-scrolling content is inset. + .py_4() + .flex() + .flex_col() + .gap_6() + .child( + div() + .flex_none() + .px_4() + .flex() + .flex_col() + .gap_2() + .child( + div() + .text_size(px(28.0)) + .font_weight(gpui::FontWeight::BOLD) + .text_color(fg) + .child(tr(&app.state, echo_core::home::local_greeting_key())), + ) + .when(empty, |el| { + el.child( + div() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.home_empty")), + ) + }), + ); + let mut index = 0; + let mut section = 1; + app.home_section_indices.clear(); + for kind in HomeShelfKind::ALL { + let Some(position) = shelves.iter().position(|shelf| shelf.kind == kind) else { + if pending.contains(&kind) { + content = content.child( + div() + .flex_none() + .px_4() + .flex() + .flex_col() + .gap_2() + .child( + div() + .text_size(px(18.0)) + .font_weight(gpui::FontWeight::BOLD) + .text_color(fg) + .child(tr(&app.state, kind.title_key())), + ) + .child( + div() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.home_loading")), + ), + ); + section += 1; + } + continue; + }; + let shelf = shelves.remove(position); + app.home_section_indices.insert(kind, section); + section += 1; + if shelf.kind == HomeShelfKind::QuickPicks { + let mut grid = div().flex_none().px_4().flex().flex_col().gap_2(); + for chunk in shelf.items.chunks(columns) { + let mut row = div().flex().gap_2().w_full(); + for item in chunk { + row = row.child(home_card(app, item.clone(), index, true, None, cx)); + index += 1; + } + for _ in chunk.len()..columns { + row = row.child(div().flex_1().min_w_0()); + } + grid = grid.child(row); + } + content = content.child(grid); + continue; + } + let scroll = app + .home_shelf_scrolls + .entry(shelf.kind) + .or_default() + .clone(); + let wheel_scroll = scroll.clone(); + let mut row = div() + .id(SharedString::from(format!("home-shelf-{:?}", shelf.kind))) + .flex() + .gap_3() + // Scroll the end spacing with the cards instead of clipping before the gutter. + .px_4() + .overflow_x_scroll() + .restrict_scroll_to_axis() + .track_scroll(&scroll) + .on_scroll_wheel(cx.listener( + move |_: &mut EchoApp, event: &gpui::ScrollWheelEvent, window, cx| { + if event.modifiers.shift { + let delta = event.delta.pixel_delta(window.line_height()); + let x = wheel_scroll.offset().x + + if delta.x != px(0.0) { delta.x } else { delta.y }; + wheel_scroll.set_offset(gpui::point( + x.clamp(-wheel_scroll.max_offset().x, px(0.0)), + px(0.0), + )); + cx.stop_propagation(); + cx.notify(); + } + }, + )); + for item in shelf.items { + row = row.child(home_card(app, item, index, false, None, cx)); + index += 1; + } + content = content.child( + div() + .id(SharedString::from(format!("home-section-{:?}", shelf.kind))) + .flex_none() + .min_w_0() + .flex() + .flex_col() + .gap_3() + .child( + div() + .text_size(px(18.0)) + .font_weight(gpui::FontWeight::BOLD) + .text_color(fg) + .px_4() + .child(tr(&app.state, shelf.kind.title_key())), + ) + .child(row) + .child(home_scrollbar(scroll, palette, accent, cx)), + ); + } + echo_core::thumbnails::drain_pending(&mut app.state, &app.worker_tx); + content +} From b205c7b342223daad2fa8770b38094ec10f074fa Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:23 -0500 Subject: [PATCH 12/44] desktop: move the context menus into views/menus.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 471 +------------------------ crates/echo-desktop/src/views/menus.rs | 471 +++++++++++++++++++++++++ 2 files changed, 473 insertions(+), 469 deletions(-) create mode 100644 crates/echo-desktop/src/views/menus.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index c44e800..3220a75 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -20,6 +20,7 @@ mod home; mod immersive; mod lyrics; mod menu_placement; +mod menus; pub(crate) mod panel_layout; mod playlist_edit; mod queue; @@ -38,6 +39,7 @@ use home::*; pub(crate) use immersive::*; pub(crate) use lyrics::*; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; +pub(crate) use menus::*; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; use queue::*; pub(crate) use sidebar::*; @@ -47,10 +49,6 @@ use crate::backdrop::{Backdrop, ImmersiveColors}; use crate::theme::{DesktopPalette, ToGpui, WINDOW_FG}; use crate::{ControlColors, EchoApp, MenuAction, TrackMenuItem, UpdateState, format_time}; -/// The add-to-playlist flyout's preferred dimensions. -const SUBMENU_WIDTH: f32 = 190.0; -const SUBMENU_MAX_H: f32 = 270.0; - /// The shape of a selectable list row: the fixed height `uniform_list` measures and the /// shorter pill drawn inside it. Hover strength comes from the palette slot the caller /// passes ([`DesktopPalette::row_hover`] for both the sidebar and the main @@ -3080,471 +3078,6 @@ fn lerp_hsla(a: gpui::Hsla, b: gpui::Hsla, t: f32) -> gpui::Hsla { .into() } -/// The sidebar right-click menu: items depend on what the row is, actions run through -/// [`EchoApp::run_menu_action`]. Destructive items stage a prompt for [`prompt_modal`]. -pub fn context_menu( - app: &mut EchoApp, - window: &Window, - cx: &mut Context, -) -> impl IntoElement { - let menu = app - .context_menu - .clone() - .expect("context_menu rendered without state"); - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let danger_color = gpui::hsla(0.0, 0.7, 0.6, 1.0); - - let mut items: Vec<(SharedString, MenuAction, bool)> = Vec::new(); - if app.state.ui.active_library_tab == LibraryTab::Albums { - if app.state.data.saved_albums.get(menu.index).is_some() { - items.push((tr(&app.state, "desktop.menu.open"), MenuAction::Open, false)); - items.push(( - tr(&app.state, "desktop.menu.remove_library"), - MenuAction::RemoveAlbum, - true, - )); - } - } else if let Some(node) = app.state.data.library_view.get(menu.index) { - match node { - LibraryNode::Folder(_) => { - items.push(( - tr(&app.state, "desktop.menu.rename"), - MenuAction::Rename, - false, - )); - items.push(( - tr(&app.state, "desktop.menu.delete_folder"), - MenuAction::DeleteFolder, - true, - )); - } - LibraryNode::SpotifyFolder { .. } => {} - LibraryNode::Playlist { playlist, indent } => { - items.push((tr(&app.state, "desktop.menu.open"), MenuAction::Open, false)); - let special = playlist.id == "LIKED_SONGS" || playlist.id == "local-library"; - let local = playlist.id.starts_with("local-playlist:"); - if !special { - let pinned = app.state.ui.library_config.pinned.contains(&playlist.id); - items.push(( - tr( - &app.state, - if pinned { - "desktop.menu.unpin" - } else { - "desktop.menu.pin" - }, - ), - MenuAction::TogglePin, - false, - )); - } - if local { - items.push(( - tr(&app.state, "desktop.menu.rename"), - MenuAction::Rename, - false, - )); - } else if echo_core::intent::owns_playlist(&app.state, &playlist.id) { - items.push(( - tr(&app.state, "desktop.edit_details"), - MenuAction::EditDetails, - false, - )); - } - if *indent >= 1 && !app.state.in_spotify_folder(&playlist.id) { - items.push(( - tr(&app.state, "desktop.menu.remove_folder"), - MenuAction::RemoveFromFolder, - false, - )); - } - let own = app.state.data.user_id.as_ref() == Some(&playlist.owner_id); - if local || (!special && own) { - items.push(( - tr(&app.state, "desktop.menu.delete_playlist"), - MenuAction::DeletePlaylist, - true, - )); - } - } - } - } - - let index = menu.index; - div() - .id("context-menu-backdrop") - .absolute() - .inset_0() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.context_menu = None; - cx.notify(); - })) - .on_mouse_down( - MouseButton::Right, - cx.listener(|this: &mut EchoApp, _event: &MouseDownEvent, _window, cx| { - this.context_menu = None; - cx.notify(); - }), - ) - .child(menu_placement( - MenuAnchor::Pointer(menu.position), - div() - .id("context-menu") - .occlude() - .w(px(210.0).min(menu_bounds(window).size.width)) - .max_h(menu_bounds(window).size.height) - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .py_1() - .flex() - .flex_col() - .overflow_y_scroll() - // Clicks on the menu itself must not reach the backdrop's close handler. - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .children(items.into_iter().map(|(label, action, danger)| { - // Inset and rounded like the list rows: a full-bleed highlight would square - // off the panel's rounded corners on the first and last item. - div() - .id(label.clone()) - .flex_shrink_0() - .mx_1() - .px_2() - .py_1() - .rounded_md() - .text_sm() - .text_color(if danger { danger_color } else { fg }) - .hover(move |style| style.bg(palette.menu_hover)) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, window, cx| { - this.run_menu_action(action, index, window, cx); - })) - .child(label) - })), - )) -} - -/// Right-click menu for a track row. The item set and labels come from the core action-menu -/// model (`ActionMenuContext::actions()` / `action_menu::label`); remove-from-playlist is -/// appended for modifiable playlists. -/// The open track menu's rows: `(label, item, is_destructive)`. Keyboard selection indexes -/// into this, so it is the single source of the menu's contents. -pub fn track_menu_items(app: &EchoApp) -> Vec<(SharedString, TrackMenuItem, bool)> { - let Some(menu) = app.track_menu.as_ref() else { - return Vec::new(); - }; - let ctx = &menu.ctx; - let mut items: Vec<(SharedString, TrackMenuItem, bool)> = ctx - .actions() - .into_iter() - .map(|action| { - ( - echo_core::action_menu::label(&app.state, ctx, action).into(), - TrackMenuItem::Action(action), - false, - ) - }) - .collect(); - // Queue rows have no playlist behind them — `active_tracklist_context` is whatever was - // last browsed, so removing would hit the wrong playlist. - if app.state.ui.active_view != ActiveView::Queue - && app - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.can_modify_playlist(app.state.data.user_id.as_ref())) - { - items.push(( - tr(&app.state, "desktop.menu.remove_playlist"), - TrackMenuItem::RemoveFromPlaylist, - true, - )); - } - items -} - -pub fn track_context_menu( - app: &mut EchoApp, - window: &Window, - cx: &mut Context, -) -> impl IntoElement { - let menu = app - .track_menu - .clone() - .expect("track_context_menu rendered without state"); - let items = track_menu_items(app); - let add_row = app.track_menu_add_row(); - let row_bounds = app.submenu_row_bounds.clone(); - // Built first: it reads `app` immutably and hangs off the menu as a sibling, because the - // menu panel clips its own children. - let submenu = menu - .submenu - .map(|choice| playlist_submenu(app, choice, window, cx)); - - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let danger_color = gpui::hsla(0.0, 0.7, 0.6, 1.0); - - let selected = menu.selected; - let submenu_open = menu.submenu.is_some(); - - div() - .id("track-menu-backdrop") - .absolute() - .inset_0() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.track_menu = None; - this.state.ui.playlist_add_filter.clear(); - cx.notify(); - })) - .on_mouse_down( - MouseButton::Right, - cx.listener(|this: &mut EchoApp, _event: &MouseDownEvent, _window, cx| { - this.track_menu = None; - this.state.ui.playlist_add_filter.clear(); - cx.notify(); - }), - ) - .child(menu_placement( - menu.position - .map_or(MenuAnchor::Center, MenuAnchor::Pointer), - div() - .id("track-menu") - .occlude() - .track_scroll(&app.track_menu_scroll) - .w(px(210.0).min(menu_bounds(window).size.width)) - .max_h(menu_bounds(window).size.height) - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .py_1() - .flex() - .flex_col() - .overflow_y_scroll() - // Clicks on the menu itself must not reach the backdrop's close handler. - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .children( - items - .into_iter() - .enumerate() - .map(|(ix, (label, item, danger))| { - let is_add = add_row == Some(ix); - let is_selected = ix == selected; - // A hover-opened flyout leaves the keyboard selection where it was, so its - // parent row keeps the hover wash for as long as the flyout is up — the - // selected wash would read as a second cursor. - let holds_submenu = is_add && submenu_open && !is_selected; - let row_bounds = row_bounds.clone(); - div() - .id(label.clone()) - .flex_shrink_0() - .relative() - .mx_1() - .px_2() - .py_1() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_2() - .text_sm() - .text_color(if danger { danger_color } else { fg }) - .when(is_selected, |el| el.bg(palette.menu_selected)) - .when(holds_submenu, |el| el.bg(palette.menu_hover)) - .when(!is_selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - // Pointer moves drive the flyout: opening it on the add row, closing it - // on any other row the pointer settles on. See - // [`EchoApp::hover_track_menu_row`]. - .on_mouse_move(cx.listener( - move |this: &mut EchoApp, - event: &gpui::MouseMoveEvent, - _window, - cx| { - this.hover_track_menu_row(ix, event.position, cx); - }, - )) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if is_add { - this.open_playlist_submenu(true, cx); - } else { - this.run_track_menu_action(item, cx); - } - }, - )) - .when(is_add, |el| { - // The flyout is a sibling of the menu, so it needs this row's - // rectangle in window space to anchor to. - el.child( - canvas( - move |bounds, _window, _cx| row_bounds.set(bounds), - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - }) - .child(div().flex_grow(1.0).child(label)) - .when(is_add, |el| { - el.child( - div().flex_none().text_xs().text_color(muted).child("▸"), - ) - }) - }), - ), - )) - .children(submenu) -} - -/// The add-to-playlist flyout: the writable playlists, hanging off the track menu's "Add to -/// playlist" row — to its right, or to its left where the window edge leaves no room. A sibling -/// of the menu panel rather than a child of that row, which `overflow_hidden` would clip. -fn playlist_submenu( - app: &EchoApp, - choice: usize, - window: &Window, - cx: &mut Context, -) -> AnyElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - - let bounds = app.submenu_bounds.clone(); - let local_label = tr(&app.state, "ui.local"); - let empty_label = tr(&app.state, "desktop.playlist_add_none"); - let choices: Vec<(SharedString, bool)> = - echo_core::action_menu::filtered_playlist_add_choices(&app.state) - .into_iter() - .map(|(_, playlist)| { - ( - SharedString::from(playlist.name), - playlist.owner_id == "local", - ) - }) - .collect(); - - let choices: Vec<_> = std::iter::once((tr(&app.state, "desktop.new_playlist"), false)) - .chain(choices) - .collect(); - - menu_placement( - MenuAnchor::Row(app.submenu_row_bounds.clone()), - div() - .id("track-menu-submenu") - .w(px(SUBMENU_WIDTH).min(menu_bounds(window).size.width)) - .max_h(px(SUBMENU_MAX_H).min(menu_bounds(window).size.height)) - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .py_1() - .flex() - .flex_col() - // Swallows clicks and wheel events so neither reaches the backdrop or the list behind. - .occlude() - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .when(!app.state.ui.playlist_add_filter.is_empty(), |el| { - el.child( - div() - .flex_shrink_0() - .px_2() - .py_1() - .text_sm() - .text_color(muted) - .truncate() - .child(app.state.ui.playlist_add_filter.clone()), - ) - }) - .child( - canvas( - move |painted, _window, _cx| bounds.set(painted), - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .child(if choices.is_empty() { - div() - .mx_1() - .px_2() - .py_1() - .text_sm() - .text_color(muted) - .child(empty_label) - .into_any_element() - } else { - div() - .id("track-menu-submenu-list") - .flex() - .flex_col() - .min_h_0() - .max_h(px(SUBMENU_MAX_H - 10.0)) - .overflow_y_scroll() - .track_scroll(&app.submenu_scroll) - .children(choices.into_iter().enumerate().map(|(ix, (name, local))| { - let is_selected = ix == choice; - let local_label = local_label.clone(); - div() - .id(ix) - .flex_shrink_0() - .mx_1() - .px_2() - .py_1() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_2() - .text_sm() - .when(is_selected, |el| el.bg(palette.menu_selected)) - .when(!is_selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - this.commit_playlist_submenu(ix, cx); - }, - )) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(name), - ) - .when(local, |el| { - el.child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(local_label), - ) - }) - })) - .into_any_element() - }), - ) - .into_any_element() -} - /// Confirm dialog for whichever destructive prompt is staged, resolved through /// `intent::confirm_prompt`/`cancel_prompt`. pub fn prompt_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { diff --git a/crates/echo-desktop/src/views/menus.rs b/crates/echo-desktop/src/views/menus.rs new file mode 100644 index 0000000..ffb675a --- /dev/null +++ b/crates/echo-desktop/src/views/menus.rs @@ -0,0 +1,471 @@ +use super::*; + +/// The add-to-playlist flyout's preferred dimensions. +const SUBMENU_WIDTH: f32 = 190.0; + +const SUBMENU_MAX_H: f32 = 270.0; + +/// The sidebar right-click menu: items depend on what the row is, actions run through +/// [`EchoApp::run_menu_action`]. Destructive items stage a prompt for [`prompt_modal`]. +pub fn context_menu( + app: &mut EchoApp, + window: &Window, + cx: &mut Context, +) -> impl IntoElement { + let menu = app + .context_menu + .clone() + .expect("context_menu rendered without state"); + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let danger_color = gpui::hsla(0.0, 0.7, 0.6, 1.0); + + let mut items: Vec<(SharedString, MenuAction, bool)> = Vec::new(); + if app.state.ui.active_library_tab == LibraryTab::Albums { + if app.state.data.saved_albums.get(menu.index).is_some() { + items.push((tr(&app.state, "desktop.menu.open"), MenuAction::Open, false)); + items.push(( + tr(&app.state, "desktop.menu.remove_library"), + MenuAction::RemoveAlbum, + true, + )); + } + } else if let Some(node) = app.state.data.library_view.get(menu.index) { + match node { + LibraryNode::Folder(_) => { + items.push(( + tr(&app.state, "desktop.menu.rename"), + MenuAction::Rename, + false, + )); + items.push(( + tr(&app.state, "desktop.menu.delete_folder"), + MenuAction::DeleteFolder, + true, + )); + } + LibraryNode::SpotifyFolder { .. } => {} + LibraryNode::Playlist { playlist, indent } => { + items.push((tr(&app.state, "desktop.menu.open"), MenuAction::Open, false)); + let special = playlist.id == "LIKED_SONGS" || playlist.id == "local-library"; + let local = playlist.id.starts_with("local-playlist:"); + if !special { + let pinned = app.state.ui.library_config.pinned.contains(&playlist.id); + items.push(( + tr( + &app.state, + if pinned { + "desktop.menu.unpin" + } else { + "desktop.menu.pin" + }, + ), + MenuAction::TogglePin, + false, + )); + } + if local { + items.push(( + tr(&app.state, "desktop.menu.rename"), + MenuAction::Rename, + false, + )); + } else if echo_core::intent::owns_playlist(&app.state, &playlist.id) { + items.push(( + tr(&app.state, "desktop.edit_details"), + MenuAction::EditDetails, + false, + )); + } + if *indent >= 1 && !app.state.in_spotify_folder(&playlist.id) { + items.push(( + tr(&app.state, "desktop.menu.remove_folder"), + MenuAction::RemoveFromFolder, + false, + )); + } + let own = app.state.data.user_id.as_ref() == Some(&playlist.owner_id); + if local || (!special && own) { + items.push(( + tr(&app.state, "desktop.menu.delete_playlist"), + MenuAction::DeletePlaylist, + true, + )); + } + } + } + } + + let index = menu.index; + div() + .id("context-menu-backdrop") + .absolute() + .inset_0() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.context_menu = None; + cx.notify(); + })) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this: &mut EchoApp, _event: &MouseDownEvent, _window, cx| { + this.context_menu = None; + cx.notify(); + }), + ) + .child(menu_placement( + MenuAnchor::Pointer(menu.position), + div() + .id("context-menu") + .occlude() + .w(px(210.0).min(menu_bounds(window).size.width)) + .max_h(menu_bounds(window).size.height) + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .py_1() + .flex() + .flex_col() + .overflow_y_scroll() + // Clicks on the menu itself must not reach the backdrop's close handler. + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .children(items.into_iter().map(|(label, action, danger)| { + // Inset and rounded like the list rows: a full-bleed highlight would square + // off the panel's rounded corners on the first and last item. + div() + .id(label.clone()) + .flex_shrink_0() + .mx_1() + .px_2() + .py_1() + .rounded_md() + .text_sm() + .text_color(if danger { danger_color } else { fg }) + .hover(move |style| style.bg(palette.menu_hover)) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, window, cx| { + this.run_menu_action(action, index, window, cx); + })) + .child(label) + })), + )) +} + +/// Right-click menu for a track row. The item set and labels come from the core action-menu +/// model (`ActionMenuContext::actions()` / `action_menu::label`); remove-from-playlist is +/// appended for modifiable playlists. +/// The open track menu's rows: `(label, item, is_destructive)`. Keyboard selection indexes +/// into this, so it is the single source of the menu's contents. +pub fn track_menu_items(app: &EchoApp) -> Vec<(SharedString, TrackMenuItem, bool)> { + let Some(menu) = app.track_menu.as_ref() else { + return Vec::new(); + }; + let ctx = &menu.ctx; + let mut items: Vec<(SharedString, TrackMenuItem, bool)> = ctx + .actions() + .into_iter() + .map(|action| { + ( + echo_core::action_menu::label(&app.state, ctx, action).into(), + TrackMenuItem::Action(action), + false, + ) + }) + .collect(); + // Queue rows have no playlist behind them — `active_tracklist_context` is whatever was + // last browsed, so removing would hit the wrong playlist. + if app.state.ui.active_view != ActiveView::Queue + && app + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.can_modify_playlist(app.state.data.user_id.as_ref())) + { + items.push(( + tr(&app.state, "desktop.menu.remove_playlist"), + TrackMenuItem::RemoveFromPlaylist, + true, + )); + } + items +} + +pub fn track_context_menu( + app: &mut EchoApp, + window: &Window, + cx: &mut Context, +) -> impl IntoElement { + let menu = app + .track_menu + .clone() + .expect("track_context_menu rendered without state"); + let items = track_menu_items(app); + let add_row = app.track_menu_add_row(); + let row_bounds = app.submenu_row_bounds.clone(); + // Built first: it reads `app` immutably and hangs off the menu as a sibling, because the + // menu panel clips its own children. + let submenu = menu + .submenu + .map(|choice| playlist_submenu(app, choice, window, cx)); + + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let danger_color = gpui::hsla(0.0, 0.7, 0.6, 1.0); + + let selected = menu.selected; + let submenu_open = menu.submenu.is_some(); + + div() + .id("track-menu-backdrop") + .absolute() + .inset_0() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.track_menu = None; + this.state.ui.playlist_add_filter.clear(); + cx.notify(); + })) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this: &mut EchoApp, _event: &MouseDownEvent, _window, cx| { + this.track_menu = None; + this.state.ui.playlist_add_filter.clear(); + cx.notify(); + }), + ) + .child(menu_placement( + menu.position + .map_or(MenuAnchor::Center, MenuAnchor::Pointer), + div() + .id("track-menu") + .occlude() + .track_scroll(&app.track_menu_scroll) + .w(px(210.0).min(menu_bounds(window).size.width)) + .max_h(menu_bounds(window).size.height) + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .py_1() + .flex() + .flex_col() + .overflow_y_scroll() + // Clicks on the menu itself must not reach the backdrop's close handler. + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .children( + items + .into_iter() + .enumerate() + .map(|(ix, (label, item, danger))| { + let is_add = add_row == Some(ix); + let is_selected = ix == selected; + // A hover-opened flyout leaves the keyboard selection where it was, so its + // parent row keeps the hover wash for as long as the flyout is up — the + // selected wash would read as a second cursor. + let holds_submenu = is_add && submenu_open && !is_selected; + let row_bounds = row_bounds.clone(); + div() + .id(label.clone()) + .flex_shrink_0() + .relative() + .mx_1() + .px_2() + .py_1() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_2() + .text_sm() + .text_color(if danger { danger_color } else { fg }) + .when(is_selected, |el| el.bg(palette.menu_selected)) + .when(holds_submenu, |el| el.bg(palette.menu_hover)) + .when(!is_selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + // Pointer moves drive the flyout: opening it on the add row, closing it + // on any other row the pointer settles on. See + // [`EchoApp::hover_track_menu_row`]. + .on_mouse_move(cx.listener( + move |this: &mut EchoApp, + event: &gpui::MouseMoveEvent, + _window, + cx| { + this.hover_track_menu_row(ix, event.position, cx); + }, + )) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if is_add { + this.open_playlist_submenu(true, cx); + } else { + this.run_track_menu_action(item, cx); + } + }, + )) + .when(is_add, |el| { + // The flyout is a sibling of the menu, so it needs this row's + // rectangle in window space to anchor to. + el.child( + canvas( + move |bounds, _window, _cx| row_bounds.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .size_full(), + ) + }) + .child(div().flex_grow(1.0).child(label)) + .when(is_add, |el| { + el.child( + div().flex_none().text_xs().text_color(muted).child("▸"), + ) + }) + }), + ), + )) + .children(submenu) +} + +/// The add-to-playlist flyout: the writable playlists, hanging off the track menu's "Add to +/// playlist" row — to its right, or to its left where the window edge leaves no room. A sibling +/// of the menu panel rather than a child of that row, which `overflow_hidden` would clip. +pub(super) fn playlist_submenu( + app: &EchoApp, + choice: usize, + window: &Window, + cx: &mut Context, +) -> AnyElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + + let bounds = app.submenu_bounds.clone(); + let local_label = tr(&app.state, "ui.local"); + let empty_label = tr(&app.state, "desktop.playlist_add_none"); + let choices: Vec<(SharedString, bool)> = + echo_core::action_menu::filtered_playlist_add_choices(&app.state) + .into_iter() + .map(|(_, playlist)| { + ( + SharedString::from(playlist.name), + playlist.owner_id == "local", + ) + }) + .collect(); + + let choices: Vec<_> = std::iter::once((tr(&app.state, "desktop.new_playlist"), false)) + .chain(choices) + .collect(); + + menu_placement( + MenuAnchor::Row(app.submenu_row_bounds.clone()), + div() + .id("track-menu-submenu") + .w(px(SUBMENU_WIDTH).min(menu_bounds(window).size.width)) + .max_h(px(SUBMENU_MAX_H).min(menu_bounds(window).size.height)) + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .py_1() + .flex() + .flex_col() + // Swallows clicks and wheel events so neither reaches the backdrop or the list behind. + .occlude() + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .when(!app.state.ui.playlist_add_filter.is_empty(), |el| { + el.child( + div() + .flex_shrink_0() + .px_2() + .py_1() + .text_sm() + .text_color(muted) + .truncate() + .child(app.state.ui.playlist_add_filter.clone()), + ) + }) + .child( + canvas( + move |painted, _window, _cx| bounds.set(painted), + |_, _, _, _| {}, + ) + .absolute() + .size_full(), + ) + .child(if choices.is_empty() { + div() + .mx_1() + .px_2() + .py_1() + .text_sm() + .text_color(muted) + .child(empty_label) + .into_any_element() + } else { + div() + .id("track-menu-submenu-list") + .flex() + .flex_col() + .min_h_0() + .max_h(px(SUBMENU_MAX_H - 10.0)) + .overflow_y_scroll() + .track_scroll(&app.submenu_scroll) + .children(choices.into_iter().enumerate().map(|(ix, (name, local))| { + let is_selected = ix == choice; + let local_label = local_label.clone(); + div() + .id(ix) + .flex_shrink_0() + .mx_1() + .px_2() + .py_1() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_2() + .text_sm() + .when(is_selected, |el| el.bg(palette.menu_selected)) + .when(!is_selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + this.commit_playlist_submenu(ix, cx); + }, + )) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(name), + ) + .when(local, |el| { + el.child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(local_label), + ) + }) + })) + .into_any_element() + }), + ) + .into_any_element() +} From ca0ff083084ed7b4c89140988448743dedafa5e5 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:26 -0500 Subject: [PATCH 13/44] desktop: move the setup screen into views/setup.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 201 +------------------------ crates/echo-desktop/src/views/setup.rs | 200 ++++++++++++++++++++++++ 2 files changed, 202 insertions(+), 199 deletions(-) create mode 100644 crates/echo-desktop/src/views/setup.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 3220a75..a974a67 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -25,6 +25,7 @@ pub(crate) mod panel_layout; mod playlist_edit; mod queue; mod search; +mod setup; mod sidebar; mod track_list; use artist::*; @@ -42,6 +43,7 @@ use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub(crate) use menus::*; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; use queue::*; +use setup::*; pub(crate) use sidebar::*; pub(crate) use track_list::*; @@ -343,205 +345,6 @@ fn rounded_content_frame(body: AnyElement, background: Hsla, border: Hsla) -> im ) } -/// First-run credentials: a BYOK (bring-your-own-key) card writing to the -/// `state.ui.setup_*` fields and submitting through the setup intent. -fn setup_view( - app: &mut EchoApp, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let id_focused = app.setup_id_focus.is_focused(window); - let secret_focused = app.setup_secret_focus.is_focused(window); - let client_id = app.state.ui.setup_client_id.clone(); - let secret_masked = "•".repeat(app.state.ui.setup_client_secret.chars().count()); - let ready = - !app.state.ui.setup_client_id.is_empty() && !app.state.ui.setup_client_secret.is_empty(); - let uri_copied = app.setup_uri_copied; - - let field = |id: &'static str, - label: SharedString, - value: String, - focused: bool, - secret: bool, - handle: gpui::FocusHandle| { - let click_handle = handle.clone(); - div() - .id(id) - .key_context(crate::SEARCH_CONTEXT) - .track_focus(&handle) - .on_key_down(cx.listener(move |this: &mut EchoApp, event, window, cx| { - this.handle_setup_key(secret, event, window, cx) - })) - .w_full() - .px_3() - .py_2() - .rounded_md() - .border_1() - .border_color(if focused { accent } else { palette.border }) - .flex() - .flex_col() - .gap_1() - .cursor_pointer() - .on_click(cx.listener(move |_this, _event, window, cx| { - window.focus(&click_handle, cx); - cx.notify(); - })) - .child(div().text_xs().text_color(muted).child(label)) - .child( - div() - .text_sm() - .text_color(fg) - .whitespace_nowrap() - .overflow_hidden() - .child(SharedString::from(if focused { - format!("{value}▏") - } else if value.is_empty() { - " ".to_string() - } else { - value - })), - ) - }; - - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .child( - div() - .w(px(460.0)) - .p_4() - .rounded_lg() - .border_1() - .border_color(palette.border) - .flex() - .flex_col() - .gap_3() - .child( - div() - .text_lg() - .text_color(fg) - .child(tr(&app.state, "desktop.setup.title")), - ) - .child( - div() - .flex() - .flex_col() - .gap_1() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.setup.step1")) - .child(tr(&app.state, "desktop.setup.step2")) - .child( - div() - .id("setup-redirect-uri") - .px_2() - .py_1() - .rounded_md() - .border_1() - .border_color(palette.border) - .bg(palette.wash) - .flex() - .items_center() - .justify_between() - .gap_2() - .cursor_pointer() - .hover(|style| style.border_color(accent)) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - cx.write_to_clipboard(gpui::ClipboardItem::new_string( - echo_core::worker::api::REDIRECT_URI.to_string(), - )); - this.setup_uri_copied = true; - cx.notify(); - })) - .child( - div() - .text_color(fg) - .whitespace_nowrap() - .overflow_hidden() - .child(echo_core::worker::api::REDIRECT_URI), - ) - .child( - div() - .text_xs() - .text_color(if uri_copied { accent } else { muted }) - .child(tr( - &app.state, - if uri_copied { - "desktop.setup.copied" - } else { - "desktop.setup.copy" - }, - )), - ), - ) - .child(tr(&app.state, "desktop.setup.step3")), - ) - .child( - div() - .id("open-dashboard") - .text_sm() - .text_color(accent) - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(|_event, _window, _cx| { - let _ = webbrowser::open("https://developer.spotify.com/dashboard"); - }) - .child(tr(&app.state, "desktop.setup.dashboard")), - ) - .child(field( - "setup-client-id", - tr(&app.state, "desktop.setup.client_id"), - client_id, - id_focused, - false, - app.setup_id_focus.clone(), - )) - .child(field( - "setup-client-secret", - tr(&app.state, "desktop.setup.client_secret"), - secret_masked, - secret_focused, - true, - app.setup_secret_focus.clone(), - )) - .child( - div() - .id("setup-submit") - .mt_1() - .px_4() - .py_2() - .rounded_md() - .flex() - .justify_center() - .text_sm() - .bg(if ready { accent } else { palette.wash }) - .text_color(if ready { - gpui::hsla(0.0, 0.0, 0.08, 1.0) - } else { - muted - }) - .when(ready, |el| el.cursor_pointer()) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::intent::submit_setup_credentials(&mut this.state) - { - this.dispatch(event); - } - cx.notify(); - })) - .child(tr(&app.state, "desktop.setup.save")), - ), - ) -} - /// The global search box. A minimal hand-rolled input: gpui ships no text field, and query /// entry needs no more than append/backspace/submit. fn search_bar( diff --git a/crates/echo-desktop/src/views/setup.rs b/crates/echo-desktop/src/views/setup.rs new file mode 100644 index 0000000..bc2efed --- /dev/null +++ b/crates/echo-desktop/src/views/setup.rs @@ -0,0 +1,200 @@ +use super::*; + +/// First-run credentials: a BYOK (bring-your-own-key) card writing to the +/// `state.ui.setup_*` fields and submitting through the setup intent. +pub(super) fn setup_view( + app: &mut EchoApp, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let id_focused = app.setup_id_focus.is_focused(window); + let secret_focused = app.setup_secret_focus.is_focused(window); + let client_id = app.state.ui.setup_client_id.clone(); + let secret_masked = "•".repeat(app.state.ui.setup_client_secret.chars().count()); + let ready = + !app.state.ui.setup_client_id.is_empty() && !app.state.ui.setup_client_secret.is_empty(); + let uri_copied = app.setup_uri_copied; + + let field = |id: &'static str, + label: SharedString, + value: String, + focused: bool, + secret: bool, + handle: gpui::FocusHandle| { + let click_handle = handle.clone(); + div() + .id(id) + .key_context(crate::SEARCH_CONTEXT) + .track_focus(&handle) + .on_key_down(cx.listener(move |this: &mut EchoApp, event, window, cx| { + this.handle_setup_key(secret, event, window, cx) + })) + .w_full() + .px_3() + .py_2() + .rounded_md() + .border_1() + .border_color(if focused { accent } else { palette.border }) + .flex() + .flex_col() + .gap_1() + .cursor_pointer() + .on_click(cx.listener(move |_this, _event, window, cx| { + window.focus(&click_handle, cx); + cx.notify(); + })) + .child(div().text_xs().text_color(muted).child(label)) + .child( + div() + .text_sm() + .text_color(fg) + .whitespace_nowrap() + .overflow_hidden() + .child(SharedString::from(if focused { + format!("{value}▏") + } else if value.is_empty() { + " ".to_string() + } else { + value + })), + ) + }; + + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .child( + div() + .w(px(460.0)) + .p_4() + .rounded_lg() + .border_1() + .border_color(palette.border) + .flex() + .flex_col() + .gap_3() + .child( + div() + .text_lg() + .text_color(fg) + .child(tr(&app.state, "desktop.setup.title")), + ) + .child( + div() + .flex() + .flex_col() + .gap_1() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.setup.step1")) + .child(tr(&app.state, "desktop.setup.step2")) + .child( + div() + .id("setup-redirect-uri") + .px_2() + .py_1() + .rounded_md() + .border_1() + .border_color(palette.border) + .bg(palette.wash) + .flex() + .items_center() + .justify_between() + .gap_2() + .cursor_pointer() + .hover(|style| style.border_color(accent)) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string( + echo_core::worker::api::REDIRECT_URI.to_string(), + )); + this.setup_uri_copied = true; + cx.notify(); + })) + .child( + div() + .text_color(fg) + .whitespace_nowrap() + .overflow_hidden() + .child(echo_core::worker::api::REDIRECT_URI), + ) + .child( + div() + .text_xs() + .text_color(if uri_copied { accent } else { muted }) + .child(tr( + &app.state, + if uri_copied { + "desktop.setup.copied" + } else { + "desktop.setup.copy" + }, + )), + ), + ) + .child(tr(&app.state, "desktop.setup.step3")), + ) + .child( + div() + .id("open-dashboard") + .text_sm() + .text_color(accent) + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(|_event, _window, _cx| { + let _ = webbrowser::open("https://developer.spotify.com/dashboard"); + }) + .child(tr(&app.state, "desktop.setup.dashboard")), + ) + .child(field( + "setup-client-id", + tr(&app.state, "desktop.setup.client_id"), + client_id, + id_focused, + false, + app.setup_id_focus.clone(), + )) + .child(field( + "setup-client-secret", + tr(&app.state, "desktop.setup.client_secret"), + secret_masked, + secret_focused, + true, + app.setup_secret_focus.clone(), + )) + .child( + div() + .id("setup-submit") + .mt_1() + .px_4() + .py_2() + .rounded_md() + .flex() + .justify_center() + .text_sm() + .bg(if ready { accent } else { palette.wash }) + .text_color(if ready { + gpui::hsla(0.0, 0.0, 0.08, 1.0) + } else { + muted + }) + .when(ready, |el| el.cursor_pointer()) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::intent::submit_setup_credentials(&mut this.state) + { + this.dispatch(event); + } + cx.notify(); + })) + .child(tr(&app.state, "desktop.setup.save")), + ), + ) +} From 04430356409384eea5de05b03cc5ddb2ef7b3d60 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:34 -0500 Subject: [PATCH 14/44] desktop: move the search results list into views/search.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 355 +----------------------- crates/echo-desktop/src/views/search.rs | 353 +++++++++++++++++++++++ 2 files changed, 354 insertions(+), 354 deletions(-) diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index a974a67..3c321a8 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -249,7 +249,7 @@ pub fn main_area( ActiveView::Home => home_view(app, window, cx).into_any_element(), ActiveView::TrackList => track_list(app, window, cx).into_any_element(), ActiveView::Queue => queue_list(app, cx).into_any_element(), - ActiveView::SearchResults => search_results(app, window, cx).into_any_element(), + ActiveView::SearchResults => search::search_results(app, window, cx).into_any_element(), ActiveView::ArtistList => artist_list(app, cx).into_any_element(), ActiveView::ArtistPage => artist_page(app, cx).into_any_element(), ActiveView::WhatsNew => whats_new(app, cx).into_any_element(), @@ -688,359 +688,6 @@ fn thumb_element( } } -fn search_results( - app: &mut EchoApp, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let outer_palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let tab = app.state.ui.active_search_tab; - let query = app.state.ui.search_context_query.clone(); - let results = &app.state.data.search_results; - let (n_tracks, n_albums, n_artists, n_playlists) = ( - results.tracks.len(), - results.albums.len(), - results.artists.len(), - results.playlists.len(), - ); - let count = match tab { - SearchTab::All => echo_core::search::all_tab_rows(results, &query).len(), - SearchTab::Tracks => n_tracks, - SearchTab::Albums => n_albums, - SearchTab::Artists => n_artists, - SearchTab::Playlists => n_playlists, - }; - - let tab_button = |id: &'static str, label: String, target: SearchTab, active: bool| { - div() - .id(id) - .px_2() - .py_1() - .rounded_full() - .bg(outer_palette.wash) - .text_sm() - .text_color(if active { accent } else { muted }) - .hover(move |style| style.bg(outer_palette.row_hover)) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.state.ui.active_search_tab = target; - this.state.ui.selected_search_index = 0; - cx.notify(); - })) - .child(SharedString::from(label)) - }; - - div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_col() - .gap_2() - .child( - div() - .text_lg() - .text_color(fg) - .child(SharedString::from(format!( - "{}{query}", - tr(&app.state, "prompts.search") - ))), - ) - .child( - div() - .flex() - .flex_row() - .gap_1() - .flex_wrap() - .child(tab_button( - "search-all", - tr(&app.state, "desktop.search_all").to_string(), - SearchTab::All, - tab == SearchTab::All, - )) - .child(tab_button( - "search-tracks", - tr(&app.state, "desktop.search_songs").to_string(), - SearchTab::Tracks, - tab == SearchTab::Tracks, - )) - .child(tab_button( - "search-albums", - tr(&app.state, "ui.albums").to_string(), - SearchTab::Albums, - tab == SearchTab::Albums, - )) - .child(tab_button( - "search-artists", - tr(&app.state, "ui.artists").to_string(), - SearchTab::Artists, - tab == SearchTab::Artists, - )) - .child(tab_button( - "search-playlists", - tr(&app.state, "ui.playlists").to_string(), - SearchTab::Playlists, - tab == SearchTab::Playlists, - )), - ), - ) - .child(if count == 0 { - search::empty_results(app) - } else if tab == SearchTab::All { - search::all_results(app, window, cx) - } else { - uniform_list( - "search-rows", - count, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - let tab = this.state.ui.active_search_tab; - let selected = this.state.ui.selected_search_index; - let visual = visual_range_in(&this.state, ActiveView::SearchResults); - - let rows: Vec = range - .map(|ix| { - pill_row( - ix, - LIST_PILL, - row_selected(ix, selected, visual), - selected_bg, - palette.row_hover, - |row| { - let row = row.gap_3().on_click(cx.listener( - move |this: &mut EchoApp, - event: &gpui::ClickEvent, - _window, - cx| { - this.state.ui.selected_search_index = ix; - if (tab != SearchTab::Tracks - || event.click_count() >= 2) - && let Some(event) = - echo_core::intent::activate_search_result( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )); - - match tab { - SearchTab::All => row, - SearchTab::Tracks => { - let track = this.state.data.search_results.tracks - [ix] - .clone(); - let is_liked = this - .state - .data - .liked_tracks - .contains(&track.id); - let secondary = this - .state - .ui - .active_theme - .secondary - .gpui(WINDOW_FG()); - row.on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_search_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }), - ) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(track.name)), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from(track.artist)), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from(track.album)), - ) - .child(liked_cell( - "search", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - .child( - div() - .flex_none() - .w(px(48.0)) - .text_color(muted) - .child(SharedString::from(format_time( - track.duration_ms, - ))), - ) - } - SearchTab::Albums => { - let album = this.state.data.search_results.albums - [ix] - .clone(); - let thumb = thumb_element( - this, - album.image_url.as_deref(), - 26.0, - false, - muted, - ); - row.child(thumb) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(album.name)), - ) - .child( - div() - .flex_grow(1.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from( - album.artist, - )), - ) - } - SearchTab::Artists => { - let artist = this.state.data.search_results.artists - [ix] - .clone(); - let thumb = thumb_element( - this, - artist.image_url.as_deref(), - 26.0, - true, - muted, - ); - row.child(thumb).child( - div() - .flex_grow(1.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(artist.name)), - ) - } - SearchTab::Playlists => { - let playlist = - this.state.data.search_results.playlists[ix] - .clone(); - let thumb_url = playlist - .thumb_url - .clone() - .or_else(|| playlist.image_url.clone()); - let thumb = thumb_element( - this, - thumb_url.as_deref(), - 26.0, - false, - muted, - ); - row.child(thumb) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from( - playlist.name, - )), - ) - .child( - div() - .flex_grow(1.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from( - playlist.owner, - )), - ) - } - } - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }, - ), - ) - .track_scroll(&app.search_scroll) - .flex_grow(1.0) - .into_any_element() - }) -} - /// The Top Tracks / Top Artists time-window selector: three small pills, the active one /// accent-bordered. Persisting the choice and refetching go through the shared intent. fn range_switcher(app: &EchoApp, cx: &mut Context) -> Div { diff --git a/crates/echo-desktop/src/views/search.rs b/crates/echo-desktop/src/views/search.rs index 272635b..584deec 100644 --- a/crates/echo-desktop/src/views/search.rs +++ b/crates/echo-desktop/src/views/search.rs @@ -508,3 +508,356 @@ pub fn all_results( echo_core::thumbnails::drain_pending(&mut app.state, &app.worker_tx); content.into_any_element() } + +pub(super) fn search_results( + app: &mut EchoApp, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let outer_palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let tab = app.state.ui.active_search_tab; + let query = app.state.ui.search_context_query.clone(); + let results = &app.state.data.search_results; + let (n_tracks, n_albums, n_artists, n_playlists) = ( + results.tracks.len(), + results.albums.len(), + results.artists.len(), + results.playlists.len(), + ); + let count = match tab { + SearchTab::All => echo_core::search::all_tab_rows(results, &query).len(), + SearchTab::Tracks => n_tracks, + SearchTab::Albums => n_albums, + SearchTab::Artists => n_artists, + SearchTab::Playlists => n_playlists, + }; + + let tab_button = |id: &'static str, label: String, target: SearchTab, active: bool| { + div() + .id(id) + .px_2() + .py_1() + .rounded_full() + .bg(outer_palette.wash) + .text_sm() + .text_color(if active { accent } else { muted }) + .hover(move |style| style.bg(outer_palette.row_hover)) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.state.ui.active_search_tab = target; + this.state.ui.selected_search_index = 0; + cx.notify(); + })) + .child(SharedString::from(label)) + }; + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_col() + .gap_2() + .child( + div() + .text_lg() + .text_color(fg) + .child(SharedString::from(format!( + "{}{query}", + tr(&app.state, "prompts.search") + ))), + ) + .child( + div() + .flex() + .flex_row() + .gap_1() + .flex_wrap() + .child(tab_button( + "search-all", + tr(&app.state, "desktop.search_all").to_string(), + SearchTab::All, + tab == SearchTab::All, + )) + .child(tab_button( + "search-tracks", + tr(&app.state, "desktop.search_songs").to_string(), + SearchTab::Tracks, + tab == SearchTab::Tracks, + )) + .child(tab_button( + "search-albums", + tr(&app.state, "ui.albums").to_string(), + SearchTab::Albums, + tab == SearchTab::Albums, + )) + .child(tab_button( + "search-artists", + tr(&app.state, "ui.artists").to_string(), + SearchTab::Artists, + tab == SearchTab::Artists, + )) + .child(tab_button( + "search-playlists", + tr(&app.state, "ui.playlists").to_string(), + SearchTab::Playlists, + tab == SearchTab::Playlists, + )), + ), + ) + .child(if count == 0 { + search::empty_results(app) + } else if tab == SearchTab::All { + search::all_results(app, window, cx) + } else { + uniform_list( + "search-rows", + count, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + let tab = this.state.ui.active_search_tab; + let selected = this.state.ui.selected_search_index; + let visual = visual_range_in(&this.state, ActiveView::SearchResults); + + let rows: Vec = range + .map(|ix| { + pill_row( + ix, + LIST_PILL, + row_selected(ix, selected, visual), + selected_bg, + palette.row_hover, + |row| { + let row = row.gap_3().on_click(cx.listener( + move |this: &mut EchoApp, + event: &gpui::ClickEvent, + _window, + cx| { + this.state.ui.selected_search_index = ix; + if (tab != SearchTab::Tracks + || event.click_count() >= 2) + && let Some(event) = + echo_core::intent::activate_search_result( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )); + + match tab { + SearchTab::All => row, + SearchTab::Tracks => { + let track = this.state.data.search_results.tracks + [ix] + .clone(); + let is_liked = this + .state + .data + .liked_tracks + .contains(&track.id); + let secondary = this + .state + .ui + .active_theme + .secondary + .gpui(WINDOW_FG()); + row.on_mouse_down( + MouseButton::Right, + cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.selected_search_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }), + ) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(track.name)), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(track.artist)), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(track.album)), + ) + .child(liked_cell( + "search", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + .child( + div() + .flex_none() + .w(px(48.0)) + .text_color(muted) + .child(SharedString::from(format_time( + track.duration_ms, + ))), + ) + } + SearchTab::Albums => { + let album = this.state.data.search_results.albums + [ix] + .clone(); + let thumb = thumb_element( + this, + album.image_url.as_deref(), + 26.0, + false, + muted, + ); + row.child(thumb) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(album.name)), + ) + .child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from( + album.artist, + )), + ) + } + SearchTab::Artists => { + let artist = this.state.data.search_results.artists + [ix] + .clone(); + let thumb = thumb_element( + this, + artist.image_url.as_deref(), + 26.0, + true, + muted, + ); + row.child(thumb).child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(artist.name)), + ) + } + SearchTab::Playlists => { + let playlist = + this.state.data.search_results.playlists[ix] + .clone(); + let thumb_url = playlist + .thumb_url + .clone() + .or_else(|| playlist.image_url.clone()); + let thumb = thumb_element( + this, + thumb_url.as_deref(), + 26.0, + false, + muted, + ); + row.child(thumb) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from( + playlist.name, + )), + ) + .child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from( + playlist.owner, + )), + ) + } + } + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows + }, + ), + ) + .track_scroll(&app.search_scroll) + .flex_grow(1.0) + .into_any_element() + }) +} From 1246e21827d581ea65efd106285896ad46bbb73a Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:43 -0500 Subject: [PATCH 15/44] desktop: move the theme picker into views/modals/theme.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 266 +----------------- crates/echo-desktop/src/views/modals.rs | 5 + crates/echo-desktop/src/views/modals/theme.rs | 265 +++++++++++++++++ 3 files changed, 272 insertions(+), 264 deletions(-) create mode 100644 crates/echo-desktop/src/views/modals.rs create mode 100644 crates/echo-desktop/src/views/modals/theme.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 3c321a8..550021a 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -21,6 +21,7 @@ mod immersive; mod lyrics; mod menu_placement; mod menus; +mod modals; pub(crate) mod panel_layout; mod playlist_edit; mod queue; @@ -41,6 +42,7 @@ pub(crate) use immersive::*; pub(crate) use lyrics::*; use menu_placement::{MenuAnchor, menu_bounds, menu_placement}; pub(crate) use menus::*; +pub(crate) use modals::*; pub use playlist_edit::{playlist_edit_modal, playlist_page_menu}; use queue::*; use setup::*; @@ -838,270 +840,6 @@ pub fn right_panel( .into_any_element() } -/// The theme picker: every loaded theme by name, the active one accented. -/// Theme names in the order the picker lists them. `EchoApp::theme_modal_index` indexes into -/// this, so keyboard selection and rendering must both go through here or the two drift. -/// The picker's rows for one appearance: its themes, each with its sibling in the other. -pub fn theme_rows( - state: &echo_core::app::AppState, - scheme: echo_core::config::Scheme, -) -> Vec { - echo_core::theme::themes_for(&state.ui.themes, scheme) -} - -/// The theme picker. -/// -/// A theme is chosen per appearance. The header sets the mode (auto / dark / light); the -/// list holds the themes of one appearance, so a pinned mode shows just its own and `Auto` -/// adds a tab for each. A dark/light pair is one row naming both, the listed one first in -/// weight; a theme with no sibling is only in its own appearance's list. -pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - use echo_core::config::{Scheme, ThemeMode}; - - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let config = &app.state.ui.library_config; - let mode = config.theme_mode.unwrap_or(ThemeMode::Auto); - let tab = app.theme_modal_tab; - let rows = theme_rows(&app.state, tab); - let chosen = echo_core::theme::selected_name(config, &app.state.ui.themes, tab); - let selected = app.theme_modal_index; - - // Background, accent and second accent of each listed theme. Choosing does not preview, - // and under `Auto` one of the two lists is never on screen, so this is how they compare. - let swatches: Vec<[gpui::Hsla; 3]> = rows - .iter() - .map(|row| { - let resolved = app - .state - .ui - .themes - .get(&row.name) - .map(echo_core::theme::ResolvedTheme::from_theme); - match resolved { - Some(t) => [ - t.background.gpui(crate::theme::WINDOW_BG()), - t.primary.gpui(WINDOW_FG()), - t.secondary.gpui(WINDOW_FG()), - ], - None => [surface; 3], - } - }) - .collect(); - - let mode_label = - |mode: ThemeMode| tr(&app.state, &format!("desktop.theme_mode.{}", mode.name())); - let scheme_label = - |scheme: Scheme| tr(&app.state, &format!("desktop.theme_mode.{}", scheme.name())); - - // One joined bar, the same control as the Mode row in Settings. - let mode_control = div() - .flex_none() - .h(px(24.0)) - .flex() - .flex_row() - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .overflow_hidden() - .children(ThemeMode::ALL.into_iter().enumerate().map(|(ix, option)| { - let active = option == mode; - div() - .id(SharedString::from(format!("theme-mode-{}", option.name()))) - .h_full() - .px_3() - .flex() - .items_center() - .text_xs() - .text_color(if active { fg } else { muted }) - .when(ix > 0, |el| { - el.border_l_1().border_color(palette.menu_border) - }) - .when(active, |el| el.bg(palette.menu_selected)) - .when(!active, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - }) - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.set_theme_mode(option, cx); - })) - .child(mode_label(option)) - })); - - // Under `Auto` only: one tab per appearance, the listed one underlined. - let tabs = (mode == ThemeMode::Auto).then(|| { - div() - .flex_none() - .flex() - .flex_row() - .gap_4() - .px_2() - .pt_1() - .children([Scheme::Dark, Scheme::Light].into_iter().map(|scheme| { - let active = scheme == tab; - div() - .id(SharedString::from(format!("theme-tab-{}", scheme.name()))) - .pb_1() - .border_b_2() - .border_color(if active { - accent - } else { - gpui::transparent_black() - }) - .text_sm() - .text_color(if active { fg } else { muted }) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.show_theme_list(scheme, cx); - })) - .child(scheme_label(scheme)) - })) - }); - - div() - .id("theme-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.theme_modal_open = false; - cx.notify(); - })) - .child( - div() - .id("theme-panel") - .w(px(340.0)) - .max_h(px(480.0)) - .rounded_lg() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .p_3() - .flex() - .flex_col() - .gap_2() - .overflow_hidden() - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .child( - div() - .flex_none() - .px_1() - .pb_3() - .border_b_1() - .border_color(palette.menu_border) - .flex() - .flex_row() - .items_center() - .justify_between() - .child( - div() - .text_base() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(fg) - .child(tr(&app.state, "desktop.theme")), - ) - .child(mode_control), - ) - .when_some(tabs, |el, tabs| el.child(tabs)) - .child(if rows.is_empty() { - div() - .py_4() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.no_themes")) - .into_any_element() - } else { - div() - .id("theme-list") - .flex() - .flex_col() - // Sized by its rows, shrinking (and scrolling) once the panel is full. - .min_h_0() - .overflow_y_scroll() - .track_scroll(&app.theme_modal_scroll) - .children(rows.into_iter().zip(swatches).enumerate().map( - |(ix, (row, swatch))| { - let is_chosen = row.name == chosen; - let is_selected = ix == selected; - let clicked = row.name.clone(); - div() - .id(ix) - .px_2() - .h(px(30.0)) - .flex_none() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_3() - .text_sm() - .when(is_selected, |el| el.bg(palette.menu_selected)) - .when(!is_selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - echo_core::intent::apply_theme( - &mut this.state, - &clicked, - ); - this.theme_modal_open = false; - cx.notify(); - }, - )) - .child( - // The theme's background, accent and second accent - // as one joined chip. - div() - .flex_none() - .flex() - .flex_row() - .rounded_sm() - .border_1() - .border_color(palette.menu_border) - .overflow_hidden() - .children(swatch.into_iter().map(|color| { - div().w(px(12.0)).h(px(14.0)).bg(color) - })), - ) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_row() - .gap_1() - .child( - div() - .text_color(if is_chosen { accent } else { fg }) - .child(SharedString::from(row.name)), - ) - .when_some(row.sibling, |el, sibling| { - el.child(div().text_color(muted).child( - SharedString::from(format!("/ {sibling}")), - )) - }), - ) - .when(is_chosen, |el| { - el.child(div().flex_none().text_color(accent).child("✓")) - }) - }, - )) - .into_any_element() - }), - ) -} - /// Keyboard shortcuts, grouped, for the help overlay, as `(section i18n key, [(keys, /// description i18n key)])` — resolved through [`tr`] at render so `:lang` applies. /// diff --git a/crates/echo-desktop/src/views/modals.rs b/crates/echo-desktop/src/views/modals.rs new file mode 100644 index 0000000..bd92262 --- /dev/null +++ b/crates/echo-desktop/src/views/modals.rs @@ -0,0 +1,5 @@ +use super::*; + +mod theme; + +pub use theme::*; diff --git a/crates/echo-desktop/src/views/modals/theme.rs b/crates/echo-desktop/src/views/modals/theme.rs new file mode 100644 index 0000000..a6d39ab --- /dev/null +++ b/crates/echo-desktop/src/views/modals/theme.rs @@ -0,0 +1,265 @@ +use super::*; + +/// The theme picker: every loaded theme by name, the active one accented. +/// Theme names in the order the picker lists them. `EchoApp::theme_modal_index` indexes into +/// this, so keyboard selection and rendering must both go through here or the two drift. +/// The picker's rows for one appearance: its themes, each with its sibling in the other. +pub fn theme_rows( + state: &echo_core::app::AppState, + scheme: echo_core::config::Scheme, +) -> Vec { + echo_core::theme::themes_for(&state.ui.themes, scheme) +} + +/// The theme picker. +/// +/// A theme is chosen per appearance. The header sets the mode (auto / dark / light); the +/// list holds the themes of one appearance, so a pinned mode shows just its own and `Auto` +/// adds a tab for each. A dark/light pair is one row naming both, the listed one first in +/// weight; a theme with no sibling is only in its own appearance's list. +pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + use echo_core::config::{Scheme, ThemeMode}; + + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let config = &app.state.ui.library_config; + let mode = config.theme_mode.unwrap_or(ThemeMode::Auto); + let tab = app.theme_modal_tab; + let rows = theme_rows(&app.state, tab); + let chosen = echo_core::theme::selected_name(config, &app.state.ui.themes, tab); + let selected = app.theme_modal_index; + + // Background, accent and second accent of each listed theme. Choosing does not preview, + // and under `Auto` one of the two lists is never on screen, so this is how they compare. + let swatches: Vec<[gpui::Hsla; 3]> = rows + .iter() + .map(|row| { + let resolved = app + .state + .ui + .themes + .get(&row.name) + .map(echo_core::theme::ResolvedTheme::from_theme); + match resolved { + Some(t) => [ + t.background.gpui(crate::theme::WINDOW_BG()), + t.primary.gpui(WINDOW_FG()), + t.secondary.gpui(WINDOW_FG()), + ], + None => [surface; 3], + } + }) + .collect(); + + let mode_label = + |mode: ThemeMode| tr(&app.state, &format!("desktop.theme_mode.{}", mode.name())); + let scheme_label = + |scheme: Scheme| tr(&app.state, &format!("desktop.theme_mode.{}", scheme.name())); + + // One joined bar, the same control as the Mode row in Settings. + let mode_control = div() + .flex_none() + .h(px(24.0)) + .flex() + .flex_row() + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .overflow_hidden() + .children(ThemeMode::ALL.into_iter().enumerate().map(|(ix, option)| { + let active = option == mode; + div() + .id(SharedString::from(format!("theme-mode-{}", option.name()))) + .h_full() + .px_3() + .flex() + .items_center() + .text_xs() + .text_color(if active { fg } else { muted }) + .when(ix > 0, |el| { + el.border_l_1().border_color(palette.menu_border) + }) + .when(active, |el| el.bg(palette.menu_selected)) + .when(!active, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + }) + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.set_theme_mode(option, cx); + })) + .child(mode_label(option)) + })); + + // Under `Auto` only: one tab per appearance, the listed one underlined. + let tabs = (mode == ThemeMode::Auto).then(|| { + div() + .flex_none() + .flex() + .flex_row() + .gap_4() + .px_2() + .pt_1() + .children([Scheme::Dark, Scheme::Light].into_iter().map(|scheme| { + let active = scheme == tab; + div() + .id(SharedString::from(format!("theme-tab-{}", scheme.name()))) + .pb_1() + .border_b_2() + .border_color(if active { + accent + } else { + gpui::transparent_black() + }) + .text_sm() + .text_color(if active { fg } else { muted }) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.show_theme_list(scheme, cx); + })) + .child(scheme_label(scheme)) + })) + }); + + div() + .id("theme-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.theme_modal_open = false; + cx.notify(); + })) + .child( + div() + .id("theme-panel") + .w(px(340.0)) + .max_h(px(480.0)) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_3() + .flex() + .flex_col() + .gap_2() + .overflow_hidden() + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .child( + div() + .flex_none() + .px_1() + .pb_3() + .border_b_1() + .border_color(palette.menu_border) + .flex() + .flex_row() + .items_center() + .justify_between() + .child( + div() + .text_base() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(fg) + .child(tr(&app.state, "desktop.theme")), + ) + .child(mode_control), + ) + .when_some(tabs, |el, tabs| el.child(tabs)) + .child(if rows.is_empty() { + div() + .py_4() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.no_themes")) + .into_any_element() + } else { + div() + .id("theme-list") + .flex() + .flex_col() + // Sized by its rows, shrinking (and scrolling) once the panel is full. + .min_h_0() + .overflow_y_scroll() + .track_scroll(&app.theme_modal_scroll) + .children(rows.into_iter().zip(swatches).enumerate().map( + |(ix, (row, swatch))| { + let is_chosen = row.name == chosen; + let is_selected = ix == selected; + let clicked = row.name.clone(); + div() + .id(ix) + .px_2() + .h(px(30.0)) + .flex_none() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_3() + .text_sm() + .when(is_selected, |el| el.bg(palette.menu_selected)) + .when(!is_selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + echo_core::intent::apply_theme( + &mut this.state, + &clicked, + ); + this.theme_modal_open = false; + cx.notify(); + }, + )) + .child( + // The theme's background, accent and second accent + // as one joined chip. + div() + .flex_none() + .flex() + .flex_row() + .rounded_sm() + .border_1() + .border_color(palette.menu_border) + .overflow_hidden() + .children(swatch.into_iter().map(|color| { + div().w(px(12.0)).h(px(14.0)).bg(color) + })), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_row() + .gap_1() + .child( + div() + .text_color(if is_chosen { accent } else { fg }) + .child(SharedString::from(row.name)), + ) + .when_some(row.sibling, |el, sibling| { + el.child(div().text_color(muted).child( + SharedString::from(format!("/ {sibling}")), + )) + }), + ) + .when(is_chosen, |el| { + el.child(div().flex_none().text_color(accent).child("✓")) + }) + }, + )) + .into_any_element() + }), + ) +} From 709b5731dcc26b4b27b815da4648857387c15d73 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:44 -0500 Subject: [PATCH 16/44] desktop: move the keyboard help into views/modals/help.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 224 ------------------ crates/echo-desktop/src/views/modals.rs | 2 + crates/echo-desktop/src/views/modals/help.rs | 225 +++++++++++++++++++ 3 files changed, 227 insertions(+), 224 deletions(-) create mode 100644 crates/echo-desktop/src/views/modals/help.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 550021a..cc9d13b 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -840,230 +840,6 @@ pub fn right_panel( .into_any_element() } -/// Keyboard shortcuts, grouped, for the help overlay, as `(section i18n key, [(keys, -/// description i18n key)])` — resolved through [`tr`] at render so `:lang` applies. -/// -/// Kept next to the `KeyBinding::new` block in `main()` conceptually — when you add a binding -/// there, add it here too. Commands are not listed: those come from -/// `echo_core::commands::COMMANDS` so they cannot go stale. -pub const KEY_HELP: &[(&str, &[(&str, &str)])] = &[ - ( - "desktop.help.nav", - &[ - ("j / k / ↓ / ↑", "desktop.help.move"), - ( - if cfg!(target_os = "macos") { - "ctrl-shift-h" - } else { - "ctrl-h" - }, - "desktop.home", - ), - ("gg / G / home / end", "desktop.help.first_last"), - ("ctrl-b / ctrl-f / pgup / pgdn", "desktop.help.page"), - ("ctrl-u / ctrl-d", "desktop.help.half_page"), - ("enter / z", "desktop.help.open"), - ("h / esc", "desktop.help.back"), - ("alt-← / alt-→", "desktop.help.history"), - ("← / →", "desktop.help.pane_focus"), - ("backspace", "desktop.help.to_sidebar"), - ("ctrl-\\", "desktop.help.toggle_sidebar"), - ("tab", "desktop.help.tabs"), - ("gc", "desktop.help.jump_playing"), - ("1-9", "desktop.help.count"), - ("y", "desktop.help.confirm"), - ], - ), - ( - "desktop.help.playback", - &[ - ("space", "desktop.help.play_pause"), - ("[ / ] / ctrl-← / ctrl-→", "desktop.help.prev_next"), - (", / . / shift-← / shift-→", "desktop.help.seek"), - ("0", "desktop.help.seek_start"), - ("- / =", "desktop.help.volume"), - ("shift-M", "desktop.help.mute"), - ("s / r", "desktop.help.shuffle_repeat"), - ("shift-D", "desktop.help.devices"), - ("shift-L", "desktop.help.lyrics"), - ("ctrl-shift-L", "desktop.help.lyrics_bar"), - ("shift-F", "desktop.help.immersive"), - ], - ), - ( - "desktop.help.library", - &[ - ("l", "desktop.help.like"), - ("a", "desktop.help.add_playlist"), - ("shift-A", "desktop.help.track_actions"), - ("q / shift-Q", "desktop.help.queue"), - ("shift-J / shift-K", "desktop.help.move_track"), - ("dd", "desktop.help.delete"), - ("v", "desktop.help.select_range"), - ("m", "desktop.help.pin"), - ("c / e", "desktop.help.new_rename"), - ("shift-R", "desktop.help.refresh"), - ], - ), - ( - "desktop.help.finding", - &[ - ("ctrl-k", "desktop.help.search"), - ("/", "desktop.help.filter"), - ("n / shift-N", "desktop.help.next_match"), - (":", "desktop.help.command_bar"), - ("f", "desktop.help.search_command"), - ("t", "desktop.help.themes"), - ("ctrl-,", "desktop.help.settings"), - ("?", "desktop.help.this_help"), - ("ctrl-q", "desktop.help.quit"), - ], - ), -]; - -/// The help overlay: every keybinding, plus every `:` command straight from the registry. -pub fn help_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let entry = |keys: &'static str, what: SharedString| { - div() - .flex() - .flex_row() - .items_baseline() - .gap_2() - .py_0p5() - .child( - div() - .flex_none() - .w(px(112.0)) - .text_xs() - .text_color(accent) - .child(keys), - ) - .child(div().text_xs().text_color(muted).child(what)) - }; - - let state = &app.state; - let section = move |title_key: &'static str, rows: &'static [(&'static str, &'static str)]| { - div() - .flex() - .flex_col() - .pb_2() - .child( - div() - .pb_1() - .text_xs() - .text_color(fg) - .child(tr(state, title_key)), - ) - .children( - rows.iter() - .map(|(keys, what_key)| entry(keys, tr(state, what_key))), - ) - }; - - div() - .id("help-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.help_open = false; - cx.notify(); - })) - .child( - div() - .id("help-panel") - .w(px(700.0)) - .max_h(px(600.0)) - .rounded_lg() - .border_1() - .border_color(DesktopPalette::resolve(&app.state.ui.active_theme).menu_border) - .bg(surface) - .p_4() - .flex() - .flex_col() - .overflow_hidden() - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .child( - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .pb_2() - .child( - div() - .text_sm() - .text_color(fg) - .child(tr(&app.state, "desktop.help.title")), - ) - .child( - div() - .text_xs() - .text_color(muted) - .child(tr(&app.state, "desktop.help.esc_close")), - ), - ) - .child( - div() - .id("help-body") - .flex() - .flex_row() - .gap_6() - .max_h(px(510.0)) - .overflow_y_scroll() - .track_scroll(&app.help_scroll) - .child( - div().flex().flex_col().w(px(320.0)).flex_none().children( - KEY_HELP.iter().map(|(title, rows)| section(title, rows)), - ), - ) - .child( - div() - .flex() - .flex_col() - .flex_grow(1.0) - .child( - div() - .pb_1() - .text_xs() - .text_color(fg) - .child(tr(&app.state, "desktop.help.commands")), - ) - .children(echo_core::commands::COMMANDS.iter().map( - |(usage, description)| { - div() - .flex() - .flex_col() - .py_0p5() - .child( - div() - .text_xs() - .text_color(accent) - .child(SharedString::from(format!(":{usage}"))), - ) - .child( - div() - .text_xs() - .text_color(muted) - .child(*description), - ) - }, - )), - ), - ), - ) -} - /// The settings sheet. /// /// Booleans are switches, a choice among several is a dropdown (the appearance mode, three diff --git a/crates/echo-desktop/src/views/modals.rs b/crates/echo-desktop/src/views/modals.rs index bd92262..ebef0e4 100644 --- a/crates/echo-desktop/src/views/modals.rs +++ b/crates/echo-desktop/src/views/modals.rs @@ -1,5 +1,7 @@ use super::*; +mod help; mod theme; +pub use help::*; pub use theme::*; diff --git a/crates/echo-desktop/src/views/modals/help.rs b/crates/echo-desktop/src/views/modals/help.rs new file mode 100644 index 0000000..8438fef --- /dev/null +++ b/crates/echo-desktop/src/views/modals/help.rs @@ -0,0 +1,225 @@ +use super::*; + +/// Keyboard shortcuts, grouped, for the help overlay, as `(section i18n key, [(keys, +/// description i18n key)])` — resolved through [`tr`] at render so `:lang` applies. +/// +/// Kept next to the `KeyBinding::new` block in `main()` conceptually — when you add a binding +/// there, add it here too. Commands are not listed: those come from +/// `echo_core::commands::COMMANDS` so they cannot go stale. +pub const KEY_HELP: &[(&str, &[(&str, &str)])] = &[ + ( + "desktop.help.nav", + &[ + ("j / k / ↓ / ↑", "desktop.help.move"), + ( + if cfg!(target_os = "macos") { + "ctrl-shift-h" + } else { + "ctrl-h" + }, + "desktop.home", + ), + ("gg / G / home / end", "desktop.help.first_last"), + ("ctrl-b / ctrl-f / pgup / pgdn", "desktop.help.page"), + ("ctrl-u / ctrl-d", "desktop.help.half_page"), + ("enter / z", "desktop.help.open"), + ("h / esc", "desktop.help.back"), + ("alt-← / alt-→", "desktop.help.history"), + ("← / →", "desktop.help.pane_focus"), + ("backspace", "desktop.help.to_sidebar"), + ("ctrl-\\", "desktop.help.toggle_sidebar"), + ("tab", "desktop.help.tabs"), + ("gc", "desktop.help.jump_playing"), + ("1-9", "desktop.help.count"), + ("y", "desktop.help.confirm"), + ], + ), + ( + "desktop.help.playback", + &[ + ("space", "desktop.help.play_pause"), + ("[ / ] / ctrl-← / ctrl-→", "desktop.help.prev_next"), + (", / . / shift-← / shift-→", "desktop.help.seek"), + ("0", "desktop.help.seek_start"), + ("- / =", "desktop.help.volume"), + ("shift-M", "desktop.help.mute"), + ("s / r", "desktop.help.shuffle_repeat"), + ("shift-D", "desktop.help.devices"), + ("shift-L", "desktop.help.lyrics"), + ("ctrl-shift-L", "desktop.help.lyrics_bar"), + ("shift-F", "desktop.help.immersive"), + ], + ), + ( + "desktop.help.library", + &[ + ("l", "desktop.help.like"), + ("a", "desktop.help.add_playlist"), + ("shift-A", "desktop.help.track_actions"), + ("q / shift-Q", "desktop.help.queue"), + ("shift-J / shift-K", "desktop.help.move_track"), + ("dd", "desktop.help.delete"), + ("v", "desktop.help.select_range"), + ("m", "desktop.help.pin"), + ("c / e", "desktop.help.new_rename"), + ("shift-R", "desktop.help.refresh"), + ], + ), + ( + "desktop.help.finding", + &[ + ("ctrl-k", "desktop.help.search"), + ("/", "desktop.help.filter"), + ("n / shift-N", "desktop.help.next_match"), + (":", "desktop.help.command_bar"), + ("f", "desktop.help.search_command"), + ("t", "desktop.help.themes"), + ("ctrl-,", "desktop.help.settings"), + ("?", "desktop.help.this_help"), + ("ctrl-q", "desktop.help.quit"), + ], + ), +]; + +/// The help overlay: every keybinding, plus every `:` command straight from the registry. +pub fn help_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let entry = |keys: &'static str, what: SharedString| { + div() + .flex() + .flex_row() + .items_baseline() + .gap_2() + .py_0p5() + .child( + div() + .flex_none() + .w(px(112.0)) + .text_xs() + .text_color(accent) + .child(keys), + ) + .child(div().text_xs().text_color(muted).child(what)) + }; + + let state = &app.state; + let section = move |title_key: &'static str, rows: &'static [(&'static str, &'static str)]| { + div() + .flex() + .flex_col() + .pb_2() + .child( + div() + .pb_1() + .text_xs() + .text_color(fg) + .child(tr(state, title_key)), + ) + .children( + rows.iter() + .map(|(keys, what_key)| entry(keys, tr(state, what_key))), + ) + }; + + div() + .id("help-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.help_open = false; + cx.notify(); + })) + .child( + div() + .id("help-panel") + .w(px(700.0)) + .max_h(px(600.0)) + .rounded_lg() + .border_1() + .border_color(DesktopPalette::resolve(&app.state.ui.active_theme).menu_border) + .bg(surface) + .p_4() + .flex() + .flex_col() + .overflow_hidden() + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .child( + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .pb_2() + .child( + div() + .text_sm() + .text_color(fg) + .child(tr(&app.state, "desktop.help.title")), + ) + .child( + div() + .text_xs() + .text_color(muted) + .child(tr(&app.state, "desktop.help.esc_close")), + ), + ) + .child( + div() + .id("help-body") + .flex() + .flex_row() + .gap_6() + .max_h(px(510.0)) + .overflow_y_scroll() + .track_scroll(&app.help_scroll) + .child( + div().flex().flex_col().w(px(320.0)).flex_none().children( + KEY_HELP.iter().map(|(title, rows)| section(title, rows)), + ), + ) + .child( + div() + .flex() + .flex_col() + .flex_grow(1.0) + .child( + div() + .pb_1() + .text_xs() + .text_color(fg) + .child(tr(&app.state, "desktop.help.commands")), + ) + .children(echo_core::commands::COMMANDS.iter().map( + |(usage, description)| { + div() + .flex() + .flex_col() + .py_0p5() + .child( + div() + .text_xs() + .text_color(accent) + .child(SharedString::from(format!(":{usage}"))), + ) + .child( + div() + .text_xs() + .text_color(muted) + .child(*description), + ) + }, + )), + ), + ), + ) +} From 7d7f88916973fc17f0eb1ff282f52be96a8d2332 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:46 -0500 Subject: [PATCH 17/44] desktop: move the settings modal into views/modals/settings.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 863 ----------------- crates/echo-desktop/src/views/modals.rs | 2 + .../echo-desktop/src/views/modals/settings.rs | 864 ++++++++++++++++++ 3 files changed, 866 insertions(+), 863 deletions(-) create mode 100644 crates/echo-desktop/src/views/modals/settings.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index cc9d13b..4fe3295 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -840,869 +840,6 @@ pub fn right_panel( .into_any_element() } -/// The settings sheet. -/// -/// Booleans are switches, a choice among several is a dropdown (the appearance mode, three -/// short options switched often, is a segmented bar), and rows carry a hint only where the -/// label cannot say it. What each control does is a `SettingChange`. -pub fn settings_modal( - app: &mut EchoApp, - window: &mut Window, - cx: &mut Context, -) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let config = app.state.ui.library_config.clone(); - let path_focused = app.settings_path_focus.is_focused(window); - let path_value = app.settings_path_input.clone(); - // Owns its language so translation never borrows `app` across the listener closures below. - let s = { - let lang = config.language.clone(); - move |key: &str| SharedString::from(echo_core::i18n::t(key, &lang)) - }; - - const ROW_HEIGHT: f32 = 34.0; - const CONTROL_HEIGHT: f32 = 24.0; - let open_dropdown = app.settings_dropdown; - - // A labelled row with its control on the right. Labels and hints arrive translated. A - // disabled row is dimmed: its setting has no effect until another one is turned on. - let row = - |label: SharedString, hint: Option, enabled: bool, control: AnyElement| { - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap_4() - .min_h(px(ROW_HEIGHT)) - .py_0p5() - .when(!enabled, |el| el.opacity(0.4)) - .child( - div() - .flex() - .flex_col() - .min_w_0() - .child(div().text_sm().text_color(fg).child(label)) - .when_some(hint, |el, hint| { - el.child(div().text_xs().text_color(muted).child(hint)) - }), - ) - .child(control) - }; - - // A section title over a rule, with an optional note that applies to the whole section. - let heading = |label: SharedString, note: Option| { - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap_4() - .mt_4() - .mb_1() - .pb_1() - .border_b_1() - .border_color(palette.menu_border) - .child( - div() - .text_xs() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(muted) - .child(label), - ) - .when_some(note, |el, note| { - el.child(div().text_xs().text_color(muted).child(note)) - }) - }; - - // An on/off switch. - let toggle = |id: &'static str, on: bool, change: SettingChange, cx: &mut Context| { - div() - .id(id) - .flex_none() - .w(px(34.0)) - .h(px(20.0)) - .p(px(2.0)) - .rounded_full() - .flex() - .flex_row() - .items_center() - .when(on, |el| el.justify_end()) - .bg(if on { accent } else { palette.menu_border }) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - change.apply(this, cx); - })) - .child( - div() - .size(px(16.0)) - .rounded_full() - .bg(if on { surface } else { muted }), - ) - .into_any_element() - }; - - // A segmented control: one joined bar, the active segment filled. - let segmented = |id: &'static str, - options: Vec<(SharedString, String, bool)>, - cx: &mut Context| { - div() - .id(id) - .flex_none() - .h(px(CONTROL_HEIGHT)) - .flex() - .flex_row() - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .overflow_hidden() - .children( - options - .into_iter() - .enumerate() - .map(|(ix, (label, cmd, active))| { - div() - .id(SharedString::from(format!("{id}-{ix}"))) - .h_full() - .px_3() - .flex() - .items_center() - .text_xs() - .text_color(if active { fg } else { muted }) - .when(ix > 0, |el| { - el.border_l_1().border_color(palette.menu_border) - }) - .when(active, |el| el.bg(palette.menu_selected)) - .when(!active, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - }) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - this.run_setting(cmd.clone(), cx); - }, - )) - .child(label) - }), - ) - .into_any_element() - }; - - // A dropdown: a button showing the current option, and while open a menu of all of them - // hanging under it. The menu is drawn deferred so the scrolling list does not clip it. - let dropdown = |id: &'static str, - options: Vec<(SharedString, SettingChange, bool)>, - enabled: bool, - cx: &mut Context| { - let current = options - .iter() - .find(|option| option.2) - .map(|option| option.0.clone()) - .unwrap_or_default(); - let is_open = enabled && open_dropdown == Some(id); - let menu = is_open.then(|| { - let items: Vec<_> = options - .into_iter() - .enumerate() - .map(|(ix, (label, change, active))| { - div() - .id(SharedString::from(format!("{id}-option-{ix}"))) - .px_2() - .py_1() - .rounded_sm() - .text_xs() - .text_color(if active { accent } else { fg }) - .when(active, |el| el.bg(palette.menu_selected)) - .cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.settings_dropdown = None; - change.apply(this, cx); - cx.stop_propagation(); - })) - .child(label) - }) - .collect(); - div().absolute().top_full().right_0().child( - gpui::deferred( - gpui::anchored() - .anchor(gpui::Anchor::TopRight) - .snap_to_window() - .child( - div() - .id(SharedString::from(format!("{id}-menu"))) - .occlude() - .mt_1() - .min_w(px(DROPDOWN_WIDTH)) - .p_1() - .flex() - .flex_col() - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .shadow_md() - .on_click( - cx.listener(|_this, _event, _window, cx| cx.stop_propagation()), - ) - .children(items), - ), - ) - .with_priority(1), - ) - }); - div() - .relative() - .flex_none() - .child( - div() - .id(id) - .h(px(CONTROL_HEIGHT)) - .min_w(px(DROPDOWN_WIDTH)) - .pl_2() - .pr_1p5() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap_2() - .rounded_md() - .border_1() - .border_color(if is_open { accent } else { palette.menu_border }) - .text_xs() - .text_color(fg) - .when(enabled, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - this.settings_dropdown = - (this.settings_dropdown != Some(id)).then_some(id); - // The panel behind closes any open dropdown on a click. - cx.stop_propagation(); - cx.notify(); - }, - )) - }) - .child(current) - .child( - svg() - .path("icons/arrow-down.svg") - .size(px(8.0)) - .text_color(muted), - ), - ) - .when_some(menu, |el, menu| el.child(menu)) - .into_any_element() - }; - - // A plain push button; the caller adds the click. `strong` accents the one that matters. - let button = |id: &'static str, label: SharedString, strong: bool| { - div() - .id(id) - .flex_none() - .h(px(CONTROL_HEIGHT)) - .px_2() - .flex() - .items_center() - .rounded_md() - .border_1() - .border_color(if strong { accent } else { palette.menu_border }) - .text_xs() - .text_color(if strong { accent } else { fg }) - .child(label) - }; - - let command = |cmd: String| SettingChange::Command(cmd); - let on_off = |on: bool| if on { "on" } else { "off" }; - - // --- General --------------------------------------------------------------------- - let language_row = row( - s("desktop.settings.language"), - None, - true, - dropdown( - "lang", - [("English", "en"), ("简体中文", "zh-CN")] - .into_iter() - .map(|(label, code)| { - ( - label.into(), - command(format!("lang {code}")), - config.language == code, - ) - }) - .collect(), - true, - cx, - ), - ); - - let tray_row = row( - s("desktop.settings.tray"), - None, - true, - toggle( - "tray", - config.close_to_tray, - command(format!("tray {}", on_off(!config.close_to_tray))), - cx, - ), - ); - - let sort_row = row( - s("desktop.settings.order"), - None, - true, - dropdown( - "libsort", - { - use echo_core::config::SortMode; - [ - // The manual drag-and-drop order. - ("order_custom", "default", SortMode::Default), - ("order_alpha", "alpha", SortMode::Alphabetical), - ("order_creator", "creator", SortMode::Creator), - ] - .into_iter() - .map(|(key, name, mode)| { - ( - s(&format!("desktop.settings.{key}")), - command(format!("sort {name}")), - config.sort_mode == mode, - ) - }) - .collect() - }, - true, - cx, - ), - ); - - let relative_row = row( - s("desktop.settings.relative"), - None, - true, - toggle( - "relative", - config.relative_line_numbers, - command(format!( - "relative {}", - on_off(!config.relative_line_numbers) - )), - cx, - ), - ); - - // --- Appearance ------------------------------------------------------------------ - let theme_mode = config - .theme_mode - .unwrap_or(echo_core::config::ThemeMode::Auto); - // The theme in use, or under `Auto` the dark and the light one. - let theme_label = { - use echo_core::config::{Scheme, ThemeMode}; - let chosen = - |scheme| echo_core::theme::selected_name(&config, &app.state.ui.themes, scheme); - match theme_mode { - ThemeMode::Auto => format!("{} / {}", chosen(Scheme::Dark), chosen(Scheme::Light)), - ThemeMode::Dark => chosen(Scheme::Dark), - ThemeMode::Light => chosen(Scheme::Light), - } - }; - let theme_row = row( - s("desktop.theme"), - None, - true, - button("settings-theme", theme_label.into(), false) - .cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.settings_open = false; - this.toggle_themes(cx); - })) - .into_any_element(), - ); - - let mode_row = row( - s("desktop.settings.mode"), - None, - true, - segmented( - "mode", - echo_core::config::ThemeMode::ALL - .into_iter() - .map(|mode| { - ( - s(&format!("desktop.theme_mode.{}", mode.name())), - format!("mode {}", mode.name()), - theme_mode == mode, - ) - }) - .collect(), - cx, - ), - ); - - // The offered sizes, plus whatever `:pixelate` / `:visbins` set outside them, so the - // button never shows blank. - let with_current = |offered: &[usize], current: usize| { - let mut values = offered.to_vec(); - if !values.contains(¤t) { - values.push(current); - values.sort_unstable(); - } - values - }; - - let pixelate_row = row( - s("desktop.settings.pixelate"), - None, - true, - dropdown( - "pixelate", - with_current(&[0, 8, 16, 32], config.cover_img_pixels as usize) - .into_iter() - .map(|n| { - ( - if n == 0 { - s("ui.off") - } else { - SharedString::from(format!("{n} px")) - }, - command(format!("pixelate {n}")), - config.cover_img_pixels as usize == n, - ) - }) - .collect(), - true, - cx, - ), - ); - - let backdrop_row = row( - s("desktop.settings.backdrop"), - None, - true, - dropdown( - "backdrop", - echo_core::config::BackdropMode::ALL - .into_iter() - .map(|mode| { - ( - s(&format!("desktop.settings.backdrops.{}", mode.name())), - command(format!("backdrop {}", mode.name())), - config.immersive_backdrop == mode, - ) - }) - .collect(), - true, - cx, - ), - ); - - let visualizer_row = row( - s("desktop.settings.visualizer"), - None, - true, - // `:vis` flips the visualizer; it takes no argument. - toggle("vis", config.enable_visualizer, command("vis".into()), cx), - ); - - let bins_row = row( - s("desktop.settings.bins"), - None, - config.enable_visualizer, - dropdown( - "visbins", - with_current(&[7, 9, 16, 24, 32], config.vis_bins) - .into_iter() - .map(|n| { - ( - SharedString::from(n.to_string()), - command(format!("visbins {n}")), - config.vis_bins == n, - ) - }) - .collect(), - config.enable_visualizer, - cx, - ), - ); - - // --- Audio quality --------------------------------------------------------------- - let bitrate_row = row( - s("desktop.settings.quality"), - None, - true, - dropdown( - "bitrate", - [96u32, 160, 320] - .into_iter() - .map(|rate| { - ( - SharedString::from(format!("{rate} kbps")), - SettingChange::Bitrate(rate), - config.bitrate == rate, - ) - }) - .collect(), - true, - cx, - ), - ); - - let normalisation = config.normalisation; - let normalisation_row = row( - s("desktop.settings.normalisation"), - None, - true, - toggle( - "normalisation", - normalisation, - SettingChange::Normalisation(!normalisation), - cx, - ), - ); - - let pregain = config.normalisation_pregain; - let step_button = - |id: &'static str, label: &'static str, delta: f64, cx: &mut Context| { - div() - .id(id) - .size(px(CONTROL_HEIGHT)) - .flex() - .items_center() - .justify_center() - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .text_xs() - .text_color(fg) - .when(normalisation, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.set_audio_quality( - |config| { - // Matches librespot's usable range; beyond this the - // limiter dominates. - config.normalisation_pregain = - (config.normalisation_pregain + delta).clamp(-10.0, 10.0); - }, - cx, - ); - })) - }) - .child(label) - }; - let pregain_row = row( - s("desktop.settings.pregain"), - Some(s("desktop.settings.pregain_desc")), - normalisation, - div() - .flex_none() - .flex() - .flex_row() - .items_center() - .gap_1() - .child(step_button("pregain-down", "−", -0.5, cx)) - .child( - div() - .w(px(56.0)) - .text_xs() - .text_color(fg) - .text_center() - .child(SharedString::from(format!("{pregain:+.1} dB"))), - ) - .child(step_button("pregain-up", "+", 0.5, cx)) - .into_any_element(), - ); - - // --- Local music ----------------------------------------------------------------- - let path_unsaved = app.local_folder_unsaved(); - let local_field = div() - .id("settings-localpath") - .key_context(crate::SEARCH_CONTEXT) - .track_focus(&app.settings_path_focus) - .on_key_down(cx.listener(|this: &mut EchoApp, event, window, cx| { - this.handle_settings_path_key(event, window, cx) - })) - .flex_1() - .min_w_0() - .h(px(CONTROL_HEIGHT)) - .px_2() - .flex() - .items_center() - .rounded_md() - .border_1() - .border_color(if path_focused { - accent - } else { - palette.menu_border - }) - .text_xs() - .text_color(if path_value.is_empty() { muted } else { fg }) - .whitespace_nowrap() - .overflow_hidden() - .cursor_pointer() - .on_click(cx.listener(|this: &mut EchoApp, _event, window, cx| { - let handle = this.settings_path_focus.clone(); - window.focus(&handle, cx); - cx.notify(); - })) - .child(SharedString::from(if path_focused { - crate::text_with_cursor(&path_value, app.settings_path_cursor) - } else if path_value.is_empty() { - s("desktop.settings.folder_empty").to_string() - } else { - path_value - })); - let local_row = div() - .flex() - .flex_row() - .items_center() - .gap_2() - .min_h(px(ROW_HEIGHT)) - .child(local_field) - .child( - // With no folder saved, or a different one typed, the button applies the field; - // otherwise there is nothing to set and it rescans. - button( - "settings-rescan", - s(if path_unsaved { - "desktop.settings.set_folder" - } else { - "desktop.settings.rescan" - }), - false, - ) - .cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(|this: &mut EchoApp, _event, window, cx| { - this.apply_or_rescan_local_folder(window, cx); - })), - ); - - // --- Updates --------------------------------------------------------------------- - // The one control here that is neither a `:` command nor a config write: it runs a network - // call, so its label and action both come from `app.update_state`. - let version_row = row( - s("desktop.settings.updates.version"), - None, - true, - div() - .text_xs() - .text_color(muted) - .child(SharedString::from(if echo_core::update::is_dev_build() { - format!( - "{} {}", - echo_core::update::current_version(), - echo_core::i18n::t("desktop.settings.updates.dev", &config.language) - ) - } else { - echo_core::update::current_version().to_string() - })) - .into_any_element(), - ); - - let translate = |key: &str, value: &str| -> SharedString { - SharedString::from(echo_core::i18n::t(key, &config.language).replace("{}", value)) - }; - let auto_update_row = row( - s("desktop.settings.updates.auto"), - None, - true, - toggle( - "autoupdate", - config.auto_update, - command(format!("autoupdate {}", on_off(!config.auto_update))), - cx, - ), - ); - // The hint only appears when there is something to report: an installed update waiting - // for a restart, or why the last attempt failed. - let (update_label, update_hint, update_active) = match &app.update_state { - UpdateState::Idle => (s("desktop.settings.updates.check"), None, true), - UpdateState::Checking => (s("desktop.settings.updates.checking"), None, false), - UpdateState::UpToDate => (s("desktop.settings.updates.uptodate"), None, true), - UpdateState::Available(release) => ( - translate("desktop.settings.updates.install", release.version()), - None, - true, - ), - UpdateState::Downloading(percent) => ( - translate("desktop.settings.updates.downloading", &percent.to_string()), - None, - false, - ), - UpdateState::Ready(version) => ( - s("desktop.settings.updates.restart"), - Some(translate("desktop.settings.updates.installed", version)), - false, - ), - UpdateState::Failed(message) => ( - s("desktop.settings.updates.retry"), - Some(SharedString::from(message.clone())), - true, - ), - // Nothing in-app can fix this one, so the button leaves for the releases page. - UpdateState::Blocked(message) => ( - s("desktop.settings.updates.open_releases"), - Some(SharedString::from(message.clone())), - true, - ), - }; - - let update_button = button("settings-update", update_label, update_active) - .when(!update_active, |el| el.text_color(muted)) - .when(update_active, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - match &this.update_state { - UpdateState::Available(_) => this.install_update(cx), - UpdateState::Blocked(_) => { - let _ = webbrowser::open(&echo_core::update::releases_url()); - } - _ => this.check_for_updates(cx), - } - })) - }) - .into_any_element(); - - let update_row = row( - s("desktop.settings.updates.label"), - update_hint, - true, - update_button, - ); - - div() - .id("settings-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - // A click outside first closes an open dropdown, then the sheet. - if this.settings_dropdown.take().is_none() { - this.settings_open = false; - } - cx.notify(); - })) - .child( - div() - .id("settings-panel") - .w(px(480.0)) - // Never taller than the window: the list below takes what is left and scrolls. - .max_h(px(580.0).min(window.viewport_size().height - px(32.0))) - .rounded_lg() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .p_4() - .flex() - .flex_col() - .overflow_hidden() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - if this.settings_dropdown.take().is_some() { - cx.notify(); - } - cx.stop_propagation(); - })) - .child( - // The rule is where scrolled rows disappear, so they never run up - // under the title. - div() - .flex_none() - .pb_3() - .border_b_1() - .border_color(palette.menu_border) - .text_base() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(fg) - .child(s("desktop.settings.title")), - ) - .child( - div() - .id("settings-list") - .flex() - .flex_col() - // Sized by its rows, shrinking (and scrolling) once the panel is full. - .min_h_0() - .overflow_y_scroll() - .track_scroll(&app.settings_scroll) - // One child holding every row: the scroll extent is measured across the list's children and - // skips the first one's top margin, which left the last row short of fully scrolling in. - .child( - div() - .flex_none() - .flex() - .flex_col() - .child(heading(s("desktop.settings.general"), None)) - .child(language_row) - .when(!cfg!(target_os = "macos"), |el| el.child(tray_row)) - .child(sort_row) - .child(relative_row) - .child(heading(s("desktop.settings.appearance"), None)) - .child(theme_row) - .child(mode_row) - .child(pixelate_row) - .child(backdrop_row) - .child(visualizer_row) - .child(bins_row) - .child(heading( - s("desktop.settings.audio"), - Some(s("desktop.settings.next_launch")), - )) - .child(bitrate_row) - .child(normalisation_row) - .child(pregain_row) - .child(heading(s("desktop.settings.local"), None)) - .child(local_row) - .child(heading(s("desktop.settings.updates.section"), None)) - .child(version_row) - .child(auto_update_row) - .child(update_row), - ), - ), - ) -} - -/// What a settings control does when used: nearly always a `:` command, so the sheet and the -/// command bar cannot drift apart. The audio-quality keys have no command and write the -/// config directly. -#[derive(Clone)] -enum SettingChange { - Command(String), - Bitrate(u32), - Normalisation(bool), -} - -impl SettingChange { - fn apply(&self, app: &mut EchoApp, cx: &mut Context) { - match *self { - Self::Command(ref cmd) => app.run_setting(cmd.clone(), cx), - Self::Bitrate(rate) => app.set_audio_quality(|config| config.bitrate = rate, cx), - Self::Normalisation(on) => { - app.set_audio_quality(|config| config.normalisation = on, cx) - } - } - } -} - -/// Every settings dropdown is this wide at least, so their right and left edges line up. -const DROPDOWN_WIDTH: f32 = 124.0; - /// The Spotify Connect device picker, painted over everything else. pub fn device_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { let theme = &app.state.ui.active_theme; diff --git a/crates/echo-desktop/src/views/modals.rs b/crates/echo-desktop/src/views/modals.rs index ebef0e4..fbddc56 100644 --- a/crates/echo-desktop/src/views/modals.rs +++ b/crates/echo-desktop/src/views/modals.rs @@ -1,7 +1,9 @@ use super::*; mod help; +mod settings; mod theme; pub use help::*; +pub use settings::*; pub use theme::*; diff --git a/crates/echo-desktop/src/views/modals/settings.rs b/crates/echo-desktop/src/views/modals/settings.rs new file mode 100644 index 0000000..b9dcf94 --- /dev/null +++ b/crates/echo-desktop/src/views/modals/settings.rs @@ -0,0 +1,864 @@ +use super::*; + +/// The settings sheet. +/// +/// Booleans are switches, a choice among several is a dropdown (the appearance mode, three +/// short options switched often, is a segmented bar), and rows carry a hint only where the +/// label cannot say it. What each control does is a `SettingChange`. +pub fn settings_modal( + app: &mut EchoApp, + window: &mut Window, + cx: &mut Context, +) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let config = app.state.ui.library_config.clone(); + let path_focused = app.settings_path_focus.is_focused(window); + let path_value = app.settings_path_input.clone(); + // Owns its language so translation never borrows `app` across the listener closures below. + let s = { + let lang = config.language.clone(); + move |key: &str| SharedString::from(echo_core::i18n::t(key, &lang)) + }; + + const ROW_HEIGHT: f32 = 34.0; + const CONTROL_HEIGHT: f32 = 24.0; + let open_dropdown = app.settings_dropdown; + + // A labelled row with its control on the right. Labels and hints arrive translated. A + // disabled row is dimmed: its setting has no effect until another one is turned on. + let row = + |label: SharedString, hint: Option, enabled: bool, control: AnyElement| { + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap_4() + .min_h(px(ROW_HEIGHT)) + .py_0p5() + .when(!enabled, |el| el.opacity(0.4)) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child(div().text_sm().text_color(fg).child(label)) + .when_some(hint, |el, hint| { + el.child(div().text_xs().text_color(muted).child(hint)) + }), + ) + .child(control) + }; + + // A section title over a rule, with an optional note that applies to the whole section. + let heading = |label: SharedString, note: Option| { + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap_4() + .mt_4() + .mb_1() + .pb_1() + .border_b_1() + .border_color(palette.menu_border) + .child( + div() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(muted) + .child(label), + ) + .when_some(note, |el, note| { + el.child(div().text_xs().text_color(muted).child(note)) + }) + }; + + // An on/off switch. + let toggle = |id: &'static str, on: bool, change: SettingChange, cx: &mut Context| { + div() + .id(id) + .flex_none() + .w(px(34.0)) + .h(px(20.0)) + .p(px(2.0)) + .rounded_full() + .flex() + .flex_row() + .items_center() + .when(on, |el| el.justify_end()) + .bg(if on { accent } else { palette.menu_border }) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + change.apply(this, cx); + })) + .child( + div() + .size(px(16.0)) + .rounded_full() + .bg(if on { surface } else { muted }), + ) + .into_any_element() + }; + + // A segmented control: one joined bar, the active segment filled. + let segmented = |id: &'static str, + options: Vec<(SharedString, String, bool)>, + cx: &mut Context| { + div() + .id(id) + .flex_none() + .h(px(CONTROL_HEIGHT)) + .flex() + .flex_row() + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .overflow_hidden() + .children( + options + .into_iter() + .enumerate() + .map(|(ix, (label, cmd, active))| { + div() + .id(SharedString::from(format!("{id}-{ix}"))) + .h_full() + .px_3() + .flex() + .items_center() + .text_xs() + .text_color(if active { fg } else { muted }) + .when(ix > 0, |el| { + el.border_l_1().border_color(palette.menu_border) + }) + .when(active, |el| el.bg(palette.menu_selected)) + .when(!active, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + this.run_setting(cmd.clone(), cx); + }, + )) + .child(label) + }), + ) + .into_any_element() + }; + + // A dropdown: a button showing the current option, and while open a menu of all of them + // hanging under it. The menu is drawn deferred so the scrolling list does not clip it. + let dropdown = |id: &'static str, + options: Vec<(SharedString, SettingChange, bool)>, + enabled: bool, + cx: &mut Context| { + let current = options + .iter() + .find(|option| option.2) + .map(|option| option.0.clone()) + .unwrap_or_default(); + let is_open = enabled && open_dropdown == Some(id); + let menu = is_open.then(|| { + let items: Vec<_> = options + .into_iter() + .enumerate() + .map(|(ix, (label, change, active))| { + div() + .id(SharedString::from(format!("{id}-option-{ix}"))) + .px_2() + .py_1() + .rounded_sm() + .text_xs() + .text_color(if active { accent } else { fg }) + .when(active, |el| el.bg(palette.menu_selected)) + .cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.settings_dropdown = None; + change.apply(this, cx); + cx.stop_propagation(); + })) + .child(label) + }) + .collect(); + div().absolute().top_full().right_0().child( + gpui::deferred( + gpui::anchored() + .anchor(gpui::Anchor::TopRight) + .snap_to_window() + .child( + div() + .id(SharedString::from(format!("{id}-menu"))) + .occlude() + .mt_1() + .min_w(px(DROPDOWN_WIDTH)) + .p_1() + .flex() + .flex_col() + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .shadow_md() + .on_click( + cx.listener(|_this, _event, _window, cx| cx.stop_propagation()), + ) + .children(items), + ), + ) + .with_priority(1), + ) + }); + div() + .relative() + .flex_none() + .child( + div() + .id(id) + .h(px(CONTROL_HEIGHT)) + .min_w(px(DROPDOWN_WIDTH)) + .pl_2() + .pr_1p5() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap_2() + .rounded_md() + .border_1() + .border_color(if is_open { accent } else { palette.menu_border }) + .text_xs() + .text_color(fg) + .when(enabled, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + this.settings_dropdown = + (this.settings_dropdown != Some(id)).then_some(id); + // The panel behind closes any open dropdown on a click. + cx.stop_propagation(); + cx.notify(); + }, + )) + }) + .child(current) + .child( + svg() + .path("icons/arrow-down.svg") + .size(px(8.0)) + .text_color(muted), + ), + ) + .when_some(menu, |el, menu| el.child(menu)) + .into_any_element() + }; + + // A plain push button; the caller adds the click. `strong` accents the one that matters. + let button = |id: &'static str, label: SharedString, strong: bool| { + div() + .id(id) + .flex_none() + .h(px(CONTROL_HEIGHT)) + .px_2() + .flex() + .items_center() + .rounded_md() + .border_1() + .border_color(if strong { accent } else { palette.menu_border }) + .text_xs() + .text_color(if strong { accent } else { fg }) + .child(label) + }; + + let command = |cmd: String| SettingChange::Command(cmd); + let on_off = |on: bool| if on { "on" } else { "off" }; + + // --- General --------------------------------------------------------------------- + let language_row = row( + s("desktop.settings.language"), + None, + true, + dropdown( + "lang", + [("English", "en"), ("简体中文", "zh-CN")] + .into_iter() + .map(|(label, code)| { + ( + label.into(), + command(format!("lang {code}")), + config.language == code, + ) + }) + .collect(), + true, + cx, + ), + ); + + let tray_row = row( + s("desktop.settings.tray"), + None, + true, + toggle( + "tray", + config.close_to_tray, + command(format!("tray {}", on_off(!config.close_to_tray))), + cx, + ), + ); + + let sort_row = row( + s("desktop.settings.order"), + None, + true, + dropdown( + "libsort", + { + use echo_core::config::SortMode; + [ + // The manual drag-and-drop order. + ("order_custom", "default", SortMode::Default), + ("order_alpha", "alpha", SortMode::Alphabetical), + ("order_creator", "creator", SortMode::Creator), + ] + .into_iter() + .map(|(key, name, mode)| { + ( + s(&format!("desktop.settings.{key}")), + command(format!("sort {name}")), + config.sort_mode == mode, + ) + }) + .collect() + }, + true, + cx, + ), + ); + + let relative_row = row( + s("desktop.settings.relative"), + None, + true, + toggle( + "relative", + config.relative_line_numbers, + command(format!( + "relative {}", + on_off(!config.relative_line_numbers) + )), + cx, + ), + ); + + // --- Appearance ------------------------------------------------------------------ + let theme_mode = config + .theme_mode + .unwrap_or(echo_core::config::ThemeMode::Auto); + // The theme in use, or under `Auto` the dark and the light one. + let theme_label = { + use echo_core::config::{Scheme, ThemeMode}; + let chosen = + |scheme| echo_core::theme::selected_name(&config, &app.state.ui.themes, scheme); + match theme_mode { + ThemeMode::Auto => format!("{} / {}", chosen(Scheme::Dark), chosen(Scheme::Light)), + ThemeMode::Dark => chosen(Scheme::Dark), + ThemeMode::Light => chosen(Scheme::Light), + } + }; + let theme_row = row( + s("desktop.theme"), + None, + true, + button("settings-theme", theme_label.into(), false) + .cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.settings_open = false; + this.toggle_themes(cx); + })) + .into_any_element(), + ); + + let mode_row = row( + s("desktop.settings.mode"), + None, + true, + segmented( + "mode", + echo_core::config::ThemeMode::ALL + .into_iter() + .map(|mode| { + ( + s(&format!("desktop.theme_mode.{}", mode.name())), + format!("mode {}", mode.name()), + theme_mode == mode, + ) + }) + .collect(), + cx, + ), + ); + + // The offered sizes, plus whatever `:pixelate` / `:visbins` set outside them, so the + // button never shows blank. + let with_current = |offered: &[usize], current: usize| { + let mut values = offered.to_vec(); + if !values.contains(¤t) { + values.push(current); + values.sort_unstable(); + } + values + }; + + let pixelate_row = row( + s("desktop.settings.pixelate"), + None, + true, + dropdown( + "pixelate", + with_current(&[0, 8, 16, 32], config.cover_img_pixels as usize) + .into_iter() + .map(|n| { + ( + if n == 0 { + s("ui.off") + } else { + SharedString::from(format!("{n} px")) + }, + command(format!("pixelate {n}")), + config.cover_img_pixels as usize == n, + ) + }) + .collect(), + true, + cx, + ), + ); + + let backdrop_row = row( + s("desktop.settings.backdrop"), + None, + true, + dropdown( + "backdrop", + echo_core::config::BackdropMode::ALL + .into_iter() + .map(|mode| { + ( + s(&format!("desktop.settings.backdrops.{}", mode.name())), + command(format!("backdrop {}", mode.name())), + config.immersive_backdrop == mode, + ) + }) + .collect(), + true, + cx, + ), + ); + + let visualizer_row = row( + s("desktop.settings.visualizer"), + None, + true, + // `:vis` flips the visualizer; it takes no argument. + toggle("vis", config.enable_visualizer, command("vis".into()), cx), + ); + + let bins_row = row( + s("desktop.settings.bins"), + None, + config.enable_visualizer, + dropdown( + "visbins", + with_current(&[7, 9, 16, 24, 32], config.vis_bins) + .into_iter() + .map(|n| { + ( + SharedString::from(n.to_string()), + command(format!("visbins {n}")), + config.vis_bins == n, + ) + }) + .collect(), + config.enable_visualizer, + cx, + ), + ); + + // --- Audio quality --------------------------------------------------------------- + let bitrate_row = row( + s("desktop.settings.quality"), + None, + true, + dropdown( + "bitrate", + [96u32, 160, 320] + .into_iter() + .map(|rate| { + ( + SharedString::from(format!("{rate} kbps")), + SettingChange::Bitrate(rate), + config.bitrate == rate, + ) + }) + .collect(), + true, + cx, + ), + ); + + let normalisation = config.normalisation; + let normalisation_row = row( + s("desktop.settings.normalisation"), + None, + true, + toggle( + "normalisation", + normalisation, + SettingChange::Normalisation(!normalisation), + cx, + ), + ); + + let pregain = config.normalisation_pregain; + let step_button = + |id: &'static str, label: &'static str, delta: f64, cx: &mut Context| { + div() + .id(id) + .size(px(CONTROL_HEIGHT)) + .flex() + .items_center() + .justify_center() + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .text_xs() + .text_color(fg) + .when(normalisation, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.set_audio_quality( + |config| { + // Matches librespot's usable range; beyond this the + // limiter dominates. + config.normalisation_pregain = + (config.normalisation_pregain + delta).clamp(-10.0, 10.0); + }, + cx, + ); + })) + }) + .child(label) + }; + let pregain_row = row( + s("desktop.settings.pregain"), + Some(s("desktop.settings.pregain_desc")), + normalisation, + div() + .flex_none() + .flex() + .flex_row() + .items_center() + .gap_1() + .child(step_button("pregain-down", "−", -0.5, cx)) + .child( + div() + .w(px(56.0)) + .text_xs() + .text_color(fg) + .text_center() + .child(SharedString::from(format!("{pregain:+.1} dB"))), + ) + .child(step_button("pregain-up", "+", 0.5, cx)) + .into_any_element(), + ); + + // --- Local music ----------------------------------------------------------------- + let path_unsaved = app.local_folder_unsaved(); + let local_field = div() + .id("settings-localpath") + .key_context(crate::SEARCH_CONTEXT) + .track_focus(&app.settings_path_focus) + .on_key_down(cx.listener(|this: &mut EchoApp, event, window, cx| { + this.handle_settings_path_key(event, window, cx) + })) + .flex_1() + .min_w_0() + .h(px(CONTROL_HEIGHT)) + .px_2() + .flex() + .items_center() + .rounded_md() + .border_1() + .border_color(if path_focused { + accent + } else { + palette.menu_border + }) + .text_xs() + .text_color(if path_value.is_empty() { muted } else { fg }) + .whitespace_nowrap() + .overflow_hidden() + .cursor_pointer() + .on_click(cx.listener(|this: &mut EchoApp, _event, window, cx| { + let handle = this.settings_path_focus.clone(); + window.focus(&handle, cx); + cx.notify(); + })) + .child(SharedString::from(if path_focused { + crate::text_with_cursor(&path_value, app.settings_path_cursor) + } else if path_value.is_empty() { + s("desktop.settings.folder_empty").to_string() + } else { + path_value + })); + let local_row = div() + .flex() + .flex_row() + .items_center() + .gap_2() + .min_h(px(ROW_HEIGHT)) + .child(local_field) + .child( + // With no folder saved, or a different one typed, the button applies the field; + // otherwise there is nothing to set and it rescans. + button( + "settings-rescan", + s(if path_unsaved { + "desktop.settings.set_folder" + } else { + "desktop.settings.rescan" + }), + false, + ) + .cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(|this: &mut EchoApp, _event, window, cx| { + this.apply_or_rescan_local_folder(window, cx); + })), + ); + + // --- Updates --------------------------------------------------------------------- + // The one control here that is neither a `:` command nor a config write: it runs a network + // call, so its label and action both come from `app.update_state`. + let version_row = row( + s("desktop.settings.updates.version"), + None, + true, + div() + .text_xs() + .text_color(muted) + .child(SharedString::from(if echo_core::update::is_dev_build() { + format!( + "{} {}", + echo_core::update::current_version(), + echo_core::i18n::t("desktop.settings.updates.dev", &config.language) + ) + } else { + echo_core::update::current_version().to_string() + })) + .into_any_element(), + ); + + let translate = |key: &str, value: &str| -> SharedString { + SharedString::from(echo_core::i18n::t(key, &config.language).replace("{}", value)) + }; + let auto_update_row = row( + s("desktop.settings.updates.auto"), + None, + true, + toggle( + "autoupdate", + config.auto_update, + command(format!("autoupdate {}", on_off(!config.auto_update))), + cx, + ), + ); + // The hint only appears when there is something to report: an installed update waiting + // for a restart, or why the last attempt failed. + let (update_label, update_hint, update_active) = match &app.update_state { + UpdateState::Idle => (s("desktop.settings.updates.check"), None, true), + UpdateState::Checking => (s("desktop.settings.updates.checking"), None, false), + UpdateState::UpToDate => (s("desktop.settings.updates.uptodate"), None, true), + UpdateState::Available(release) => ( + translate("desktop.settings.updates.install", release.version()), + None, + true, + ), + UpdateState::Downloading(percent) => ( + translate("desktop.settings.updates.downloading", &percent.to_string()), + None, + false, + ), + UpdateState::Ready(version) => ( + s("desktop.settings.updates.restart"), + Some(translate("desktop.settings.updates.installed", version)), + false, + ), + UpdateState::Failed(message) => ( + s("desktop.settings.updates.retry"), + Some(SharedString::from(message.clone())), + true, + ), + // Nothing in-app can fix this one, so the button leaves for the releases page. + UpdateState::Blocked(message) => ( + s("desktop.settings.updates.open_releases"), + Some(SharedString::from(message.clone())), + true, + ), + }; + + let update_button = button("settings-update", update_label, update_active) + .when(!update_active, |el| el.text_color(muted)) + .when(update_active, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + match &this.update_state { + UpdateState::Available(_) => this.install_update(cx), + UpdateState::Blocked(_) => { + let _ = webbrowser::open(&echo_core::update::releases_url()); + } + _ => this.check_for_updates(cx), + } + })) + }) + .into_any_element(); + + let update_row = row( + s("desktop.settings.updates.label"), + update_hint, + true, + update_button, + ); + + div() + .id("settings-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + // A click outside first closes an open dropdown, then the sheet. + if this.settings_dropdown.take().is_none() { + this.settings_open = false; + } + cx.notify(); + })) + .child( + div() + .id("settings-panel") + .w(px(480.0)) + // Never taller than the window: the list below takes what is left and scrolls. + .max_h(px(580.0).min(window.viewport_size().height - px(32.0))) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_4() + .flex() + .flex_col() + .overflow_hidden() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + if this.settings_dropdown.take().is_some() { + cx.notify(); + } + cx.stop_propagation(); + })) + .child( + // The rule is where scrolled rows disappear, so they never run up + // under the title. + div() + .flex_none() + .pb_3() + .border_b_1() + .border_color(palette.menu_border) + .text_base() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(fg) + .child(s("desktop.settings.title")), + ) + .child( + div() + .id("settings-list") + .flex() + .flex_col() + // Sized by its rows, shrinking (and scrolling) once the panel is full. + .min_h_0() + .overflow_y_scroll() + .track_scroll(&app.settings_scroll) + // One child holding every row: the scroll extent is measured across the list's children and + // skips the first one's top margin, which left the last row short of fully scrolling in. + .child( + div() + .flex_none() + .flex() + .flex_col() + .child(heading(s("desktop.settings.general"), None)) + .child(language_row) + .when(!cfg!(target_os = "macos"), |el| el.child(tray_row)) + .child(sort_row) + .child(relative_row) + .child(heading(s("desktop.settings.appearance"), None)) + .child(theme_row) + .child(mode_row) + .child(pixelate_row) + .child(backdrop_row) + .child(visualizer_row) + .child(bins_row) + .child(heading( + s("desktop.settings.audio"), + Some(s("desktop.settings.next_launch")), + )) + .child(bitrate_row) + .child(normalisation_row) + .child(pregain_row) + .child(heading(s("desktop.settings.local"), None)) + .child(local_row) + .child(heading(s("desktop.settings.updates.section"), None)) + .child(version_row) + .child(auto_update_row) + .child(update_row), + ), + ), + ) +} + +/// What a settings control does when used: nearly always a `:` command, so the sheet and the +/// command bar cannot drift apart. The audio-quality keys have no command and write the +/// config directly. +#[derive(Clone)] +enum SettingChange { + Command(String), + Bitrate(u32), + Normalisation(bool), +} + +impl SettingChange { + fn apply(&self, app: &mut EchoApp, cx: &mut Context) { + match *self { + Self::Command(ref cmd) => app.run_setting(cmd.clone(), cx), + Self::Bitrate(rate) => app.set_audio_quality(|config| config.bitrate = rate, cx), + Self::Normalisation(on) => { + app.set_audio_quality(|config| config.normalisation = on, cx) + } + } + } +} + +/// Every settings dropdown is this wide at least, so their right and left edges line up. +const DROPDOWN_WIDTH: f32 = 124.0; From 9eff4de6ba4d8ac036cc8618b5014b28d2c933fc Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:47 -0500 Subject: [PATCH 18/44] desktop: move the device picker into views/modals/device.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 117 ----------------- crates/echo-desktop/src/views/modals.rs | 2 + .../echo-desktop/src/views/modals/device.rs | 118 ++++++++++++++++++ 3 files changed, 120 insertions(+), 117 deletions(-) create mode 100644 crates/echo-desktop/src/views/modals/device.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 4fe3295..6f55edf 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -840,123 +840,6 @@ pub fn right_panel( .into_any_element() } -/// The Spotify Connect device picker, painted over everything else. -pub fn device_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let selected_bg = palette.menu_selected; - let selected = app.state.ui.selected_device_index; - - let devices = app.state.data.devices.clone(); - - div() - .id("device-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.state.ui.device_modal_open = false; - cx.notify(); - })) - .child( - div() - .id("device-panel") - .w(px(400.0)) - .max_h(px(420.0)) - .rounded_lg() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .p_3() - .flex() - .flex_col() - .gap_1() - .overflow_hidden() - // Clicks on the panel itself must not reach the backdrop's close handler. - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .child( - div() - .pb_2() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.devices_title")), - ) - .child(if devices.is_empty() { - div() - .py_4() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.devices_none")) - .into_any_element() - } else { - div() - .id("device-list") - .flex() - .flex_col() - .max_h(px(340.0)) - .overflow_y_scroll() - .track_scroll(&app.device_modal_scroll) - .children(devices.into_iter().enumerate().map(|(ix, device)| { - let name_color = if device.is_active { accent } else { fg }; - div() - .id(ix) - .px_2() - .py_2() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_2() - .text_sm() - .when(ix == selected, |el| el.bg(selected_bg)) - .when(ix != selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = echo_core::intent::transfer_to_device( - &mut this.state, - ix, - ) { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(name_color) - .child(SharedString::from(device.name.clone())), - ) - .child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(device.device_type.clone())), - ) - .when(device.is_active, |el| { - el.child(div().flex_none().text_color(accent).child("●")) - }) - })) - .into_any_element() - }), - ) -} - /// Add-to-playlist picker over the core choices (own Spotify playlists plus local ones); Enter /// and row clicks resolve through `action_menu::commit_playlist_add`. pub fn playlist_add_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { diff --git a/crates/echo-desktop/src/views/modals.rs b/crates/echo-desktop/src/views/modals.rs index fbddc56..2010683 100644 --- a/crates/echo-desktop/src/views/modals.rs +++ b/crates/echo-desktop/src/views/modals.rs @@ -1,9 +1,11 @@ use super::*; +mod device; mod help; mod settings; mod theme; +pub use device::*; pub use help::*; pub use settings::*; pub use theme::*; diff --git a/crates/echo-desktop/src/views/modals/device.rs b/crates/echo-desktop/src/views/modals/device.rs new file mode 100644 index 0000000..88a6447 --- /dev/null +++ b/crates/echo-desktop/src/views/modals/device.rs @@ -0,0 +1,118 @@ +use super::*; + +/// The Spotify Connect device picker, painted over everything else. +pub fn device_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let selected_bg = palette.menu_selected; + let selected = app.state.ui.selected_device_index; + + let devices = app.state.data.devices.clone(); + + div() + .id("device-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.state.ui.device_modal_open = false; + cx.notify(); + })) + .child( + div() + .id("device-panel") + .w(px(400.0)) + .max_h(px(420.0)) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_3() + .flex() + .flex_col() + .gap_1() + .overflow_hidden() + // Clicks on the panel itself must not reach the backdrop's close handler. + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .child( + div() + .pb_2() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.devices_title")), + ) + .child(if devices.is_empty() { + div() + .py_4() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.devices_none")) + .into_any_element() + } else { + div() + .id("device-list") + .flex() + .flex_col() + .max_h(px(340.0)) + .overflow_y_scroll() + .track_scroll(&app.device_modal_scroll) + .children(devices.into_iter().enumerate().map(|(ix, device)| { + let name_color = if device.is_active { accent } else { fg }; + div() + .id(ix) + .px_2() + .py_2() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_2() + .text_sm() + .when(ix == selected, |el| el.bg(selected_bg)) + .when(ix != selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = echo_core::intent::transfer_to_device( + &mut this.state, + ix, + ) { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(name_color) + .child(SharedString::from(device.name.clone())), + ) + .child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(device.device_type.clone())), + ) + .when(device.is_active, |el| { + el.child(div().flex_none().text_color(accent).child("●")) + }) + })) + .into_any_element() + }), + ) +} From 017d5cb382c2d32293b68634925aa7a0ec14323c Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:49 -0500 Subject: [PATCH 19/44] desktop: move the add-to-playlist modal into views/modals/playlist_add.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 156 ----------------- crates/echo-desktop/src/views/modals.rs | 2 + .../src/views/modals/playlist_add.rs | 157 ++++++++++++++++++ 3 files changed, 159 insertions(+), 156 deletions(-) create mode 100644 crates/echo-desktop/src/views/modals/playlist_add.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 6f55edf..3f4e820 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -840,162 +840,6 @@ pub fn right_panel( .into_any_element() } -/// Add-to-playlist picker over the core choices (own Spotify playlists plus local ones); Enter -/// and row clicks resolve through `action_menu::commit_playlist_add`. -pub fn playlist_add_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let selected_bg = palette.menu_selected; - let selected = app.state.ui.selected_playlist_modal_index; - - // Materialized before the element closures capture anything from `app`. - let choices: Vec<(SharedString, bool)> = - echo_core::action_menu::filtered_playlist_add_choices(&app.state) - .into_iter() - .map(|(_, playlist)| { - let local = playlist.owner_id == "local"; - (SharedString::from(playlist.name), local) - }) - .collect(); - - let choices: Vec<_> = std::iter::once((tr(&app.state, "desktop.new_playlist"), false)) - .chain(choices) - .collect(); - div() - .id("playlist-add-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - // Modal: the backdrop swallows pointer events, so a scroll wheel over it can't reach the - // track list behind the overlay. - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - echo_core::action_menu::cancel_playlist_add(&mut this.state); - cx.notify(); - })) - .child( - div() - .id("playlist-add-panel") - .w(px(400.0)) - .max_h(px(420.0)) - .rounded_lg() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .p_3() - .flex() - .flex_col() - .gap_1() - .overflow_hidden() - // Clicks on the panel itself must not reach the backdrop's close handler. - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .child( - div() - .pb_2() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.playlist_add_title")), - ) - .child( - div() - .flex() - .gap_2() - .items_center() - .px_2() - .py_2() - .rounded_md() - .bg(palette.wash) - .text_sm() - .text_color(muted) - .child( - svg() - .path("icons/search.svg") - .size(px(14.0)) - .text_color(muted), - ) - .child(div().truncate().child( - if app.state.ui.playlist_add_filter.is_empty() { - tr(&app.state, "desktop.filter_playlists") - } else { - app.state.ui.playlist_add_filter.clone().into() - }, - )), - ) - .child(if choices.is_empty() { - div() - .py_4() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.playlist_add_none")) - .into_any_element() - } else { - div() - .id("playlist-add-list") - .flex() - .flex_col() - .max_h(px(340.0)) - .overflow_y_scroll() - .track_scroll(&app.playlist_modal_scroll) - .children(choices.into_iter().enumerate().map(|(ix, (name, local))| { - let local_label = tr(&app.state, "ui.local"); - div() - .id(ix) - .px_2() - .py_2() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_2() - .text_sm() - .when(ix == selected, |el| el.bg(selected_bg)) - .when(ix != selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::action_menu::commit_filtered_playlist_add( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(name), - ) - .when(local, |el| { - el.child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(local_label), - ) - }) - })) - .into_any_element() - }), - ) -} - /// The main-area empty state: the ECHO wordmark with a vertical secondary→primary gradient, or /// plain status text while authenticating. fn library_placeholder(app: &EchoApp) -> AnyElement { diff --git a/crates/echo-desktop/src/views/modals.rs b/crates/echo-desktop/src/views/modals.rs index 2010683..deb5d1b 100644 --- a/crates/echo-desktop/src/views/modals.rs +++ b/crates/echo-desktop/src/views/modals.rs @@ -2,10 +2,12 @@ use super::*; mod device; mod help; +mod playlist_add; mod settings; mod theme; pub use device::*; pub use help::*; +pub use playlist_add::*; pub use settings::*; pub use theme::*; diff --git a/crates/echo-desktop/src/views/modals/playlist_add.rs b/crates/echo-desktop/src/views/modals/playlist_add.rs new file mode 100644 index 0000000..16bead9 --- /dev/null +++ b/crates/echo-desktop/src/views/modals/playlist_add.rs @@ -0,0 +1,157 @@ +use super::*; + +/// Add-to-playlist picker over the core choices (own Spotify playlists plus local ones); Enter +/// and row clicks resolve through `action_menu::commit_playlist_add`. +pub fn playlist_add_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let selected_bg = palette.menu_selected; + let selected = app.state.ui.selected_playlist_modal_index; + + // Materialized before the element closures capture anything from `app`. + let choices: Vec<(SharedString, bool)> = + echo_core::action_menu::filtered_playlist_add_choices(&app.state) + .into_iter() + .map(|(_, playlist)| { + let local = playlist.owner_id == "local"; + (SharedString::from(playlist.name), local) + }) + .collect(); + + let choices: Vec<_> = std::iter::once((tr(&app.state, "desktop.new_playlist"), false)) + .chain(choices) + .collect(); + div() + .id("playlist-add-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + // Modal: the backdrop swallows pointer events, so a scroll wheel over it can't reach the + // track list behind the overlay. + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + echo_core::action_menu::cancel_playlist_add(&mut this.state); + cx.notify(); + })) + .child( + div() + .id("playlist-add-panel") + .w(px(400.0)) + .max_h(px(420.0)) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_3() + .flex() + .flex_col() + .gap_1() + .overflow_hidden() + // Clicks on the panel itself must not reach the backdrop's close handler. + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .child( + div() + .pb_2() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.playlist_add_title")), + ) + .child( + div() + .flex() + .gap_2() + .items_center() + .px_2() + .py_2() + .rounded_md() + .bg(palette.wash) + .text_sm() + .text_color(muted) + .child( + svg() + .path("icons/search.svg") + .size(px(14.0)) + .text_color(muted), + ) + .child(div().truncate().child( + if app.state.ui.playlist_add_filter.is_empty() { + tr(&app.state, "desktop.filter_playlists") + } else { + app.state.ui.playlist_add_filter.clone().into() + }, + )), + ) + .child(if choices.is_empty() { + div() + .py_4() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.playlist_add_none")) + .into_any_element() + } else { + div() + .id("playlist-add-list") + .flex() + .flex_col() + .max_h(px(340.0)) + .overflow_y_scroll() + .track_scroll(&app.playlist_modal_scroll) + .children(choices.into_iter().enumerate().map(|(ix, (name, local))| { + let local_label = tr(&app.state, "ui.local"); + div() + .id(ix) + .px_2() + .py_2() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_2() + .text_sm() + .when(ix == selected, |el| el.bg(selected_bg)) + .when(ix != selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::action_menu::commit_filtered_playlist_add( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(name), + ) + .when(local, |el| { + el.child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(local_label), + ) + }) + })) + .into_any_element() + }), + ) +} From 7b68ca168d17f72916fab787986b3766569a2a26 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:23:50 -0500 Subject: [PATCH 20/44] desktop: move the prompt modal into views/modals/prompt.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 206 ----------------- crates/echo-desktop/src/views/modals.rs | 2 + .../echo-desktop/src/views/modals/prompt.rs | 207 ++++++++++++++++++ 3 files changed, 209 insertions(+), 206 deletions(-) create mode 100644 crates/echo-desktop/src/views/modals/prompt.rs diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index 3f4e820..d04b020 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -905,209 +905,3 @@ fn lerp_hsla(a: gpui::Hsla, b: gpui::Hsla, t: f32) -> gpui::Hsla { } .into() } - -/// Confirm dialog for whichever destructive prompt is staged, resolved through -/// `intent::confirm_prompt`/`cancel_prompt`. -pub fn prompt_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let danger_color = theme.error.gpui(WINDOW_FG()); - - let ui = &app.state.ui; - let delete_label = tr(&app.state, "desktop.prompt.delete"); - let remove_label = tr(&app.state, "desktop.prompt.remove"); - let (message, confirm_label): (String, SharedString) = - if let Some(prompt) = &ui.duplicate_prompt { - let message = if prompt.duplicates.len() == 1 { - let song = prompt - .tracks - .iter() - .find(|t| prompt.duplicates.contains(&t.id)) - .map(|t| t.name.as_str()) - .unwrap_or_default(); - tr(&app.state, "desktop.duplicate_one").replace("{song}", song) - } else { - tr(&app.state, "desktop.duplicate_many") - .replace("{n}", &prompt.duplicates.len().to_string()) - }; - ( - message.replace("{playlist}", &prompt.playlist_name), - tr(&app.state, "desktop.add_anyway"), - ) - } else if let Some(name) = &ui.folder_delete_prompt { - ( - tr(&app.state, "desktop.prompt.delete_folder").replace("{}", name), - delete_label, - ) - } else if let Some(ids) = &ui.playlist_delete_prompt { - let name = ids - .first() - .and_then(|id| { - app.state - .data - .library_view - .iter() - .find_map(|node| match node { - LibraryNode::Playlist { playlist, .. } if &playlist.id == id => { - Some(playlist.name.clone()) - } - _ => None, - }) - }) - .unwrap_or_else(|| tr(&app.state, "desktop.prompt.this_playlist").to_string()); - ( - tr(&app.state, "desktop.prompt.delete_playlist").replace("{}", &name), - delete_label, - ) - } else if let Some(ids) = &ui.album_mass_delete_prompt { - let name = ids - .first() - .and_then(|id| { - app.state - .data - .saved_albums - .iter() - .find(|album| &album.id == id) - .map(|album| album.name.clone()) - }) - .unwrap_or_else(|| tr(&app.state, "desktop.prompt.this_album").to_string()); - ( - tr(&app.state, "desktop.prompt.remove_album").replace("{}", &name), - remove_label, - ) - } else if ui.track_delete_prompt.is_some() { - ( - tr(&app.state, "desktop.prompt.remove_tracks").to_string(), - remove_label, - ) - } else { - ( - tr(&app.state, "desktop.prompt.remove_liked").to_string(), - remove_label, - ) - }; - - let button = |id: &'static str, - label: SharedString, - color: gpui::Hsla, - border: gpui::Hsla, - hover_bg: gpui::Hsla| { - div() - .id(id) - .px_3() - .py_1() - .rounded_md() - .border_1() - .border_color(border) - .text_sm() - .text_color(color) - .cursor_pointer() - .hover(move |style| style.bg(hover_bg)) - .child(label) - }; - - div() - .id("prompt-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - echo_core::intent::cancel_prompt(&mut this.state); - cx.notify(); - })) - .child( - div() - .id("prompt-panel") - .w(px(380.0)) - .rounded_lg() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .p_4() - .flex() - .flex_col() - .gap_3() - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) - .child( - div() - .text_sm() - .text_color(fg) - .child(SharedString::from(message)), - ) - .child( - div() - .flex() - .flex_row() - .justify_end() - .gap_2() - .child( - button( - "prompt-cancel", - tr(&app.state, "desktop.prompt.cancel"), - muted, - palette.menu_border, - palette.menu_hover, - ) - .on_click(cx.listener( - |this: &mut EchoApp, _event, _window, cx| { - echo_core::intent::cancel_prompt(&mut this.state); - cx.notify(); - }, - )), - ) - .when( - ui.duplicate_prompt.as_ref().is_some_and(|p| { - p.tracks.iter().any(|t| !p.duplicates.contains(&t.id)) - }), - |el| { - el.child( - button( - "duplicate-skip", - tr(&app.state, "desktop.skip_duplicates"), - fg, - palette.menu_border, - palette.menu_hover, - ) - .on_click(cx.listener( - |this: &mut EchoApp, _, _, cx| { - if let Some(event) = - echo_core::intent::confirm_duplicate_skip( - &mut this.state, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )), - ) - }, - ) - .child( - button( - "prompt-confirm", - confirm_label, - danger_color, - palette.danger_border, - palette.danger_wash, - ) - .on_click(cx.listener( - |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::intent::confirm_prompt(&mut this.state) - { - this.dispatch(event); - } - cx.notify(); - }, - )), - ), - ), - ) -} diff --git a/crates/echo-desktop/src/views/modals.rs b/crates/echo-desktop/src/views/modals.rs index deb5d1b..f05e992 100644 --- a/crates/echo-desktop/src/views/modals.rs +++ b/crates/echo-desktop/src/views/modals.rs @@ -3,11 +3,13 @@ use super::*; mod device; mod help; mod playlist_add; +mod prompt; mod settings; mod theme; pub use device::*; pub use help::*; pub use playlist_add::*; +pub use prompt::*; pub use settings::*; pub use theme::*; diff --git a/crates/echo-desktop/src/views/modals/prompt.rs b/crates/echo-desktop/src/views/modals/prompt.rs new file mode 100644 index 0000000..46866bb --- /dev/null +++ b/crates/echo-desktop/src/views/modals/prompt.rs @@ -0,0 +1,207 @@ +use super::*; + +/// Confirm dialog for whichever destructive prompt is staged, resolved through +/// `intent::confirm_prompt`/`cancel_prompt`. +pub fn prompt_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let surface = theme.surface.gpui(crate::theme::PANEL_BG()); + let danger_color = theme.error.gpui(WINDOW_FG()); + + let ui = &app.state.ui; + let delete_label = tr(&app.state, "desktop.prompt.delete"); + let remove_label = tr(&app.state, "desktop.prompt.remove"); + let (message, confirm_label): (String, SharedString) = + if let Some(prompt) = &ui.duplicate_prompt { + let message = if prompt.duplicates.len() == 1 { + let song = prompt + .tracks + .iter() + .find(|t| prompt.duplicates.contains(&t.id)) + .map(|t| t.name.as_str()) + .unwrap_or_default(); + tr(&app.state, "desktop.duplicate_one").replace("{song}", song) + } else { + tr(&app.state, "desktop.duplicate_many") + .replace("{n}", &prompt.duplicates.len().to_string()) + }; + ( + message.replace("{playlist}", &prompt.playlist_name), + tr(&app.state, "desktop.add_anyway"), + ) + } else if let Some(name) = &ui.folder_delete_prompt { + ( + tr(&app.state, "desktop.prompt.delete_folder").replace("{}", name), + delete_label, + ) + } else if let Some(ids) = &ui.playlist_delete_prompt { + let name = ids + .first() + .and_then(|id| { + app.state + .data + .library_view + .iter() + .find_map(|node| match node { + LibraryNode::Playlist { playlist, .. } if &playlist.id == id => { + Some(playlist.name.clone()) + } + _ => None, + }) + }) + .unwrap_or_else(|| tr(&app.state, "desktop.prompt.this_playlist").to_string()); + ( + tr(&app.state, "desktop.prompt.delete_playlist").replace("{}", &name), + delete_label, + ) + } else if let Some(ids) = &ui.album_mass_delete_prompt { + let name = ids + .first() + .and_then(|id| { + app.state + .data + .saved_albums + .iter() + .find(|album| &album.id == id) + .map(|album| album.name.clone()) + }) + .unwrap_or_else(|| tr(&app.state, "desktop.prompt.this_album").to_string()); + ( + tr(&app.state, "desktop.prompt.remove_album").replace("{}", &name), + remove_label, + ) + } else if ui.track_delete_prompt.is_some() { + ( + tr(&app.state, "desktop.prompt.remove_tracks").to_string(), + remove_label, + ) + } else { + ( + tr(&app.state, "desktop.prompt.remove_liked").to_string(), + remove_label, + ) + }; + + let button = |id: &'static str, + label: SharedString, + color: gpui::Hsla, + border: gpui::Hsla, + hover_bg: gpui::Hsla| { + div() + .id(id) + .px_3() + .py_1() + .rounded_md() + .border_1() + .border_color(border) + .text_sm() + .text_color(color) + .cursor_pointer() + .hover(move |style| style.bg(hover_bg)) + .child(label) + }; + + div() + .id("prompt-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + echo_core::intent::cancel_prompt(&mut this.state); + cx.notify(); + })) + .child( + div() + .id("prompt-panel") + .w(px(380.0)) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_4() + .flex() + .flex_col() + .gap_3() + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .child( + div() + .text_sm() + .text_color(fg) + .child(SharedString::from(message)), + ) + .child( + div() + .flex() + .flex_row() + .justify_end() + .gap_2() + .child( + button( + "prompt-cancel", + tr(&app.state, "desktop.prompt.cancel"), + muted, + palette.menu_border, + palette.menu_hover, + ) + .on_click(cx.listener( + |this: &mut EchoApp, _event, _window, cx| { + echo_core::intent::cancel_prompt(&mut this.state); + cx.notify(); + }, + )), + ) + .when( + ui.duplicate_prompt.as_ref().is_some_and(|p| { + p.tracks.iter().any(|t| !p.duplicates.contains(&t.id)) + }), + |el| { + el.child( + button( + "duplicate-skip", + tr(&app.state, "desktop.skip_duplicates"), + fg, + palette.menu_border, + palette.menu_hover, + ) + .on_click(cx.listener( + |this: &mut EchoApp, _, _, cx| { + if let Some(event) = + echo_core::intent::confirm_duplicate_skip( + &mut this.state, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )), + ) + }, + ) + .child( + button( + "prompt-confirm", + confirm_label, + danger_color, + palette.danger_border, + palette.danger_wash, + ) + .on_click(cx.listener( + |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::intent::confirm_prompt(&mut this.state) + { + this.dispatch(event); + } + cx.notify(); + }, + )), + ), + ), + ) +} From d54c20579c2b4fa20ff81be3bffab4378a32787f Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:24:04 -0500 Subject: [PATCH 21/44] desktop: describe views.rs as the shared helpers its submodules build on Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/echo-desktop/src/views.rs b/crates/echo-desktop/src/views.rs index d04b020..a61bfd5 100644 --- a/crates/echo-desktop/src/views.rs +++ b/crates/echo-desktop/src/views.rs @@ -1,8 +1,8 @@ -//! Library sidebar and track list — the first real views of the desktop app. +//! Everything the window draws, one submodule per screen area, plus the row, thumbnail and +//! label helpers they share. //! -//! Both are thin projections of [`AppState`]: rows come straight from `library_view` / -//! `saved_albums` / `tracks`, and keyboard or pointer activation goes through -//! [`echo_core::intent`]. +//! Views are thin projections of [`echo_core::app::AppState`]: rows come straight from the +//! state, and keyboard or pointer activation goes through [`echo_core::intent`]. //! //! Thumbnails ride the core's [`echo_core::thumbnails`] cache. Rendering a row requests its //! cover; `drain_pending` (called after each row batch) spawns the fetches, and the resulting From acafea76475679beb88bdb20080f25ec21163aa0 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:07 -0500 Subject: [PATCH 22/44] desktop: move the text field editing helpers into text_input.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/main.rs | 131 +------------------------ crates/echo-desktop/src/text_input.rs | 132 ++++++++++++++++++++++++++ 2 files changed, 134 insertions(+), 129 deletions(-) create mode 100644 crates/echo-desktop/src/text_input.rs diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 118ec2d..7e6b4ef 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -17,6 +17,7 @@ mod images; mod playlist_ui; mod regions; mod single_instance; +mod text_input; mod theme; mod tray; mod views; @@ -35,6 +36,7 @@ use gpui::{ WindowOptions, actions, canvas, div, prelude::*, px, size, svg, }; use gpui_platform::application; +pub(crate) use text_input::*; use theme::{DesktopPalette, ToGpui, WINDOW_BG, WINDOW_FG}; actions!( @@ -369,88 +371,6 @@ const DRAG_EDGE: f32 = 48.0; /// Pixels per frame at the very edge. const DRAG_SCROLL_MAX: f32 = 14.0; -/// Byte index of the char boundary one character before `cursor` (or `cursor` at the start). -fn prev_char_boundary(value: &str, cursor: usize) -> usize { - value[..cursor.min(value.len())] - .char_indices() - .next_back() - .map(|(i, _)| i) - .unwrap_or(0) -} - -/// Byte index of the char boundary one character after `cursor` (or `cursor` at the end). -fn next_char_boundary(value: &str, cursor: usize) -> usize { - let cursor = cursor.min(value.len()); - value[cursor..] - .chars() - .next() - .map(|c| cursor + c.len_utf8()) - .unwrap_or(cursor) -} - -/// Insert `text` into `value` at the byte offset `cursor`, advancing the cursor past it. The -/// shared insertion path for both typed characters and pastes in the hand-rolled fields. -fn insert_at_cursor(value: &mut String, cursor: &mut usize, text: &str) { - *cursor = (*cursor).min(value.len()); - value.insert_str(*cursor, text); - *cursor += text.len(); -} - -/// Apply the cursor-aware editing keys shared by the hand-rolled text fields — arrow keys, -/// Home/End, Backspace, Delete, and printable character insertion — to `value`/`cursor`. -/// -/// Returns `true` when the event was one of those keys (so the caller can stop). Enter, Escape, -/// Tab, and paste stay with the caller: each field submits, cancels, and filters pasted text -/// differently. Cursor positions are byte offsets kept on char boundaries so multi-byte queries -/// (e.g. CJK search terms) navigate a character at a time rather than splitting a codepoint. -fn apply_text_edit(value: &mut String, cursor: &mut usize, event: &gpui::KeyDownEvent) -> bool { - *cursor = (*cursor).min(value.len()); - match event.keystroke.key.as_str() { - "left" => *cursor = prev_char_boundary(value, *cursor), - "right" => *cursor = next_char_boundary(value, *cursor), - "home" => *cursor = 0, - "end" => *cursor = value.len(), - "backspace" => { - if *cursor > 0 { - let start = prev_char_boundary(value, *cursor); - value.replace_range(start..*cursor, ""); - *cursor = start; - } - } - "delete" => { - if *cursor < value.len() { - let end = next_char_boundary(value, *cursor); - value.replace_range(*cursor..end, ""); - } - } - _ => { - // Insert only genuine typed text: a modifier chord (ctrl-v, cmd-a) is not input, and - // named keys with no glyph report no `key_char`. - let modifiers = &event.keystroke.modifiers; - if modifiers.control || modifiers.platform { - return false; - } - match event.keystroke.key_char.as_deref() { - Some(text) if !text.is_empty() && !text.chars().any(char::is_control) => { - insert_at_cursor(value, cursor, text); - } - _ => return false, - } - } - } - true -} - -/// Render a field's text with the block caret drawn at `cursor` (a byte offset), so the hand-rolled -/// inputs show where the next edit lands instead of pinning the caret to the end. -pub(crate) fn text_with_cursor(value: &str, cursor: usize) -> String { - let mut cursor = cursor.min(value.len()); - while cursor > 0 && !value.is_char_boundary(cursor) { - cursor -= 1; - } - format!("{}▏{}", &value[..cursor], &value[cursor..]) -} - /// Picks a fixed-pitch family that is actually installed. gpui matches families by exact name /// against the system font database — there is no generic "monospace" alias and no substitution /// when the name misses, so naming one font hard-codes a platform: "Consolas" is Windows-only, @@ -4516,50 +4436,3 @@ fn open_main_window(cx: &mut App) { .update(cx, |_, window, _| window.activate_window()) .ok(); } - -#[cfg(test)] -mod text_edit_tests { - use super::{insert_at_cursor, next_char_boundary, prev_char_boundary, text_with_cursor}; - - #[test] - fn boundaries_step_over_multibyte_chars() { - // "é" is two bytes, "中" is three: navigation must land on char boundaries, not bytes. - let value = "aé中b"; // bytes: a(1) é(2) 中(3) b(1) - assert_eq!(next_char_boundary(value, 0), 1); // past 'a' - assert_eq!(next_char_boundary(value, 1), 3); // past 'é' - assert_eq!(next_char_boundary(value, 3), 6); // past '中' - assert_eq!(next_char_boundary(value, 6), 7); // past 'b' - assert_eq!(next_char_boundary(value, 7), 7); // clamped at end - - assert_eq!(prev_char_boundary(value, 7), 6); - assert_eq!(prev_char_boundary(value, 6), 3); - assert_eq!(prev_char_boundary(value, 3), 1); - assert_eq!(prev_char_boundary(value, 1), 0); - assert_eq!(prev_char_boundary(value, 0), 0); // clamped at start - } - - #[test] - fn insert_advances_cursor_past_inserted_text() { - let mut value = "cd".to_string(); - let mut cursor = 0; - insert_at_cursor(&mut value, &mut cursor, "ab"); - assert_eq!(value, "abcd"); - assert_eq!(cursor, 2); - - // Insert a multi-byte char at the caret; the cursor moves by its byte length. - insert_at_cursor(&mut value, &mut cursor, "é"); - assert_eq!(value, "abécd"); - assert_eq!(cursor, 4); - } - - #[test] - fn caret_renders_at_cursor_and_survives_stale_index() { - assert_eq!(text_with_cursor("abc", 0), "▏abc"); - assert_eq!(text_with_cursor("abc", 1), "a▏bc"); - assert_eq!(text_with_cursor("abc", 3), "abc▏"); - // A byte index past the end is clamped rather than panicking. - assert_eq!(text_with_cursor("abc", 9), "abc▏"); - // An index landing mid-codepoint snaps back to a boundary. - assert_eq!(text_with_cursor("é", 1), "▏é"); - } -} diff --git a/crates/echo-desktop/src/text_input.rs b/crates/echo-desktop/src/text_input.rs new file mode 100644 index 0000000..5ae97d5 --- /dev/null +++ b/crates/echo-desktop/src/text_input.rs @@ -0,0 +1,132 @@ +/// Byte index of the char boundary one character before `cursor` (or `cursor` at the start). +fn prev_char_boundary(value: &str, cursor: usize) -> usize { + value[..cursor.min(value.len())] + .char_indices() + .next_back() + .map(|(i, _)| i) + .unwrap_or(0) +} + +/// Byte index of the char boundary one character after `cursor` (or `cursor` at the end). +fn next_char_boundary(value: &str, cursor: usize) -> usize { + let cursor = cursor.min(value.len()); + value[cursor..] + .chars() + .next() + .map(|c| cursor + c.len_utf8()) + .unwrap_or(cursor) +} + +/// Insert `text` into `value` at the byte offset `cursor`, advancing the cursor past it. The +/// shared insertion path for both typed characters and pastes in the hand-rolled fields. +pub(crate) fn insert_at_cursor(value: &mut String, cursor: &mut usize, text: &str) { + *cursor = (*cursor).min(value.len()); + value.insert_str(*cursor, text); + *cursor += text.len(); +} + +/// Apply the cursor-aware editing keys shared by the hand-rolled text fields — arrow keys, +/// Home/End, Backspace, Delete, and printable character insertion — to `value`/`cursor`. +/// +/// Returns `true` when the event was one of those keys (so the caller can stop). Enter, Escape, +/// Tab, and paste stay with the caller: each field submits, cancels, and filters pasted text +/// differently. Cursor positions are byte offsets kept on char boundaries so multi-byte queries +/// (e.g. CJK search terms) navigate a character at a time rather than splitting a codepoint. +pub(crate) fn apply_text_edit( + value: &mut String, + cursor: &mut usize, + event: &gpui::KeyDownEvent, +) -> bool { + *cursor = (*cursor).min(value.len()); + match event.keystroke.key.as_str() { + "left" => *cursor = prev_char_boundary(value, *cursor), + "right" => *cursor = next_char_boundary(value, *cursor), + "home" => *cursor = 0, + "end" => *cursor = value.len(), + "backspace" => { + if *cursor > 0 { + let start = prev_char_boundary(value, *cursor); + value.replace_range(start..*cursor, ""); + *cursor = start; + } + } + "delete" => { + if *cursor < value.len() { + let end = next_char_boundary(value, *cursor); + value.replace_range(*cursor..end, ""); + } + } + _ => { + // Insert only genuine typed text: a modifier chord (ctrl-v, cmd-a) is not input, and + // named keys with no glyph report no `key_char`. + let modifiers = &event.keystroke.modifiers; + if modifiers.control || modifiers.platform { + return false; + } + match event.keystroke.key_char.as_deref() { + Some(text) if !text.is_empty() && !text.chars().any(char::is_control) => { + insert_at_cursor(value, cursor, text); + } + _ => return false, + } + } + } + true +} + +/// Render a field's text with the block caret drawn at `cursor` (a byte offset), so the hand-rolled +/// inputs show where the next edit lands instead of pinning the caret to the end. +pub(crate) fn text_with_cursor(value: &str, cursor: usize) -> String { + let mut cursor = cursor.min(value.len()); + while cursor > 0 && !value.is_char_boundary(cursor) { + cursor -= 1; + } + format!("{}▏{}", &value[..cursor], &value[cursor..]) +} + +#[cfg(test)] +mod text_edit_tests { + use super::{insert_at_cursor, next_char_boundary, prev_char_boundary, text_with_cursor}; + + #[test] + fn boundaries_step_over_multibyte_chars() { + // "é" is two bytes, "中" is three: navigation must land on char boundaries, not bytes. + let value = "aé中b"; // bytes: a(1) é(2) 中(3) b(1) + assert_eq!(next_char_boundary(value, 0), 1); // past 'a' + assert_eq!(next_char_boundary(value, 1), 3); // past 'é' + assert_eq!(next_char_boundary(value, 3), 6); // past '中' + assert_eq!(next_char_boundary(value, 6), 7); // past 'b' + assert_eq!(next_char_boundary(value, 7), 7); // clamped at end + + assert_eq!(prev_char_boundary(value, 7), 6); + assert_eq!(prev_char_boundary(value, 6), 3); + assert_eq!(prev_char_boundary(value, 3), 1); + assert_eq!(prev_char_boundary(value, 1), 0); + assert_eq!(prev_char_boundary(value, 0), 0); // clamped at start + } + + #[test] + fn insert_advances_cursor_past_inserted_text() { + let mut value = "cd".to_string(); + let mut cursor = 0; + insert_at_cursor(&mut value, &mut cursor, "ab"); + assert_eq!(value, "abcd"); + assert_eq!(cursor, 2); + + // Insert a multi-byte char at the caret; the cursor moves by its byte length. + insert_at_cursor(&mut value, &mut cursor, "é"); + assert_eq!(value, "abécd"); + assert_eq!(cursor, 4); + } + + #[test] + fn caret_renders_at_cursor_and_survives_stale_index() { + assert_eq!(text_with_cursor("abc", 0), "▏abc"); + assert_eq!(text_with_cursor("abc", 1), "a▏bc"); + assert_eq!(text_with_cursor("abc", 3), "abc▏"); + // A byte index past the end is clamped rather than panicking. + assert_eq!(text_with_cursor("abc", 9), "abc▏"); + // An index landing mid-codepoint snaps back to a boundary. + assert_eq!(text_with_cursor("é", 1), "▏é"); + } +} From 5917c87e988ba4f4070320dc2b9b9311b7bb6c2b Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:09 -0500 Subject: [PATCH 23/44] desktop: move the playback bar into playback_bar.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/main.rs | 712 +----------------------- crates/echo-desktop/src/playback_bar.rs | 712 ++++++++++++++++++++++++ 2 files changed, 715 insertions(+), 709 deletions(-) create mode 100644 crates/echo-desktop/src/playback_bar.rs diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 7e6b4ef..f1001d6 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -14,6 +14,7 @@ mod assets; mod backdrop; mod dock_icon; mod images; +mod playback_bar; mod playlist_ui; mod regions; mod single_instance; @@ -36,6 +37,7 @@ use gpui::{ WindowOptions, actions, canvas, div, prelude::*, px, size, svg, }; use gpui_platform::application; +pub(crate) use playback_bar::*; pub(crate) use text_input::*; use theme::{DesktopPalette, ToGpui, WINDOW_BG, WINDOW_FG}; @@ -2974,470 +2976,8 @@ impl EchoApp { } let _ = self.app_tx.send(event); } - - pub(crate) fn render_playback_bar(&mut self, cx: &mut Context) -> impl IntoElement { - let theme = &self.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let playback = &self.state.playback; - let title: SharedString = if playback.playing_track_title.is_empty() { - views::tr(&self.state, "desktop.nothing_playing") - } else { - playback.playing_track_title.clone().into() - }; - let artist: SharedString = playback.playing_track_artist.clone().into(); - let has_track = playback.playing_track_id.is_some(); - - let controls = ControlColors { - fg, - muted, - accent, - hover: palette.wash, - track: palette.border, - }; - let volume_fraction = (playback.volume as f32 / 100.0).clamp(0.0, 1.0); - let volume_label: SharedString = format!("{}%", playback.volume).into(); - let mute_icon = if playback.volume == 0 { - "icons/volume-off.svg" - } else { - "icons/volume-high.svg" - }; - let queue_color = if self.right_panel == Some(RightPanel::Queue) { - accent - } else { - muted - }; - let lyrics_color = if self.right_panel == Some(RightPanel::Lyrics) { - accent - } else { - muted - }; - let secondary = theme.secondary.gpui(WINDOW_FG()); - let liked_button = playback - .playing_track_id - .clone() - .filter(|_| { - playback.playing_track_source == Some(echo_core::models::TrackSource::Spotify) - }) - .map(|track_id| { - let liked = self.state.data.liked_tracks.contains(&track_id); - playing_like_button(track_id, liked, secondary, palette.like_dim, cx) - }); - // Playback on another Connect device (a phone, a speaker) gets a pill naming it; - // echo's own device and local files are the norm and stay unlabelled. - let playing_on: Option = (has_track - && playback.device_name != echo_core::worker::audio::DEVICE_NAME - && playback.device_name != "Local" - && !playback.device_name.is_empty()) - .then(|| { - views::tr(&self.state, "desktop.playing_on") - .replace("{}", &playback.device_name) - .into() - }); - let visualizer_bands = (self.state.ui.library_config.enable_visualizer - && self.state.playback.is_playing) - .then(|| self.state.playback.audio_visualization.clone()) - .flatten(); - let vis_bins = self.state.ui.vis_bins.clamp(5, 32); - - // Keep showing the previous cover while the current one refetches after a pixelate - // change. - let cover = self - .state - .playback - .playing_track_image - .as_ref() - .or(self.state.playback.previous_track_image.as_ref()) - .cloned() - .and_then(|artwork| self.images.get(&artwork)); - let drag_colors = views::DragColors::resolve(&self.state.ui.active_theme); - let drag_payload = echo_core::history::playing_track(&self.state) - .map(|track| views::single_drag_payload(&track, cover.clone())); - - // The condensed-lyrics line shows the current lyric accented with the next one below, - // riding the same playback tick that advances the seek bar. - let inline_lyrics = self - .state - .ui - .condensed_lyrics_enabled - .then(|| { - if let Some(lyrics) = self.state.playback.current_lyrics.as_ref() { - if lyrics.lines.is_empty() { - return ( - views::tr(&self.state, "desktop.no_lyrics_found").to_string(), - String::new(), - ); - } - let progress = self.state.playback.display_progress_ms(); - let current = views::current_lyric_index(&lyrics.lines, progress); - ( - lyrics.lines[current].text.clone(), - lyrics - .lines - .get(current + 1) - .map(|line| line.text.clone()) - .unwrap_or_default(), - ) - } else if !self.state.playback.playing_track_title.is_empty() { - ( - views::tr(&self.state, "desktop.no_lyrics_found").to_string(), - String::new(), - ) - } else { - (String::new(), String::new()) - } - }) - .filter(|(current, _)| !current.is_empty()); - - // Inline lyrics keep the top-row center slot; "Playing from X" fills it otherwise. - let playing_from = if inline_lyrics.is_none() && has_track { - views::playing_context_label(&self.state) - } else { - None - }; - - let volume_bounds = self.volume_bounds.clone(); - - div() - .flex() - .flex_col() - .justify_center() - .gap_1() - .h(px(regions::PLAYBACK_BAR_HEIGHT)) - .px_4() - .border_t_1() - .border_color(palette.border) - .child( - // Top row: song card, condensed lyric line, visualizer. Its contents come and go; - // its height doesn't, so nothing here can move the row below. - div() - .flex() - .flex_row() - .items_center() - .gap_3() - .h(px(PLAYBACK_ROW_HEIGHT)) - .child( - div() - .id("playing-card") - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .flex() - .flex_row() - .items_center() - .gap_2() - .when_some(drag_payload, |el, payload| { - el.on_drag(payload, move |drag, _offset, _window, cx| { - views::track_drag_preview(drag, drag_colors, cx) - }) - }) - .child(match cover { - Some(image) => { - views::cover_image(image, 36.0, 6.0).into_any_element() - } - None => div() - .flex_none() - .w(px(36.0)) - .h(px(36.0)) - .rounded_md() - .bg(palette.wash) - .flex() - .items_center() - .justify_center() - .child( - svg() - .path("icons/music-note.svg") - .w(px(16.0)) - .h(px(16.0)) - .text_color(muted), - ) - .into_any_element(), - }) - .child( - div() - .flex_col() - .flex_grow(1.0) - .overflow_hidden() - .child( - playing_track_link( - "playing-title", - title, - fg, - has_track, - echo_core::models::ActionMenuAction::GoToAlbum, - cx, - ) - .text_sm(), - ) - .child( - playing_track_link( - "playing-artist", - artist, - muted, - has_track, - echo_core::models::ActionMenuAction::GoToArtist, - cx, - ) - .text_xs(), - ), - ) - .children(liked_button), - ) - .child( - div() - .flex_grow(1.0) - .flex() - .flex_col() - .items_center() - .justify_center() - .overflow_hidden() - .when_some(inline_lyrics, |el, (current, next)| { - el.child( - div() - .text_sm() - .text_color(accent) - .whitespace_nowrap() - .max_w_full() - .overflow_hidden() - .child(SharedString::from(current)), - ) - .when(!next.is_empty(), |el| { - el.child( - div() - .text_xs() - .text_color(muted) - .whitespace_nowrap() - .max_w_full() - .overflow_hidden() - .child(SharedString::from(next)), - ) - }) - }) - .when_some(playing_from, |el, label| { - el.child( - div() - .text_xs() - .text_color(muted) - .whitespace_nowrap() - .max_w_full() - .overflow_hidden() - .text_ellipsis() - .child(SharedString::from(label)), - ) - }), - ) - .child( - div() - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .flex() - .flex_row() - .items_center() - .justify_end() - .gap_3() - .when_some(playing_on, |el, label| { - el.child( - div() - .id("playing-on") - .flex_none() - .max_w(px(160.0)) - .px_2() - .py_1() - .rounded_full() - .border_1() - .border_color(accent) - .flex() - .flex_row() - .items_center() - .gap_1() - .cursor_pointer() - .hover(move |style| style.bg(palette.wash)) - .on_click(cx.listener(|this, _event, _window, cx| { - this.open_devices(cx) - })) - .child( - svg() - .path("icons/computer.svg") - .size(px(12.0)) - .text_color(accent), - ) - .child( - div() - .text_xs() - .text_color(accent) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(label), - ), - ) - }) - .when_some(visualizer_bands, |el, bands| { - // The engine always fills 32 bands, 0–100; they are averaged down - // to the configured bin count (`:visbins`) and painted as - // bottom-anchored bars. Repaints ride the fast tick. - el.child( - div().flex_none().w(px(120.0)).h(px(32.0)).child( - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let bands = bands.lock(); - let chunk = bands.len() as f32 / vis_bins as f32; - let band_width = - bounds.size.width / vis_bins as f32; - for index in 0..vis_bins { - let start = (index as f32 * chunk) as usize; - let end = if index == vis_bins - 1 { - bands.len() - } else { - ((index + 1) as f32 * chunk) as usize - }; - let slice = &bands[start..end.max(start + 1)]; - let value = slice.iter().sum::() - / slice.len() as f32; - let ratio = (value / 100.0).clamp(0.0, 1.0); - let bar_height = bounds.size.height * ratio; - let origin = gpui::point( - bounds.origin.x + band_width * index as f32, - bounds.origin.y + bounds.size.height - - bar_height, - ); - let bar = Bounds { - origin, - size: size(band_width * 0.8, bar_height), - }; - window.paint_quad(gpui::fill(bar, accent)); - } - }, - ) - .size_full(), - ), - ) - }), - ), - ) - .child( - // Bottom row: transport, seek and volume on one line, so the seek bar sits on the - // buttons' baseline no matter what the row above is doing. - div() - .flex() - .flex_row() - .items_center() - .gap_3() - .h(px(PLAYBACK_ROW_HEIGHT)) - .child( - self.transport_controls(controls, cx) - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .child(icon_button( - "lyrics", - "icons/mic.svg", - lyrics_color, - palette.wash, - cx, - |this, cx| this.toggle_lyrics(cx), - )), - ) - .child(self.seek_bar(controls, cx)) - .child( - div() - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .flex() - .flex_row() - .items_center() - .justify_end() - .gap_1() - .child(icon_button( - "queue", - "icons/playlist.svg", - queue_color, - palette.wash, - cx, - |this, cx| this.toggle_right_panel(RightPanel::Queue, cx), - )) - .child(icon_button( - "devices", - "icons/computer.svg", - muted, - palette.wash, - cx, - |this, cx| this.open_devices(cx), - )) - .child(icon_button( - "mute", - mute_icon, - muted, - palette.wash, - cx, - |this, cx| this.toggle_mute(cx), - )) - .child( - div() - .id("volume-bar") - .flex_none() - .w(px(90.0)) - .py_2() - .cursor_pointer() - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener( - |this, event: &gpui::MouseDownEvent, _window, cx| { - this.begin_scrub( - Scrub::Volume, - event.position.x, - cx, - ); - }, - ), - ) - .child( - div() - .relative() - .w_full() - .h(px(6.0)) - .rounded_full() - .bg(palette.border) - .child( - canvas( - move |bounds, _window, _cx| { - volume_bounds.set(bounds) - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .child( - div() - .h_full() - .rounded_full() - .bg(fg) - .w(gpui::relative(volume_fraction)), - ), - ), - ) - .child( - div() - .flex_none() - .w(px(34.0)) - .text_xs() - .text_color(fg) - .child(volume_label), - ), - ), - ) - } } -/// The playback bar's two rows share this three-slot geometry — fixed side columns around a -/// growing center — so the seek bar lines up with the transport and volume controls below it. -const PLAYBACK_SIDE_WIDTH: f32 = 240.0; -/// Fixed so that showing or hiding the lyric line and the visualizer can't move the seek bar. -const PLAYBACK_ROW_HEIGHT: f32 = 40.0; - /// A small round icon button for the playback bar. `icon` is an embedded SVG path (see /// [`assets`]), tinted with `color` like any themed text. /// The `:sort` argument that produces `sort`, so the picker can mark the active option. @@ -3454,248 +2994,7 @@ pub(crate) fn sort_arg(sort: echo_core::app::TrackSort) -> &'static str { } } -/// The playback bar's heart for the playing track: the list rows' liked cell at bar size. -fn playing_like_button( - track_id: String, - liked: bool, - color: Hsla, - dim: Hsla, - cx: &mut Context, -) -> gpui::Stateful
{ - div() - .id("playing-like") - .group("playing-like") - .flex_none() - .w(px(24.0)) - .h(px(24.0)) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .on_click(cx.listener(move |this, _event, _window, cx| { - if let Some(event) = - echo_core::intent::toggle_like_track(&mut this.state, track_id.clone()) - { - this.dispatch(event); - } - cx.notify(); - })) - .child( - svg() - .path("icons/heart.svg") - .size(px(14.0)) - .text_color(if liked { color } else { dim }) - .when(!liked, |el| { - el.group_hover("playing-like", move |style| style.text_color(color)) - }), - ) -} - -/// The playing track's title or artist as a link: clicking jumps to the album or artist page -/// through the same action-menu path the context menu uses. Callers add the text size. -pub(crate) fn playing_track_link( - id: &'static str, - text: SharedString, - color: Hsla, - has_track: bool, - action: echo_core::models::ActionMenuAction, - cx: &mut Context, -) -> gpui::Stateful
{ - div() - .id(id) - .text_color(color) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .when(has_track, |el| { - el.cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this, _event, _window, cx| { - if let Some(ctx) = this.playing_track_context() { - this.go_to(ctx, action, cx); - } - })) - }) - .child(text) -} - -pub(crate) fn icon_button( - id: &'static str, - icon: &'static str, - color: Hsla, - hover_bg: Hsla, - cx: &mut Context, - on_click: impl Fn(&mut EchoApp, &mut Context) + 'static, -) -> impl IntoElement { - div() - .id(id) - .flex_none() - .w(px(32.0)) - .h(px(32.0)) - .flex() - .items_center() - .justify_center() - .rounded_full() - .hover(move |style| style.bg(hover_bg)) - .on_click(cx.listener(move |this, _event, _window, cx| on_click(this, cx))) - .child(svg().path(icon).w(px(16.0)).h(px(16.0)).text_color(color)) -} - -/// The colors the transport and seek bar draw in: the theme's in the playback bar, the -/// cover's in the immersive view. -#[derive(Clone, Copy)] -pub(crate) struct ControlColors { - pub fg: Hsla, - pub muted: Hsla, - pub accent: Hsla, - pub hover: Hsla, - pub track: Hsla, -} - -impl EchoApp { - /// Shuffle, previous, play/pause, next and repeat in a row, two each side of play so it - /// centers; the caller sizes the row. - pub(crate) fn transport_controls(&self, colors: ControlColors, cx: &mut Context) -> Div { - let playback = &self.state.playback; - let play_icon = if playback.is_playing { - "icons/pause.svg" - } else { - "icons/play.svg" - }; - let shuffle_color = if playback.is_shuffled { - colors.accent - } else { - colors.muted - }; - let (repeat_icon, repeat_color) = match playback.repeat_mode.as_str() { - "Track" => ("icons/repeat-one.svg", colors.accent), - "Context" => ("icons/repeat.svg", colors.accent), - _ => ("icons/repeat.svg", colors.muted), - }; - div() - .flex() - .flex_row() - .items_center() - .gap_1() - .child(icon_button( - "shuffle", - "icons/shuffle.svg", - shuffle_color, - colors.hover, - cx, - |this, cx| this.toggle_shuffle(cx), - )) - .child(icon_button( - "previous", - "icons/previous.svg", - colors.fg, - colors.hover, - cx, - |this, cx| this.play_previous(cx), - )) - .child( - div() - .id("play-pause") - .flex_none() - .w(px(36.0)) - .h(px(36.0)) - .flex() - .items_center() - .justify_center() - .rounded_full() - .hover(move |style| style.bg(colors.hover)) - .on_click(cx.listener(|this, _event, _window, cx| this.toggle_playback(cx))) - .child( - svg() - .path(play_icon) - .w(px(20.0)) - .h(px(20.0)) - .text_color(colors.fg), - ), - ) - .child(icon_button( - "next", - "icons/next.svg", - colors.fg, - colors.hover, - cx, - |this, cx| this.play_next(cx), - )) - .child(icon_button( - "repeat", - repeat_icon, - repeat_color, - colors.hover, - cx, - |this, cx| this.cycle_repeat(cx), - )) - } - - /// Elapsed time, the seek bar and the duration on one line, growing to the caller's width. - /// The canvas overlay records the track's bounds each paint, and a click anywhere in the - /// (taller) hit area seeks to that fraction. - pub(crate) fn seek_bar(&self, colors: ControlColors, cx: &mut Context) -> Div { - let playback = &self.state.playback; - let progress_ms = playback.display_progress_ms(); - let fraction = if playback.duration_ms > 0 { - (progress_ms as f32 / playback.duration_ms as f32).clamp(0.0, 1.0) - } else { - 0.0 - }; - let seek_bounds = self.seek_bounds.clone(); - let label = |ms: u32| { - div() - .flex_none() - .text_color(colors.muted) - .text_xs() - .child(SharedString::from(format_time(ms))) - }; - div() - .flex_grow(1.0) - .flex() - .flex_row() - .items_center() - .gap_2() - .child(label(progress_ms)) - .child( - div() - .id("seek-bar") - .flex_grow(1.0) - .py_2() - .cursor_pointer() - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| { - this.begin_scrub(Scrub::Seek, event.position.x, cx); - }), - ) - .child( - div() - .relative() - .w_full() - .h(px(6.0)) - .rounded_full() - .bg(colors.track) - .child( - canvas( - move |bounds, _window, _cx| seek_bounds.set(bounds), - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .child( - div() - .h_full() - .rounded_full() - .bg(colors.accent) - .w(gpui::relative(fraction)), - ), - ), - ) - .child(label(playback.duration_ms)) - } -} +impl EchoApp {} impl Render for EchoApp { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { @@ -4175,11 +3474,6 @@ impl Render for EchoApp { } } -pub(crate) fn format_time(ms: u32) -> String { - let seconds = ms / 1000; - format!("{}:{:02}", seconds / 60, seconds % 60) -} - fn main() { // Neither launch path has a stderr anyone reads — the Linux .desktop entry sets // Terminal=false and the Windows build is a windows_subsystem app — so a panic before the diff --git a/crates/echo-desktop/src/playback_bar.rs b/crates/echo-desktop/src/playback_bar.rs new file mode 100644 index 0000000..ef47cf4 --- /dev/null +++ b/crates/echo-desktop/src/playback_bar.rs @@ -0,0 +1,712 @@ +use super::*; + +/// The playback bar's two rows share this three-slot geometry — fixed side columns around a +/// growing center — so the seek bar lines up with the transport and volume controls below it. +pub(crate) const PLAYBACK_SIDE_WIDTH: f32 = 240.0; + +/// Fixed so that showing or hiding the lyric line and the visualizer can't move the seek bar. +pub(crate) const PLAYBACK_ROW_HEIGHT: f32 = 40.0; + +/// The playback bar's heart for the playing track: the list rows' liked cell at bar size. +pub(crate) fn playing_like_button( + track_id: String, + liked: bool, + color: Hsla, + dim: Hsla, + cx: &mut Context, +) -> gpui::Stateful
{ + div() + .id("playing-like") + .group("playing-like") + .flex_none() + .w(px(24.0)) + .h(px(24.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .on_click(cx.listener(move |this, _event, _window, cx| { + if let Some(event) = + echo_core::intent::toggle_like_track(&mut this.state, track_id.clone()) + { + this.dispatch(event); + } + cx.notify(); + })) + .child( + svg() + .path("icons/heart.svg") + .size(px(14.0)) + .text_color(if liked { color } else { dim }) + .when(!liked, |el| { + el.group_hover("playing-like", move |style| style.text_color(color)) + }), + ) +} + +/// The playing track's title or artist as a link: clicking jumps to the album or artist page +/// through the same action-menu path the context menu uses. Callers add the text size. +pub(crate) fn playing_track_link( + id: &'static str, + text: SharedString, + color: Hsla, + has_track: bool, + action: echo_core::models::ActionMenuAction, + cx: &mut Context, +) -> gpui::Stateful
{ + div() + .id(id) + .text_color(color) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .when(has_track, |el| { + el.cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener(move |this, _event, _window, cx| { + if let Some(ctx) = this.playing_track_context() { + this.go_to(ctx, action, cx); + } + })) + }) + .child(text) +} + +pub(crate) fn icon_button( + id: &'static str, + icon: &'static str, + color: Hsla, + hover_bg: Hsla, + cx: &mut Context, + on_click: impl Fn(&mut EchoApp, &mut Context) + 'static, +) -> impl IntoElement { + div() + .id(id) + .flex_none() + .w(px(32.0)) + .h(px(32.0)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .hover(move |style| style.bg(hover_bg)) + .on_click(cx.listener(move |this, _event, _window, cx| on_click(this, cx))) + .child(svg().path(icon).w(px(16.0)).h(px(16.0)).text_color(color)) +} + +/// The colors the transport and seek bar draw in: the theme's in the playback bar, the +/// cover's in the immersive view. +#[derive(Clone, Copy)] +pub(crate) struct ControlColors { + pub fg: Hsla, + pub muted: Hsla, + pub accent: Hsla, + pub hover: Hsla, + pub track: Hsla, +} + +pub(crate) fn format_time(ms: u32) -> String { + let seconds = ms / 1000; + format!("{}:{:02}", seconds / 60, seconds % 60) +} + +impl EchoApp { + pub(crate) fn render_playback_bar(&mut self, cx: &mut Context) -> impl IntoElement { + let theme = &self.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let playback = &self.state.playback; + let title: SharedString = if playback.playing_track_title.is_empty() { + views::tr(&self.state, "desktop.nothing_playing") + } else { + playback.playing_track_title.clone().into() + }; + let artist: SharedString = playback.playing_track_artist.clone().into(); + let has_track = playback.playing_track_id.is_some(); + + let controls = ControlColors { + fg, + muted, + accent, + hover: palette.wash, + track: palette.border, + }; + let volume_fraction = (playback.volume as f32 / 100.0).clamp(0.0, 1.0); + let volume_label: SharedString = format!("{}%", playback.volume).into(); + let mute_icon = if playback.volume == 0 { + "icons/volume-off.svg" + } else { + "icons/volume-high.svg" + }; + let queue_color = if self.right_panel == Some(RightPanel::Queue) { + accent + } else { + muted + }; + let lyrics_color = if self.right_panel == Some(RightPanel::Lyrics) { + accent + } else { + muted + }; + let secondary = theme.secondary.gpui(WINDOW_FG()); + let liked_button = playback + .playing_track_id + .clone() + .filter(|_| { + playback.playing_track_source == Some(echo_core::models::TrackSource::Spotify) + }) + .map(|track_id| { + let liked = self.state.data.liked_tracks.contains(&track_id); + playing_like_button(track_id, liked, secondary, palette.like_dim, cx) + }); + // Playback on another Connect device (a phone, a speaker) gets a pill naming it; + // echo's own device and local files are the norm and stay unlabelled. + let playing_on: Option = (has_track + && playback.device_name != echo_core::worker::audio::DEVICE_NAME + && playback.device_name != "Local" + && !playback.device_name.is_empty()) + .then(|| { + views::tr(&self.state, "desktop.playing_on") + .replace("{}", &playback.device_name) + .into() + }); + let visualizer_bands = (self.state.ui.library_config.enable_visualizer + && self.state.playback.is_playing) + .then(|| self.state.playback.audio_visualization.clone()) + .flatten(); + let vis_bins = self.state.ui.vis_bins.clamp(5, 32); + + // Keep showing the previous cover while the current one refetches after a pixelate + // change. + let cover = self + .state + .playback + .playing_track_image + .as_ref() + .or(self.state.playback.previous_track_image.as_ref()) + .cloned() + .and_then(|artwork| self.images.get(&artwork)); + let drag_colors = views::DragColors::resolve(&self.state.ui.active_theme); + let drag_payload = echo_core::history::playing_track(&self.state) + .map(|track| views::single_drag_payload(&track, cover.clone())); + + // The condensed-lyrics line shows the current lyric accented with the next one below, + // riding the same playback tick that advances the seek bar. + let inline_lyrics = self + .state + .ui + .condensed_lyrics_enabled + .then(|| { + if let Some(lyrics) = self.state.playback.current_lyrics.as_ref() { + if lyrics.lines.is_empty() { + return ( + views::tr(&self.state, "desktop.no_lyrics_found").to_string(), + String::new(), + ); + } + let progress = self.state.playback.display_progress_ms(); + let current = views::current_lyric_index(&lyrics.lines, progress); + ( + lyrics.lines[current].text.clone(), + lyrics + .lines + .get(current + 1) + .map(|line| line.text.clone()) + .unwrap_or_default(), + ) + } else if !self.state.playback.playing_track_title.is_empty() { + ( + views::tr(&self.state, "desktop.no_lyrics_found").to_string(), + String::new(), + ) + } else { + (String::new(), String::new()) + } + }) + .filter(|(current, _)| !current.is_empty()); + + // Inline lyrics keep the top-row center slot; "Playing from X" fills it otherwise. + let playing_from = if inline_lyrics.is_none() && has_track { + views::playing_context_label(&self.state) + } else { + None + }; + + let volume_bounds = self.volume_bounds.clone(); + + div() + .flex() + .flex_col() + .justify_center() + .gap_1() + .h(px(regions::PLAYBACK_BAR_HEIGHT)) + .px_4() + .border_t_1() + .border_color(palette.border) + .child( + // Top row: song card, condensed lyric line, visualizer. Its contents come and go; + // its height doesn't, so nothing here can move the row below. + div() + .flex() + .flex_row() + .items_center() + .gap_3() + .h(px(PLAYBACK_ROW_HEIGHT)) + .child( + div() + .id("playing-card") + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .flex() + .flex_row() + .items_center() + .gap_2() + .when_some(drag_payload, |el, payload| { + el.on_drag(payload, move |drag, _offset, _window, cx| { + views::track_drag_preview(drag, drag_colors, cx) + }) + }) + .child(match cover { + Some(image) => { + views::cover_image(image, 36.0, 6.0).into_any_element() + } + None => div() + .flex_none() + .w(px(36.0)) + .h(px(36.0)) + .rounded_md() + .bg(palette.wash) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path("icons/music-note.svg") + .w(px(16.0)) + .h(px(16.0)) + .text_color(muted), + ) + .into_any_element(), + }) + .child( + div() + .flex_col() + .flex_grow(1.0) + .overflow_hidden() + .child( + playing_track_link( + "playing-title", + title, + fg, + has_track, + echo_core::models::ActionMenuAction::GoToAlbum, + cx, + ) + .text_sm(), + ) + .child( + playing_track_link( + "playing-artist", + artist, + muted, + has_track, + echo_core::models::ActionMenuAction::GoToArtist, + cx, + ) + .text_xs(), + ), + ) + .children(liked_button), + ) + .child( + div() + .flex_grow(1.0) + .flex() + .flex_col() + .items_center() + .justify_center() + .overflow_hidden() + .when_some(inline_lyrics, |el, (current, next)| { + el.child( + div() + .text_sm() + .text_color(accent) + .whitespace_nowrap() + .max_w_full() + .overflow_hidden() + .child(SharedString::from(current)), + ) + .when(!next.is_empty(), |el| { + el.child( + div() + .text_xs() + .text_color(muted) + .whitespace_nowrap() + .max_w_full() + .overflow_hidden() + .child(SharedString::from(next)), + ) + }) + }) + .when_some(playing_from, |el, label| { + el.child( + div() + .text_xs() + .text_color(muted) + .whitespace_nowrap() + .max_w_full() + .overflow_hidden() + .text_ellipsis() + .child(SharedString::from(label)), + ) + }), + ) + .child( + div() + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .flex() + .flex_row() + .items_center() + .justify_end() + .gap_3() + .when_some(playing_on, |el, label| { + el.child( + div() + .id("playing-on") + .flex_none() + .max_w(px(160.0)) + .px_2() + .py_1() + .rounded_full() + .border_1() + .border_color(accent) + .flex() + .flex_row() + .items_center() + .gap_1() + .cursor_pointer() + .hover(move |style| style.bg(palette.wash)) + .on_click(cx.listener(|this, _event, _window, cx| { + this.open_devices(cx) + })) + .child( + svg() + .path("icons/computer.svg") + .size(px(12.0)) + .text_color(accent), + ) + .child( + div() + .text_xs() + .text_color(accent) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(label), + ), + ) + }) + .when_some(visualizer_bands, |el, bands| { + // The engine always fills 32 bands, 0–100; they are averaged down + // to the configured bin count (`:visbins`) and painted as + // bottom-anchored bars. Repaints ride the fast tick. + el.child( + div().flex_none().w(px(120.0)).h(px(32.0)).child( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let bands = bands.lock(); + let chunk = bands.len() as f32 / vis_bins as f32; + let band_width = + bounds.size.width / vis_bins as f32; + for index in 0..vis_bins { + let start = (index as f32 * chunk) as usize; + let end = if index == vis_bins - 1 { + bands.len() + } else { + ((index + 1) as f32 * chunk) as usize + }; + let slice = &bands[start..end.max(start + 1)]; + let value = slice.iter().sum::() + / slice.len() as f32; + let ratio = (value / 100.0).clamp(0.0, 1.0); + let bar_height = bounds.size.height * ratio; + let origin = gpui::point( + bounds.origin.x + band_width * index as f32, + bounds.origin.y + bounds.size.height + - bar_height, + ); + let bar = Bounds { + origin, + size: size(band_width * 0.8, bar_height), + }; + window.paint_quad(gpui::fill(bar, accent)); + } + }, + ) + .size_full(), + ), + ) + }), + ), + ) + .child( + // Bottom row: transport, seek and volume on one line, so the seek bar sits on the + // buttons' baseline no matter what the row above is doing. + div() + .flex() + .flex_row() + .items_center() + .gap_3() + .h(px(PLAYBACK_ROW_HEIGHT)) + .child( + self.transport_controls(controls, cx) + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .child(icon_button( + "lyrics", + "icons/mic.svg", + lyrics_color, + palette.wash, + cx, + |this, cx| this.toggle_lyrics(cx), + )), + ) + .child(self.seek_bar(controls, cx)) + .child( + div() + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .flex() + .flex_row() + .items_center() + .justify_end() + .gap_1() + .child(icon_button( + "queue", + "icons/playlist.svg", + queue_color, + palette.wash, + cx, + |this, cx| this.toggle_right_panel(RightPanel::Queue, cx), + )) + .child(icon_button( + "devices", + "icons/computer.svg", + muted, + palette.wash, + cx, + |this, cx| this.open_devices(cx), + )) + .child(icon_button( + "mute", + mute_icon, + muted, + palette.wash, + cx, + |this, cx| this.toggle_mute(cx), + )) + .child( + div() + .id("volume-bar") + .flex_none() + .w(px(90.0)) + .py_2() + .cursor_pointer() + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener( + |this, event: &gpui::MouseDownEvent, _window, cx| { + this.begin_scrub( + Scrub::Volume, + event.position.x, + cx, + ); + }, + ), + ) + .child( + div() + .relative() + .w_full() + .h(px(6.0)) + .rounded_full() + .bg(palette.border) + .child( + canvas( + move |bounds, _window, _cx| { + volume_bounds.set(bounds) + }, + |_, _, _, _| {}, + ) + .absolute() + .size_full(), + ) + .child( + div() + .h_full() + .rounded_full() + .bg(fg) + .w(gpui::relative(volume_fraction)), + ), + ), + ) + .child( + div() + .flex_none() + .w(px(34.0)) + .text_xs() + .text_color(fg) + .child(volume_label), + ), + ), + ) + } + + /// Shuffle, previous, play/pause, next and repeat in a row, two each side of play so it + /// centers; the caller sizes the row. + pub(crate) fn transport_controls(&self, colors: ControlColors, cx: &mut Context) -> Div { + let playback = &self.state.playback; + let play_icon = if playback.is_playing { + "icons/pause.svg" + } else { + "icons/play.svg" + }; + let shuffle_color = if playback.is_shuffled { + colors.accent + } else { + colors.muted + }; + let (repeat_icon, repeat_color) = match playback.repeat_mode.as_str() { + "Track" => ("icons/repeat-one.svg", colors.accent), + "Context" => ("icons/repeat.svg", colors.accent), + _ => ("icons/repeat.svg", colors.muted), + }; + div() + .flex() + .flex_row() + .items_center() + .gap_1() + .child(icon_button( + "shuffle", + "icons/shuffle.svg", + shuffle_color, + colors.hover, + cx, + |this, cx| this.toggle_shuffle(cx), + )) + .child(icon_button( + "previous", + "icons/previous.svg", + colors.fg, + colors.hover, + cx, + |this, cx| this.play_previous(cx), + )) + .child( + div() + .id("play-pause") + .flex_none() + .w(px(36.0)) + .h(px(36.0)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .hover(move |style| style.bg(colors.hover)) + .on_click(cx.listener(|this, _event, _window, cx| this.toggle_playback(cx))) + .child( + svg() + .path(play_icon) + .w(px(20.0)) + .h(px(20.0)) + .text_color(colors.fg), + ), + ) + .child(icon_button( + "next", + "icons/next.svg", + colors.fg, + colors.hover, + cx, + |this, cx| this.play_next(cx), + )) + .child(icon_button( + "repeat", + repeat_icon, + repeat_color, + colors.hover, + cx, + |this, cx| this.cycle_repeat(cx), + )) + } + + /// Elapsed time, the seek bar and the duration on one line, growing to the caller's width. + /// The canvas overlay records the track's bounds each paint, and a click anywhere in the + /// (taller) hit area seeks to that fraction. + pub(crate) fn seek_bar(&self, colors: ControlColors, cx: &mut Context) -> Div { + let playback = &self.state.playback; + let progress_ms = playback.display_progress_ms(); + let fraction = if playback.duration_ms > 0 { + (progress_ms as f32 / playback.duration_ms as f32).clamp(0.0, 1.0) + } else { + 0.0 + }; + let seek_bounds = self.seek_bounds.clone(); + let label = |ms: u32| { + div() + .flex_none() + .text_color(colors.muted) + .text_xs() + .child(SharedString::from(format_time(ms))) + }; + div() + .flex_grow(1.0) + .flex() + .flex_row() + .items_center() + .gap_2() + .child(label(progress_ms)) + .child( + div() + .id("seek-bar") + .flex_grow(1.0) + .py_2() + .cursor_pointer() + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| { + this.begin_scrub(Scrub::Seek, event.position.x, cx); + }), + ) + .child( + div() + .relative() + .w_full() + .h(px(6.0)) + .rounded_full() + .bg(colors.track) + .child( + canvas( + move |bounds, _window, _cx| seek_bounds.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .size_full(), + ) + .child( + div() + .h_full() + .rounded_full() + .bg(colors.accent) + .w(gpui::relative(fraction)), + ), + ), + ) + .child(label(playback.duration_ms)) + } +} From 09f7ff9c5f26ba7abd79c17924e3fc2e48aca58e Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:25 -0500 Subject: [PATCH 24/44] desktop: move list selection and activation into app/selection.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 5 + crates/echo-desktop/src/app/selection.rs | 522 +++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 522 +---------------------- 3 files changed, 528 insertions(+), 521 deletions(-) create mode 100644 crates/echo-desktop/src/app.rs create mode 100644 crates/echo-desktop/src/app/selection.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs new file mode 100644 index 0000000..bf3b8e3 --- /dev/null +++ b/crates/echo-desktop/src/app.rs @@ -0,0 +1,5 @@ +//! What `EchoApp` does in response to input, one submodule per concern. + +use super::*; + +mod selection; diff --git a/crates/echo-desktop/src/app/selection.rs b/crates/echo-desktop/src/app/selection.rs new file mode 100644 index 0000000..24cc316 --- /dev/null +++ b/crates/echo-desktop/src/app/selection.rs @@ -0,0 +1,522 @@ +use super::*; + +impl EchoApp { + /// Rows in whatever currently has keyboard focus: the device modal when open, else the + /// `active_view` list. + fn list_len(&self) -> usize { + if self.state.ui.playlist_edit.is_some() { + return 0; + } + if self.page_menu.is_some() { + return echo_core::intent::playlist_page_actions(&self.state).len(); + } + if self.state.ui.playlist_add_modal_open { + return echo_core::action_menu::filtered_playlist_add_choices(&self.state).len() + 1; + } + if self.state.ui.device_modal_open { + return self.state.data.devices.len(); + } + if self.theme_modal_open { + return views::theme_rows(&self.state, self.theme_modal_tab).len(); + } + if let Some(menu) = self.track_menu.as_ref() { + // The flyout takes over navigation while it is open, exactly like a nested list. + if menu.submenu.is_some() { + return echo_core::action_menu::filtered_playlist_add_choices(&self.state).len() + + 1; + } + return views::track_menu_items(self).len(); + } + if self.sort_menu_open { + return views::SORT_OPTIONS.len(); + } + match self.state.ui.active_view { + ActiveView::Home => echo_core::home::home_shelves(&self.state) + .iter() + .map(|shelf| shelf.items.len()) + .sum(), + ActiveView::TrackList => self.state.data.tracks.len(), + ActiveView::Queue => self.state.queue_view_len(), + ActiveView::SearchResults => match self.state.ui.active_search_tab { + SearchTab::All => echo_core::search::all_tab_rows( + &self.state.data.search_results, + &self.state.ui.search_context_query, + ) + .len(), + echo_core::app::SearchTab::Tracks => self.state.data.search_results.tracks.len(), + echo_core::app::SearchTab::Albums => self.state.data.search_results.albums.len(), + echo_core::app::SearchTab::Artists => self.state.data.search_results.artists.len(), + echo_core::app::SearchTab::Playlists => { + self.state.data.search_results.playlists.len() + } + }, + ActiveView::ArtistList => self.state.artist_list().len(), + ActiveView::WhatsNew => self.state.data.whats_new.len(), + // Combined index space: Popular rows first, then the album rows and the chip's + // Load more row. + ActiveView::ArtistPage => { + let filter = self.state.ui.artist_discography_filter; + self.state.data.artist_page_data.as_ref().map_or(0, |data| { + data.top_tracks.len() + data.album_row_count(filter) + }) + } + _ => match self.state.ui.active_library_tab { + LibraryTab::Albums => self.state.data.saved_albums.len(), + LibraryTab::Artists => self.state.data.followed_artists.len(), + _ => self.state.data.library_view.len(), + }, + } + } + + /// Switches the discography chip and lands the cursor on the first album row, past the + /// Popular rows the combined index space puts first. + pub(crate) fn set_discography_filter(&mut self, filter: echo_core::models::DiscographyFilter) { + if let Some(event) = echo_core::intent::set_discography_filter(&mut self.state, filter) { + self.dispatch(event); + } + self.state.ui.artist_page_album_index = self.artist_page_top_len(); + self.artist_albums_scroll + .scroll_to_item(0, ScrollStrategy::Top); + } + + /// Rows the artist page's Popular section occupies at the head of its combined index space. + pub(crate) fn artist_page_top_len(&self) -> usize { + self.state + .data + .artist_page_data + .as_ref() + .map_or(0, |data| data.top_tracks.len()) + } + + pub(crate) fn set_selection(&mut self, index: usize, cx: &mut Context) { + if self.state.ui.playlist_edit.is_some() { + return; + } + if let Some((_, selected)) = self.page_menu.as_mut() { + *selected = index; + cx.notify(); + return; + } + // A confirm prompt is modal: moving the list behind it would leave the prompt + // describing a row that is no longer selected. + if echo_core::intent::prompt_active(&self.state) { + return; + } + // An armed `d` belongs to the row it was pressed on; moving off that row disarms it so + // the second `d` can't delete something the user never pointed at. + self.state.ui.pending_d_press = false; + echo_core::intent::clear_picks(&mut self.state); + if self.state.ui.playlist_add_modal_open { + self.state.ui.selected_playlist_modal_index = index; + self.playlist_modal_scroll.scroll_to_item(index); + } else if self.state.ui.device_modal_open { + self.state.ui.selected_device_index = index; + self.device_modal_scroll.scroll_to_item(index); + } else if self.theme_modal_open { + self.theme_modal_index = index; + self.theme_modal_scroll.scroll_to_item(index); + } else if let Some(menu) = self.track_menu.as_mut() { + if menu.submenu.is_some() { + menu.submenu = Some(index); + self.submenu_scroll.scroll_to_item(index); + } else { + menu.selected = index; + self.track_menu_scroll.scroll_to_item(index); + } + } else if self.sort_menu_open { + self.sort_menu_index = index; + } else { + match self.state.ui.active_view { + ActiveView::Home => { + self.state.ui.selected_home_index = index; + let shelves = echo_core::home::home_shelves(&self.state); + let mut start = 0; + for shelf in &shelves { + if index < start + shelf.items.len() { + if let Some(section) = self.home_section_indices.get(&shelf.kind) { + self.home_scroll.scroll_to_item(*section); + } + if let Some(scroll) = self.home_shelf_scrolls.get(&shelf.kind) { + scroll.scroll_to_item(index - start); + } + break; + } + start += shelf.items.len(); + } + } + ActiveView::TrackList => { + self.state.ui.selected_track_index = index; + self.tracks_scroll + .scroll_to_item(index, ScrollStrategy::Nearest); + } + ActiveView::Queue => { + self.state.ui.selected_queue_index = index; + let row = match self.state.ui.queue_tab { + echo_core::app::QueueTab::Queue => { + self.state.queue_row_of(index).unwrap_or(index) + } + echo_core::app::QueueTab::Recent => index, + }; + self.queue_scroll + .scroll_to_item(row, ScrollStrategy::Nearest); + } + ActiveView::SearchResults => { + self.state.ui.selected_search_index = index; + if self.state.ui.active_search_tab == SearchTab::All { + if let Some((section, horizontal)) = self.search_all_positions.get(index) { + self.search_all_scroll.scroll_to_item(*section); + if let Some((tab, row)) = horizontal + && let Some(scroll) = self.search_section_scrolls.get(tab) + { + scroll.scroll_to_item(*row); + } + } + } else { + self.search_scroll + .scroll_to_item(index, ScrollStrategy::Nearest); + } + } + ActiveView::ArtistList => { + self.state.ui.selected_artist_index = index; + self.artist_list_scroll + .scroll_to_item(index, ScrollStrategy::Nearest); + } + ActiveView::WhatsNew => { + self.state.ui.selected_whats_new_index = index; + self.whats_new_scroll + .scroll_to_item(index, ScrollStrategy::Nearest); + } + ActiveView::ArtistPage => { + self.state.ui.artist_page_album_index = index; + // The combined index spans two lists; scroll whichever owns the row. + let top_len = self.artist_page_top_len(); + if index < top_len { + self.artist_top_tracks_scroll + .scroll_to_item(index, ScrollStrategy::Nearest); + } else { + self.artist_albums_scroll + .scroll_to_item(index - top_len, ScrollStrategy::Nearest); + } + } + _ => { + self.state.ui.selected_playlist_index = index; + self.library_scroll + .scroll_to_item(index, ScrollStrategy::Nearest); + } + } + } + cx.notify(); + } + + pub(crate) fn move_selection(&mut self, delta: isize, cx: &mut Context) { + let len = self.list_len(); + if len == 0 { + return; + } + let current = if let Some((_, selected)) = self.page_menu { + selected + } else if self.state.ui.playlist_add_modal_open { + self.state.ui.selected_playlist_modal_index + } else if self.state.ui.device_modal_open { + self.state.ui.selected_device_index + } else if self.theme_modal_open { + self.theme_modal_index + } else if let Some(menu) = self.track_menu.as_ref() { + menu.submenu.unwrap_or(menu.selected) + } else if self.sort_menu_open { + self.sort_menu_index + } else { + match self.state.ui.active_view { + ActiveView::Home => self.state.ui.selected_home_index, + ActiveView::TrackList => self.state.ui.selected_track_index, + ActiveView::Queue => self.state.ui.selected_queue_index, + ActiveView::SearchResults => self.state.ui.selected_search_index, + ActiveView::ArtistList => self.state.ui.selected_artist_index, + ActiveView::ArtistPage => self.state.ui.artist_page_album_index, + ActiveView::WhatsNew => self.state.ui.selected_whats_new_index, + _ => self.state.ui.selected_playlist_index, + } + }; + self.set_selection(current.saturating_add_signed(delta).min(len - 1), cx); + } + + /// `l`: like/unlike the focused track. On library rows it acts as Enter; un-liking stages + /// the confirm prompt. + pub(crate) fn toggle_like(&mut self, cx: &mut Context) { + if self.overlay_open() { + return; + } + if self.state.ui.active_view == ActiveView::Library { + self.activate_selection(cx); + return; + } + if let Some(event) = echo_core::intent::toggle_like_selected(&mut self.state) { + self.dispatch(event); + } + cx.notify(); + } + + /// `shift-j`/`shift-k`: move the selected track within an owned playlist. The intent + /// enforces the writable-context and original-order guards. + pub(crate) fn move_selected_track(&mut self, delta: isize, cx: &mut Context) { + if self.overlay_open() || self.state.ui.active_view != ActiveView::TrackList { + return; + } + let from = self.state.ui.selected_track_index; + let to = from.saturating_add_signed(delta); + if let Some(event) = echo_core::intent::move_track_in_playlist(&mut self.state, from, to) { + self.dispatch(event); + self.tracks_scroll + .scroll_to_item(self.state.ui.selected_track_index, ScrollStrategy::Nearest); + } + cx.notify(); + } + + pub(crate) fn select_last(&mut self, cx: &mut Context) { + let len = self.list_len(); + if len > 0 { + self.set_selection(len - 1, cx); + } + } + + /// Accept an open confirm prompt, mirroring the Confirm button in `views::prompt_modal`. + /// Bound to Enter (through [`Self::activate_selection`]) and to `y`. + pub(crate) fn confirm_prompt(&mut self, cx: &mut Context) { + self.pending_count = None; + if !echo_core::intent::prompt_active(&self.state) { + return; + } + if let Some(event) = echo_core::intent::confirm_prompt(&mut self.state) { + self.dispatch(event); + } + // A prompt staged from a visual range consumes it, so the range goes away with it. + echo_core::intent::exit_visual(&mut self.state); + cx.notify(); + } + + /// Enter on the focused list — the same intents the row click handlers use. + pub(crate) fn activate_selection(&mut self, cx: &mut Context) { + if self.state.ui.playlist_edit.is_some() { + self.save_playlist_edit(cx); + return; + } + if let Some((_, selected)) = self.page_menu { + if let Some(action) = + echo_core::intent::playlist_page_actions(&self.state).get(selected) + { + self.run_page_action(*action, cx); + } + return; + } + // A confirm prompt sits above everything else, exactly as it does in `dismiss`. + if echo_core::intent::prompt_active(&self.state) { + self.confirm_prompt(cx); + return; + } + self.pending_count = None; + let event = if self.state.ui.playlist_add_modal_open { + let index = self.state.ui.selected_playlist_modal_index; + echo_core::action_menu::commit_filtered_playlist_add(&mut self.state, index) + } else if self.state.ui.device_modal_open { + let index = self.state.ui.selected_device_index; + echo_core::intent::transfer_to_device(&mut self.state, index) + } else if self.theme_modal_open { + if let Some(row) = + views::theme_rows(&self.state, self.theme_modal_tab).get(self.theme_modal_index) + { + echo_core::intent::apply_theme(&mut self.state, &row.name); + } + self.theme_modal_open = false; + None + } else if let Some(menu) = self.track_menu.as_ref() { + if let Some(choice) = menu.submenu { + self.commit_playlist_submenu(choice, cx); + } else { + let selected = menu.selected; + // Enter on "Add to playlist" steps into the flyout instead of running an + // action; every other item runs and closes the menu. + if self.track_menu_add_row() == Some(selected) { + self.open_playlist_submenu(true, cx); + } else if let Some((_, item, _)) = + views::track_menu_items(self).into_iter().nth(selected) + { + self.run_track_menu_action(item, cx); + } + } + None + } else if self.sort_menu_open { + if let Some((_, arg)) = views::SORT_OPTIONS.get(self.sort_menu_index) { + self.apply_sort(arg, cx); + } + None + } else { + match self.state.ui.active_view { + ActiveView::Home => { + let item = echo_core::home::home_shelves(&self.state) + .into_iter() + .flat_map(|shelf| shelf.items) + .nth(self.state.ui.selected_home_index); + item.and_then(|item| echo_core::intent::open_home_item(&mut self.state, item)) + } + ActiveView::TrackList => { + let index = self.state.ui.selected_track_index; + echo_core::intent::play_track_at(&mut self.state, index) + } + ActiveView::Queue => { + let index = self.state.ui.selected_queue_index; + echo_core::intent::play_queue_track_at(&mut self.state, index) + } + ActiveView::SearchResults => { + let index = self.state.ui.selected_search_index; + echo_core::intent::activate_search_result(&mut self.state, index) + } + ActiveView::ArtistList => { + let index = self.state.ui.selected_artist_index; + echo_core::intent::open_artist_at(&mut self.state, index) + } + ActiveView::ArtistPage => { + let index = self.state.ui.artist_page_album_index; + echo_core::intent::activate_artist_page_row(&mut self.state, index) + } + ActiveView::WhatsNew => { + let index = self.state.ui.selected_whats_new_index; + echo_core::intent::open_whats_new_album(&mut self.state, index) + } + _ => { + let index = self.state.ui.selected_playlist_index; + match self.state.ui.active_library_tab { + LibraryTab::Albums => echo_core::intent::open_album(&mut self.state, index), + LibraryTab::Artists => { + echo_core::intent::open_followed_artist(&mut self.state, index) + } + _ => echo_core::intent::open_library_entry(&mut self.state, index), + } + } + } + }; + if let Some(event) = event { + self.dispatch(event); + } + cx.notify(); + } + + /// Whether a visual-mode range is being built. + pub(crate) fn in_visual(&self) -> bool { + self.state.ui.mode == AppMode::Visual + } + + /// Whether a range action covers more than the focused row: a visual range or picked rows. + pub(crate) fn multi_selected(&self) -> bool { + echo_core::intent::has_multi_selection(&self.state) + } + + /// Called on every drag move over a list: within [`DRAG_EDGE`] of its top or bottom edge + /// the list scrolls toward that edge, faster the closer the pointer gets, on a frame tick + /// that runs only while a drag is alive and the pointer stays near an edge. + pub(crate) fn drag_autoscroll( + &mut self, + list: DragList, + pointer_y: Pixels, + bounds: Bounds, + cx: &mut Context, + ) { + let top = f32::from(pointer_y - bounds.origin.y); + let bottom = f32::from(bounds.origin.y + bounds.size.height - pointer_y); + let speed = if top < DRAG_EDGE { + -((DRAG_EDGE - top.max(0.0)) / DRAG_EDGE) * DRAG_SCROLL_MAX + } else if bottom < DRAG_EDGE { + ((DRAG_EDGE - bottom.max(0.0)) / DRAG_EDGE) * DRAG_SCROLL_MAX + } else { + self.drag_scroll = None; + return; + }; + self.drag_scroll = Some((list, speed)); + if self.drag_scroll_ticking { + return; + } + self.drag_scroll_ticking = true; + cx.spawn(async move |this, cx| { + loop { + cx.background_executor() + .timer(Duration::from_millis(16)) + .await; + let keep_going = this.update(cx, |app, cx| { + let Some((list, speed)) = app.drag_scroll else { + return false; + }; + if !cx.has_active_drag() { + app.drag_scroll = None; + return false; + } + let handle = match list { + DragList::Tracks => &app.tracks_scroll, + DragList::Library => &app.library_scroll, + }; + let base = handle.0.borrow().base_handle.clone(); + let mut offset = base.offset(); + let lowest = -base.max_offset().y; + offset.y = (offset.y - px(speed)).clamp(lowest.min(px(0.0)), px(0.0)); + base.set_offset(offset); + cx.notify(); + true + }); + if !matches!(keep_going, Ok(true)) { + let _ = this.update(cx, |app, _| app.drag_scroll_ticking = false); + break; + } + } + }) + .detach(); + } + + /// Shift-click on row `ix`: anchor at the row that was focused (unless a range is already + /// open, which keeps its anchor) and extend the selection to `ix`. + pub(crate) fn extend_selection_to(&mut self, ix: usize, cx: &mut Context) { + if !self.in_visual() { + let anchor = match self.state.ui.active_view { + ActiveView::TrackList => self.state.ui.selected_track_index, + ActiveView::Queue => self.state.ui.selected_queue_index, + ActiveView::SearchResults => self.state.ui.selected_search_index, + ActiveView::Library => self.state.ui.selected_playlist_index, + _ => return, + }; + echo_core::intent::set_visual_anchor(&mut self.state, anchor); + } + self.set_selection(ix, cx); + cx.notify(); + } + + /// `v` — start a range selection, or leave one already in progress. + pub(crate) fn toggle_visual(&mut self, cx: &mut Context) { + self.pending_count = None; + if self.in_visual() { + echo_core::intent::exit_visual(&mut self.state); + } else { + echo_core::intent::enter_visual(&mut self.state); + } + cx.notify(); + } + + pub(crate) fn next_match(&mut self, forward: bool, cx: &mut Context) { + echo_core::intent::next_search_match(&mut self.state, forward); + self.scroll_to_selected_track(); + cx.notify(); + } + + pub(crate) fn scroll_to_selected_track(&mut self) { + self.tracks_scroll + .scroll_to_item(self.state.ui.selected_track_index, ScrollStrategy::Nearest); + } + + /// `g c`: select whatever is playing, loading its context first when needed. + pub(crate) fn jump_to_current(&mut self, cx: &mut Context) { + if let Some(event) = echo_core::intent::jump_to_current_context(&mut self.state) { + self.dispatch(event); + } + if self.state.ui.active_view == ActiveView::TrackList { + self.tracks_scroll + .scroll_to_item(self.state.ui.selected_track_index, ScrollStrategy::Center); + } + cx.notify(); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index f1001d6..acf7d42 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -10,6 +10,7 @@ #![windows_subsystem = "windows"] +mod app; mod assets; mod backdrop; mod dock_icon; @@ -680,405 +681,6 @@ impl EchoApp { self.state.save_library_config(); } - /// Rows in whatever currently has keyboard focus: the device modal when open, else the - /// `active_view` list. - fn list_len(&self) -> usize { - if self.state.ui.playlist_edit.is_some() { - return 0; - } - if self.page_menu.is_some() { - return echo_core::intent::playlist_page_actions(&self.state).len(); - } - if self.state.ui.playlist_add_modal_open { - return echo_core::action_menu::filtered_playlist_add_choices(&self.state).len() + 1; - } - if self.state.ui.device_modal_open { - return self.state.data.devices.len(); - } - if self.theme_modal_open { - return views::theme_rows(&self.state, self.theme_modal_tab).len(); - } - if let Some(menu) = self.track_menu.as_ref() { - // The flyout takes over navigation while it is open, exactly like a nested list. - if menu.submenu.is_some() { - return echo_core::action_menu::filtered_playlist_add_choices(&self.state).len() - + 1; - } - return views::track_menu_items(self).len(); - } - if self.sort_menu_open { - return views::SORT_OPTIONS.len(); - } - match self.state.ui.active_view { - ActiveView::Home => echo_core::home::home_shelves(&self.state) - .iter() - .map(|shelf| shelf.items.len()) - .sum(), - ActiveView::TrackList => self.state.data.tracks.len(), - ActiveView::Queue => self.state.queue_view_len(), - ActiveView::SearchResults => match self.state.ui.active_search_tab { - SearchTab::All => echo_core::search::all_tab_rows( - &self.state.data.search_results, - &self.state.ui.search_context_query, - ) - .len(), - echo_core::app::SearchTab::Tracks => self.state.data.search_results.tracks.len(), - echo_core::app::SearchTab::Albums => self.state.data.search_results.albums.len(), - echo_core::app::SearchTab::Artists => self.state.data.search_results.artists.len(), - echo_core::app::SearchTab::Playlists => { - self.state.data.search_results.playlists.len() - } - }, - ActiveView::ArtistList => self.state.artist_list().len(), - ActiveView::WhatsNew => self.state.data.whats_new.len(), - // Combined index space: Popular rows first, then the album rows and the chip's - // Load more row. - ActiveView::ArtistPage => { - let filter = self.state.ui.artist_discography_filter; - self.state.data.artist_page_data.as_ref().map_or(0, |data| { - data.top_tracks.len() + data.album_row_count(filter) - }) - } - _ => match self.state.ui.active_library_tab { - LibraryTab::Albums => self.state.data.saved_albums.len(), - LibraryTab::Artists => self.state.data.followed_artists.len(), - _ => self.state.data.library_view.len(), - }, - } - } - - /// Switches the discography chip and lands the cursor on the first album row, past the - /// Popular rows the combined index space puts first. - pub(crate) fn set_discography_filter(&mut self, filter: echo_core::models::DiscographyFilter) { - if let Some(event) = echo_core::intent::set_discography_filter(&mut self.state, filter) { - self.dispatch(event); - } - self.state.ui.artist_page_album_index = self.artist_page_top_len(); - self.artist_albums_scroll - .scroll_to_item(0, ScrollStrategy::Top); - } - - /// Rows the artist page's Popular section occupies at the head of its combined index space. - pub(crate) fn artist_page_top_len(&self) -> usize { - self.state - .data - .artist_page_data - .as_ref() - .map_or(0, |data| data.top_tracks.len()) - } - - fn set_selection(&mut self, index: usize, cx: &mut Context) { - if self.state.ui.playlist_edit.is_some() { - return; - } - if let Some((_, selected)) = self.page_menu.as_mut() { - *selected = index; - cx.notify(); - return; - } - // A confirm prompt is modal: moving the list behind it would leave the prompt - // describing a row that is no longer selected. - if echo_core::intent::prompt_active(&self.state) { - return; - } - // An armed `d` belongs to the row it was pressed on; moving off that row disarms it so - // the second `d` can't delete something the user never pointed at. - self.state.ui.pending_d_press = false; - echo_core::intent::clear_picks(&mut self.state); - if self.state.ui.playlist_add_modal_open { - self.state.ui.selected_playlist_modal_index = index; - self.playlist_modal_scroll.scroll_to_item(index); - } else if self.state.ui.device_modal_open { - self.state.ui.selected_device_index = index; - self.device_modal_scroll.scroll_to_item(index); - } else if self.theme_modal_open { - self.theme_modal_index = index; - self.theme_modal_scroll.scroll_to_item(index); - } else if let Some(menu) = self.track_menu.as_mut() { - if menu.submenu.is_some() { - menu.submenu = Some(index); - self.submenu_scroll.scroll_to_item(index); - } else { - menu.selected = index; - self.track_menu_scroll.scroll_to_item(index); - } - } else if self.sort_menu_open { - self.sort_menu_index = index; - } else { - match self.state.ui.active_view { - ActiveView::Home => { - self.state.ui.selected_home_index = index; - let shelves = echo_core::home::home_shelves(&self.state); - let mut start = 0; - for shelf in &shelves { - if index < start + shelf.items.len() { - if let Some(section) = self.home_section_indices.get(&shelf.kind) { - self.home_scroll.scroll_to_item(*section); - } - if let Some(scroll) = self.home_shelf_scrolls.get(&shelf.kind) { - scroll.scroll_to_item(index - start); - } - break; - } - start += shelf.items.len(); - } - } - ActiveView::TrackList => { - self.state.ui.selected_track_index = index; - self.tracks_scroll - .scroll_to_item(index, ScrollStrategy::Nearest); - } - ActiveView::Queue => { - self.state.ui.selected_queue_index = index; - let row = match self.state.ui.queue_tab { - echo_core::app::QueueTab::Queue => { - self.state.queue_row_of(index).unwrap_or(index) - } - echo_core::app::QueueTab::Recent => index, - }; - self.queue_scroll - .scroll_to_item(row, ScrollStrategy::Nearest); - } - ActiveView::SearchResults => { - self.state.ui.selected_search_index = index; - if self.state.ui.active_search_tab == SearchTab::All { - if let Some((section, horizontal)) = self.search_all_positions.get(index) { - self.search_all_scroll.scroll_to_item(*section); - if let Some((tab, row)) = horizontal - && let Some(scroll) = self.search_section_scrolls.get(tab) - { - scroll.scroll_to_item(*row); - } - } - } else { - self.search_scroll - .scroll_to_item(index, ScrollStrategy::Nearest); - } - } - ActiveView::ArtistList => { - self.state.ui.selected_artist_index = index; - self.artist_list_scroll - .scroll_to_item(index, ScrollStrategy::Nearest); - } - ActiveView::WhatsNew => { - self.state.ui.selected_whats_new_index = index; - self.whats_new_scroll - .scroll_to_item(index, ScrollStrategy::Nearest); - } - ActiveView::ArtistPage => { - self.state.ui.artist_page_album_index = index; - // The combined index spans two lists; scroll whichever owns the row. - let top_len = self.artist_page_top_len(); - if index < top_len { - self.artist_top_tracks_scroll - .scroll_to_item(index, ScrollStrategy::Nearest); - } else { - self.artist_albums_scroll - .scroll_to_item(index - top_len, ScrollStrategy::Nearest); - } - } - _ => { - self.state.ui.selected_playlist_index = index; - self.library_scroll - .scroll_to_item(index, ScrollStrategy::Nearest); - } - } - } - cx.notify(); - } - - fn move_selection(&mut self, delta: isize, cx: &mut Context) { - let len = self.list_len(); - if len == 0 { - return; - } - let current = if let Some((_, selected)) = self.page_menu { - selected - } else if self.state.ui.playlist_add_modal_open { - self.state.ui.selected_playlist_modal_index - } else if self.state.ui.device_modal_open { - self.state.ui.selected_device_index - } else if self.theme_modal_open { - self.theme_modal_index - } else if let Some(menu) = self.track_menu.as_ref() { - menu.submenu.unwrap_or(menu.selected) - } else if self.sort_menu_open { - self.sort_menu_index - } else { - match self.state.ui.active_view { - ActiveView::Home => self.state.ui.selected_home_index, - ActiveView::TrackList => self.state.ui.selected_track_index, - ActiveView::Queue => self.state.ui.selected_queue_index, - ActiveView::SearchResults => self.state.ui.selected_search_index, - ActiveView::ArtistList => self.state.ui.selected_artist_index, - ActiveView::ArtistPage => self.state.ui.artist_page_album_index, - ActiveView::WhatsNew => self.state.ui.selected_whats_new_index, - _ => self.state.ui.selected_playlist_index, - } - }; - self.set_selection(current.saturating_add_signed(delta).min(len - 1), cx); - } - - /// `l`: like/unlike the focused track. On library rows it acts as Enter; un-liking stages - /// the confirm prompt. - fn toggle_like(&mut self, cx: &mut Context) { - if self.overlay_open() { - return; - } - if self.state.ui.active_view == ActiveView::Library { - self.activate_selection(cx); - return; - } - if let Some(event) = echo_core::intent::toggle_like_selected(&mut self.state) { - self.dispatch(event); - } - cx.notify(); - } - - /// `shift-j`/`shift-k`: move the selected track within an owned playlist. The intent - /// enforces the writable-context and original-order guards. - fn move_selected_track(&mut self, delta: isize, cx: &mut Context) { - if self.overlay_open() || self.state.ui.active_view != ActiveView::TrackList { - return; - } - let from = self.state.ui.selected_track_index; - let to = from.saturating_add_signed(delta); - if let Some(event) = echo_core::intent::move_track_in_playlist(&mut self.state, from, to) { - self.dispatch(event); - self.tracks_scroll - .scroll_to_item(self.state.ui.selected_track_index, ScrollStrategy::Nearest); - } - cx.notify(); - } - - fn select_last(&mut self, cx: &mut Context) { - let len = self.list_len(); - if len > 0 { - self.set_selection(len - 1, cx); - } - } - - /// Accept an open confirm prompt, mirroring the Confirm button in `views::prompt_modal`. - /// Bound to Enter (through [`Self::activate_selection`]) and to `y`. - fn confirm_prompt(&mut self, cx: &mut Context) { - self.pending_count = None; - if !echo_core::intent::prompt_active(&self.state) { - return; - } - if let Some(event) = echo_core::intent::confirm_prompt(&mut self.state) { - self.dispatch(event); - } - // A prompt staged from a visual range consumes it, so the range goes away with it. - echo_core::intent::exit_visual(&mut self.state); - cx.notify(); - } - - /// Enter on the focused list — the same intents the row click handlers use. - fn activate_selection(&mut self, cx: &mut Context) { - if self.state.ui.playlist_edit.is_some() { - self.save_playlist_edit(cx); - return; - } - if let Some((_, selected)) = self.page_menu { - if let Some(action) = - echo_core::intent::playlist_page_actions(&self.state).get(selected) - { - self.run_page_action(*action, cx); - } - return; - } - // A confirm prompt sits above everything else, exactly as it does in `dismiss`. - if echo_core::intent::prompt_active(&self.state) { - self.confirm_prompt(cx); - return; - } - self.pending_count = None; - let event = if self.state.ui.playlist_add_modal_open { - let index = self.state.ui.selected_playlist_modal_index; - echo_core::action_menu::commit_filtered_playlist_add(&mut self.state, index) - } else if self.state.ui.device_modal_open { - let index = self.state.ui.selected_device_index; - echo_core::intent::transfer_to_device(&mut self.state, index) - } else if self.theme_modal_open { - if let Some(row) = - views::theme_rows(&self.state, self.theme_modal_tab).get(self.theme_modal_index) - { - echo_core::intent::apply_theme(&mut self.state, &row.name); - } - self.theme_modal_open = false; - None - } else if let Some(menu) = self.track_menu.as_ref() { - if let Some(choice) = menu.submenu { - self.commit_playlist_submenu(choice, cx); - } else { - let selected = menu.selected; - // Enter on "Add to playlist" steps into the flyout instead of running an - // action; every other item runs and closes the menu. - if self.track_menu_add_row() == Some(selected) { - self.open_playlist_submenu(true, cx); - } else if let Some((_, item, _)) = - views::track_menu_items(self).into_iter().nth(selected) - { - self.run_track_menu_action(item, cx); - } - } - None - } else if self.sort_menu_open { - if let Some((_, arg)) = views::SORT_OPTIONS.get(self.sort_menu_index) { - self.apply_sort(arg, cx); - } - None - } else { - match self.state.ui.active_view { - ActiveView::Home => { - let item = echo_core::home::home_shelves(&self.state) - .into_iter() - .flat_map(|shelf| shelf.items) - .nth(self.state.ui.selected_home_index); - item.and_then(|item| echo_core::intent::open_home_item(&mut self.state, item)) - } - ActiveView::TrackList => { - let index = self.state.ui.selected_track_index; - echo_core::intent::play_track_at(&mut self.state, index) - } - ActiveView::Queue => { - let index = self.state.ui.selected_queue_index; - echo_core::intent::play_queue_track_at(&mut self.state, index) - } - ActiveView::SearchResults => { - let index = self.state.ui.selected_search_index; - echo_core::intent::activate_search_result(&mut self.state, index) - } - ActiveView::ArtistList => { - let index = self.state.ui.selected_artist_index; - echo_core::intent::open_artist_at(&mut self.state, index) - } - ActiveView::ArtistPage => { - let index = self.state.ui.artist_page_album_index; - echo_core::intent::activate_artist_page_row(&mut self.state, index) - } - ActiveView::WhatsNew => { - let index = self.state.ui.selected_whats_new_index; - echo_core::intent::open_whats_new_album(&mut self.state, index) - } - _ => { - let index = self.state.ui.selected_playlist_index; - match self.state.ui.active_library_tab { - LibraryTab::Albums => echo_core::intent::open_album(&mut self.state, index), - LibraryTab::Artists => { - echo_core::intent::open_followed_artist(&mut self.state, index) - } - _ => echo_core::intent::open_library_entry(&mut self.state, index), - } - } - } - }; - if let Some(event) = event { - self.dispatch(event); - } - cx.notify(); - } - /// Opening the queue leaves the immersive view, which has nowhere to show it. /// `shift-Q`: the full-page, keyboard-navigable queue view. pub(crate) fn toggle_queue_view(&mut self, cx: &mut Context) { @@ -1650,16 +1252,6 @@ impl EchoApp { cx.notify(); } - /// Whether a visual-mode range is being built. - pub(crate) fn in_visual(&self) -> bool { - self.state.ui.mode == AppMode::Visual - } - - /// Whether a range action covers more than the focused row: a visual range or picked rows. - pub(crate) fn multi_selected(&self) -> bool { - echo_core::intent::has_multi_selection(&self.state) - } - /// Redraws only what shows the playback position or the volume: the playback bar, the /// lyrics panel, and the immersive view, which is drawn by the app itself. fn notify_playback_position(&mut self, cx: &mut Context) { @@ -1703,93 +1295,6 @@ impl EchoApp { (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() } - /// Called on every drag move over a list: within [`DRAG_EDGE`] of its top or bottom edge - /// the list scrolls toward that edge, faster the closer the pointer gets, on a frame tick - /// that runs only while a drag is alive and the pointer stays near an edge. - pub(crate) fn drag_autoscroll( - &mut self, - list: DragList, - pointer_y: Pixels, - bounds: Bounds, - cx: &mut Context, - ) { - let top = f32::from(pointer_y - bounds.origin.y); - let bottom = f32::from(bounds.origin.y + bounds.size.height - pointer_y); - let speed = if top < DRAG_EDGE { - -((DRAG_EDGE - top.max(0.0)) / DRAG_EDGE) * DRAG_SCROLL_MAX - } else if bottom < DRAG_EDGE { - ((DRAG_EDGE - bottom.max(0.0)) / DRAG_EDGE) * DRAG_SCROLL_MAX - } else { - self.drag_scroll = None; - return; - }; - self.drag_scroll = Some((list, speed)); - if self.drag_scroll_ticking { - return; - } - self.drag_scroll_ticking = true; - cx.spawn(async move |this, cx| { - loop { - cx.background_executor() - .timer(Duration::from_millis(16)) - .await; - let keep_going = this.update(cx, |app, cx| { - let Some((list, speed)) = app.drag_scroll else { - return false; - }; - if !cx.has_active_drag() { - app.drag_scroll = None; - return false; - } - let handle = match list { - DragList::Tracks => &app.tracks_scroll, - DragList::Library => &app.library_scroll, - }; - let base = handle.0.borrow().base_handle.clone(); - let mut offset = base.offset(); - let lowest = -base.max_offset().y; - offset.y = (offset.y - px(speed)).clamp(lowest.min(px(0.0)), px(0.0)); - base.set_offset(offset); - cx.notify(); - true - }); - if !matches!(keep_going, Ok(true)) { - let _ = this.update(cx, |app, _| app.drag_scroll_ticking = false); - break; - } - } - }) - .detach(); - } - - /// Shift-click on row `ix`: anchor at the row that was focused (unless a range is already - /// open, which keeps its anchor) and extend the selection to `ix`. - pub(crate) fn extend_selection_to(&mut self, ix: usize, cx: &mut Context) { - if !self.in_visual() { - let anchor = match self.state.ui.active_view { - ActiveView::TrackList => self.state.ui.selected_track_index, - ActiveView::Queue => self.state.ui.selected_queue_index, - ActiveView::SearchResults => self.state.ui.selected_search_index, - ActiveView::Library => self.state.ui.selected_playlist_index, - _ => return, - }; - echo_core::intent::set_visual_anchor(&mut self.state, anchor); - } - self.set_selection(ix, cx); - cx.notify(); - } - - /// `v` — start a range selection, or leave one already in progress. - fn toggle_visual(&mut self, cx: &mut Context) { - self.pending_count = None; - if self.in_visual() { - echo_core::intent::exit_visual(&mut self.state); - } else { - echo_core::intent::enter_visual(&mut self.state); - } - cx.notify(); - } - /// `a` — add the selection to a playlist, or save the album when an album row is focused. /// The picker commits through `action_menu::commit_playlist_add`, which resolves the /// tracks from the current selection. @@ -2348,29 +1853,6 @@ impl EchoApp { cx.notify(); } - fn next_match(&mut self, forward: bool, cx: &mut Context) { - echo_core::intent::next_search_match(&mut self.state, forward); - self.scroll_to_selected_track(); - cx.notify(); - } - - fn scroll_to_selected_track(&mut self) { - self.tracks_scroll - .scroll_to_item(self.state.ui.selected_track_index, ScrollStrategy::Nearest); - } - - /// `g c`: select whatever is playing, loading its context first when needed. - fn jump_to_current(&mut self, cx: &mut Context) { - if let Some(event) = echo_core::intent::jump_to_current_context(&mut self.state) { - self.dispatch(event); - } - if self.state.ui.active_view == ActiveView::TrackList { - self.tracks_scroll - .scroll_to_item(self.state.ui.selected_track_index, ScrollStrategy::Center); - } - cx.notify(); - } - fn add_to_queue(&mut self, cx: &mut Context) { // In visual mode `q` queues the whole range. if self.multi_selected() { @@ -2994,8 +2476,6 @@ pub(crate) fn sort_arg(sort: echo_core::app::TrackSort) -> &'static str { } } -impl EchoApp {} - impl Render for EchoApp { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { // Every theme change re-renders the app, so this is the one place that catches them From b86bd7595e84caed6927a86c11f0c0864268b9e5 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:26 -0500 Subject: [PATCH 25/44] desktop: move panel toggles, overlays and pane resizing into app/panels.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/panels.rs | 253 ++++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 240 ------------------------ 3 files changed, 254 insertions(+), 240 deletions(-) create mode 100644 crates/echo-desktop/src/app/panels.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index bf3b8e3..0184f7c 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -2,4 +2,5 @@ use super::*; +mod panels; mod selection; diff --git a/crates/echo-desktop/src/app/panels.rs b/crates/echo-desktop/src/app/panels.rs new file mode 100644 index 0000000..f2e0205 --- /dev/null +++ b/crates/echo-desktop/src/app/panels.rs @@ -0,0 +1,253 @@ +use super::*; + +impl EchoApp { + /// Opening the queue leaves the immersive view, which has nowhere to show it. + /// `shift-Q`: the full-page, keyboard-navigable queue view. + pub(crate) fn toggle_queue_view(&mut self, cx: &mut Context) { + if self.state.ui.active_view == ActiveView::Queue { + // `q` from the queue view returns to the library. + self.state.ui.active_view = ActiveView::Library; + } else { + let event = echo_core::intent::open_queue(&mut self.state); + self.dispatch(event); + self.immersive = false; + } + cx.notify(); + } + + /// Opens, closes or swaps the docked panel. Opening the queue fetches it once; the core's + /// `queue_visible` keeps it fresh from there. + pub(crate) fn set_right_panel(&mut self, panel: Option, cx: &mut Context) { + if self.panel_resizing.is_some_and(|resize| resize.right) { + self.finish_panel_resize(cx); + } + self.right_panel = panel; + self.state.ui.library_config.right_panel = panel; + self.state.save_library_config(); + let queue_open = panel == Some(RightPanel::Queue); + if queue_open && !self.state.ui.queue_panel_open { + self.dispatch(AppEvent::FetchQueue); + } + self.state.ui.queue_panel_open = queue_open; + cx.notify(); + } + + pub(crate) fn toggle_right_panel(&mut self, panel: RightPanel, cx: &mut Context) { + let next = (self.right_panel != Some(panel)).then_some(panel); + self.set_right_panel(next, cx); + } + + pub(crate) fn open_devices(&mut self, cx: &mut Context) { + let event = echo_core::intent::open_device_picker(&mut self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn toggle_lyrics(&mut self, cx: &mut Context) { + self.toggle_right_panel(RightPanel::Lyrics, cx); + } + + pub(crate) fn toggle_immersive(&mut self, cx: &mut Context) { + self.immersive = !self.immersive; + cx.notify(); + } + + /// Escape / `h` / backspace: close whatever is topmost, else go back, checking modals first. + pub(crate) fn dismiss(&mut self, cx: &mut Context) { + if self.state.ui.playlist_edit.is_some() { + echo_core::intent::cancel_playlist_edit(&mut self.state); + cx.notify(); + return; + } + if self.page_menu.take().is_some() { + cx.notify(); + return; + } + self.pending_count = None; + self.state.ui.pending_d_press = false; + if echo_core::intent::prompt_active(&self.state) { + echo_core::intent::cancel_prompt(&mut self.state); + } else if self.multi_selected() { + // Escape drops the range before it starts walking the view history. + echo_core::intent::exit_visual(&mut self.state); + } else if self.context_menu.is_some() { + self.context_menu = None; + } else if self + .track_menu + .as_ref() + .is_some_and(|menu| menu.submenu.is_some()) + { + // The flyout is the topmost layer: escape steps back to the menu items. + self.close_playlist_submenu(cx); + } else if self.track_menu.is_some() { + self.track_menu = None; + self.state.ui.playlist_add_filter.clear(); + } else if self.state.ui.playlist_add_modal_open { + echo_core::action_menu::cancel_playlist_add(&mut self.state); + } else if self.state.ui.device_modal_open { + self.state.ui.device_modal_open = false; + } else if self.theme_modal_open { + self.theme_modal_open = false; + } else if self.sort_menu_open { + self.sort_menu_open = false; + } else if self.settings_open { + // An open dropdown is the topmost layer of the sheet. + if self.settings_dropdown.take().is_none() { + self.settings_open = false; + } + } else if self.help_open { + self.help_open = false; + } else if self.immersive { + self.immersive = false; + } else if self.history_back(cx) { + } else if self.state.ui.active_view == ActiveView::TrackList { + self.state.ui.active_view = if self.search_has_results() { + ActiveView::SearchResults + } else { + ActiveView::Library + }; + } else if self.state.ui.active_view == ActiveView::ArtistPage { + if self.search_has_results() { + self.state.ui.active_view = ActiveView::SearchResults; + self.state.clear_pending_artist_page(); + self.dispatch(AppEvent::CancelArtistPageLoad); + } else { + self.close_artist_page(cx); + } + } else if self.state.ui.active_view == ActiveView::SearchResults { + // Leaving search results drops them entirely. + self.state.ui.active_view = ActiveView::Library; + self.state.data.search_results = Default::default(); + self.state.ui.search_context_query.clear(); + self.state.ui.status_message = None; + if self.state.data.tracklist_image_url.is_some() { + self.dispatch(AppEvent::ReloadHeaderImage); + } + } else if self.state.ui.active_view == ActiveView::Queue { + self.state.ui.active_view = ActiveView::Library; + if self.state.data.tracklist_image_url.is_some() { + self.dispatch(AppEvent::ReloadHeaderImage); + } + } + cx.notify(); + } + + fn search_has_results(&self) -> bool { + !self.state.data.search_results.tracks.is_empty() + || !self.state.data.search_results.albums.is_empty() + || !self.state.data.search_results.artists.is_empty() + } + + pub(crate) fn overlay_open(&self) -> bool { + if self.state.ui.playlist_edit.is_some() || self.page_menu.is_some() { + return true; + } + echo_core::intent::prompt_active(&self.state) + || self.context_menu.is_some() + || self.track_menu.is_some() + || self.state.ui.playlist_add_modal_open + || self.state.ui.device_modal_open + || self.theme_modal_open + || self.sort_menu_open + || self.settings_open + || self.help_open + } + + pub(crate) fn toggle_inline_lyrics(&mut self, cx: &mut Context) { + echo_core::intent::toggle_condensed_lyrics(&mut self.state); + cx.notify(); + } + + fn width_beside_library(&self, window: &Window) -> f32 { + (views::client_content_width(window) + - if self.sidebar_collapsed { + 0.0 + } else { + self.sidebar_width + }) + .max(0.0) + } + + pub(crate) fn effective_right_panel_width(&self, window: &Window) -> f32 { + views::panel_layout::fitted_width(self.right_panel_width, self.width_beside_library(window)) + } + + pub(crate) fn main_content_width(&self, window: &Window) -> f32 { + (self.width_beside_library(window) + - if self.right_panel.is_some() { + self.effective_right_panel_width(window) + } else { + 0.0 + }) + .max(0.0) + } + + pub(crate) fn begin_sidebar_resize(&mut self, x: Pixels, cx: &mut Context) { + self.panel_resizing = Some(PanelResize { + start_x: x, + start_width: self.sidebar_width, + right: false, + }); + cx.notify(); + } + + pub(crate) fn begin_right_panel_resize( + &mut self, + x: Pixels, + window: &Window, + cx: &mut Context, + ) { + self.panel_resizing = Some(PanelResize { + start_x: x, + start_width: self.effective_right_panel_width(window), + right: true, + }); + cx.notify(); + } + + pub(crate) fn update_panel_resize( + &mut self, + x: Pixels, + window: &Window, + cx: &mut Context, + ) { + let Some(resize) = self.panel_resizing else { + return; + }; + let delta = x - resize.start_x; + if resize.right { + self.right_panel_width = views::panel_layout::fitted_width( + resize.start_width - f32::from(delta), + self.width_beside_library(window), + ); + } else { + self.sidebar_width = (resize.start_width + f32::from(delta)).clamp(180.0, 480.0); + } + cx.notify(); + } + + pub(crate) fn finish_panel_resize(&mut self, cx: &mut Context) { + if let Some(resize) = self.panel_resizing.take() { + // Saved on release rather than on every pointer move — a drag is one decision, not + // a few hundred config writes. + if resize.right { + self.state.ui.library_config.right_panel_width = Some(self.right_panel_width); + } else { + self.state.ui.library_config.sidebar_width = Some(self.sidebar_width); + } + self.state.save_library_config(); + cx.notify(); + } + } + + pub(crate) fn set_sidebar_collapsed(&mut self, collapsed: bool, cx: &mut Context) { + self.sidebar_collapsed = collapsed; + self.state.ui.library_config.sidebar_collapsed = Some(collapsed); + self.state.save_library_config(); + cx.notify(); + } + + pub(crate) fn toggle_sidebar(&mut self, cx: &mut Context) { + self.set_sidebar_collapsed(!self.sidebar_collapsed, cx); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index acf7d42..045dae3 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -681,57 +681,6 @@ impl EchoApp { self.state.save_library_config(); } - /// Opening the queue leaves the immersive view, which has nowhere to show it. - /// `shift-Q`: the full-page, keyboard-navigable queue view. - pub(crate) fn toggle_queue_view(&mut self, cx: &mut Context) { - if self.state.ui.active_view == ActiveView::Queue { - // `q` from the queue view returns to the library. - self.state.ui.active_view = ActiveView::Library; - } else { - let event = echo_core::intent::open_queue(&mut self.state); - self.dispatch(event); - self.immersive = false; - } - cx.notify(); - } - - /// Opens, closes or swaps the docked panel. Opening the queue fetches it once; the core's - /// `queue_visible` keeps it fresh from there. - pub(crate) fn set_right_panel(&mut self, panel: Option, cx: &mut Context) { - if self.panel_resizing.is_some_and(|resize| resize.right) { - self.finish_panel_resize(cx); - } - self.right_panel = panel; - self.state.ui.library_config.right_panel = panel; - self.state.save_library_config(); - let queue_open = panel == Some(RightPanel::Queue); - if queue_open && !self.state.ui.queue_panel_open { - self.dispatch(AppEvent::FetchQueue); - } - self.state.ui.queue_panel_open = queue_open; - cx.notify(); - } - - pub(crate) fn toggle_right_panel(&mut self, panel: RightPanel, cx: &mut Context) { - let next = (self.right_panel != Some(panel)).then_some(panel); - self.set_right_panel(next, cx); - } - - fn open_devices(&mut self, cx: &mut Context) { - let event = echo_core::intent::open_device_picker(&mut self.state); - self.dispatch(event); - cx.notify(); - } - - fn toggle_lyrics(&mut self, cx: &mut Context) { - self.toggle_right_panel(RightPanel::Lyrics, cx); - } - - pub(crate) fn toggle_immersive(&mut self, cx: &mut Context) { - self.immersive = !self.immersive; - cx.notify(); - } - fn toggle_themes(&mut self, cx: &mut Context) { self.theme_modal_open = !self.theme_modal_open; if self.theme_modal_open { @@ -808,92 +757,6 @@ impl EchoApp { self.set_theme_mode(next, cx); } - /// Escape / `h` / backspace: close whatever is topmost, else go back, checking modals first. - fn dismiss(&mut self, cx: &mut Context) { - if self.state.ui.playlist_edit.is_some() { - echo_core::intent::cancel_playlist_edit(&mut self.state); - cx.notify(); - return; - } - if self.page_menu.take().is_some() { - cx.notify(); - return; - } - self.pending_count = None; - self.state.ui.pending_d_press = false; - if echo_core::intent::prompt_active(&self.state) { - echo_core::intent::cancel_prompt(&mut self.state); - } else if self.multi_selected() { - // Escape drops the range before it starts walking the view history. - echo_core::intent::exit_visual(&mut self.state); - } else if self.context_menu.is_some() { - self.context_menu = None; - } else if self - .track_menu - .as_ref() - .is_some_and(|menu| menu.submenu.is_some()) - { - // The flyout is the topmost layer: escape steps back to the menu items. - self.close_playlist_submenu(cx); - } else if self.track_menu.is_some() { - self.track_menu = None; - self.state.ui.playlist_add_filter.clear(); - } else if self.state.ui.playlist_add_modal_open { - echo_core::action_menu::cancel_playlist_add(&mut self.state); - } else if self.state.ui.device_modal_open { - self.state.ui.device_modal_open = false; - } else if self.theme_modal_open { - self.theme_modal_open = false; - } else if self.sort_menu_open { - self.sort_menu_open = false; - } else if self.settings_open { - // An open dropdown is the topmost layer of the sheet. - if self.settings_dropdown.take().is_none() { - self.settings_open = false; - } - } else if self.help_open { - self.help_open = false; - } else if self.immersive { - self.immersive = false; - } else if self.history_back(cx) { - } else if self.state.ui.active_view == ActiveView::TrackList { - self.state.ui.active_view = if self.search_has_results() { - ActiveView::SearchResults - } else { - ActiveView::Library - }; - } else if self.state.ui.active_view == ActiveView::ArtistPage { - if self.search_has_results() { - self.state.ui.active_view = ActiveView::SearchResults; - self.state.clear_pending_artist_page(); - self.dispatch(AppEvent::CancelArtistPageLoad); - } else { - self.close_artist_page(cx); - } - } else if self.state.ui.active_view == ActiveView::SearchResults { - // Leaving search results drops them entirely. - self.state.ui.active_view = ActiveView::Library; - self.state.data.search_results = Default::default(); - self.state.ui.search_context_query.clear(); - self.state.ui.status_message = None; - if self.state.data.tracklist_image_url.is_some() { - self.dispatch(AppEvent::ReloadHeaderImage); - } - } else if self.state.ui.active_view == ActiveView::Queue { - self.state.ui.active_view = ActiveView::Library; - if self.state.data.tracklist_image_url.is_some() { - self.dispatch(AppEvent::ReloadHeaderImage); - } - } - cx.notify(); - } - - fn search_has_results(&self) -> bool { - !self.state.data.search_results.tracks.is_empty() - || !self.state.data.search_results.albums.is_empty() - || !self.state.data.search_results.artists.is_empty() - } - /// Runs a context-menu item against sidebar row `index`, then closes the menu. Destructive /// items only stage a `*_prompt` — the confirm modal fires the actual event. pub(crate) fn run_menu_action( @@ -1683,21 +1546,6 @@ impl EchoApp { self.pending_count.take().unwrap_or(1).max(1) as isize } - fn overlay_open(&self) -> bool { - if self.state.ui.playlist_edit.is_some() || self.page_menu.is_some() { - return true; - } - echo_core::intent::prompt_active(&self.state) - || self.context_menu.is_some() - || self.track_menu.is_some() - || self.state.ui.playlist_add_modal_open - || self.state.ui.device_modal_open - || self.theme_modal_open - || self.sort_menu_open - || self.settings_open - || self.help_open - } - /// Backspace: close the topmost overlay if one is open, else hand keyboard focus back to the /// library sidebar while keeping the current page visible, without walking the view history /// the way `h`/escape do. @@ -1954,11 +1802,6 @@ impl EchoApp { cx.notify(); } - fn toggle_inline_lyrics(&mut self, cx: &mut Context) { - echo_core::intent::toggle_condensed_lyrics(&mut self.state); - cx.notify(); - } - /// The `:`/`/` bar. Rendered only while one of the two modes is active; carries the /// search key context so plain letters type instead of triggering list bindings. fn render_command_bar(&mut self, cx: &mut Context) -> impl IntoElement { @@ -2307,92 +2150,9 @@ impl EchoApp { scroll.set_offset(gpui::point(-scroll.max_offset().x * fraction, px(0.0))); } - fn width_beside_library(&self, window: &Window) -> f32 { - (views::client_content_width(window) - - if self.sidebar_collapsed { - 0.0 - } else { - self.sidebar_width - }) - .max(0.0) - } - - pub(crate) fn effective_right_panel_width(&self, window: &Window) -> f32 { - views::panel_layout::fitted_width(self.right_panel_width, self.width_beside_library(window)) - } - - pub(crate) fn main_content_width(&self, window: &Window) -> f32 { - (self.width_beside_library(window) - - if self.right_panel.is_some() { - self.effective_right_panel_width(window) - } else { - 0.0 - }) - .max(0.0) - } - // Both docks track drags at window level and persist only on release. The right dock's // left edge moves in the opposite direction to the library's right edge. - fn begin_sidebar_resize(&mut self, x: Pixels, cx: &mut Context) { - self.panel_resizing = Some(PanelResize { - start_x: x, - start_width: self.sidebar_width, - right: false, - }); - cx.notify(); - } - - fn begin_right_panel_resize(&mut self, x: Pixels, window: &Window, cx: &mut Context) { - self.panel_resizing = Some(PanelResize { - start_x: x, - start_width: self.effective_right_panel_width(window), - right: true, - }); - cx.notify(); - } - - fn update_panel_resize(&mut self, x: Pixels, window: &Window, cx: &mut Context) { - let Some(resize) = self.panel_resizing else { - return; - }; - let delta = x - resize.start_x; - if resize.right { - self.right_panel_width = views::panel_layout::fitted_width( - resize.start_width - f32::from(delta), - self.width_beside_library(window), - ); - } else { - self.sidebar_width = (resize.start_width + f32::from(delta)).clamp(180.0, 480.0); - } - cx.notify(); - } - - fn finish_panel_resize(&mut self, cx: &mut Context) { - if let Some(resize) = self.panel_resizing.take() { - // Saved on release rather than on every pointer move — a drag is one decision, not - // a few hundred config writes. - if resize.right { - self.state.ui.library_config.right_panel_width = Some(self.right_panel_width); - } else { - self.state.ui.library_config.sidebar_width = Some(self.sidebar_width); - } - self.state.save_library_config(); - cx.notify(); - } - } - - pub(crate) fn set_sidebar_collapsed(&mut self, collapsed: bool, cx: &mut Context) { - self.sidebar_collapsed = collapsed; - self.state.ui.library_config.sidebar_collapsed = Some(collapsed); - self.state.save_library_config(); - cx.notify(); - } - - pub(crate) fn toggle_sidebar(&mut self, cx: &mut Context) { - self.set_sidebar_collapsed(!self.sidebar_collapsed, cx); - } - pub(crate) fn history_back(&mut self, cx: &mut Context) -> bool { if !self.state.pop_view_history() { return false; From f1a676f0a409851624a03ea2f92975d362560c10 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:28 -0500 Subject: [PATCH 26/44] desktop: move theme picking and appearance sync into app/themes.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/themes.rs | 79 +++++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 76 -------------------------- 3 files changed, 80 insertions(+), 76 deletions(-) create mode 100644 crates/echo-desktop/src/app/themes.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 0184f7c..26b797d 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -4,3 +4,4 @@ use super::*; mod panels; mod selection; +mod themes; diff --git a/crates/echo-desktop/src/app/themes.rs b/crates/echo-desktop/src/app/themes.rs new file mode 100644 index 0000000..595b073 --- /dev/null +++ b/crates/echo-desktop/src/app/themes.rs @@ -0,0 +1,79 @@ +use super::*; + +impl EchoApp { + pub(crate) fn toggle_themes(&mut self, cx: &mut Context) { + self.theme_modal_open = !self.theme_modal_open; + if self.theme_modal_open { + // Open on the appearance in use and the theme chosen for it, so j/k start from + // where the user is. + self.show_theme_list(self.active_scheme(), cx); + } + cx.notify(); + } + + /// Tells the core which appearance the system is in; under `Auto` that swaps the theme. + pub(crate) fn sync_system_appearance( + &mut self, + appearance: gpui::WindowAppearance, + cx: &mut Context, + ) { + use echo_core::config::Scheme; + use gpui::WindowAppearance::*; + let scheme = match appearance { + Dark | VibrantDark => Scheme::Dark, + Light | VibrantLight => Scheme::Light, + }; + if echo_core::intent::set_system_scheme(&mut self.state, scheme) { + // An open picker under `Auto` keeps the list the user is looking at. + cx.notify(); + } + } + + /// Shows one appearance's themes in the picker, with the cursor on the one chosen for it. + pub(crate) fn show_theme_list( + &mut self, + scheme: echo_core::config::Scheme, + cx: &mut Context, + ) { + self.theme_modal_tab = scheme; + let chosen = echo_core::theme::selected_name( + &self.state.ui.library_config, + &self.state.ui.themes, + scheme, + ); + self.theme_modal_index = views::theme_rows(&self.state, scheme) + .iter() + .position(|row| row.name == chosen) + .unwrap_or(0); + self.theme_modal_scroll + .scroll_to_item(self.theme_modal_index); + cx.notify(); + } + + /// The appearance in effect right now: the pinned one, or the system's under `Auto`. + fn active_scheme(&self) -> echo_core::config::Scheme { + echo_core::theme::active_scheme(&self.state.ui.library_config, self.state.ui.system_scheme) + } + + /// The picker's mode control: sets dark / light / auto and lists the appearance now on + /// screen. + pub(crate) fn set_theme_mode( + &mut self, + mode: echo_core::config::ThemeMode, + cx: &mut Context, + ) { + echo_core::intent::set_theme_mode(&mut self.state, mode); + self.show_theme_list(self.active_scheme(), cx); + } + + /// `m` in the picker: auto → dark → light → auto. + pub(crate) fn cycle_theme_mode(&mut self, cx: &mut Context) { + use echo_core::config::ThemeMode; + let next = match self.state.ui.library_config.theme_mode { + Some(ThemeMode::Dark) => ThemeMode::Light, + Some(ThemeMode::Light) => ThemeMode::Auto, + _ => ThemeMode::Dark, + }; + self.set_theme_mode(next, cx); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 045dae3..459cc3d 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -681,82 +681,6 @@ impl EchoApp { self.state.save_library_config(); } - fn toggle_themes(&mut self, cx: &mut Context) { - self.theme_modal_open = !self.theme_modal_open; - if self.theme_modal_open { - // Open on the appearance in use and the theme chosen for it, so j/k start from - // where the user is. - self.show_theme_list(self.active_scheme(), cx); - } - cx.notify(); - } - - /// Tells the core which appearance the system is in; under `Auto` that swaps the theme. - fn sync_system_appearance( - &mut self, - appearance: gpui::WindowAppearance, - cx: &mut Context, - ) { - use echo_core::config::Scheme; - use gpui::WindowAppearance::*; - let scheme = match appearance { - Dark | VibrantDark => Scheme::Dark, - Light | VibrantLight => Scheme::Light, - }; - if echo_core::intent::set_system_scheme(&mut self.state, scheme) { - // An open picker under `Auto` keeps the list the user is looking at. - cx.notify(); - } - } - - /// Shows one appearance's themes in the picker, with the cursor on the one chosen for it. - pub(crate) fn show_theme_list( - &mut self, - scheme: echo_core::config::Scheme, - cx: &mut Context, - ) { - self.theme_modal_tab = scheme; - let chosen = echo_core::theme::selected_name( - &self.state.ui.library_config, - &self.state.ui.themes, - scheme, - ); - self.theme_modal_index = views::theme_rows(&self.state, scheme) - .iter() - .position(|row| row.name == chosen) - .unwrap_or(0); - self.theme_modal_scroll - .scroll_to_item(self.theme_modal_index); - cx.notify(); - } - - /// The appearance in effect right now: the pinned one, or the system's under `Auto`. - fn active_scheme(&self) -> echo_core::config::Scheme { - echo_core::theme::active_scheme(&self.state.ui.library_config, self.state.ui.system_scheme) - } - - /// The picker's mode control: sets dark / light / auto and lists the appearance now on - /// screen. - pub(crate) fn set_theme_mode( - &mut self, - mode: echo_core::config::ThemeMode, - cx: &mut Context, - ) { - echo_core::intent::set_theme_mode(&mut self.state, mode); - self.show_theme_list(self.active_scheme(), cx); - } - - /// `m` in the picker: auto → dark → light → auto. - fn cycle_theme_mode(&mut self, cx: &mut Context) { - use echo_core::config::ThemeMode; - let next = match self.state.ui.library_config.theme_mode { - Some(ThemeMode::Dark) => ThemeMode::Light, - Some(ThemeMode::Light) => ThemeMode::Auto, - _ => ThemeMode::Dark, - }; - self.set_theme_mode(next, cx); - } - /// Runs a context-menu item against sidebar row `index`, then closes the menu. Destructive /// items only stage a `*_prompt` — the confirm modal fires the actual event. pub(crate) fn run_menu_action( From a9ad98595a9542e624ddbc29db15f93332908fe2 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:29 -0500 Subject: [PATCH 27/44] desktop: move context and track menu actions into app/menus.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/menus.rs | 367 +++++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 364 -------------------------- 3 files changed, 368 insertions(+), 364 deletions(-) create mode 100644 crates/echo-desktop/src/app/menus.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 26b797d..78aa7ea 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -2,6 +2,7 @@ use super::*; +mod menus; mod panels; mod selection; mod themes; diff --git a/crates/echo-desktop/src/app/menus.rs b/crates/echo-desktop/src/app/menus.rs new file mode 100644 index 0000000..a7f9280 --- /dev/null +++ b/crates/echo-desktop/src/app/menus.rs @@ -0,0 +1,367 @@ +use super::*; + +impl EchoApp { + /// Runs a context-menu item against sidebar row `index`, then closes the menu. Destructive + /// items only stage a `*_prompt` — the confirm modal fires the actual event. + pub(crate) fn run_menu_action( + &mut self, + action: MenuAction, + index: usize, + window: &mut Window, + cx: &mut Context, + ) { + self.context_menu = None; + if self.state.ui.active_library_tab == LibraryTab::Albums { + match action { + MenuAction::Open => { + if let Some(event) = echo_core::intent::open_album(&mut self.state, index) { + self.dispatch(event); + } + } + MenuAction::RemoveAlbum => { + if let Some(album) = self.state.data.saved_albums.get(index) { + self.state.ui.album_mass_delete_prompt = Some(vec![album.id.clone()]); + } + } + _ => {} + } + cx.notify(); + return; + } + + let Some(node) = self.state.data.library_view.get(index).cloned() else { + cx.notify(); + return; + }; + match action { + MenuAction::EditDetails => { + if let echo_core::models::LibraryNode::Playlist { playlist, .. } = &node { + echo_core::intent::open_playlist_edit(&mut self.state, &playlist.id); + window.focus(&self.focus_handle, cx); + } + } + MenuAction::Open => { + self.state.ui.selected_playlist_index = index; + if let Some(event) = echo_core::intent::open_library_entry(&mut self.state, index) { + self.dispatch(event); + } + } + MenuAction::TogglePin => { + self.state.ui.selected_playlist_index = index; + echo_core::intent::toggle_pin_selected(&mut self.state); + } + MenuAction::Rename => { + let name = match &node { + echo_core::models::LibraryNode::Playlist { playlist, .. } => { + playlist.name.clone() + } + echo_core::models::LibraryNode::Folder(folder) => folder.name.clone(), + echo_core::models::LibraryNode::SpotifyFolder { .. } => return, + }; + self.state.ui.selected_playlist_index = index; + self.open_command(&format!("rename {name}"), window, cx); + } + MenuAction::RemoveFromFolder => { + if let echo_core::models::LibraryNode::Playlist { playlist, .. } = &node { + echo_core::intent::remove_playlist_from_folders(&mut self.state, &playlist.id); + } + } + MenuAction::DeletePlaylist => { + if let echo_core::models::LibraryNode::Playlist { playlist, .. } = &node { + self.state.ui.playlist_delete_prompt = Some(vec![playlist.id.clone()]); + } + } + MenuAction::DeleteFolder => { + if let echo_core::models::LibraryNode::Folder(folder) = &node { + self.state.ui.folder_delete_prompt = Some(folder.name.clone()); + } + } + MenuAction::RemoveAlbum => {} + } + cx.notify(); + } + + /// Runs a track-menu item against the menu's staged context, then closes the menu. Remove + /// only stages `track_delete_prompt` — the confirm modal fires the actual event. + pub(crate) fn run_track_menu_action(&mut self, item: TrackMenuItem, cx: &mut Context) { + self.state.ui.playlist_add_filter.clear(); + let Some(menu) = self.track_menu.take() else { + cx.notify(); + return; + }; + let ctx = menu.ctx; + match item { + TrackMenuItem::Action(action) => { + if let Some(event) = echo_core::action_menu::run(&mut self.state, ctx, action) { + self.dispatch(event); + } + } + TrackMenuItem::RemoveFromPlaylist => { + if let Some(context) = self + .state + .data + .active_tracklist_context + .clone() + .filter(|c| c.can_modify_playlist(self.state.data.user_id.as_ref())) + { + self.state.ui.track_delete_prompt = Some((context.id, vec![ctx.track_id])); + } + } + } + cx.notify(); + } + + /// Index of the "Add to playlist" row in the open track menu, if it has one. The flyout + /// anchors to it, and the hover/keyboard handlers key off it. + pub(crate) fn track_menu_add_row(&self) -> Option { + views::track_menu_items(self) + .iter() + .position(|(_, item, _)| { + matches!( + item, + TrackMenuItem::Action(echo_core::models::ActionMenuAction::AddToPlaylist) + ) + }) + } + + /// Open the flyout. `focus_row` also parks the menu's keyboard selection on the row it + /// hangs off, which is what Enter and a click mean; a hover leaves the selection where the + /// keyboard put it, since the view lights that row for as long as the flyout is open. + pub(crate) fn open_playlist_submenu(&mut self, focus_row: bool, cx: &mut Context) { + let Some(row) = self.track_menu_add_row() else { + return; + }; + if let Some(menu) = self.track_menu.as_mut() { + if focus_row { + menu.selected = row; + self.track_menu_scroll.scroll_to_item(row); + } + if menu.submenu.is_none() { + self.state.ui.playlist_add_filter.clear(); + menu.submenu = Some(0); + self.submenu_scroll.scroll_to_item(0); + } + } + cx.notify(); + } + + /// Close the flyout but keep the menu itself: what escape, the left arrow and a hover that + /// leaves the row all mean. + pub(crate) fn close_playlist_submenu(&mut self, cx: &mut Context) { + self.state.ui.playlist_add_filter.clear(); + if let Some(menu) = self.track_menu.as_mut() { + menu.submenu = None; + } + cx.notify(); + } + + /// Add the menu's track to flyout choice `index`, then close the whole menu. The register + /// is what `commit_playlist_add` resolves tracks from, the same handoff + /// `action_menu::run(AddToPlaylist)` makes before opening the modal picker. + pub(crate) fn commit_playlist_submenu(&mut self, index: usize, cx: &mut Context) { + // Out of range only happens with no playlists at all, where Enter should do nothing + // rather than close the menu; it would also leave the register staged. + if index > echo_core::action_menu::filtered_playlist_add_choices(&self.state).len() { + return; + } + let Some(menu) = self.track_menu.take() else { + return; + }; + self.state.ui.operation_register = vec![menu.ctx.track_id]; + if let Some(event) = + echo_core::action_menu::commit_filtered_playlist_add(&mut self.state, index) + { + self.dispatch(event); + } + cx.notify(); + } + + /// A pointer move over track-menu row `ix`. Hovering the "Add to playlist" row opens the + /// flyout; hovering any other row closes it — unless the pointer is inside the triangle + /// spanned by where it left that row and the flyout's near edge, which is the diagonal a + /// user aiming at the flyout travels through. + pub(crate) fn hover_track_menu_row( + &mut self, + ix: usize, + position: gpui::Point, + cx: &mut Context, + ) { + if self.track_menu_add_row() != Some(ix) { + if self + .track_menu + .as_ref() + .is_some_and(|menu| menu.submenu.is_some()) + && !self.pointer_aims_at_submenu(position) + { + self.close_playlist_submenu(cx); + } + return; + } + self.submenu_apex = position; + if self + .track_menu + .as_ref() + .is_some_and(|menu| menu.submenu.is_none()) + { + self.open_playlist_submenu(false, cx); + } + } + + /// Whether `position` falls in the triangle from [`Self::submenu_apex`] to the flyout's + /// near edge. Degenerate while the flyout has yet to be painted, which reads as "not + /// aiming" and simply closes it a frame early. + fn pointer_aims_at_submenu(&self, position: gpui::Point) -> bool { + let flyout = self.submenu_bounds.get(); + if flyout.size.height <= px(0.0) { + return false; + } + // The flyout sits on whichever side of the menu had room (`views::playlist_submenu`), + // so the near edge — and which way "toward it" is — follows from where it landed. + let flipped = flyout.left() < self.submenu_row_bounds.get().left(); + let edge = if flipped { + flyout.right() + } else { + flyout.left() + }; + // The flyout can be much taller than the menu, so the triangle alone would cover most + // of the rows below: a move only counts as aiming while it still travels toward the + // flyout. Straight down the menu closes it at once. + let toward = if flipped { + position.x < self.submenu_apex.x + } else { + position.x > self.submenu_apex.x + }; + if !toward { + return false; + } + // A few pixels of slack at both corners: the flyout's own border and rounding mean the + // exact corner is not where the pointer needs to land. + let apex = self.submenu_apex; + let top = gpui::point(edge, flyout.top() - px(4.0)); + let bottom = gpui::point(edge, flyout.bottom() + px(4.0)); + let side = |a: gpui::Point, b: gpui::Point| { + f32::from(b.x - a.x) * f32::from(position.y - a.y) + - f32::from(b.y - a.y) * f32::from(position.x - a.x) + }; + let (ab, bc, ca) = (side(apex, top), side(top, bottom), side(bottom, apex)); + (ab >= 0.0 && bc >= 0.0 && ca >= 0.0) || (ab <= 0.0 && bc <= 0.0 && ca <= 0.0) + } + + /// The track `a` / `shift-a` act on: the focused row where the view has one, otherwise the + /// currently playing track. + pub(crate) fn action_target(&self) -> Option { + use echo_core::models::ActionMenuContext; + let ui = &self.state.ui; + let data = &self.state.data; + let row = match ui.active_view { + ActiveView::TrackList => data.tracks.get(ui.selected_track_index), + ActiveView::Queue => self.state.queue_view_track(ui.selected_queue_index), + ActiveView::ArtistPage => echo_core::intent::selected_artist_top_track(&self.state), + ActiveView::SearchResults => { + return echo_core::intent::selected_search_track(&self.state) + .map(ActionMenuContext::from); + } + _ => None, + }; + if let Some(track) = row { + return Some(ActionMenuContext::from(track)); + } + + self.playing_track_context() + } + + /// Menu context for the currently playing track: `action_target`'s fallback and the + /// playback bar's click-to-navigate target. + pub(crate) fn playing_track_context(&self) -> Option { + let playback = &self.state.playback; + let track_id = playback.playing_track_id.clone()?; + // Playback state only carries the joined "A, B, C" artist string; when the playing + // track is in the current list or queue, prefer its structured data so go-to-artist + // gets the first artist's own name. + if let Some(track) = self + .state + .data + .tracks + .iter() + .chain(self.state.data.queue.iter()) + .find(|track| track.id == track_id) + { + return Some(echo_core::models::ActionMenuContext::from(track)); + } + Some(echo_core::models::ActionMenuContext { + album_name: self + .state + .data + .local_library + .tracks + .iter() + .find(|track| track.id == track_id) + .map(|track| track.album.clone()) + .unwrap_or_default(), + track_id, + source: playback + .playing_track_source + .unwrap_or(echo_core::models::TrackSource::Spotify), + track_name: playback.playing_track_title.clone(), + local_path: playback.playing_track_local_path.clone(), + album_id: playback.playing_track_album_id.clone(), + artist_id: playback.playing_track_artist_id.clone(), + artist_name: playback.playing_track_artist.clone(), + }) + } + + /// `shift-a` — the track action menu, centered because there is no click to anchor it to. + pub(crate) fn open_action_menu(&mut self, cx: &mut Context) { + self.pending_count = None; + if let Some(ctx) = self.action_target() { + self.context_menu = None; + self.track_menu = Some(TrackMenuState { + ctx, + position: None, + selected: 0, + submenu: None, + }); + } + cx.notify(); + } + + /// `a` — add the selection to a playlist, or save the album when an album row is focused. + /// The picker commits through `action_menu::commit_playlist_add`, which resolves the + /// tracks from the current selection. + pub(crate) fn add_to_playlist(&mut self, cx: &mut Context) { + self.pending_count = None; + if self.multi_selected() { + echo_core::intent::add_visual_selection_to_playlist(&mut self.state); + cx.notify(); + return; + } + let album_id = match self.state.ui.active_view { + ActiveView::SearchResults + if self.state.ui.active_search_tab == echo_core::app::SearchTab::Albums => + { + self.state + .data + .search_results + .albums + .get(self.state.ui.selected_search_index) + .map(|album| (album.id.clone(), album.name.clone())) + } + _ => None, + }; + + if let Some((id, name)) = album_id { + let language = self.state.ui.library_config.language.clone(); + self.state.ui.status_message = Some( + echo_core::i18n::t("messages.saved_to_library", &language).replace("{}", &name), + ); + self.state.ui.status_message_expiry = + Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); + self.dispatch(AppEvent::SaveAlbums(vec![id])); + } else { + self.state.ui.playlist_add_modal_open = true; + self.state.ui.playlist_add_filter.clear(); + self.state.ui.selected_playlist_modal_index = 0; + } + cx.notify(); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 459cc3d..96fea29 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -681,318 +681,9 @@ impl EchoApp { self.state.save_library_config(); } - /// Runs a context-menu item against sidebar row `index`, then closes the menu. Destructive - /// items only stage a `*_prompt` — the confirm modal fires the actual event. - pub(crate) fn run_menu_action( - &mut self, - action: MenuAction, - index: usize, - window: &mut Window, - cx: &mut Context, - ) { - self.context_menu = None; - if self.state.ui.active_library_tab == LibraryTab::Albums { - match action { - MenuAction::Open => { - if let Some(event) = echo_core::intent::open_album(&mut self.state, index) { - self.dispatch(event); - } - } - MenuAction::RemoveAlbum => { - if let Some(album) = self.state.data.saved_albums.get(index) { - self.state.ui.album_mass_delete_prompt = Some(vec![album.id.clone()]); - } - } - _ => {} - } - cx.notify(); - return; - } - - let Some(node) = self.state.data.library_view.get(index).cloned() else { - cx.notify(); - return; - }; - match action { - MenuAction::EditDetails => { - if let echo_core::models::LibraryNode::Playlist { playlist, .. } = &node { - echo_core::intent::open_playlist_edit(&mut self.state, &playlist.id); - window.focus(&self.focus_handle, cx); - } - } - MenuAction::Open => { - self.state.ui.selected_playlist_index = index; - if let Some(event) = echo_core::intent::open_library_entry(&mut self.state, index) { - self.dispatch(event); - } - } - MenuAction::TogglePin => { - self.state.ui.selected_playlist_index = index; - echo_core::intent::toggle_pin_selected(&mut self.state); - } - MenuAction::Rename => { - let name = match &node { - echo_core::models::LibraryNode::Playlist { playlist, .. } => { - playlist.name.clone() - } - echo_core::models::LibraryNode::Folder(folder) => folder.name.clone(), - echo_core::models::LibraryNode::SpotifyFolder { .. } => return, - }; - self.state.ui.selected_playlist_index = index; - self.open_command(&format!("rename {name}"), window, cx); - } - MenuAction::RemoveFromFolder => { - if let echo_core::models::LibraryNode::Playlist { playlist, .. } = &node { - echo_core::intent::remove_playlist_from_folders(&mut self.state, &playlist.id); - } - } - MenuAction::DeletePlaylist => { - if let echo_core::models::LibraryNode::Playlist { playlist, .. } = &node { - self.state.ui.playlist_delete_prompt = Some(vec![playlist.id.clone()]); - } - } - MenuAction::DeleteFolder => { - if let echo_core::models::LibraryNode::Folder(folder) = &node { - self.state.ui.folder_delete_prompt = Some(folder.name.clone()); - } - } - MenuAction::RemoveAlbum => {} - } - cx.notify(); - } - - /// Runs a track-menu item against the menu's staged context, then closes the menu. Remove - /// only stages `track_delete_prompt` — the confirm modal fires the actual event. - pub(crate) fn run_track_menu_action(&mut self, item: TrackMenuItem, cx: &mut Context) { - self.state.ui.playlist_add_filter.clear(); - let Some(menu) = self.track_menu.take() else { - cx.notify(); - return; - }; - let ctx = menu.ctx; - match item { - TrackMenuItem::Action(action) => { - if let Some(event) = echo_core::action_menu::run(&mut self.state, ctx, action) { - self.dispatch(event); - } - } - TrackMenuItem::RemoveFromPlaylist => { - if let Some(context) = self - .state - .data - .active_tracklist_context - .clone() - .filter(|c| c.can_modify_playlist(self.state.data.user_id.as_ref())) - { - self.state.ui.track_delete_prompt = Some((context.id, vec![ctx.track_id])); - } - } - } - cx.notify(); - } - // The add-to-playlist flyout. The track menu's "Add to playlist" row opens a second panel // beside it rather than the full-screen picker `a` uses, so the choice stays in one gesture. - /// Index of the "Add to playlist" row in the open track menu, if it has one. The flyout - /// anchors to it, and the hover/keyboard handlers key off it. - pub(crate) fn track_menu_add_row(&self) -> Option { - views::track_menu_items(self) - .iter() - .position(|(_, item, _)| { - matches!( - item, - TrackMenuItem::Action(echo_core::models::ActionMenuAction::AddToPlaylist) - ) - }) - } - - /// Open the flyout. `focus_row` also parks the menu's keyboard selection on the row it - /// hangs off, which is what Enter and a click mean; a hover leaves the selection where the - /// keyboard put it, since the view lights that row for as long as the flyout is open. - pub(crate) fn open_playlist_submenu(&mut self, focus_row: bool, cx: &mut Context) { - let Some(row) = self.track_menu_add_row() else { - return; - }; - if let Some(menu) = self.track_menu.as_mut() { - if focus_row { - menu.selected = row; - self.track_menu_scroll.scroll_to_item(row); - } - if menu.submenu.is_none() { - self.state.ui.playlist_add_filter.clear(); - menu.submenu = Some(0); - self.submenu_scroll.scroll_to_item(0); - } - } - cx.notify(); - } - - /// Close the flyout but keep the menu itself: what escape, the left arrow and a hover that - /// leaves the row all mean. - pub(crate) fn close_playlist_submenu(&mut self, cx: &mut Context) { - self.state.ui.playlist_add_filter.clear(); - if let Some(menu) = self.track_menu.as_mut() { - menu.submenu = None; - } - cx.notify(); - } - - /// Add the menu's track to flyout choice `index`, then close the whole menu. The register - /// is what `commit_playlist_add` resolves tracks from, the same handoff - /// `action_menu::run(AddToPlaylist)` makes before opening the modal picker. - pub(crate) fn commit_playlist_submenu(&mut self, index: usize, cx: &mut Context) { - // Out of range only happens with no playlists at all, where Enter should do nothing - // rather than close the menu; it would also leave the register staged. - if index > echo_core::action_menu::filtered_playlist_add_choices(&self.state).len() { - return; - } - let Some(menu) = self.track_menu.take() else { - return; - }; - self.state.ui.operation_register = vec![menu.ctx.track_id]; - if let Some(event) = - echo_core::action_menu::commit_filtered_playlist_add(&mut self.state, index) - { - self.dispatch(event); - } - cx.notify(); - } - - /// A pointer move over track-menu row `ix`. Hovering the "Add to playlist" row opens the - /// flyout; hovering any other row closes it — unless the pointer is inside the triangle - /// spanned by where it left that row and the flyout's near edge, which is the diagonal a - /// user aiming at the flyout travels through. - pub(crate) fn hover_track_menu_row( - &mut self, - ix: usize, - position: gpui::Point, - cx: &mut Context, - ) { - if self.track_menu_add_row() != Some(ix) { - if self - .track_menu - .as_ref() - .is_some_and(|menu| menu.submenu.is_some()) - && !self.pointer_aims_at_submenu(position) - { - self.close_playlist_submenu(cx); - } - return; - } - self.submenu_apex = position; - if self - .track_menu - .as_ref() - .is_some_and(|menu| menu.submenu.is_none()) - { - self.open_playlist_submenu(false, cx); - } - } - - /// Whether `position` falls in the triangle from [`Self::submenu_apex`] to the flyout's - /// near edge. Degenerate while the flyout has yet to be painted, which reads as "not - /// aiming" and simply closes it a frame early. - fn pointer_aims_at_submenu(&self, position: gpui::Point) -> bool { - let flyout = self.submenu_bounds.get(); - if flyout.size.height <= px(0.0) { - return false; - } - // The flyout sits on whichever side of the menu had room (`views::playlist_submenu`), - // so the near edge — and which way "toward it" is — follows from where it landed. - let flipped = flyout.left() < self.submenu_row_bounds.get().left(); - let edge = if flipped { - flyout.right() - } else { - flyout.left() - }; - // The flyout can be much taller than the menu, so the triangle alone would cover most - // of the rows below: a move only counts as aiming while it still travels toward the - // flyout. Straight down the menu closes it at once. - let toward = if flipped { - position.x < self.submenu_apex.x - } else { - position.x > self.submenu_apex.x - }; - if !toward { - return false; - } - // A few pixels of slack at both corners: the flyout's own border and rounding mean the - // exact corner is not where the pointer needs to land. - let apex = self.submenu_apex; - let top = gpui::point(edge, flyout.top() - px(4.0)); - let bottom = gpui::point(edge, flyout.bottom() + px(4.0)); - let side = |a: gpui::Point, b: gpui::Point| { - f32::from(b.x - a.x) * f32::from(position.y - a.y) - - f32::from(b.y - a.y) * f32::from(position.x - a.x) - }; - let (ab, bc, ca) = (side(apex, top), side(top, bottom), side(bottom, apex)); - (ab >= 0.0 && bc >= 0.0 && ca >= 0.0) || (ab <= 0.0 && bc <= 0.0 && ca <= 0.0) - } - - /// The track `a` / `shift-a` act on: the focused row where the view has one, otherwise the - /// currently playing track. - pub(crate) fn action_target(&self) -> Option { - use echo_core::models::ActionMenuContext; - let ui = &self.state.ui; - let data = &self.state.data; - let row = match ui.active_view { - ActiveView::TrackList => data.tracks.get(ui.selected_track_index), - ActiveView::Queue => self.state.queue_view_track(ui.selected_queue_index), - ActiveView::ArtistPage => echo_core::intent::selected_artist_top_track(&self.state), - ActiveView::SearchResults => { - return echo_core::intent::selected_search_track(&self.state) - .map(ActionMenuContext::from); - } - _ => None, - }; - if let Some(track) = row { - return Some(ActionMenuContext::from(track)); - } - - self.playing_track_context() - } - - /// Menu context for the currently playing track: `action_target`'s fallback and the - /// playback bar's click-to-navigate target. - pub(crate) fn playing_track_context(&self) -> Option { - let playback = &self.state.playback; - let track_id = playback.playing_track_id.clone()?; - // Playback state only carries the joined "A, B, C" artist string; when the playing - // track is in the current list or queue, prefer its structured data so go-to-artist - // gets the first artist's own name. - if let Some(track) = self - .state - .data - .tracks - .iter() - .chain(self.state.data.queue.iter()) - .find(|track| track.id == track_id) - { - return Some(echo_core::models::ActionMenuContext::from(track)); - } - Some(echo_core::models::ActionMenuContext { - album_name: self - .state - .data - .local_library - .tracks - .iter() - .find(|track| track.id == track_id) - .map(|track| track.album.clone()) - .unwrap_or_default(), - track_id, - source: playback - .playing_track_source - .unwrap_or(echo_core::models::TrackSource::Spotify), - track_name: playback.playing_track_title.clone(), - local_path: playback.playing_track_local_path.clone(), - album_id: playback.playing_track_album_id.clone(), - artist_id: playback.playing_track_artist_id.clone(), - artist_name: playback.playing_track_artist.clone(), - }) - } - /// Opens an artist page directly by id — the per-artist click path in track rows. pub(crate) fn open_artist( &mut self, @@ -1024,21 +715,6 @@ impl EchoApp { cx.notify(); } - /// `shift-a` — the track action menu, centered because there is no click to anchor it to. - fn open_action_menu(&mut self, cx: &mut Context) { - self.pending_count = None; - if let Some(ctx) = self.action_target() { - self.context_menu = None; - self.track_menu = Some(TrackMenuState { - ctx, - position: None, - selected: 0, - submenu: None, - }); - } - cx.notify(); - } - /// Redraws only what shows the playback position or the volume: the playback bar, the /// lyrics panel, and the immersive view, which is drawn by the app itself. fn notify_playback_position(&mut self, cx: &mut Context) { @@ -1082,46 +758,6 @@ impl EchoApp { (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() } - /// `a` — add the selection to a playlist, or save the album when an album row is focused. - /// The picker commits through `action_menu::commit_playlist_add`, which resolves the - /// tracks from the current selection. - fn add_to_playlist(&mut self, cx: &mut Context) { - self.pending_count = None; - if self.multi_selected() { - echo_core::intent::add_visual_selection_to_playlist(&mut self.state); - cx.notify(); - return; - } - let album_id = match self.state.ui.active_view { - ActiveView::SearchResults - if self.state.ui.active_search_tab == echo_core::app::SearchTab::Albums => - { - self.state - .data - .search_results - .albums - .get(self.state.ui.selected_search_index) - .map(|album| (album.id.clone(), album.name.clone())) - } - _ => None, - }; - - if let Some((id, name)) = album_id { - let language = self.state.ui.library_config.language.clone(); - self.state.ui.status_message = Some( - echo_core::i18n::t("messages.saved_to_library", &language).replace("{}", &name), - ); - self.state.ui.status_message_expiry = - Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); - self.dispatch(AppEvent::SaveAlbums(vec![id])); - } else { - self.state.ui.playlist_add_modal_open = true; - self.state.ui.playlist_add_filter.clear(); - self.state.ui.selected_playlist_modal_index = 0; - } - cx.notify(); - } - /// Open or close the settings sheet, seeding the folder field from the saved config. pub(crate) fn toggle_settings(&mut self, cx: &mut Context) { self.settings_open = !self.settings_open; From 138e98ceee28a7d96b594c78724c1b229cf7fe46 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:31 -0500 Subject: [PATCH 28/44] desktop: move view navigation and history into app/navigation.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/navigation.rs | 177 ++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 174 --------------------- 3 files changed, 178 insertions(+), 174 deletions(-) create mode 100644 crates/echo-desktop/src/app/navigation.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 78aa7ea..10b9384 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -3,6 +3,7 @@ use super::*; mod menus; +mod navigation; mod panels; mod selection; mod themes; diff --git a/crates/echo-desktop/src/app/navigation.rs b/crates/echo-desktop/src/app/navigation.rs new file mode 100644 index 0000000..42d41a4 --- /dev/null +++ b/crates/echo-desktop/src/app/navigation.rs @@ -0,0 +1,177 @@ +use super::*; + +impl EchoApp { + /// Opens an artist page directly by id — the per-artist click path in track rows. + pub(crate) fn open_artist( + &mut self, + artist_id: String, + artist_name: String, + cx: &mut Context, + ) { + self.state + .begin_artist_page_load(artist_id.clone(), artist_name.clone(), None); + self.dispatch(AppEvent::LoadArtistPage { + artist_id, + artist_name: Some(artist_name), + artist_image_url: None, + }); + cx.notify(); + } + + /// Runs one go-to action (album/artist) for a track context — the click-to-navigate path + /// shared by track-row cells and the playback bar. + pub(crate) fn go_to( + &mut self, + ctx: echo_core::models::ActionMenuContext, + action: echo_core::models::ActionMenuAction, + cx: &mut Context, + ) { + if let Some(event) = echo_core::action_menu::run(&mut self.state, ctx, action) { + self.dispatch(event); + } + cx.notify(); + } + + /// Backspace: close the topmost overlay if one is open, else hand keyboard focus back to the + /// library sidebar while keeping the current page visible, without walking the view history + /// the way `h`/escape do. + pub(crate) fn back_or_focus_library(&mut self, cx: &mut Context) { + self.pending_count = None; + if self.overlay_open() { + self.dismiss(cx); + } else { + self.focus_library(cx); + } + } + + pub(crate) fn refresh_view(&mut self, cx: &mut Context) { + if self.state.ui.active_view == ActiveView::Home { + for event in echo_core::intent::refresh_home(&mut self.state) { + self.dispatch(event); + } + cx.notify(); + return; + } + if let Some(event) = echo_core::intent::refresh_view(&mut self.state) { + self.dispatch(event); + } + cx.notify(); + } + + /// Tab: cycle the tabs of whichever tabbed view is active. The desktop has no Browse + /// library tab — those entries live in the sidebar — so the library just flips between + /// Playlists and Albums. + pub(crate) fn cycle_tab(&mut self, cx: &mut Context) { + self.state.ui.pending_d_press = false; + if self.theme_modal_open { + // Under `Auto` the picker has a dark and a light list; a pinned mode has one. + if self.state.ui.library_config.theme_mode == Some(echo_core::config::ThemeMode::Auto) { + self.show_theme_list(self.theme_modal_tab.other(), cx); + } + return; + } + match self.state.ui.active_view { + ActiveView::SearchResults => { + self.state.ui.active_search_tab = match self.state.ui.active_search_tab { + SearchTab::All => SearchTab::Tracks, + SearchTab::Tracks => SearchTab::Albums, + SearchTab::Albums => SearchTab::Artists, + SearchTab::Artists => SearchTab::Playlists, + SearchTab::Playlists => SearchTab::All, + }; + self.state.ui.selected_search_index = 0; + } + ActiveView::Library => { + self.state.ui.active_library_tab = match self.state.ui.active_library_tab { + LibraryTab::Playlists => LibraryTab::Albums, + LibraryTab::Albums => LibraryTab::Artists, + _ => LibraryTab::Playlists, + }; + self.state.ui.selected_playlist_index = 0; + if self.state.ui.active_library_tab == LibraryTab::Artists + && self.state.data.followed_artists.is_empty() + { + self.dispatch(AppEvent::FetchFollowedArtists); + } + } + ActiveView::Queue => echo_core::intent::cycle_queue_tab(&mut self.state), + ActiveView::ArtistPage => { + self.set_discography_filter(self.state.ui.artist_discography_filter.next()) + } + _ => {} + } + cx.notify(); + } + + pub(crate) fn open_home(&mut self, cx: &mut Context) { + self.immersive = false; + for event in echo_core::intent::open_home(&mut self.state) { + self.dispatch(event); + } + cx.notify(); + } + + pub(crate) fn focus_library(&mut self, cx: &mut Context) { + // With a menu open the arrows belong to it: left closes the add-to-playlist flyout + // rather than moving pane focus behind the overlay. + if self.track_menu.is_some() { + self.close_playlist_submenu(cx); + return; + } + self.state.ui.pending_d_press = false; + if self.sidebar_collapsed { + // Focusing an invisible pane would strand the cursor; bring the sidebar back. + self.set_sidebar_collapsed(false, cx); + } + self.state.ui.active_view = ActiveView::Library; + cx.notify(); + } + + pub(crate) fn focus_tracks(&mut self, cx: &mut Context) { + // Right steps into the flyout when the menu's "Add to playlist" row is selected. + if self.track_menu.is_some() { + if self.track_menu_add_row() == self.track_menu.as_ref().map(|menu| menu.selected) { + self.open_playlist_submenu(true, cx); + } + return; + } + self.state.ui.pending_d_press = false; + // Nothing to focus before a context has been opened. + if !self.state.data.tracks.is_empty() || self.state.data.active_tracklist_context.is_some() + { + self.state.ui.active_view = ActiveView::TrackList; + cx.notify(); + } + } + + pub(crate) fn history_back(&mut self, cx: &mut Context) -> bool { + if !self.state.pop_view_history() { + return false; + } + self.state.clear_pending_artist_page(); + if self.state.data.tracklist_image_url.is_some() { + self.dispatch(AppEvent::ReloadHeaderImage); + } + cx.notify(); + true + } + + pub(crate) fn history_forward(&mut self, cx: &mut Context) -> bool { + if !self.state.forward_view_history() { + return false; + } + self.state.clear_pending_artist_page(); + if self.state.data.tracklist_image_url.is_some() { + self.dispatch(AppEvent::ReloadHeaderImage); + } + cx.notify(); + true + } + + pub(crate) fn close_artist_page(&mut self, cx: &mut Context) { + self.state.ui.active_view = ActiveView::Library; + self.state.clear_pending_artist_page(); + self.dispatch(AppEvent::CancelArtistPageLoad); + cx.notify(); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 96fea29..a99b1ef 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -684,37 +684,6 @@ impl EchoApp { // The add-to-playlist flyout. The track menu's "Add to playlist" row opens a second panel // beside it rather than the full-screen picker `a` uses, so the choice stays in one gesture. - /// Opens an artist page directly by id — the per-artist click path in track rows. - pub(crate) fn open_artist( - &mut self, - artist_id: String, - artist_name: String, - cx: &mut Context, - ) { - self.state - .begin_artist_page_load(artist_id.clone(), artist_name.clone(), None); - self.dispatch(AppEvent::LoadArtistPage { - artist_id, - artist_name: Some(artist_name), - artist_image_url: None, - }); - cx.notify(); - } - - /// Runs one go-to action (album/artist) for a track context — the click-to-navigate path - /// shared by track-row cells and the playback bar. - pub(crate) fn go_to( - &mut self, - ctx: echo_core::models::ActionMenuContext, - action: echo_core::models::ActionMenuAction, - cx: &mut Context, - ) { - if let Some(event) = echo_core::action_menu::run(&mut self.state, ctx, action) { - self.dispatch(event); - } - cx.notify(); - } - /// Redraws only what shows the playback position or the volume: the playback bar, the /// lyrics panel, and the immersive view, which is drawn by the app itself. fn notify_playback_position(&mut self, cx: &mut Context) { @@ -1106,18 +1075,6 @@ impl EchoApp { self.pending_count.take().unwrap_or(1).max(1) as isize } - /// Backspace: close the topmost overlay if one is open, else hand keyboard focus back to the - /// library sidebar while keeping the current page visible, without walking the view history - /// the way `h`/escape do. - fn back_or_focus_library(&mut self, cx: &mut Context) { - self.pending_count = None; - if self.overlay_open() { - self.dismiss(cx); - } else { - self.focus_library(cx); - } - } - // Vim-style command mode (`:`) and track filter (`/`) — a bar above the playback bar that // owns key handling while one of the modes is active. The command registry itself lives in // `echo_core::commands`. @@ -1290,20 +1247,6 @@ impl EchoApp { cx.notify(); } - fn refresh_view(&mut self, cx: &mut Context) { - if self.state.ui.active_view == ActiveView::Home { - for event in echo_core::intent::refresh_home(&mut self.state) { - self.dispatch(event); - } - cx.notify(); - return; - } - if let Some(event) = echo_core::intent::refresh_view(&mut self.state) { - self.dispatch(event); - } - cx.notify(); - } - fn adjust_volume(&mut self, delta: i32, cx: &mut Context) { let event = echo_core::intent::adjust_volume(&mut self.state, delta); self.dispatch(event); @@ -1317,51 +1260,6 @@ impl EchoApp { cx.notify(); } - /// Tab: cycle the tabs of whichever tabbed view is active. The desktop has no Browse - /// library tab — those entries live in the sidebar — so the library just flips between - /// Playlists and Albums. - fn cycle_tab(&mut self, cx: &mut Context) { - self.state.ui.pending_d_press = false; - if self.theme_modal_open { - // Under `Auto` the picker has a dark and a light list; a pinned mode has one. - if self.state.ui.library_config.theme_mode == Some(echo_core::config::ThemeMode::Auto) { - self.show_theme_list(self.theme_modal_tab.other(), cx); - } - return; - } - match self.state.ui.active_view { - ActiveView::SearchResults => { - self.state.ui.active_search_tab = match self.state.ui.active_search_tab { - SearchTab::All => SearchTab::Tracks, - SearchTab::Tracks => SearchTab::Albums, - SearchTab::Albums => SearchTab::Artists, - SearchTab::Artists => SearchTab::Playlists, - SearchTab::Playlists => SearchTab::All, - }; - self.state.ui.selected_search_index = 0; - } - ActiveView::Library => { - self.state.ui.active_library_tab = match self.state.ui.active_library_tab { - LibraryTab::Playlists => LibraryTab::Albums, - LibraryTab::Albums => LibraryTab::Artists, - _ => LibraryTab::Playlists, - }; - self.state.ui.selected_playlist_index = 0; - if self.state.ui.active_library_tab == LibraryTab::Artists - && self.state.data.followed_artists.is_empty() - { - self.dispatch(AppEvent::FetchFollowedArtists); - } - } - ActiveView::Queue => echo_core::intent::cycle_queue_tab(&mut self.state), - ActiveView::ArtistPage => { - self.set_discography_filter(self.state.ui.artist_discography_filter.next()) - } - _ => {} - } - cx.notify(); - } - /// The `:`/`/` bar. Rendered only while one of the two modes is active; carries the /// search key context so plain letters type instead of triggering list bindings. fn render_command_bar(&mut self, cx: &mut Context) -> impl IntoElement { @@ -1532,47 +1430,6 @@ impl EchoApp { cx.notify(); } - pub(crate) fn open_home(&mut self, cx: &mut Context) { - self.immersive = false; - for event in echo_core::intent::open_home(&mut self.state) { - self.dispatch(event); - } - cx.notify(); - } - - fn focus_library(&mut self, cx: &mut Context) { - // With a menu open the arrows belong to it: left closes the add-to-playlist flyout - // rather than moving pane focus behind the overlay. - if self.track_menu.is_some() { - self.close_playlist_submenu(cx); - return; - } - self.state.ui.pending_d_press = false; - if self.sidebar_collapsed { - // Focusing an invisible pane would strand the cursor; bring the sidebar back. - self.set_sidebar_collapsed(false, cx); - } - self.state.ui.active_view = ActiveView::Library; - cx.notify(); - } - - fn focus_tracks(&mut self, cx: &mut Context) { - // Right steps into the flyout when the menu's "Add to playlist" row is selected. - if self.track_menu.is_some() { - if self.track_menu_add_row() == self.track_menu.as_ref().map(|menu| menu.selected) { - self.open_playlist_submenu(true, cx); - } - return; - } - self.state.ui.pending_d_press = false; - // Nothing to focus before a context has been opened. - if !self.state.data.tracks.is_empty() || self.state.data.active_tracklist_context.is_some() - { - self.state.ui.active_view = ActiveView::TrackList; - cx.notify(); - } - } - // Transport, all via the shared intents (optimistic flip + worker event). fn toggle_playback(&mut self, cx: &mut Context) { @@ -1713,37 +1570,6 @@ impl EchoApp { // Both docks track drags at window level and persist only on release. The right dock's // left edge moves in the opposite direction to the library's right edge. - pub(crate) fn history_back(&mut self, cx: &mut Context) -> bool { - if !self.state.pop_view_history() { - return false; - } - self.state.clear_pending_artist_page(); - if self.state.data.tracklist_image_url.is_some() { - self.dispatch(AppEvent::ReloadHeaderImage); - } - cx.notify(); - true - } - - pub(crate) fn history_forward(&mut self, cx: &mut Context) -> bool { - if !self.state.forward_view_history() { - return false; - } - self.state.clear_pending_artist_page(); - if self.state.data.tracklist_image_url.is_some() { - self.dispatch(AppEvent::ReloadHeaderImage); - } - cx.notify(); - true - } - - pub(crate) fn close_artist_page(&mut self, cx: &mut Context) { - self.state.ui.active_view = ActiveView::Library; - self.state.clear_pending_artist_page(); - self.dispatch(AppEvent::CancelArtistPageLoad); - cx.notify(); - } - /// Sends an intent-produced event to the worker with its required side channels: a /// LoadContextTracks with cover art also kicks off the header image fetch, and /// ReloadHeaderImage is handled entirely here (the worker has no handler for it). From fad4800896441adb2dd6480784dda776f963bdad Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:32 -0500 Subject: [PATCH 29/44] desktop: move settings actions into app/settings.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/settings.rs | 115 ++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 112 ----------------------- 3 files changed, 116 insertions(+), 112 deletions(-) create mode 100644 crates/echo-desktop/src/app/settings.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 10b9384..10812a0 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -6,4 +6,5 @@ mod menus; mod navigation; mod panels; mod selection; +mod settings; mod themes; diff --git a/crates/echo-desktop/src/app/settings.rs b/crates/echo-desktop/src/app/settings.rs new file mode 100644 index 0000000..a98f905 --- /dev/null +++ b/crates/echo-desktop/src/app/settings.rs @@ -0,0 +1,115 @@ +use super::*; + +impl EchoApp { + /// Open or close the settings sheet, seeding the folder field from the saved config. + pub(crate) fn toggle_settings(&mut self, cx: &mut Context) { + self.settings_open = !self.settings_open; + self.settings_dropdown = None; + if self.settings_open { + self.settings_path_input = self + .state + .ui + .library_config + .local_music_dir + .as_ref() + .map(|path| path.display().to_string()) + .unwrap_or_default(); + self.settings_path_cursor = self.settings_path_input.len(); + } + cx.notify(); + } + + /// Run a settings control through the `:` registry. Every command the sheet exposes already + /// validates its own input and sets its own status message, so the rows stay declarative. + pub(crate) fn run_setting(&mut self, cmd: String, cx: &mut Context) { + if let Some(event) = echo_core::commands::run(&mut self.state, &cmd) { + self.dispatch(event); + } + cx.notify(); + } + + /// Audio-quality keys have no `:` command, so they write the config directly. They are read + /// when the librespot daemon starts, hence the "next launch" note in the sheet. + pub(crate) fn set_audio_quality( + &mut self, + apply: impl FnOnce(&mut echo_core::config::LibraryConfig), + cx: &mut Context, + ) { + apply(&mut self.state.ui.library_config); + self.state.save_library_config(); + self.state.ui.status_message = + Some(views::tr(&self.state, "desktop.saved_next_launch").to_string()); + self.state.ui.status_message_expiry = + Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); + cx.notify(); + } + + /// True when the folder field holds something other than the saved folder, including when + /// none is saved yet. + pub(crate) fn local_folder_unsaved(&self) -> bool { + let saved = self + .state + .ui + .library_config + .local_music_dir + .as_ref() + .map(|path| path.display().to_string()); + saved.as_deref() != Some(self.settings_path_input.trim()) + } + + /// Enter in the folder field, or its button: save and scan what was typed, or rescan when + /// the field already matches the saved folder. + pub(crate) fn apply_or_rescan_local_folder( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { + if self.local_folder_unsaved() { + let path = self.settings_path_input.trim().to_string(); + if !path.is_empty() { + self.run_setting(format!("localpath {path}"), cx); + // Show the folder as saved: `~` expanded, and the button back to rescan. + if let Some(saved) = &self.state.ui.library_config.local_music_dir + && echo_core::commands::expand_home(&path) == *saved + { + self.settings_path_input = saved.display().to_string(); + self.settings_path_cursor = self.settings_path_input.len(); + } + } + } else { + self.run_setting("rescanlocal".to_string(), cx); + } + window.focus(&self.focus_handle.clone(), cx); + cx.notify(); + } + + /// Typing in the settings sheet's local-folder field. Enter submits it as `:localpath`. + pub(crate) fn handle_settings_path_key( + &mut self, + event: &gpui::KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + match event.keystroke.key.as_str() { + "enter" => self.apply_or_rescan_local_folder(window, cx), + "escape" => window.focus(&self.focus_handle.clone(), cx), + "v" if is_paste_chord(&event.keystroke.modifiers) => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + insert_at_cursor( + &mut self.settings_path_input, + &mut self.settings_path_cursor, + text.trim(), + ); + } + } + _ => { + apply_text_edit( + &mut self.settings_path_input, + &mut self.settings_path_cursor, + event, + ); + } + } + cx.notify(); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index a99b1ef..b3a0ce0 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -727,49 +727,6 @@ impl EchoApp { (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() } - /// Open or close the settings sheet, seeding the folder field from the saved config. - pub(crate) fn toggle_settings(&mut self, cx: &mut Context) { - self.settings_open = !self.settings_open; - self.settings_dropdown = None; - if self.settings_open { - self.settings_path_input = self - .state - .ui - .library_config - .local_music_dir - .as_ref() - .map(|path| path.display().to_string()) - .unwrap_or_default(); - self.settings_path_cursor = self.settings_path_input.len(); - } - cx.notify(); - } - - /// Run a settings control through the `:` registry. Every command the sheet exposes already - /// validates its own input and sets its own status message, so the rows stay declarative. - pub(crate) fn run_setting(&mut self, cmd: String, cx: &mut Context) { - if let Some(event) = echo_core::commands::run(&mut self.state, &cmd) { - self.dispatch(event); - } - cx.notify(); - } - - /// Audio-quality keys have no `:` command, so they write the config directly. They are read - /// when the librespot daemon starts, hence the "next launch" note in the sheet. - pub(crate) fn set_audio_quality( - &mut self, - apply: impl FnOnce(&mut echo_core::config::LibraryConfig), - cx: &mut Context, - ) { - apply(&mut self.state.ui.library_config); - self.state.save_library_config(); - self.state.ui.status_message = - Some(views::tr(&self.state, "desktop.saved_next_launch").to_string()); - self.state.ui.status_message_expiry = - Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); - cx.notify(); - } - /// Ask GitHub whether a newer release exists. /// /// The second exception to the "every setting is a `:` command" rule, alongside @@ -991,75 +948,6 @@ impl EchoApp { .detach(); } - /// True when the folder field holds something other than the saved folder, including when - /// none is saved yet. - pub(crate) fn local_folder_unsaved(&self) -> bool { - let saved = self - .state - .ui - .library_config - .local_music_dir - .as_ref() - .map(|path| path.display().to_string()); - saved.as_deref() != Some(self.settings_path_input.trim()) - } - - /// Enter in the folder field, or its button: save and scan what was typed, or rescan when - /// the field already matches the saved folder. - pub(crate) fn apply_or_rescan_local_folder( - &mut self, - window: &mut Window, - cx: &mut Context, - ) { - if self.local_folder_unsaved() { - let path = self.settings_path_input.trim().to_string(); - if !path.is_empty() { - self.run_setting(format!("localpath {path}"), cx); - // Show the folder as saved: `~` expanded, and the button back to rescan. - if let Some(saved) = &self.state.ui.library_config.local_music_dir - && echo_core::commands::expand_home(&path) == *saved - { - self.settings_path_input = saved.display().to_string(); - self.settings_path_cursor = self.settings_path_input.len(); - } - } - } else { - self.run_setting("rescanlocal".to_string(), cx); - } - window.focus(&self.focus_handle.clone(), cx); - cx.notify(); - } - - /// Typing in the settings sheet's local-folder field. Enter submits it as `:localpath`. - fn handle_settings_path_key( - &mut self, - event: &gpui::KeyDownEvent, - window: &mut Window, - cx: &mut Context, - ) { - match event.keystroke.key.as_str() { - "enter" => self.apply_or_rescan_local_folder(window, cx), - "escape" => window.focus(&self.focus_handle.clone(), cx), - "v" if is_paste_chord(&event.keystroke.modifiers) => { - if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - insert_at_cursor( - &mut self.settings_path_input, - &mut self.settings_path_cursor, - text.trim(), - ); - } - } - _ => { - apply_text_edit( - &mut self.settings_path_input, - &mut self.settings_path_cursor, - event, - ); - } - } - cx.notify(); - } - /// Apply a sort from the picker by running the matching `:sort` command, so picker behavior /// cannot drift from the command. pub(crate) fn apply_sort(&mut self, arg: &str, cx: &mut Context) { From 8e7a30d75e7f86e3dec64fb8cf21e67c8775c77d Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:34 -0500 Subject: [PATCH 30/44] desktop: move the update flow into app/updates.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/updates.rs | 224 +++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 221 ------------------------ 3 files changed, 225 insertions(+), 221 deletions(-) create mode 100644 crates/echo-desktop/src/app/updates.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 10812a0..a2e0be7 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -8,3 +8,4 @@ mod panels; mod selection; mod settings; mod themes; +mod updates; diff --git a/crates/echo-desktop/src/app/updates.rs b/crates/echo-desktop/src/app/updates.rs new file mode 100644 index 0000000..068e3cc --- /dev/null +++ b/crates/echo-desktop/src/app/updates.rs @@ -0,0 +1,224 @@ +use super::*; + +impl EchoApp { + /// Ask GitHub whether a newer release exists. + /// + /// The second exception to the "every setting is a `:` command" rule, alongside + /// [`Self::set_audio_quality`]: `commands::execute` is synchronous and returns an + /// `Option`, which cannot express an in-flight network call. + pub(crate) fn check_for_updates(&mut self, cx: &mut Context) { + self.start_update_check(false, cx); + } + + pub(crate) fn maybe_auto_update(&mut self, cx: &mut Context) { + use echo_core::update::{self, AutoStep, AutoUpdateInputs}; + let now = std::time::Instant::now(); + match update::auto_step(AutoUpdateInputs { + dev_build: update::is_dev_build(), + enabled: self.state.ui.library_config.auto_update, + startup_elapsed: now.duration_since(self.started_at) + >= update::AUTO_CHECK_STARTUP_DELAY, + due: update::auto_check_due(self.last_auto_check, now, update::AUTO_CHECK_INTERVAL), + busy: matches!( + self.update_state, + UpdateState::Checking | UpdateState::Downloading(_) + ), + available: matches!(self.update_state, UpdateState::Available(_)), + pending: self.auto_update_pending, + installed: self.auto_update_installed, + ready: matches!(self.update_state, UpdateState::Ready(_)), + }) { + AutoStep::Check => { + self.last_auto_check = Some(now); + self.start_update_check(true, cx); + } + AutoStep::Install => self.install_update(cx), + AutoStep::Skip | AutoStep::Notify => {} + } + } + + fn finish_update_operation(&mut self) { + if self.auto_update_pending { + match &self.update_state { + UpdateState::Failed(error) | UpdateState::Blocked(error) => { + use std::io::Write; + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(echo_core::config::debug_log_path("echo-debug-update.log")) + { + let _ = writeln!(file, "{}", error.replace(['\r', '\n'], " ")); + } + } + UpdateState::Ready(_) => self.auto_update_installed = true, + _ => {} + } + if !matches!(self.update_state, UpdateState::Available(_)) { + self.auto_update_pending = false; + } + } + if matches!(self.update_state, UpdateState::Ready(_)) { + self.update_banner_dismissed = false; + } + } + + pub(crate) fn restart_updated(&mut self, cx: &mut Context) { + if self.restarting { + return; + } + self.restarting = true; + let executable = self.launch_executable.clone(); + let shell = cx.global_mut::(); + let task = shell.instance_task.take(); + let tray_tx = shell.tray_tx.clone(); + let (tx, rx) = tokio::sync::oneshot::channel(); + self.tokio.spawn(async move { + if let Some(task) = task { + task.abort(); + let _ = task.await; + } + let result = executable + .ok_or_else(|| std::io::Error::other("Executable path unavailable")) + .and_then(|exe| { + std::process::Command::new(exe) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .map(|_| ()) + }); + let listener = if result.is_err() { + match single_instance::claim(&echo_core::config::echo_config_root()) { + single_instance::Instance::Primary(Some(listener)) => { + Some(listener.serve(tray_tx)) + } + _ => None, + } + } else { + None + }; + let _ = tx.send((result, listener)); + }); + cx.spawn(async move |this, cx| { + if let Ok((result, listener)) = rx.await { + let _ = this.update(cx, |app, cx| { + if result.is_ok() { + cx.quit(); + } else { + cx.global_mut::().instance_task = listener; + app.restarting = false; + app.state.ui.status_message = Some( + views::tr(&app.state, "desktop.settings.updates.restart_failed") + .to_string(), + ); + app.state.ui.status_message_expiry = + Some(std::time::Instant::now() + Duration::from_secs(5)); + cx.notify(); + } + }); + } + }) + .detach(); + } + + fn start_update_check(&mut self, automatic: bool, cx: &mut Context) { + if matches!( + self.update_state, + UpdateState::Checking | UpdateState::Downloading(_) + ) { + return; + } + self.auto_update_pending = automatic; + self.update_state = UpdateState::Checking; + cx.notify(); + + // reqwest needs the tokio reactor, so the request runs on the runtime; the result comes + // back over a oneshot, which is reactor-free and therefore safe to await on GPUI's + // foreground executor (the same reasoning as the worker-event bridge above). + let (tx, rx) = tokio::sync::oneshot::channel(); + self.tokio.spawn(async move { + let _ = tx.send(echo_core::update::check().await); + }); + + cx.spawn(async move |this, cx| { + let outcome = rx.await; + let _ = this.update(cx, |app: &mut EchoApp, cx| { + app.update_state = match outcome { + Ok(Ok(echo_core::update::Check::UpToDate)) => UpdateState::UpToDate, + Ok(Ok(echo_core::update::Check::Available(release))) => { + UpdateState::Available(release) + } + Ok(Err(error)) => UpdateState::from_error(error), + Err(_) => UpdateState::Failed( + views::tr(&app.state, "desktop.settings.updates.failed").to_string(), + ), + }; + app.finish_update_operation(); + if app.auto_update_pending { + app.maybe_auto_update(cx); + } + cx.notify(); + }); + }) + .detach(); + } + + /// Download the release found by [`Self::check_for_updates`] and swap it in. + pub(crate) fn install_update(&mut self, cx: &mut Context) { + let UpdateState::Available(release) = self.update_state.clone() else { + return; + }; + // Resolved before the download so a read-only install fails immediately. + let plan = match echo_core::update::plan() { + Ok(plan) => plan, + Err(error) => { + self.update_state = UpdateState::from_error(error); + self.finish_update_operation(); + cx.notify(); + return; + } + }; + + self.update_state = UpdateState::Downloading(0); + cx.notify(); + + let (progress_tx, mut progress_rx) = tokio::sync::mpsc::unbounded_channel(); + let (done_tx, done_rx) = tokio::sync::oneshot::channel(); + self.tokio.spawn(async move { + let staged = echo_core::update::download(plan, &release, move |percent| { + let _ = progress_tx.send(percent); + }) + .await; + // The swap is blocking filesystem work, but it is a handful of renames — keeping it + // on the runtime rather than the UI thread is enough. + let _ = done_tx.send(staged.and_then(echo_core::update::apply)); + }); + + cx.spawn(async move |this, cx| { + // The progress sender is dropped when the download future completes, which ends + // this loop and lets the outcome through. + while let Some(percent) = progress_rx.recv().await { + let applied = this.update(cx, |app: &mut EchoApp, cx| { + app.update_state = UpdateState::Downloading(percent); + cx.notify(); + }); + if applied.is_err() { + return; // entity dropped — app is shutting down + } + } + let outcome = done_rx.await; + let _ = this.update(cx, |app: &mut EchoApp, cx| { + app.update_state = match outcome { + Ok(Ok(version)) => UpdateState::Ready(version), + Ok(Err(error)) => UpdateState::from_error(error), + Err(_) => UpdateState::Failed( + views::tr(&app.state, "desktop.settings.updates.failed").to_string(), + ), + }; + app.finish_update_operation(); + cx.notify(); + }); + }) + .detach(); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index b3a0ce0..4735c44 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -727,227 +727,6 @@ impl EchoApp { (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() } - /// Ask GitHub whether a newer release exists. - /// - /// The second exception to the "every setting is a `:` command" rule, alongside - /// [`Self::set_audio_quality`]: `commands::execute` is synchronous and returns an - /// `Option`, which cannot express an in-flight network call. - pub(crate) fn check_for_updates(&mut self, cx: &mut Context) { - self.start_update_check(false, cx); - } - - fn maybe_auto_update(&mut self, cx: &mut Context) { - use echo_core::update::{self, AutoStep, AutoUpdateInputs}; - let now = std::time::Instant::now(); - match update::auto_step(AutoUpdateInputs { - dev_build: update::is_dev_build(), - enabled: self.state.ui.library_config.auto_update, - startup_elapsed: now.duration_since(self.started_at) - >= update::AUTO_CHECK_STARTUP_DELAY, - due: update::auto_check_due(self.last_auto_check, now, update::AUTO_CHECK_INTERVAL), - busy: matches!( - self.update_state, - UpdateState::Checking | UpdateState::Downloading(_) - ), - available: matches!(self.update_state, UpdateState::Available(_)), - pending: self.auto_update_pending, - installed: self.auto_update_installed, - ready: matches!(self.update_state, UpdateState::Ready(_)), - }) { - AutoStep::Check => { - self.last_auto_check = Some(now); - self.start_update_check(true, cx); - } - AutoStep::Install => self.install_update(cx), - AutoStep::Skip | AutoStep::Notify => {} - } - } - - fn finish_update_operation(&mut self) { - if self.auto_update_pending { - match &self.update_state { - UpdateState::Failed(error) | UpdateState::Blocked(error) => { - use std::io::Write; - if let Ok(mut file) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(echo_core::config::debug_log_path("echo-debug-update.log")) - { - let _ = writeln!(file, "{}", error.replace(['\r', '\n'], " ")); - } - } - UpdateState::Ready(_) => self.auto_update_installed = true, - _ => {} - } - if !matches!(self.update_state, UpdateState::Available(_)) { - self.auto_update_pending = false; - } - } - if matches!(self.update_state, UpdateState::Ready(_)) { - self.update_banner_dismissed = false; - } - } - - fn restart_updated(&mut self, cx: &mut Context) { - if self.restarting { - return; - } - self.restarting = true; - let executable = self.launch_executable.clone(); - let shell = cx.global_mut::(); - let task = shell.instance_task.take(); - let tray_tx = shell.tray_tx.clone(); - let (tx, rx) = tokio::sync::oneshot::channel(); - self.tokio.spawn(async move { - if let Some(task) = task { - task.abort(); - let _ = task.await; - } - let result = executable - .ok_or_else(|| std::io::Error::other("Executable path unavailable")) - .and_then(|exe| { - std::process::Command::new(exe) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .map(|_| ()) - }); - let listener = if result.is_err() { - match single_instance::claim(&echo_core::config::echo_config_root()) { - single_instance::Instance::Primary(Some(listener)) => { - Some(listener.serve(tray_tx)) - } - _ => None, - } - } else { - None - }; - let _ = tx.send((result, listener)); - }); - cx.spawn(async move |this, cx| { - if let Ok((result, listener)) = rx.await { - let _ = this.update(cx, |app, cx| { - if result.is_ok() { - cx.quit(); - } else { - cx.global_mut::().instance_task = listener; - app.restarting = false; - app.state.ui.status_message = Some( - views::tr(&app.state, "desktop.settings.updates.restart_failed") - .to_string(), - ); - app.state.ui.status_message_expiry = - Some(std::time::Instant::now() + Duration::from_secs(5)); - cx.notify(); - } - }); - } - }) - .detach(); - } - - fn start_update_check(&mut self, automatic: bool, cx: &mut Context) { - if matches!( - self.update_state, - UpdateState::Checking | UpdateState::Downloading(_) - ) { - return; - } - self.auto_update_pending = automatic; - self.update_state = UpdateState::Checking; - cx.notify(); - - // reqwest needs the tokio reactor, so the request runs on the runtime; the result comes - // back over a oneshot, which is reactor-free and therefore safe to await on GPUI's - // foreground executor (the same reasoning as the worker-event bridge above). - let (tx, rx) = tokio::sync::oneshot::channel(); - self.tokio.spawn(async move { - let _ = tx.send(echo_core::update::check().await); - }); - - cx.spawn(async move |this, cx| { - let outcome = rx.await; - let _ = this.update(cx, |app: &mut EchoApp, cx| { - app.update_state = match outcome { - Ok(Ok(echo_core::update::Check::UpToDate)) => UpdateState::UpToDate, - Ok(Ok(echo_core::update::Check::Available(release))) => { - UpdateState::Available(release) - } - Ok(Err(error)) => UpdateState::from_error(error), - Err(_) => UpdateState::Failed( - views::tr(&app.state, "desktop.settings.updates.failed").to_string(), - ), - }; - app.finish_update_operation(); - if app.auto_update_pending { - app.maybe_auto_update(cx); - } - cx.notify(); - }); - }) - .detach(); - } - - /// Download the release found by [`Self::check_for_updates`] and swap it in. - pub(crate) fn install_update(&mut self, cx: &mut Context) { - let UpdateState::Available(release) = self.update_state.clone() else { - return; - }; - // Resolved before the download so a read-only install fails immediately. - let plan = match echo_core::update::plan() { - Ok(plan) => plan, - Err(error) => { - self.update_state = UpdateState::from_error(error); - self.finish_update_operation(); - cx.notify(); - return; - } - }; - - self.update_state = UpdateState::Downloading(0); - cx.notify(); - - let (progress_tx, mut progress_rx) = tokio::sync::mpsc::unbounded_channel(); - let (done_tx, done_rx) = tokio::sync::oneshot::channel(); - self.tokio.spawn(async move { - let staged = echo_core::update::download(plan, &release, move |percent| { - let _ = progress_tx.send(percent); - }) - .await; - // The swap is blocking filesystem work, but it is a handful of renames — keeping it - // on the runtime rather than the UI thread is enough. - let _ = done_tx.send(staged.and_then(echo_core::update::apply)); - }); - - cx.spawn(async move |this, cx| { - // The progress sender is dropped when the download future completes, which ends - // this loop and lets the outcome through. - while let Some(percent) = progress_rx.recv().await { - let applied = this.update(cx, |app: &mut EchoApp, cx| { - app.update_state = UpdateState::Downloading(percent); - cx.notify(); - }); - if applied.is_err() { - return; // entity dropped — app is shutting down - } - } - let outcome = done_rx.await; - let _ = this.update(cx, |app: &mut EchoApp, cx| { - app.update_state = match outcome { - Ok(Ok(version)) => UpdateState::Ready(version), - Ok(Err(error)) => UpdateState::from_error(error), - Err(_) => UpdateState::Failed( - views::tr(&app.state, "desktop.settings.updates.failed").to_string(), - ), - }; - app.finish_update_operation(); - cx.notify(); - }); - }) - .detach(); - } - /// Apply a sort from the picker by running the matching `:sort` command, so picker behavior /// cannot drift from the command. pub(crate) fn apply_sort(&mut self, arg: &str, cx: &mut Context) { From 0b6cb2f2e5935f660ef71958ce7c9dfd5ec761f3 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:35 -0500 Subject: [PATCH 31/44] desktop: move the command bar, filter and text-entry key handling into app/command.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/command.rs | 332 +++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 324 ------------------------ 3 files changed, 333 insertions(+), 324 deletions(-) create mode 100644 crates/echo-desktop/src/app/command.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index a2e0be7..35d13e5 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -2,6 +2,7 @@ use super::*; +mod command; mod menus; mod navigation; mod panels; diff --git a/crates/echo-desktop/src/app/command.rs b/crates/echo-desktop/src/app/command.rs new file mode 100644 index 0000000..dd1ff79 --- /dev/null +++ b/crates/echo-desktop/src/app/command.rs @@ -0,0 +1,332 @@ +use super::*; + +impl EchoApp { + /// Apply a sort from the picker by running the matching `:sort` command, so picker behavior + /// cannot drift from the command. + pub(crate) fn apply_sort(&mut self, arg: &str, cx: &mut Context) { + self.sort_menu_open = false; + if let Some(event) = echo_core::commands::run(&mut self.state, &format!("sort {arg}")) { + self.dispatch(event); + } + cx.notify(); + } + + /// Consume the pending vim count, defaulting to a single step. + pub(crate) fn take_count(&mut self) -> isize { + self.pending_count.take().unwrap_or(1).max(1) as isize + } + + pub(crate) fn open_command( + &mut self, + prefill: &str, + window: &mut Window, + cx: &mut Context, + ) { + echo_core::commands::clear_suggestions(&mut self.state); + self.state.ui.mode = AppMode::Command; + self.state.ui.command_buffer = prefill.to_string(); + self.state.ui.status_message = None; + window.focus(&self.command_focus.clone(), cx); + cx.notify(); + } + + pub(crate) fn open_filter(&mut self, window: &mut Window, cx: &mut Context) { + self.state.ui.mode = AppMode::Search; + self.state.ui.search_query.clear(); + self.state.ui.search_matches.clear(); + self.state.ui.status_message = None; + window.focus(&self.command_focus.clone(), cx); + cx.notify(); + } + + /// `e` in the sidebar: prefill `:rename` with the selected playlist/folder name. + pub(crate) fn rename_prompt(&mut self, window: &mut Window, cx: &mut Context) { + if self.state.ui.active_view != ActiveView::Library { + return; + } + let Some(node) = self + .state + .data + .library_view + .get(self.state.ui.selected_playlist_index) + else { + return; + }; + let name = match node { + echo_core::models::LibraryNode::Playlist { playlist, .. } => playlist.name.clone(), + echo_core::models::LibraryNode::Folder(f) => f.name.clone(), + // Spotify's folders keep the name Spotify gives them. + echo_core::models::LibraryNode::SpotifyFolder { .. } => return, + }; + self.open_command(&format!("rename {name}"), window, cx); + } + + fn handle_command_key( + &mut self, + event: &gpui::KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + match event.keystroke.key.as_str() { + "enter" => { + if let Some(event) = echo_core::commands::submit(&mut self.state) { + self.dispatch(event); + } + window.focus(&self.focus_handle.clone(), cx); + // `:q` and friends land here. + if !self.state.ui.is_running { + cx.quit(); + } + } + "escape" => { + echo_core::commands::clear_suggestions(&mut self.state); + self.state.ui.mode = AppMode::Normal; + self.state.ui.command_buffer.clear(); + window.focus(&self.focus_handle.clone(), cx); + } + "tab" => { + echo_core::commands::cycle_suggestion( + &mut self.state, + !event.keystroke.modifiers.shift, + ); + } + "backspace" => { + echo_core::commands::clear_suggestions(&mut self.state); + self.state.ui.command_buffer.pop(); + } + "v" if is_paste_chord(&event.keystroke.modifiers) => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + echo_core::commands::clear_suggestions(&mut self.state); + self.state + .ui + .command_buffer + .extend(text.chars().filter(|c| *c != '\r' && *c != '\n')); + } + } + _ => { + if let Some(text) = event.keystroke.key_char.as_deref() { + echo_core::commands::clear_suggestions(&mut self.state); + self.state.ui.command_buffer.push_str(text); + } + } + } + cx.notify(); + } + + fn handle_filter_key( + &mut self, + event: &gpui::KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + match event.keystroke.key.as_str() { + "enter" => { + self.state.ui.mode = AppMode::Normal; + if !self.state.ui.search_matches.is_empty() { + self.state.ui.selected_track_index = self.state.ui.search_matches[0]; + self.scroll_to_selected_track(); + } + window.focus(&self.focus_handle.clone(), cx); + } + "escape" => { + self.state.ui.mode = AppMode::Normal; + self.state.ui.search_query.clear(); + self.state.ui.search_matches.clear(); + window.focus(&self.focus_handle.clone(), cx); + } + "backspace" => { + self.state.ui.search_query.pop(); + echo_core::intent::update_search_matches(&mut self.state); + self.scroll_to_selected_track(); + } + "v" if is_paste_chord(&event.keystroke.modifiers) => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + self.state + .ui + .search_query + .extend(text.chars().filter(|c| *c != '\r' && *c != '\n')); + echo_core::intent::update_search_matches(&mut self.state); + self.scroll_to_selected_track(); + } + } + _ => { + if let Some(text) = event.keystroke.key_char.as_deref() { + self.state.ui.search_query.push_str(text); + echo_core::intent::update_search_matches(&mut self.state); + self.scroll_to_selected_track(); + } + } + } + cx.notify(); + } + + /// The `:`/`/` bar. Rendered only while one of the two modes is active; carries the + /// search key context so plain letters type instead of triggering list bindings. + pub(crate) fn render_command_bar(&mut self, cx: &mut Context) -> impl IntoElement { + let theme = &self.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + let is_command = self.state.ui.mode == AppMode::Command; + let prefix: SharedString = if is_command { ":" } else { "/" }.into(); + let buffer = if is_command { + self.state.ui.command_buffer.clone() + } else { + self.state.ui.search_query.clone() + }; + let suggestions = self.state.ui.command_suggestions.clone(); + let selected_suggestion = self.state.ui.command_suggestion_index; + let match_hint: Option = (!is_command + && !self.state.ui.search_query.is_empty()) + .then(|| format!("{} matches", self.state.ui.search_matches.len()).into()); + + div() + .id("command-bar") + .key_context(SEARCH_CONTEXT) + .track_focus(&self.command_focus) + .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { + if this.state.ui.mode == AppMode::Command { + this.handle_command_key(event, window, cx); + } else { + this.handle_filter_key(event, window, cx); + } + })) + .flex_none() + .flex() + .flex_col() + .gap_1() + .px_4() + .py_1() + .border_t_1() + .border_color(palette.border) + .when(is_command && !suggestions.is_empty(), |el| { + el.child( + div().flex().flex_row().gap_2().overflow_hidden().children( + suggestions + .into_iter() + .enumerate() + .map(|(index, suggestion)| { + let selected = selected_suggestion == Some(index); + div() + .px_2() + .rounded_sm() + .text_xs() + .map(|el| { + if selected { + el.bg(palette.row_selected).text_color(fg) + } else { + el.text_color(muted) + } + }) + .child(SharedString::from(suggestion)) + }), + ), + ) + }) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_1() + .child(div().text_sm().text_color(accent).child(prefix)) + .child( + div() + .text_sm() + .text_color(fg) + .child(SharedString::from(format!("{buffer}▏"))), + ) + .when_some(match_hint, |el, hint| { + el.child(div().flex_grow(1.0)) + .child(div().text_xs().text_color(muted).child(hint)) + }), + ) + } + + /// Typing for the two setup fields. Credentials are pasted more often than typed, so + /// ctrl-v pulls from the clipboard (with whitespace stripped). + pub(crate) fn handle_setup_key( + &mut self, + secret: bool, + event: &gpui::KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + let field = if secret { + &mut self.state.ui.setup_client_secret + } else { + &mut self.state.ui.setup_client_id + }; + match event.keystroke.key.as_str() { + "enter" => { + if let Some(event) = echo_core::intent::submit_setup_credentials(&mut self.state) { + self.dispatch(event); + } + } + "tab" => { + let target = if secret { + self.setup_id_focus.clone() + } else { + self.setup_secret_focus.clone() + }; + window.focus(&target, cx); + } + "escape" => window.focus(&self.focus_handle.clone(), cx), + "backspace" => { + field.pop(); + } + "v" if is_paste_chord(&event.keystroke.modifiers) => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + field.extend(text.chars().filter(|c| !c.is_whitespace())); + } + } + _ => { + if let Some(text) = event.keystroke.key_char.as_deref() { + field.push_str(text); + } + } + } + cx.notify(); + } + + /// Enter/escape and typing for the search box, which owns key handling while focused. + pub(crate) fn handle_search_key( + &mut self, + event: &gpui::KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + match event.keystroke.key.as_str() { + "enter" => { + let query = self.search_input.clone(); + if let Some(event) = echo_core::intent::global_search(&mut self.state, &query) { + self.dispatch(event); + } + window.focus(&self.focus_handle, cx); + } + "escape" => { + if self.search_input.is_empty() { + window.focus(&self.focus_handle, cx); + } else { + self.search_input.clear(); + self.search_cursor = 0; + } + } + // Spaces are kept — unlike the credential fields, a query is words — but newlines + // are dropped so a copied line does not smuggle one into the search term. + "v" if is_paste_chord(&event.keystroke.modifiers) => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + let filtered: String = + text.chars().filter(|c| *c != '\r' && *c != '\n').collect(); + insert_at_cursor(&mut self.search_input, &mut self.search_cursor, &filtered); + } + } + _ => { + apply_text_edit(&mut self.search_input, &mut self.search_cursor, event); + } + } + cx.notify(); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 4735c44..9422864 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -727,164 +727,10 @@ impl EchoApp { (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() } - /// Apply a sort from the picker by running the matching `:sort` command, so picker behavior - /// cannot drift from the command. - pub(crate) fn apply_sort(&mut self, arg: &str, cx: &mut Context) { - self.sort_menu_open = false; - if let Some(event) = echo_core::commands::run(&mut self.state, &format!("sort {arg}")) { - self.dispatch(event); - } - cx.notify(); - } - - /// Consume the pending vim count, defaulting to a single step. - fn take_count(&mut self) -> isize { - self.pending_count.take().unwrap_or(1).max(1) as isize - } - // Vim-style command mode (`:`) and track filter (`/`) — a bar above the playback bar that // owns key handling while one of the modes is active. The command registry itself lives in // `echo_core::commands`. - fn open_command(&mut self, prefill: &str, window: &mut Window, cx: &mut Context) { - echo_core::commands::clear_suggestions(&mut self.state); - self.state.ui.mode = AppMode::Command; - self.state.ui.command_buffer = prefill.to_string(); - self.state.ui.status_message = None; - window.focus(&self.command_focus.clone(), cx); - cx.notify(); - } - - fn open_filter(&mut self, window: &mut Window, cx: &mut Context) { - self.state.ui.mode = AppMode::Search; - self.state.ui.search_query.clear(); - self.state.ui.search_matches.clear(); - self.state.ui.status_message = None; - window.focus(&self.command_focus.clone(), cx); - cx.notify(); - } - - /// `e` in the sidebar: prefill `:rename` with the selected playlist/folder name. - fn rename_prompt(&mut self, window: &mut Window, cx: &mut Context) { - if self.state.ui.active_view != ActiveView::Library { - return; - } - let Some(node) = self - .state - .data - .library_view - .get(self.state.ui.selected_playlist_index) - else { - return; - }; - let name = match node { - echo_core::models::LibraryNode::Playlist { playlist, .. } => playlist.name.clone(), - echo_core::models::LibraryNode::Folder(f) => f.name.clone(), - // Spotify's folders keep the name Spotify gives them. - echo_core::models::LibraryNode::SpotifyFolder { .. } => return, - }; - self.open_command(&format!("rename {name}"), window, cx); - } - - fn handle_command_key( - &mut self, - event: &gpui::KeyDownEvent, - window: &mut Window, - cx: &mut Context, - ) { - match event.keystroke.key.as_str() { - "enter" => { - if let Some(event) = echo_core::commands::submit(&mut self.state) { - self.dispatch(event); - } - window.focus(&self.focus_handle.clone(), cx); - // `:q` and friends land here. - if !self.state.ui.is_running { - cx.quit(); - } - } - "escape" => { - echo_core::commands::clear_suggestions(&mut self.state); - self.state.ui.mode = AppMode::Normal; - self.state.ui.command_buffer.clear(); - window.focus(&self.focus_handle.clone(), cx); - } - "tab" => { - echo_core::commands::cycle_suggestion( - &mut self.state, - !event.keystroke.modifiers.shift, - ); - } - "backspace" => { - echo_core::commands::clear_suggestions(&mut self.state); - self.state.ui.command_buffer.pop(); - } - "v" if is_paste_chord(&event.keystroke.modifiers) => { - if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - echo_core::commands::clear_suggestions(&mut self.state); - self.state - .ui - .command_buffer - .extend(text.chars().filter(|c| *c != '\r' && *c != '\n')); - } - } - _ => { - if let Some(text) = event.keystroke.key_char.as_deref() { - echo_core::commands::clear_suggestions(&mut self.state); - self.state.ui.command_buffer.push_str(text); - } - } - } - cx.notify(); - } - - fn handle_filter_key( - &mut self, - event: &gpui::KeyDownEvent, - window: &mut Window, - cx: &mut Context, - ) { - match event.keystroke.key.as_str() { - "enter" => { - self.state.ui.mode = AppMode::Normal; - if !self.state.ui.search_matches.is_empty() { - self.state.ui.selected_track_index = self.state.ui.search_matches[0]; - self.scroll_to_selected_track(); - } - window.focus(&self.focus_handle.clone(), cx); - } - "escape" => { - self.state.ui.mode = AppMode::Normal; - self.state.ui.search_query.clear(); - self.state.ui.search_matches.clear(); - window.focus(&self.focus_handle.clone(), cx); - } - "backspace" => { - self.state.ui.search_query.pop(); - echo_core::intent::update_search_matches(&mut self.state); - self.scroll_to_selected_track(); - } - "v" if is_paste_chord(&event.keystroke.modifiers) => { - if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - self.state - .ui - .search_query - .extend(text.chars().filter(|c| *c != '\r' && *c != '\n')); - echo_core::intent::update_search_matches(&mut self.state); - self.scroll_to_selected_track(); - } - } - _ => { - if let Some(text) = event.keystroke.key_char.as_deref() { - self.state.ui.search_query.push_str(text); - echo_core::intent::update_search_matches(&mut self.state); - self.scroll_to_selected_track(); - } - } - } - cx.notify(); - } - fn add_to_queue(&mut self, cx: &mut Context) { // In visual mode `q` queues the whole range. if self.multi_selected() { @@ -927,176 +773,6 @@ impl EchoApp { cx.notify(); } - /// The `:`/`/` bar. Rendered only while one of the two modes is active; carries the - /// search key context so plain letters type instead of triggering list bindings. - fn render_command_bar(&mut self, cx: &mut Context) -> impl IntoElement { - let theme = &self.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let is_command = self.state.ui.mode == AppMode::Command; - let prefix: SharedString = if is_command { ":" } else { "/" }.into(); - let buffer = if is_command { - self.state.ui.command_buffer.clone() - } else { - self.state.ui.search_query.clone() - }; - let suggestions = self.state.ui.command_suggestions.clone(); - let selected_suggestion = self.state.ui.command_suggestion_index; - let match_hint: Option = (!is_command - && !self.state.ui.search_query.is_empty()) - .then(|| format!("{} matches", self.state.ui.search_matches.len()).into()); - - div() - .id("command-bar") - .key_context(SEARCH_CONTEXT) - .track_focus(&self.command_focus) - .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { - if this.state.ui.mode == AppMode::Command { - this.handle_command_key(event, window, cx); - } else { - this.handle_filter_key(event, window, cx); - } - })) - .flex_none() - .flex() - .flex_col() - .gap_1() - .px_4() - .py_1() - .border_t_1() - .border_color(palette.border) - .when(is_command && !suggestions.is_empty(), |el| { - el.child( - div().flex().flex_row().gap_2().overflow_hidden().children( - suggestions - .into_iter() - .enumerate() - .map(|(index, suggestion)| { - let selected = selected_suggestion == Some(index); - div() - .px_2() - .rounded_sm() - .text_xs() - .map(|el| { - if selected { - el.bg(palette.row_selected).text_color(fg) - } else { - el.text_color(muted) - } - }) - .child(SharedString::from(suggestion)) - }), - ), - ) - }) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap_1() - .child(div().text_sm().text_color(accent).child(prefix)) - .child( - div() - .text_sm() - .text_color(fg) - .child(SharedString::from(format!("{buffer}▏"))), - ) - .when_some(match_hint, |el, hint| { - el.child(div().flex_grow(1.0)) - .child(div().text_xs().text_color(muted).child(hint)) - }), - ) - } - - /// Typing for the two setup fields. Credentials are pasted more often than typed, so - /// ctrl-v pulls from the clipboard (with whitespace stripped). - fn handle_setup_key( - &mut self, - secret: bool, - event: &gpui::KeyDownEvent, - window: &mut Window, - cx: &mut Context, - ) { - let field = if secret { - &mut self.state.ui.setup_client_secret - } else { - &mut self.state.ui.setup_client_id - }; - match event.keystroke.key.as_str() { - "enter" => { - if let Some(event) = echo_core::intent::submit_setup_credentials(&mut self.state) { - self.dispatch(event); - } - } - "tab" => { - let target = if secret { - self.setup_id_focus.clone() - } else { - self.setup_secret_focus.clone() - }; - window.focus(&target, cx); - } - "escape" => window.focus(&self.focus_handle.clone(), cx), - "backspace" => { - field.pop(); - } - "v" if is_paste_chord(&event.keystroke.modifiers) => { - if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - field.extend(text.chars().filter(|c| !c.is_whitespace())); - } - } - _ => { - if let Some(text) = event.keystroke.key_char.as_deref() { - field.push_str(text); - } - } - } - cx.notify(); - } - - /// Enter/escape and typing for the search box, which owns key handling while focused. - fn handle_search_key( - &mut self, - event: &gpui::KeyDownEvent, - window: &mut Window, - cx: &mut Context, - ) { - match event.keystroke.key.as_str() { - "enter" => { - let query = self.search_input.clone(); - if let Some(event) = echo_core::intent::global_search(&mut self.state, &query) { - self.dispatch(event); - } - window.focus(&self.focus_handle, cx); - } - "escape" => { - if self.search_input.is_empty() { - window.focus(&self.focus_handle, cx); - } else { - self.search_input.clear(); - self.search_cursor = 0; - } - } - // Spaces are kept — unlike the credential fields, a query is words — but newlines - // are dropped so a copied line does not smuggle one into the search term. - "v" if is_paste_chord(&event.keystroke.modifiers) => { - if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - let filtered: String = - text.chars().filter(|c| *c != '\r' && *c != '\n').collect(); - insert_at_cursor(&mut self.search_input, &mut self.search_cursor, &filtered); - } - } - _ => { - apply_text_edit(&mut self.search_input, &mut self.search_cursor, event); - } - } - cx.notify(); - } - // Transport, all via the shared intents (optimistic flip + worker event). fn toggle_playback(&mut self, cx: &mut Context) { From ae6f4605df77551b89bc2bf6b5dcadf6c99a7f38 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:25:37 -0500 Subject: [PATCH 32/44] desktop: move playback controls and scrubbing into app/playback.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/playback.rs | 220 ++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 217 ----------------------- 3 files changed, 221 insertions(+), 217 deletions(-) create mode 100644 crates/echo-desktop/src/app/playback.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 35d13e5..98e13b6 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -6,6 +6,7 @@ mod command; mod menus; mod navigation; mod panels; +mod playback; mod selection; mod settings; mod themes; diff --git a/crates/echo-desktop/src/app/playback.rs b/crates/echo-desktop/src/app/playback.rs new file mode 100644 index 0000000..a2ab016 --- /dev/null +++ b/crates/echo-desktop/src/app/playback.rs @@ -0,0 +1,220 @@ +use super::*; + +impl EchoApp { + /// Redraws only what shows the playback position or the volume: the playback bar, the + /// lyrics panel, and the immersive view, which is drawn by the app itself. + pub(crate) fn notify_playback_position(&mut self, cx: &mut Context) { + if self.immersive { + cx.notify(); + return; + } + self.regions.notify(regions::Region::PlaybackBar, cx); + if self.right_panel == Some(RightPanel::Lyrics) { + self.regions.notify(regions::Region::RightPanel, cx); + } + } + + /// The phase, in `0..1`, to draw the playing row's bars at. Calling this from a render + /// keeps the track list repainting every [`PLAYING_BARS_FRAME`] for as long as renders keep + /// calling it. + pub(crate) fn animate_playing_bars(&self, cx: &mut Context) -> f32 { + if self.playing_bars.replace(PlayingBars::Drawn) == PlayingBars::Hidden { + cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(PLAYING_BARS_FRAME).await; + let keep_going = this.update(cx, |app, cx| match app.playing_bars.get() { + PlayingBars::Drawn => { + app.playing_bars.set(PlayingBars::Stale); + app.regions.notify(regions::Region::Main, cx); + true + } + PlayingBars::Stale | PlayingBars::Hidden => { + app.playing_bars.set(PlayingBars::Hidden); + false + } + }); + if !matches!(keep_going, Ok(true)) { + break; + } + } + }) + .detach(); + } + let elapsed = self.started_at.elapsed().as_secs_f32(); + (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() + } + + pub(crate) fn add_to_queue(&mut self, cx: &mut Context) { + // In visual mode `q` queues the whole range. + if self.multi_selected() { + if let Some(event) = echo_core::intent::queue_visual_selection(&mut self.state) { + self.dispatch(event); + } + cx.notify(); + return; + } + if let Some(event) = echo_core::intent::queue_selected_track(&self.state) { + self.dispatch(event); + self.state.ui.status_message = + Some(views::tr(&self.state, "desktop.added_to_queue").to_string()); + self.state.ui.status_message_expiry = + Some(std::time::Instant::now() + Duration::from_secs(3)); + } + cx.notify(); + } + + pub(crate) fn toggle_pin(&mut self, cx: &mut Context) { + if self.theme_modal_open { + // `m` is the mode key while the theme picker is up. + self.cycle_theme_mode(cx); + return; + } + echo_core::intent::toggle_pin_selected(&mut self.state); + cx.notify(); + } + + pub(crate) fn adjust_volume(&mut self, delta: i32, cx: &mut Context) { + let event = echo_core::intent::adjust_volume(&mut self.state, delta); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn seek_start(&mut self, cx: &mut Context) { + if let Some(event) = echo_core::intent::seek_to(&mut self.state, 0) { + self.dispatch(event); + } + cx.notify(); + } + + pub(crate) fn toggle_playback(&mut self, cx: &mut Context) { + let event = echo_core::intent::toggle_playback(&mut self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn play_next(&mut self, cx: &mut Context) { + let event = echo_core::intent::next_track(&mut self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn play_previous(&mut self, cx: &mut Context) { + let event = echo_core::intent::previous_track(&self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn toggle_shuffle(&mut self, cx: &mut Context) { + if self.state.ui.duplicate_prompt.is_some() { + if let Some(event) = echo_core::intent::confirm_duplicate_skip(&mut self.state) { + self.dispatch(event); + } + cx.notify(); + return; + } + let event = echo_core::intent::toggle_shuffle(&mut self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn cycle_repeat(&mut self, cx: &mut Context) { + let event = echo_core::intent::cycle_repeat(&mut self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn toggle_mute(&mut self, cx: &mut Context) { + let event = echo_core::intent::toggle_mute(&mut self.state); + self.dispatch(event); + cx.notify(); + } + + pub(crate) fn seek_relative(&mut self, seconds: i64, cx: &mut Context) { + if let Some(event) = echo_core::intent::seek_by(&mut self.state, seconds) { + self.dispatch(event); + } + cx.notify(); + } + + fn seek_to_fraction(&mut self, fraction: f32, cx: &mut Context) { + let target = (self.state.playback.duration_ms as f32 * fraction.clamp(0.0, 1.0)) as u32; + if let Some(event) = echo_core::intent::seek_to(&mut self.state, target) { + self.dispatch(event); + } + cx.notify(); + } + + fn set_volume_fraction(&mut self, fraction: f32, cx: &mut Context) { + let volume = (fraction.clamp(0.0, 1.0) * 100.0).round() as u8; + let event = echo_core::intent::set_volume(&mut self.state, volume); + self.dispatch(event); + cx.notify(); + } + + fn scrub_bounds(&self, target: Scrub) -> Bounds { + match target { + Scrub::Seek => self.seek_bounds.get(), + Scrub::Volume => self.volume_bounds.get(), + } + } + + pub(crate) fn begin_scrub(&mut self, target: Scrub, x: Pixels, cx: &mut Context) { + self.scrubbing = Some(target); + self.update_scrub(x, cx); + } + + pub(crate) fn update_scrub(&mut self, x: Pixels, cx: &mut Context) { + let Some(target) = self.scrubbing else { return }; + let bounds = self.scrub_bounds(target); + if bounds.size.width <= px(0.0) { + return; + } + let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); + match target { + Scrub::Seek => { + if self.state.playback.duration_ms > 0 + && self.state.playback.playing_track_id.is_some() + { + let target_ms = (self.state.playback.duration_ms as f32 * fraction) as u32; + self.state.playback.set_optimistic_progress(target_ms); + } + } + Scrub::Volume => { + self.state.playback.volume = (fraction * 100.0).round() as u32; + } + } + self.notify_playback_position(cx); + } + + pub(crate) fn finish_scrub(&mut self, x: Pixels, cx: &mut Context) { + let Some(target) = self.scrubbing.take() else { + return; + }; + let bounds = self.scrub_bounds(target); + if bounds.size.width <= px(0.0) { + cx.notify(); + return; + } + let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); + match target { + Scrub::Seek => self.seek_to_fraction(fraction, cx), + Scrub::Volume => self.set_volume_fraction(fraction, cx), + } + } + + pub(crate) fn begin_shelf_scrub(&mut self, scroll: gpui::ScrollHandle, x: Pixels) { + self.shelf_scrub = Some(scroll); + self.update_shelf_scrub(x); + } + + /// Scrolls the dragged shelf so the thumb follows the pointer's fraction of the bar (the + /// bar spans the shelf row's width). + pub(crate) fn update_shelf_scrub(&mut self, x: Pixels) { + let Some(scroll) = self.shelf_scrub.as_ref() else { + return; + }; + let bounds = scroll.bounds(); + let fraction = ((x - bounds.left()) / bounds.size.width.max(px(1.0))).clamp(0.0, 1.0); + scroll.set_offset(gpui::point(-scroll.max_offset().x * fraction, px(0.0))); + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 9422864..fe95451 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -684,232 +684,15 @@ impl EchoApp { // The add-to-playlist flyout. The track menu's "Add to playlist" row opens a second panel // beside it rather than the full-screen picker `a` uses, so the choice stays in one gesture. - /// Redraws only what shows the playback position or the volume: the playback bar, the - /// lyrics panel, and the immersive view, which is drawn by the app itself. - fn notify_playback_position(&mut self, cx: &mut Context) { - if self.immersive { - cx.notify(); - return; - } - self.regions.notify(regions::Region::PlaybackBar, cx); - if self.right_panel == Some(RightPanel::Lyrics) { - self.regions.notify(regions::Region::RightPanel, cx); - } - } - - /// The phase, in `0..1`, to draw the playing row's bars at. Calling this from a render - /// keeps the track list repainting every [`PLAYING_BARS_FRAME`] for as long as renders keep - /// calling it. - pub(crate) fn animate_playing_bars(&self, cx: &mut Context) -> f32 { - if self.playing_bars.replace(PlayingBars::Drawn) == PlayingBars::Hidden { - cx.spawn(async move |this, cx| { - loop { - cx.background_executor().timer(PLAYING_BARS_FRAME).await; - let keep_going = this.update(cx, |app, cx| match app.playing_bars.get() { - PlayingBars::Drawn => { - app.playing_bars.set(PlayingBars::Stale); - app.regions.notify(regions::Region::Main, cx); - true - } - PlayingBars::Stale | PlayingBars::Hidden => { - app.playing_bars.set(PlayingBars::Hidden); - false - } - }); - if !matches!(keep_going, Ok(true)) { - break; - } - } - }) - .detach(); - } - let elapsed = self.started_at.elapsed().as_secs_f32(); - (elapsed / PLAYING_BARS_LOOP.as_secs_f32()).fract() - } - // Vim-style command mode (`:`) and track filter (`/`) — a bar above the playback bar that // owns key handling while one of the modes is active. The command registry itself lives in // `echo_core::commands`. - fn add_to_queue(&mut self, cx: &mut Context) { - // In visual mode `q` queues the whole range. - if self.multi_selected() { - if let Some(event) = echo_core::intent::queue_visual_selection(&mut self.state) { - self.dispatch(event); - } - cx.notify(); - return; - } - if let Some(event) = echo_core::intent::queue_selected_track(&self.state) { - self.dispatch(event); - self.state.ui.status_message = - Some(views::tr(&self.state, "desktop.added_to_queue").to_string()); - self.state.ui.status_message_expiry = - Some(std::time::Instant::now() + Duration::from_secs(3)); - } - cx.notify(); - } - - fn toggle_pin(&mut self, cx: &mut Context) { - if self.theme_modal_open { - // `m` is the mode key while the theme picker is up. - self.cycle_theme_mode(cx); - return; - } - echo_core::intent::toggle_pin_selected(&mut self.state); - cx.notify(); - } - - fn adjust_volume(&mut self, delta: i32, cx: &mut Context) { - let event = echo_core::intent::adjust_volume(&mut self.state, delta); - self.dispatch(event); - cx.notify(); - } - - fn seek_start(&mut self, cx: &mut Context) { - if let Some(event) = echo_core::intent::seek_to(&mut self.state, 0) { - self.dispatch(event); - } - cx.notify(); - } - // Transport, all via the shared intents (optimistic flip + worker event). - fn toggle_playback(&mut self, cx: &mut Context) { - let event = echo_core::intent::toggle_playback(&mut self.state); - self.dispatch(event); - cx.notify(); - } - - fn play_next(&mut self, cx: &mut Context) { - let event = echo_core::intent::next_track(&mut self.state); - self.dispatch(event); - cx.notify(); - } - - fn play_previous(&mut self, cx: &mut Context) { - let event = echo_core::intent::previous_track(&self.state); - self.dispatch(event); - cx.notify(); - } - - fn toggle_shuffle(&mut self, cx: &mut Context) { - if self.state.ui.duplicate_prompt.is_some() { - if let Some(event) = echo_core::intent::confirm_duplicate_skip(&mut self.state) { - self.dispatch(event); - } - cx.notify(); - return; - } - let event = echo_core::intent::toggle_shuffle(&mut self.state); - self.dispatch(event); - cx.notify(); - } - - fn cycle_repeat(&mut self, cx: &mut Context) { - let event = echo_core::intent::cycle_repeat(&mut self.state); - self.dispatch(event); - cx.notify(); - } - - fn toggle_mute(&mut self, cx: &mut Context) { - let event = echo_core::intent::toggle_mute(&mut self.state); - self.dispatch(event); - cx.notify(); - } - - fn seek_relative(&mut self, seconds: i64, cx: &mut Context) { - if let Some(event) = echo_core::intent::seek_by(&mut self.state, seconds) { - self.dispatch(event); - } - cx.notify(); - } - - fn seek_to_fraction(&mut self, fraction: f32, cx: &mut Context) { - let target = (self.state.playback.duration_ms as f32 * fraction.clamp(0.0, 1.0)) as u32; - if let Some(event) = echo_core::intent::seek_to(&mut self.state, target) { - self.dispatch(event); - } - cx.notify(); - } - - fn set_volume_fraction(&mut self, fraction: f32, cx: &mut Context) { - let volume = (fraction.clamp(0.0, 1.0) * 100.0).round() as u8; - let event = echo_core::intent::set_volume(&mut self.state, volume); - self.dispatch(event); - cx.notify(); - } - // Drag-to-scrub: mouse-down on a bar starts it, window-level mouse-move updates the state // optimistically for live feedback, and release fires the worker event once. - fn scrub_bounds(&self, target: Scrub) -> Bounds { - match target { - Scrub::Seek => self.seek_bounds.get(), - Scrub::Volume => self.volume_bounds.get(), - } - } - - fn begin_scrub(&mut self, target: Scrub, x: Pixels, cx: &mut Context) { - self.scrubbing = Some(target); - self.update_scrub(x, cx); - } - - fn update_scrub(&mut self, x: Pixels, cx: &mut Context) { - let Some(target) = self.scrubbing else { return }; - let bounds = self.scrub_bounds(target); - if bounds.size.width <= px(0.0) { - return; - } - let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); - match target { - Scrub::Seek => { - if self.state.playback.duration_ms > 0 - && self.state.playback.playing_track_id.is_some() - { - let target_ms = (self.state.playback.duration_ms as f32 * fraction) as u32; - self.state.playback.set_optimistic_progress(target_ms); - } - } - Scrub::Volume => { - self.state.playback.volume = (fraction * 100.0).round() as u32; - } - } - self.notify_playback_position(cx); - } - - fn finish_scrub(&mut self, x: Pixels, cx: &mut Context) { - let Some(target) = self.scrubbing.take() else { - return; - }; - let bounds = self.scrub_bounds(target); - if bounds.size.width <= px(0.0) { - cx.notify(); - return; - } - let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); - match target { - Scrub::Seek => self.seek_to_fraction(fraction, cx), - Scrub::Volume => self.set_volume_fraction(fraction, cx), - } - } - - pub(crate) fn begin_shelf_scrub(&mut self, scroll: gpui::ScrollHandle, x: Pixels) { - self.shelf_scrub = Some(scroll); - self.update_shelf_scrub(x); - } - - /// Scrolls the dragged shelf so the thumb follows the pointer's fraction of the bar (the - /// bar spans the shelf row's width). - fn update_shelf_scrub(&mut self, x: Pixels) { - let Some(scroll) = self.shelf_scrub.as_ref() else { - return; - }; - let bounds = scroll.bounds(); - let fraction = ((x - bounds.left()) / bounds.size.width.max(px(1.0))).clamp(0.0, 1.0); - scroll.set_offset(gpui::point(-scroll.max_offset().x * fraction, px(0.0))); - } - // Both docks track drags at window level and persist only on release. The right dock's // left edge moves in the opposite direction to the library's right edge. From c1fa329efc4c9fe1ebd0f44ea732c4ad043411b6 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:26:00 -0500 Subject: [PATCH 33/44] desktop: move the drag-scroll, playing-bars and paste-chord definitions next to their only users Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app/playback.rs | 7 +++++++ crates/echo-desktop/src/app/selection.rs | 6 ++++++ crates/echo-desktop/src/main.rs | 21 --------------------- crates/echo-desktop/src/text_input.rs | 10 ++++++++++ 4 files changed, 23 insertions(+), 21 deletions(-) diff --git a/crates/echo-desktop/src/app/playback.rs b/crates/echo-desktop/src/app/playback.rs index a2ab016..8cba765 100644 --- a/crates/echo-desktop/src/app/playback.rs +++ b/crates/echo-desktop/src/app/playback.rs @@ -1,5 +1,12 @@ use super::*; +/// One bounce of the playing row's bars. +pub(crate) const PLAYING_BARS_LOOP: Duration = Duration::from_millis(900); + +/// How often the bars repaint. Every frame re-renders the track list, so this stays well +/// under the display's refresh rate. +pub(crate) const PLAYING_BARS_FRAME: Duration = Duration::from_millis(33); + impl EchoApp { /// Redraws only what shows the playback position or the volume: the playback bar, the /// lyrics panel, and the immersive view, which is drawn by the app itself. diff --git a/crates/echo-desktop/src/app/selection.rs b/crates/echo-desktop/src/app/selection.rs index 24cc316..bdefdb5 100644 --- a/crates/echo-desktop/src/app/selection.rs +++ b/crates/echo-desktop/src/app/selection.rs @@ -1,5 +1,11 @@ use super::*; +/// How close to a list edge, in pixels, a drag starts scrolling it. +pub(crate) const DRAG_EDGE: f32 = 48.0; + +/// Pixels per frame at the very edge. +pub(crate) const DRAG_SCROLL_MAX: f32 = 14.0; + impl EchoApp { /// Rows in whatever currently has keyboard focus: the device modal when open, else the /// `active_view` list. diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index fe95451..778cfdd 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -333,16 +333,6 @@ fn mac_menus() -> Vec { ] } -/// Whether a keystroke's modifiers mean "paste" for the hand-rolled text fields. -/// -/// `Modifiers::secondary` is cmd on macOS and ctrl elsewhere; a Mac that only matched `control` -/// ignored cmd-v, which made the setup card — the first thing a new install shows, and a place -/// where credentials are pasted rather than typed — impossible to paste into. ctrl-v is still -/// accepted everywhere as an alternative shortcut. -fn is_paste_chord(modifiers: &gpui::Modifiers) -> bool { - modifiers.secondary() || modifiers.control -} - /// The animation of the playing row's bars. A render that draws them moves this to `Drawn` /// and each tick of the animation's task moves it one step back, so the task ends itself one /// tick after the row leaves the screen. @@ -356,12 +346,6 @@ enum PlayingBars { Stale, } -/// One bounce of the playing row's bars. -const PLAYING_BARS_LOOP: Duration = Duration::from_millis(900); -/// How often the bars repaint. Every frame re-renders the track list, so this stays well -/// under the display's refresh rate. -const PLAYING_BARS_FRAME: Duration = Duration::from_millis(33); - /// The lists a drag can scroll by hovering near their edges. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum DragList { @@ -369,11 +353,6 @@ pub(crate) enum DragList { Library, } -/// How close to a list edge, in pixels, a drag starts scrolling it. -const DRAG_EDGE: f32 = 48.0; -/// Pixels per frame at the very edge. -const DRAG_SCROLL_MAX: f32 = 14.0; - /// Picks a fixed-pitch family that is actually installed. gpui matches families by exact name /// against the system font database — there is no generic "monospace" alias and no substitution /// when the name misses, so naming one font hard-codes a platform: "Consolas" is Windows-only, diff --git a/crates/echo-desktop/src/text_input.rs b/crates/echo-desktop/src/text_input.rs index 5ae97d5..e74daca 100644 --- a/crates/echo-desktop/src/text_input.rs +++ b/crates/echo-desktop/src/text_input.rs @@ -84,6 +84,16 @@ pub(crate) fn text_with_cursor(value: &str, cursor: usize) -> String { format!("{}▏{}", &value[..cursor], &value[cursor..]) } +/// Whether a keystroke's modifiers mean "paste" for the hand-rolled text fields. +/// +/// `Modifiers::secondary` is cmd on macOS and ctrl elsewhere; a Mac that only matched `control` +/// ignored cmd-v, which made the setup card — the first thing a new install shows, and a place +/// where credentials are pasted rather than typed — impossible to paste into. ctrl-v is still +/// accepted everywhere as an alternative shortcut. +pub(crate) fn is_paste_chord(modifiers: &gpui::Modifiers) -> bool { + modifiers.secondary() || modifiers.control +} + #[cfg(test)] mod text_edit_tests { use super::{insert_at_cursor, next_char_boundary, prev_char_boundary, text_with_cursor}; From b526d2fbb5086f6758dbe66cc56c9a23e2e8bba4 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:26:17 -0500 Subject: [PATCH 34/44] desktop: move the window's render into app/render.rs Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app.rs | 1 + crates/echo-desktop/src/app/render.rs | 479 ++++++++++++++++++++++++++ crates/echo-desktop/src/main.rs | 478 ------------------------- 3 files changed, 480 insertions(+), 478 deletions(-) create mode 100644 crates/echo-desktop/src/app/render.rs diff --git a/crates/echo-desktop/src/app.rs b/crates/echo-desktop/src/app.rs index 98e13b6..627127f 100644 --- a/crates/echo-desktop/src/app.rs +++ b/crates/echo-desktop/src/app.rs @@ -7,6 +7,7 @@ mod menus; mod navigation; mod panels; mod playback; +mod render; mod selection; mod settings; mod themes; diff --git a/crates/echo-desktop/src/app/render.rs b/crates/echo-desktop/src/app/render.rs new file mode 100644 index 0000000..7bff2c4 --- /dev/null +++ b/crates/echo-desktop/src/app/render.rs @@ -0,0 +1,479 @@ +use super::*; + +impl Render for EchoApp { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // Every theme change re-renders the app, so this is the one place that catches them + // all (startup, the theme picker, a hot-reloaded theme file). + self.dock_icon.sync(&self.state.ui.active_theme, cx); + let theme = &self.state.ui.active_theme; + let bg = theme.background.gpui(WINDOW_BG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + + // Built ahead of the chain because they borrow self mutably, like the other views. + let command_bar = matches!(self.state.ui.mode, AppMode::Command | AppMode::Search) + .then(|| self.render_command_bar(cx).into_any_element()); + // Visual mode says so on the status line: without a mode indicator a range selection + // looks like the list has simply highlighted several rows for no reason. + let status_line = match self.state.ui.mode { + AppMode::Visual => Some( + self.state + .ui + .status_message + .clone() + .map(|message| format!("-- VISUAL -- {message}")) + .unwrap_or_else(|| { + format!( + "-- VISUAL -- {}", + views::tr(&self.state, "desktop.visual_hint") + ) + }), + ), + AppMode::Normal => self.state.ui.status_message.clone(), + _ => None, + } + .map(|message| { + div() + .flex_none() + .px_4() + .py_1() + .text_xs() + .text_color(muted) + .child(SharedString::from(message)) + .into_any_element() + }); + // The audio-device failure banner is persistent (no expiry) and separate from the + // status line, so transient statuses can't hide it. Core clears it on recovery. + let audio_banner = self.state.ui.audio_output_error.clone().map(|message| { + let error = self.state.ui.active_theme.error.gpui(WINDOW_FG()); + let banner_bg = DesktopPalette::resolve(&self.state.ui.active_theme).error_wash; + div() + .flex_none() + .px_4() + .py_1() + .text_xs() + .bg(banner_bg) + .text_color(error) + .child(SharedString::from(message)) + .into_any_element() + }); + let update_banner = match &self.update_state { + UpdateState::Ready(version) if !self.update_banner_dismissed => { + let palette = DesktopPalette::resolve(&self.state.ui.active_theme); + let text = views::tr(&self.state, "desktop.settings.updates.installed") + .replace("{}", version); + Some( + div() + .flex_none() + .flex() + .items_center() + .gap_3() + .px_4() + .py_2() + .bg(palette.wash) + .border_t_1() + .border_color(palette.border) + .text_sm() + .child(div().flex_1().child(text)) + .child( + div() + .id("restart-update") + .px_3() + .py_1() + .rounded_md() + .border_1() + .border_color(palette.border) + .cursor_pointer() + .hover(move |s| s.bg(palette.row_hover)) + .on_click(cx.listener(|this, _, _, cx| this.restart_updated(cx))) + .child(views::tr( + &self.state, + "desktop.settings.updates.restart_now", + )), + ) + .child( + div() + .id("dismiss-update") + .cursor_pointer() + .on_click(cx.listener(|this, _, _, cx| { + this.update_banner_dismissed = true; + cx.notify(); + })) + .child(views::tr(&self.state, "desktop.settings.updates.later")), + ) + .into_any_element(), + ) + } + _ => None, + }; + let theme_modal = self + .theme_modal_open + .then(|| views::theme_modal(self, cx).into_any_element()); + let device_modal = self + .state + .ui + .device_modal_open + .then(|| views::device_modal(self, cx).into_any_element()); + let sort_menu = self + .sort_menu_open + .then(|| views::sort_menu(self, cx).into_any_element()); + let settings_modal = self + .settings_open + .then(|| views::settings_modal(self, window, cx).into_any_element()); + let help_modal = self + .help_open + .then(|| views::help_modal(self, cx).into_any_element()); + let context_menu = self + .context_menu + .is_some() + .then(|| views::context_menu(self, window, cx).into_any_element()); + if self.track_menu.is_none() { + self.track_menu_scroll.scroll_to_item(0); + } + let track_menu = self + .track_menu + .is_some() + .then(|| views::track_context_menu(self, window, cx).into_any_element()); + let playlist_add_modal = self + .state + .ui + .playlist_add_modal_open + .then(|| views::playlist_add_modal(self, cx).into_any_element()); + let prompt_modal = echo_core::intent::prompt_active(&self.state) + .then(|| views::prompt_modal(self, cx).into_any_element()); + let frame_palette = crate::theme::DesktopPalette::resolve(&self.state.ui.active_theme); + // Resolved before the chain so the style closure below borrows this rather than `window`. + let corners = views::client_corners(window); + // Windows and macOS hide the native bar (`appears_transparent`) and always want ours. + // Linux only gets it when the app actually owns the frame: the `Client` decorations + // requested at open are downgraded to `Server` on an X11 session with no compositor, and + // there the window manager draws a real titlebar that ours would sit underneath. + let owns_frame = !cfg!(target_os = "linux") || corners.is_some(); + // The immersive backdrop while that view is up: its colors replace the theme's for the + // window fill and the titlebar, and its picture goes under everything. + let backdrop = self.immersive.then(|| { + let playback = &self.state.playback; + let cover = playback + .playing_track_image + .as_ref() + .or(playback.previous_track_image.as_ref()); + let fallback = backdrop::theme_palette(&self.state.ui.active_theme); + let mode = self.state.ui.library_config.immersive_backdrop; + let backdrop = self.backdrops.get(mode, cover, &fallback); + if let Some(build) = self.backdrops.take_build() { + cx.spawn(async move |this, cx| { + let built = cx.background_spawn(async move { build.run() }).await; + this.update(cx, |app: &mut EchoApp, cx| { + app.backdrops.install(built); + cx.notify(); + }) + .ok(); + }) + .detach(); + } + self.backdrops.release(|image| { + window.drop_image(image).ok(); + }); + backdrop + }); + let phase = if cx.reduce_motion() { + 0.0 + } else { + self.backdrops.phase() + }; + let titlebar = owns_frame.then(|| { + views::titlebar(self, backdrop.as_ref().map(|b| &b.colors), window, cx) + .into_any_element() + }); + + let root = div() + .key_context(if self.playlist_input_open() { + "list search" + } else { + LIST_CONTEXT + }) + .track_focus(&self.focus_handle) + // Scrubs track the pointer at the window level so dragging keeps working when the + // pointer leaves the bar; release (or a move without the button) ends them. + .on_mouse_move( + cx.listener(|this, event: &gpui::MouseMoveEvent, window, cx| { + if this.panel_resizing.is_some() { + if event.pressed_button == Some(gpui::MouseButton::Left) { + this.update_panel_resize(event.position.x, window, cx); + } else { + this.finish_panel_resize(cx); + } + } + if this.scrubbing.is_some() { + if event.pressed_button == Some(gpui::MouseButton::Left) { + this.update_scrub(event.position.x, cx); + } else { + this.finish_scrub(event.position.x, cx); + } + } + if this.shelf_scrub.is_some() { + if event.pressed_button == Some(gpui::MouseButton::Left) { + this.update_shelf_scrub(event.position.x); + } else { + this.shelf_scrub = None; + } + cx.notify(); + } + }), + ) + .on_mouse_up( + gpui::MouseButton::Left, + cx.listener(|this, event: &gpui::MouseUpEvent, _window, cx| { + this.finish_panel_resize(cx); + this.finish_scrub(event.position.x, cx); + this.shelf_scrub = None; + }), + ) + .on_action( + cx.listener(|this, _: &TogglePlayback, _window, cx| this.toggle_playback(cx)), + ) + .on_action(cx.listener(|this, _: &MoveUp, _window, cx| { + let count = this.take_count(); + this.move_selection(-count, cx) + })) + .on_action(cx.listener(|this, _: &MoveDown, _window, cx| { + let count = this.take_count(); + this.move_selection(count, cx) + })) + .on_action( + cx.listener(|this, _: &PageUp, _window, cx| this.move_selection(-PAGE_ROWS, cx)), + ) + .on_action( + cx.listener(|this, _: &PageDown, _window, cx| this.move_selection(PAGE_ROWS, cx)), + ) + // Takes precedence over the app-level `Quit` handler registered in `main`, which + // cannot see the window, so the ctrl-q binding remembers the window rectangle the + // way the platform's own close request does. The Linux caption button's close + // dispatches `CloseWindow` instead: the same tray-or-quit decision as that request. + .on_action(cx.listener(|this, _: &Quit, window, cx| { + this.persist_window_bounds(window); + cx.quit(); + })) + .on_action(cx.listener(|this, _: &CloseWindow, window, cx| { + if this.on_close_request(window, cx) { + window.remove_window(); + } + })) + // The macOS Window menu's two entries. Handled here rather than app-wide because + // both need the window; `Hide`/`HideOthers`/`ShowAll` do not, so those stay in + // `main` alongside the menu itself. + .on_action(cx.listener(|_, _: &MinimizeWindow, window, _cx| window.minimize_window())) + .on_action(cx.listener(|_, _: &ZoomWindow, window, _cx| window.zoom_window())) + .on_action(cx.listener(|this, _: &SelectFirst, _window, cx| this.set_selection(0, cx))) + .on_action(cx.listener(|this, _: &SelectLast, _window, cx| this.select_last(cx))) + .on_action(cx.listener(|this, _: &Activate, _window, cx| this.activate_selection(cx))) + .on_action(cx.listener(|this, _: &ConfirmPrompt, _window, cx| this.confirm_prompt(cx))) + .on_action(cx.listener(|this, _: &AddToPlaylist, _window, cx| this.add_to_playlist(cx))) + .on_action( + cx.listener(|this, _: &OpenActionMenu, _window, cx| this.open_action_menu(cx)), + ) + .on_action( + cx.listener(|this, _: &ToggleSettings, _window, cx| this.toggle_settings(cx)), + ) + .on_action(cx.listener(|this, _: &ToggleHelp, _window, cx| { + this.help_open = !this.help_open; + cx.notify(); + })) + .on_action(cx.listener(|this, _: &MarkDelete, _window, cx| { + this.pending_count = None; + if this.multi_selected() { + echo_core::intent::delete_visual_selection(&mut this.state); + } else { + echo_core::intent::mark_selected_for_delete(&mut this.state); + } + cx.notify(); + })) + .on_action(cx.listener(|this, _: &EnterVisual, _window, cx| this.toggle_visual(cx))) + .on_action(cx.listener(|this, _: &MoveTrackUp, _window, cx| { + let count = this.take_count(); + this.move_selected_track(-count, cx) + })) + .on_action(cx.listener(|this, _: &MoveTrackDown, _window, cx| { + let count = this.take_count(); + this.move_selected_track(count, cx) + })) + .on_action(cx.listener(|this, _: &ToggleLike, _window, cx| this.toggle_like(cx))) + .on_action(cx.listener(|this, _: &FocusLibrary, _window, cx| this.focus_library(cx))) + .on_action(cx.listener(|this, _: &FocusTracks, _window, cx| this.focus_tracks(cx))) + .on_action(cx.listener(|this, _: &ToggleSidebar, _window, cx| this.toggle_sidebar(cx))) + .on_action(cx.listener(|this, _: &HistoryBack, _window, cx| { + // Global binding, so keep the view still while an overlay is on top. + if !this.overlay_open() { + this.history_back(cx); + } + })) + .on_action(cx.listener(|this, _: &HistoryForward, _window, cx| { + if !this.overlay_open() { + this.history_forward(cx); + } + })) + .on_action(cx.listener(|this, _: &NextTrack, _window, cx| this.play_next(cx))) + .on_action(cx.listener(|this, _: &PreviousTrack, _window, cx| this.play_previous(cx))) + .on_action(cx.listener(|this, _: &ToggleShuffle, _window, cx| this.toggle_shuffle(cx))) + .on_action(cx.listener(|this, _: &CycleRepeat, _window, cx| this.cycle_repeat(cx))) + .on_action(cx.listener(|this, _: &ToggleMute, _window, cx| this.toggle_mute(cx))) + .on_action(cx.listener(|this, _: &SeekForward, _window, cx| this.seek_relative(5, cx))) + .on_action( + cx.listener(|this, _: &SeekBackward, _window, cx| this.seek_relative(-5, cx)), + ) + .on_action(cx.listener(|this, _: &ToggleQueue, _window, cx| this.toggle_queue_view(cx))) + .on_action(cx.listener(|this, _: &OpenDevices, _window, cx| this.open_devices(cx))) + .on_action(cx.listener(|this, _: &Dismiss, _window, cx| this.dismiss(cx))) + .on_action(cx.listener(|this, _: &FocusSearch, window, cx| { + window.focus(&this.search_focus, cx); + cx.notify(); + })) + .on_action(cx.listener(|this, _: &ToggleLyrics, _window, cx| this.toggle_lyrics(cx))) + .on_action(cx.listener(|this, _: &ToggleThemes, _window, cx| this.toggle_themes(cx))) + .on_action( + cx.listener(|this, _: &ToggleImmersive, _window, cx| this.toggle_immersive(cx)), + ) + .on_action(cx.listener(|this, _: &HalfPageUp, _window, cx| { + this.move_selection(-PAGE_ROWS / 2, cx) + })) + .on_action(cx.listener(|this, _: &HalfPageDown, _window, cx| { + this.move_selection(PAGE_ROWS / 2, cx) + })) + // `0` extends a pending count (`10j`); bare `0` keeps its seek-to-start role. + .on_action(cx.listener(|this, _: &SeekStart, _window, cx| { + if let Some(count) = this.pending_count { + this.pending_count = Some(count.saturating_mul(10).min(9999)); + cx.notify(); + } else { + this.seek_start(cx) + } + })) + .on_action(cx.listener(|this, _: &VolumeUp, _window, cx| this.adjust_volume(1, cx))) + .on_action(cx.listener(|this, _: &VolumeDown, _window, cx| this.adjust_volume(-1, cx))) + .on_action(cx.listener(|this, _: &VolumeUpBig, _window, cx| this.adjust_volume(5, cx))) + .on_action( + cx.listener(|this, _: &VolumeDownBig, _window, cx| this.adjust_volume(-5, cx)), + ) + .on_action(cx.listener(|this, _: &JumpToCurrent, _window, cx| this.jump_to_current(cx))) + .on_action( + cx.listener(|this, _: &OpenCommand, window, cx| this.open_command("", window, cx)), + ) + .on_action(cx.listener(|this, _: &CommandSearch, window, cx| { + this.open_command("search ", window, cx) + })) + .on_action(cx.listener(|this, _: &NewPlaylistPrompt, window, cx| { + if this.state.ui.active_view == ActiveView::Library { + this.open_command("newplaylist ", window, cx); + } + })) + .on_action( + cx.listener(|this, _: &RenamePrompt, window, cx| this.rename_prompt(window, cx)), + ) + .on_action(cx.listener(|this, _: &AddToQueue, _window, cx| this.add_to_queue(cx))) + .on_action(cx.listener(|this, _: &TogglePin, _window, cx| this.toggle_pin(cx))) + .on_action(cx.listener(|this, _: &CycleTab, _window, cx| this.cycle_tab(cx))) + .on_action(cx.listener(|this, _: &Refresh, _window, cx| this.refresh_view(cx))) + .on_action(cx.listener(|this, _: &OpenHome, window, cx| { + this.open_home(cx); + window.focus(&this.focus_handle, cx); + })) + .on_action(cx.listener(|this, _: &OpenFilter, window, cx| this.open_filter(window, cx))) + .on_action(cx.listener(|this, _: &NextMatch, _window, cx| this.next_match(true, cx))) + .on_action(cx.listener(|this, _: &PrevMatch, _window, cx| this.next_match(false, cx))) + .on_action(cx.listener(|this, _: &ToggleInlineLyrics, _window, cx| { + this.toggle_inline_lyrics(cx) + })) + .on_action(cx.listener(|this, _: &BackOrFocusLibrary, _window, cx| { + this.back_or_focus_library(cx) + })) + // Digits are unbound, so they fall through the key bindings to this listener and + // accumulate a vim-style count for j/k. Only while the list itself has focus — + // digits typed into the search/command inputs must not count. + .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { + if this.handle_playlist_input(event, window, cx) { + return; + } + if !this.focus_handle.is_focused(window) { + return; + } + let keystroke = &event.keystroke; + if keystroke.modifiers.control + || keystroke.modifiers.alt + || keystroke.modifiers.platform + || keystroke.modifiers.shift + { + return; + } + match keystroke.key.as_str() { + digit @ ("1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") => { + let digit = (digit.as_bytes()[0] - b'0') as usize; + let current = this.pending_count.unwrap_or(0); + this.pending_count = + Some(current.saturating_mul(10).saturating_add(digit).min(9999)); + cx.notify(); + } + // Any other unbound key cancels the pending count. + _ => { + if this.pending_count.take().is_some() { + cx.notify(); + } + } + } + })) + .relative() + .flex() + .flex_col() + .size_full() + .bg(backdrop.as_ref().map_or(bg, |b| b.colors.background)) + // The window's backdrop: the one fill covering every corner, so it rounds all four. + .map(|el| views::round_client_corners(el, corners, views::ClientCorners::All)) + .when_some(backdrop.as_ref(), |el, backdrop| { + el.child(views::backdrop_layer(backdrop.clone(), phase, corners)) + }) + .when_some(titlebar, |el, bar| el.child(bar)) + .map(|el| { + if let Some(backdrop) = &backdrop { + el.child(views::immersive_view(self, backdrop, window, cx)) + } else { + el.child( + div() + .flex_grow(1.0) + .flex() + .flex_row() + .overflow_hidden() + .when(!self.sidebar_collapsed, |el| { + el.child(self.regions.sidebar(self.sidebar_width)) + }) + .child(self.regions.main()) + .when(self.right_panel.is_some(), |el| { + let width = self.effective_right_panel_width(window); + el.child(self.regions.right_panel(width)) + }), + ) + .when_some(status_line, |el, line| el.child(line)) + } + }) + .when_some(command_bar, |el, bar| el.child(bar)) + .when_some(audio_banner, |el, banner| el.child(banner)) + .when_some(update_banner, |el, banner| el.child(banner)) + .when(!self.immersive, |el| el.child(self.regions.playback_bar())) + .when_some(theme_modal, |el, modal| el.child(modal)) + .when_some(device_modal, |el, modal| el.child(modal)) + .when_some(playlist_add_modal, |el, modal| el.child(modal)) + .when_some(sort_menu, |el, menu| el.child(menu)) + .when_some(settings_modal, |el, modal| el.child(modal)) + .when_some(help_modal, |el, modal| el.child(modal)) + .when_some(context_menu, |el, menu| el.child(menu)) + .when_some(track_menu, |el, menu| el.child(menu)) + .when_some(prompt_modal, |el, modal| el.child(modal)) + .when(self.page_menu.is_some(), |el| { + el.child(views::playlist_page_menu(self, cx)) + }) + .when(self.state.ui.playlist_edit.is_some(), |el| { + el.child(views::playlist_edit_modal(self, cx)) + }); + + // Adds the border and resize edges when the compositor refuses to draw them; a + // pass-through when it does. + views::window_frame(root, window, frame_palette) + } +} diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index 778cfdd..ff83f0d 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -727,484 +727,6 @@ pub(crate) fn sort_arg(sort: echo_core::app::TrackSort) -> &'static str { } } -impl Render for EchoApp { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - // Every theme change re-renders the app, so this is the one place that catches them - // all (startup, the theme picker, a hot-reloaded theme file). - self.dock_icon.sync(&self.state.ui.active_theme, cx); - let theme = &self.state.ui.active_theme; - let bg = theme.background.gpui(WINDOW_BG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - - // Built ahead of the chain because they borrow self mutably, like the other views. - let command_bar = matches!(self.state.ui.mode, AppMode::Command | AppMode::Search) - .then(|| self.render_command_bar(cx).into_any_element()); - // Visual mode says so on the status line: without a mode indicator a range selection - // looks like the list has simply highlighted several rows for no reason. - let status_line = match self.state.ui.mode { - AppMode::Visual => Some( - self.state - .ui - .status_message - .clone() - .map(|message| format!("-- VISUAL -- {message}")) - .unwrap_or_else(|| { - format!( - "-- VISUAL -- {}", - views::tr(&self.state, "desktop.visual_hint") - ) - }), - ), - AppMode::Normal => self.state.ui.status_message.clone(), - _ => None, - } - .map(|message| { - div() - .flex_none() - .px_4() - .py_1() - .text_xs() - .text_color(muted) - .child(SharedString::from(message)) - .into_any_element() - }); - // The audio-device failure banner is persistent (no expiry) and separate from the - // status line, so transient statuses can't hide it. Core clears it on recovery. - let audio_banner = self.state.ui.audio_output_error.clone().map(|message| { - let error = self.state.ui.active_theme.error.gpui(WINDOW_FG()); - let banner_bg = DesktopPalette::resolve(&self.state.ui.active_theme).error_wash; - div() - .flex_none() - .px_4() - .py_1() - .text_xs() - .bg(banner_bg) - .text_color(error) - .child(SharedString::from(message)) - .into_any_element() - }); - let update_banner = match &self.update_state { - UpdateState::Ready(version) if !self.update_banner_dismissed => { - let palette = DesktopPalette::resolve(&self.state.ui.active_theme); - let text = views::tr(&self.state, "desktop.settings.updates.installed") - .replace("{}", version); - Some( - div() - .flex_none() - .flex() - .items_center() - .gap_3() - .px_4() - .py_2() - .bg(palette.wash) - .border_t_1() - .border_color(palette.border) - .text_sm() - .child(div().flex_1().child(text)) - .child( - div() - .id("restart-update") - .px_3() - .py_1() - .rounded_md() - .border_1() - .border_color(palette.border) - .cursor_pointer() - .hover(move |s| s.bg(palette.row_hover)) - .on_click(cx.listener(|this, _, _, cx| this.restart_updated(cx))) - .child(views::tr( - &self.state, - "desktop.settings.updates.restart_now", - )), - ) - .child( - div() - .id("dismiss-update") - .cursor_pointer() - .on_click(cx.listener(|this, _, _, cx| { - this.update_banner_dismissed = true; - cx.notify(); - })) - .child(views::tr(&self.state, "desktop.settings.updates.later")), - ) - .into_any_element(), - ) - } - _ => None, - }; - let theme_modal = self - .theme_modal_open - .then(|| views::theme_modal(self, cx).into_any_element()); - let device_modal = self - .state - .ui - .device_modal_open - .then(|| views::device_modal(self, cx).into_any_element()); - let sort_menu = self - .sort_menu_open - .then(|| views::sort_menu(self, cx).into_any_element()); - let settings_modal = self - .settings_open - .then(|| views::settings_modal(self, window, cx).into_any_element()); - let help_modal = self - .help_open - .then(|| views::help_modal(self, cx).into_any_element()); - let context_menu = self - .context_menu - .is_some() - .then(|| views::context_menu(self, window, cx).into_any_element()); - if self.track_menu.is_none() { - self.track_menu_scroll.scroll_to_item(0); - } - let track_menu = self - .track_menu - .is_some() - .then(|| views::track_context_menu(self, window, cx).into_any_element()); - let playlist_add_modal = self - .state - .ui - .playlist_add_modal_open - .then(|| views::playlist_add_modal(self, cx).into_any_element()); - let prompt_modal = echo_core::intent::prompt_active(&self.state) - .then(|| views::prompt_modal(self, cx).into_any_element()); - let frame_palette = crate::theme::DesktopPalette::resolve(&self.state.ui.active_theme); - // Resolved before the chain so the style closure below borrows this rather than `window`. - let corners = views::client_corners(window); - // Windows and macOS hide the native bar (`appears_transparent`) and always want ours. - // Linux only gets it when the app actually owns the frame: the `Client` decorations - // requested at open are downgraded to `Server` on an X11 session with no compositor, and - // there the window manager draws a real titlebar that ours would sit underneath. - let owns_frame = !cfg!(target_os = "linux") || corners.is_some(); - // The immersive backdrop while that view is up: its colors replace the theme's for the - // window fill and the titlebar, and its picture goes under everything. - let backdrop = self.immersive.then(|| { - let playback = &self.state.playback; - let cover = playback - .playing_track_image - .as_ref() - .or(playback.previous_track_image.as_ref()); - let fallback = backdrop::theme_palette(&self.state.ui.active_theme); - let mode = self.state.ui.library_config.immersive_backdrop; - let backdrop = self.backdrops.get(mode, cover, &fallback); - if let Some(build) = self.backdrops.take_build() { - cx.spawn(async move |this, cx| { - let built = cx.background_spawn(async move { build.run() }).await; - this.update(cx, |app: &mut EchoApp, cx| { - app.backdrops.install(built); - cx.notify(); - }) - .ok(); - }) - .detach(); - } - self.backdrops.release(|image| { - window.drop_image(image).ok(); - }); - backdrop - }); - let phase = if cx.reduce_motion() { - 0.0 - } else { - self.backdrops.phase() - }; - let titlebar = owns_frame.then(|| { - views::titlebar(self, backdrop.as_ref().map(|b| &b.colors), window, cx) - .into_any_element() - }); - - let root = div() - .key_context(if self.playlist_input_open() { - "list search" - } else { - LIST_CONTEXT - }) - .track_focus(&self.focus_handle) - // Scrubs track the pointer at the window level so dragging keeps working when the - // pointer leaves the bar; release (or a move without the button) ends them. - .on_mouse_move( - cx.listener(|this, event: &gpui::MouseMoveEvent, window, cx| { - if this.panel_resizing.is_some() { - if event.pressed_button == Some(gpui::MouseButton::Left) { - this.update_panel_resize(event.position.x, window, cx); - } else { - this.finish_panel_resize(cx); - } - } - if this.scrubbing.is_some() { - if event.pressed_button == Some(gpui::MouseButton::Left) { - this.update_scrub(event.position.x, cx); - } else { - this.finish_scrub(event.position.x, cx); - } - } - if this.shelf_scrub.is_some() { - if event.pressed_button == Some(gpui::MouseButton::Left) { - this.update_shelf_scrub(event.position.x); - } else { - this.shelf_scrub = None; - } - cx.notify(); - } - }), - ) - .on_mouse_up( - gpui::MouseButton::Left, - cx.listener(|this, event: &gpui::MouseUpEvent, _window, cx| { - this.finish_panel_resize(cx); - this.finish_scrub(event.position.x, cx); - this.shelf_scrub = None; - }), - ) - .on_action( - cx.listener(|this, _: &TogglePlayback, _window, cx| this.toggle_playback(cx)), - ) - .on_action(cx.listener(|this, _: &MoveUp, _window, cx| { - let count = this.take_count(); - this.move_selection(-count, cx) - })) - .on_action(cx.listener(|this, _: &MoveDown, _window, cx| { - let count = this.take_count(); - this.move_selection(count, cx) - })) - .on_action( - cx.listener(|this, _: &PageUp, _window, cx| this.move_selection(-PAGE_ROWS, cx)), - ) - .on_action( - cx.listener(|this, _: &PageDown, _window, cx| this.move_selection(PAGE_ROWS, cx)), - ) - // Takes precedence over the app-level `Quit` handler registered in `main`, which - // cannot see the window, so the ctrl-q binding remembers the window rectangle the - // way the platform's own close request does. The Linux caption button's close - // dispatches `CloseWindow` instead: the same tray-or-quit decision as that request. - .on_action(cx.listener(|this, _: &Quit, window, cx| { - this.persist_window_bounds(window); - cx.quit(); - })) - .on_action(cx.listener(|this, _: &CloseWindow, window, cx| { - if this.on_close_request(window, cx) { - window.remove_window(); - } - })) - // The macOS Window menu's two entries. Handled here rather than app-wide because - // both need the window; `Hide`/`HideOthers`/`ShowAll` do not, so those stay in - // `main` alongside the menu itself. - .on_action(cx.listener(|_, _: &MinimizeWindow, window, _cx| window.minimize_window())) - .on_action(cx.listener(|_, _: &ZoomWindow, window, _cx| window.zoom_window())) - .on_action(cx.listener(|this, _: &SelectFirst, _window, cx| this.set_selection(0, cx))) - .on_action(cx.listener(|this, _: &SelectLast, _window, cx| this.select_last(cx))) - .on_action(cx.listener(|this, _: &Activate, _window, cx| this.activate_selection(cx))) - .on_action(cx.listener(|this, _: &ConfirmPrompt, _window, cx| this.confirm_prompt(cx))) - .on_action(cx.listener(|this, _: &AddToPlaylist, _window, cx| this.add_to_playlist(cx))) - .on_action( - cx.listener(|this, _: &OpenActionMenu, _window, cx| this.open_action_menu(cx)), - ) - .on_action( - cx.listener(|this, _: &ToggleSettings, _window, cx| this.toggle_settings(cx)), - ) - .on_action(cx.listener(|this, _: &ToggleHelp, _window, cx| { - this.help_open = !this.help_open; - cx.notify(); - })) - .on_action(cx.listener(|this, _: &MarkDelete, _window, cx| { - this.pending_count = None; - if this.multi_selected() { - echo_core::intent::delete_visual_selection(&mut this.state); - } else { - echo_core::intent::mark_selected_for_delete(&mut this.state); - } - cx.notify(); - })) - .on_action(cx.listener(|this, _: &EnterVisual, _window, cx| this.toggle_visual(cx))) - .on_action(cx.listener(|this, _: &MoveTrackUp, _window, cx| { - let count = this.take_count(); - this.move_selected_track(-count, cx) - })) - .on_action(cx.listener(|this, _: &MoveTrackDown, _window, cx| { - let count = this.take_count(); - this.move_selected_track(count, cx) - })) - .on_action(cx.listener(|this, _: &ToggleLike, _window, cx| this.toggle_like(cx))) - .on_action(cx.listener(|this, _: &FocusLibrary, _window, cx| this.focus_library(cx))) - .on_action(cx.listener(|this, _: &FocusTracks, _window, cx| this.focus_tracks(cx))) - .on_action(cx.listener(|this, _: &ToggleSidebar, _window, cx| this.toggle_sidebar(cx))) - .on_action(cx.listener(|this, _: &HistoryBack, _window, cx| { - // Global binding, so keep the view still while an overlay is on top. - if !this.overlay_open() { - this.history_back(cx); - } - })) - .on_action(cx.listener(|this, _: &HistoryForward, _window, cx| { - if !this.overlay_open() { - this.history_forward(cx); - } - })) - .on_action(cx.listener(|this, _: &NextTrack, _window, cx| this.play_next(cx))) - .on_action(cx.listener(|this, _: &PreviousTrack, _window, cx| this.play_previous(cx))) - .on_action(cx.listener(|this, _: &ToggleShuffle, _window, cx| this.toggle_shuffle(cx))) - .on_action(cx.listener(|this, _: &CycleRepeat, _window, cx| this.cycle_repeat(cx))) - .on_action(cx.listener(|this, _: &ToggleMute, _window, cx| this.toggle_mute(cx))) - .on_action(cx.listener(|this, _: &SeekForward, _window, cx| this.seek_relative(5, cx))) - .on_action( - cx.listener(|this, _: &SeekBackward, _window, cx| this.seek_relative(-5, cx)), - ) - .on_action(cx.listener(|this, _: &ToggleQueue, _window, cx| this.toggle_queue_view(cx))) - .on_action(cx.listener(|this, _: &OpenDevices, _window, cx| this.open_devices(cx))) - .on_action(cx.listener(|this, _: &Dismiss, _window, cx| this.dismiss(cx))) - .on_action(cx.listener(|this, _: &FocusSearch, window, cx| { - window.focus(&this.search_focus, cx); - cx.notify(); - })) - .on_action(cx.listener(|this, _: &ToggleLyrics, _window, cx| this.toggle_lyrics(cx))) - .on_action(cx.listener(|this, _: &ToggleThemes, _window, cx| this.toggle_themes(cx))) - .on_action( - cx.listener(|this, _: &ToggleImmersive, _window, cx| this.toggle_immersive(cx)), - ) - .on_action(cx.listener(|this, _: &HalfPageUp, _window, cx| { - this.move_selection(-PAGE_ROWS / 2, cx) - })) - .on_action(cx.listener(|this, _: &HalfPageDown, _window, cx| { - this.move_selection(PAGE_ROWS / 2, cx) - })) - // `0` extends a pending count (`10j`); bare `0` keeps its seek-to-start role. - .on_action(cx.listener(|this, _: &SeekStart, _window, cx| { - if let Some(count) = this.pending_count { - this.pending_count = Some(count.saturating_mul(10).min(9999)); - cx.notify(); - } else { - this.seek_start(cx) - } - })) - .on_action(cx.listener(|this, _: &VolumeUp, _window, cx| this.adjust_volume(1, cx))) - .on_action(cx.listener(|this, _: &VolumeDown, _window, cx| this.adjust_volume(-1, cx))) - .on_action(cx.listener(|this, _: &VolumeUpBig, _window, cx| this.adjust_volume(5, cx))) - .on_action( - cx.listener(|this, _: &VolumeDownBig, _window, cx| this.adjust_volume(-5, cx)), - ) - .on_action(cx.listener(|this, _: &JumpToCurrent, _window, cx| this.jump_to_current(cx))) - .on_action( - cx.listener(|this, _: &OpenCommand, window, cx| this.open_command("", window, cx)), - ) - .on_action(cx.listener(|this, _: &CommandSearch, window, cx| { - this.open_command("search ", window, cx) - })) - .on_action(cx.listener(|this, _: &NewPlaylistPrompt, window, cx| { - if this.state.ui.active_view == ActiveView::Library { - this.open_command("newplaylist ", window, cx); - } - })) - .on_action( - cx.listener(|this, _: &RenamePrompt, window, cx| this.rename_prompt(window, cx)), - ) - .on_action(cx.listener(|this, _: &AddToQueue, _window, cx| this.add_to_queue(cx))) - .on_action(cx.listener(|this, _: &TogglePin, _window, cx| this.toggle_pin(cx))) - .on_action(cx.listener(|this, _: &CycleTab, _window, cx| this.cycle_tab(cx))) - .on_action(cx.listener(|this, _: &Refresh, _window, cx| this.refresh_view(cx))) - .on_action(cx.listener(|this, _: &OpenHome, window, cx| { - this.open_home(cx); - window.focus(&this.focus_handle, cx); - })) - .on_action(cx.listener(|this, _: &OpenFilter, window, cx| this.open_filter(window, cx))) - .on_action(cx.listener(|this, _: &NextMatch, _window, cx| this.next_match(true, cx))) - .on_action(cx.listener(|this, _: &PrevMatch, _window, cx| this.next_match(false, cx))) - .on_action(cx.listener(|this, _: &ToggleInlineLyrics, _window, cx| { - this.toggle_inline_lyrics(cx) - })) - .on_action(cx.listener(|this, _: &BackOrFocusLibrary, _window, cx| { - this.back_or_focus_library(cx) - })) - // Digits are unbound, so they fall through the key bindings to this listener and - // accumulate a vim-style count for j/k. Only while the list itself has focus — - // digits typed into the search/command inputs must not count. - .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { - if this.handle_playlist_input(event, window, cx) { - return; - } - if !this.focus_handle.is_focused(window) { - return; - } - let keystroke = &event.keystroke; - if keystroke.modifiers.control - || keystroke.modifiers.alt - || keystroke.modifiers.platform - || keystroke.modifiers.shift - { - return; - } - match keystroke.key.as_str() { - digit @ ("1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") => { - let digit = (digit.as_bytes()[0] - b'0') as usize; - let current = this.pending_count.unwrap_or(0); - this.pending_count = - Some(current.saturating_mul(10).saturating_add(digit).min(9999)); - cx.notify(); - } - // Any other unbound key cancels the pending count. - _ => { - if this.pending_count.take().is_some() { - cx.notify(); - } - } - } - })) - .relative() - .flex() - .flex_col() - .size_full() - .bg(backdrop.as_ref().map_or(bg, |b| b.colors.background)) - // The window's backdrop: the one fill covering every corner, so it rounds all four. - .map(|el| views::round_client_corners(el, corners, views::ClientCorners::All)) - .when_some(backdrop.as_ref(), |el, backdrop| { - el.child(views::backdrop_layer(backdrop.clone(), phase, corners)) - }) - .when_some(titlebar, |el, bar| el.child(bar)) - .map(|el| { - if let Some(backdrop) = &backdrop { - el.child(views::immersive_view(self, backdrop, window, cx)) - } else { - el.child( - div() - .flex_grow(1.0) - .flex() - .flex_row() - .overflow_hidden() - .when(!self.sidebar_collapsed, |el| { - el.child(self.regions.sidebar(self.sidebar_width)) - }) - .child(self.regions.main()) - .when(self.right_panel.is_some(), |el| { - let width = self.effective_right_panel_width(window); - el.child(self.regions.right_panel(width)) - }), - ) - .when_some(status_line, |el, line| el.child(line)) - } - }) - .when_some(command_bar, |el, bar| el.child(bar)) - .when_some(audio_banner, |el, banner| el.child(banner)) - .when_some(update_banner, |el, banner| el.child(banner)) - .when(!self.immersive, |el| el.child(self.regions.playback_bar())) - .when_some(theme_modal, |el, modal| el.child(modal)) - .when_some(device_modal, |el, modal| el.child(modal)) - .when_some(playlist_add_modal, |el, modal| el.child(modal)) - .when_some(sort_menu, |el, menu| el.child(menu)) - .when_some(settings_modal, |el, modal| el.child(modal)) - .when_some(help_modal, |el, modal| el.child(modal)) - .when_some(context_menu, |el, menu| el.child(menu)) - .when_some(track_menu, |el, menu| el.child(menu)) - .when_some(prompt_modal, |el, modal| el.child(modal)) - .when(self.page_menu.is_some(), |el| { - el.child(views::playlist_page_menu(self, cx)) - }) - .when(self.state.ui.playlist_edit.is_some(), |el| { - el.child(views::playlist_edit_modal(self, cx)) - }); - - // Adds the border and resize edges when the compositor refuses to draw them; a - // pass-through when it does. - views::window_frame(root, window, frame_palette) - } -} - fn main() { // Neither launch path has a stderr anyone reads — the Linux .desktop entry sets // Terminal=false and the Windows build is a windows_subsystem app — so a panic before the From 8ee5fa47601f228d31e8decd4c24494a538dac27 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:27:33 -0500 Subject: [PATCH 35/44] desktop: split the window's render into named pieces Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/app/render.rs | 648 ++++++++++++++------------ 1 file changed, 338 insertions(+), 310 deletions(-) diff --git a/crates/echo-desktop/src/app/render.rs b/crates/echo-desktop/src/app/render.rs index 7bff2c4..b4b2334 100644 --- a/crates/echo-desktop/src/app/render.rs +++ b/crates/echo-desktop/src/app/render.rs @@ -7,14 +7,142 @@ impl Render for EchoApp { self.dock_icon.sync(&self.state.ui.active_theme, cx); let theme = &self.state.ui.active_theme; let bg = theme.background.gpui(WINDOW_BG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); // Built ahead of the chain because they borrow self mutably, like the other views. let command_bar = matches!(self.state.ui.mode, AppMode::Command | AppMode::Search) .then(|| self.render_command_bar(cx).into_any_element()); + let status_line = self.status_line(); + let audio_banner = self.audio_banner(); + let update_banner = self.update_banner(cx); + let theme_modal = self + .theme_modal_open + .then(|| views::theme_modal(self, cx).into_any_element()); + let device_modal = self + .state + .ui + .device_modal_open + .then(|| views::device_modal(self, cx).into_any_element()); + let sort_menu = self + .sort_menu_open + .then(|| views::sort_menu(self, cx).into_any_element()); + let settings_modal = self + .settings_open + .then(|| views::settings_modal(self, window, cx).into_any_element()); + let help_modal = self + .help_open + .then(|| views::help_modal(self, cx).into_any_element()); + let context_menu = self + .context_menu + .is_some() + .then(|| views::context_menu(self, window, cx).into_any_element()); + if self.track_menu.is_none() { + self.track_menu_scroll.scroll_to_item(0); + } + let track_menu = self + .track_menu + .is_some() + .then(|| views::track_context_menu(self, window, cx).into_any_element()); + let playlist_add_modal = self + .state + .ui + .playlist_add_modal_open + .then(|| views::playlist_add_modal(self, cx).into_any_element()); + let prompt_modal = echo_core::intent::prompt_active(&self.state) + .then(|| views::prompt_modal(self, cx).into_any_element()); + let frame_palette = crate::theme::DesktopPalette::resolve(&self.state.ui.active_theme); + // Resolved before the chain so the style closure below borrows this rather than `window`. + let corners = views::client_corners(window); + // Windows and macOS hide the native bar (`appears_transparent`) and always want ours. + // Linux only gets it when the app actually owns the frame: the `Client` decorations + // requested at open are downgraded to `Server` on an X11 session with no compositor, and + // there the window manager draws a real titlebar that ours would sit underneath. + let owns_frame = !cfg!(target_os = "linux") || corners.is_some(); + let backdrop = self.immersive_backdrop(window, cx); + let phase = if cx.reduce_motion() { + 0.0 + } else { + self.backdrops.phase() + }; + let titlebar = owns_frame.then(|| { + views::titlebar(self, backdrop.as_ref().map(|b| &b.colors), window, cx) + .into_any_element() + }); + + let root = div() + .key_context(if self.playlist_input_open() { + "list search" + } else { + LIST_CONTEXT + }) + .track_focus(&self.focus_handle); + let root = Self::bind_pointer_drags(root, cx); + let root = Self::bind_actions(root, cx) + .on_key_down(cx.listener(Self::handle_count_key)) + .relative() + .flex() + .flex_col() + .size_full() + .bg(backdrop.as_ref().map_or(bg, |b| b.colors.background)) + // The window's backdrop: the one fill covering every corner, so it rounds all four. + .map(|el| views::round_client_corners(el, corners, views::ClientCorners::All)) + .when_some(backdrop.as_ref(), |el, backdrop| { + el.child(views::backdrop_layer(backdrop.clone(), phase, corners)) + }) + .when_some(titlebar, |el, bar| el.child(bar)) + .map(|el| { + if let Some(backdrop) = &backdrop { + el.child(views::immersive_view(self, backdrop, window, cx)) + } else { + el.child( + div() + .flex_grow(1.0) + .flex() + .flex_row() + .overflow_hidden() + .when(!self.sidebar_collapsed, |el| { + el.child(self.regions.sidebar(self.sidebar_width)) + }) + .child(self.regions.main()) + .when(self.right_panel.is_some(), |el| { + let width = self.effective_right_panel_width(window); + el.child(self.regions.right_panel(width)) + }), + ) + .when_some(status_line, |el, line| el.child(line)) + } + }) + .when_some(command_bar, |el, bar| el.child(bar)) + .when_some(audio_banner, |el, banner| el.child(banner)) + .when_some(update_banner, |el, banner| el.child(banner)) + .when(!self.immersive, |el| el.child(self.regions.playback_bar())) + .when_some(theme_modal, |el, modal| el.child(modal)) + .when_some(device_modal, |el, modal| el.child(modal)) + .when_some(playlist_add_modal, |el, modal| el.child(modal)) + .when_some(sort_menu, |el, menu| el.child(menu)) + .when_some(settings_modal, |el, modal| el.child(modal)) + .when_some(help_modal, |el, modal| el.child(modal)) + .when_some(context_menu, |el, menu| el.child(menu)) + .when_some(track_menu, |el, menu| el.child(menu)) + .when_some(prompt_modal, |el, modal| el.child(modal)) + .when(self.page_menu.is_some(), |el| { + el.child(views::playlist_page_menu(self, cx)) + }) + .when(self.state.ui.playlist_edit.is_some(), |el| { + el.child(views::playlist_edit_modal(self, cx)) + }); + + // Adds the border and resize edges when the compositor refuses to draw them; a + // pass-through when it does. + views::window_frame(root, window, frame_palette) + } +} + +impl EchoApp { + fn status_line(&self) -> Option { + let muted = self.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); // Visual mode says so on the status line: without a mode indicator a range selection // looks like the list has simply highlighted several rows for no reason. - let status_line = match self.state.ui.mode { + match self.state.ui.mode { AppMode::Visual => Some( self.state .ui @@ -40,10 +168,13 @@ impl Render for EchoApp { .text_color(muted) .child(SharedString::from(message)) .into_any_element() - }); + }) + } + + fn audio_banner(&self) -> Option { // The audio-device failure banner is persistent (no expiry) and separate from the // status line, so transient statuses can't hide it. Core clears it on recovery. - let audio_banner = self.state.ui.audio_output_error.clone().map(|message| { + self.state.ui.audio_output_error.clone().map(|message| { let error = self.state.ui.active_theme.error.gpui(WINDOW_FG()); let banner_bg = DesktopPalette::resolve(&self.state.ui.active_theme).error_wash; div() @@ -55,8 +186,11 @@ impl Render for EchoApp { .text_color(error) .child(SharedString::from(message)) .into_any_element() - }); - let update_banner = match &self.update_state { + }) + } + + fn update_banner(&self, cx: &mut Context) -> Option { + match &self.update_state { UpdateState::Ready(version) if !self.update_banner_dismissed => { let palette = DesktopPalette::resolve(&self.state.ui.active_theme); let text = views::tr(&self.state, "desktop.settings.updates.installed") @@ -104,53 +238,17 @@ impl Render for EchoApp { ) } _ => None, - }; - let theme_modal = self - .theme_modal_open - .then(|| views::theme_modal(self, cx).into_any_element()); - let device_modal = self - .state - .ui - .device_modal_open - .then(|| views::device_modal(self, cx).into_any_element()); - let sort_menu = self - .sort_menu_open - .then(|| views::sort_menu(self, cx).into_any_element()); - let settings_modal = self - .settings_open - .then(|| views::settings_modal(self, window, cx).into_any_element()); - let help_modal = self - .help_open - .then(|| views::help_modal(self, cx).into_any_element()); - let context_menu = self - .context_menu - .is_some() - .then(|| views::context_menu(self, window, cx).into_any_element()); - if self.track_menu.is_none() { - self.track_menu_scroll.scroll_to_item(0); } - let track_menu = self - .track_menu - .is_some() - .then(|| views::track_context_menu(self, window, cx).into_any_element()); - let playlist_add_modal = self - .state - .ui - .playlist_add_modal_open - .then(|| views::playlist_add_modal(self, cx).into_any_element()); - let prompt_modal = echo_core::intent::prompt_active(&self.state) - .then(|| views::prompt_modal(self, cx).into_any_element()); - let frame_palette = crate::theme::DesktopPalette::resolve(&self.state.ui.active_theme); - // Resolved before the chain so the style closure below borrows this rather than `window`. - let corners = views::client_corners(window); - // Windows and macOS hide the native bar (`appears_transparent`) and always want ours. - // Linux only gets it when the app actually owns the frame: the `Client` decorations - // requested at open are downgraded to `Server` on an X11 session with no compositor, and - // there the window manager draws a real titlebar that ours would sit underneath. - let owns_frame = !cfg!(target_os = "linux") || corners.is_some(); + } + + fn immersive_backdrop( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> Option> { // The immersive backdrop while that view is up: its colors replace the theme's for the // window fill and the titlebar, and its picture goes under everything. - let backdrop = self.immersive.then(|| { + self.immersive.then(|| { let playback = &self.state.playback; let cover = playback .playing_track_image @@ -174,24 +272,11 @@ impl Render for EchoApp { window.drop_image(image).ok(); }); backdrop - }); - let phase = if cx.reduce_motion() { - 0.0 - } else { - self.backdrops.phase() - }; - let titlebar = owns_frame.then(|| { - views::titlebar(self, backdrop.as_ref().map(|b| &b.colors), window, cx) - .into_any_element() - }); + }) + } - let root = div() - .key_context(if self.playlist_input_open() { - "list search" - } else { - LIST_CONTEXT - }) - .track_focus(&self.focus_handle) + fn bind_pointer_drags(root: Div, cx: &mut Context) -> Div { + root // Scrubs track the pointer at the window level so dragging keeps working when the // pointer leaves the bar; release (or a move without the button) ends them. .on_mouse_move( @@ -228,252 +313,195 @@ impl Render for EchoApp { this.shelf_scrub = None; }), ) - .on_action( - cx.listener(|this, _: &TogglePlayback, _window, cx| this.toggle_playback(cx)), - ) - .on_action(cx.listener(|this, _: &MoveUp, _window, cx| { - let count = this.take_count(); - this.move_selection(-count, cx) - })) - .on_action(cx.listener(|this, _: &MoveDown, _window, cx| { - let count = this.take_count(); - this.move_selection(count, cx) - })) - .on_action( - cx.listener(|this, _: &PageUp, _window, cx| this.move_selection(-PAGE_ROWS, cx)), - ) - .on_action( - cx.listener(|this, _: &PageDown, _window, cx| this.move_selection(PAGE_ROWS, cx)), - ) - // Takes precedence over the app-level `Quit` handler registered in `main`, which - // cannot see the window, so the ctrl-q binding remembers the window rectangle the - // way the platform's own close request does. The Linux caption button's close - // dispatches `CloseWindow` instead: the same tray-or-quit decision as that request. - .on_action(cx.listener(|this, _: &Quit, window, cx| { - this.persist_window_bounds(window); - cx.quit(); - })) - .on_action(cx.listener(|this, _: &CloseWindow, window, cx| { - if this.on_close_request(window, cx) { - window.remove_window(); - } - })) - // The macOS Window menu's two entries. Handled here rather than app-wide because - // both need the window; `Hide`/`HideOthers`/`ShowAll` do not, so those stay in - // `main` alongside the menu itself. - .on_action(cx.listener(|_, _: &MinimizeWindow, window, _cx| window.minimize_window())) - .on_action(cx.listener(|_, _: &ZoomWindow, window, _cx| window.zoom_window())) - .on_action(cx.listener(|this, _: &SelectFirst, _window, cx| this.set_selection(0, cx))) - .on_action(cx.listener(|this, _: &SelectLast, _window, cx| this.select_last(cx))) - .on_action(cx.listener(|this, _: &Activate, _window, cx| this.activate_selection(cx))) - .on_action(cx.listener(|this, _: &ConfirmPrompt, _window, cx| this.confirm_prompt(cx))) - .on_action(cx.listener(|this, _: &AddToPlaylist, _window, cx| this.add_to_playlist(cx))) - .on_action( - cx.listener(|this, _: &OpenActionMenu, _window, cx| this.open_action_menu(cx)), - ) - .on_action( - cx.listener(|this, _: &ToggleSettings, _window, cx| this.toggle_settings(cx)), - ) - .on_action(cx.listener(|this, _: &ToggleHelp, _window, cx| { - this.help_open = !this.help_open; - cx.notify(); - })) - .on_action(cx.listener(|this, _: &MarkDelete, _window, cx| { - this.pending_count = None; - if this.multi_selected() { - echo_core::intent::delete_visual_selection(&mut this.state); - } else { - echo_core::intent::mark_selected_for_delete(&mut this.state); - } - cx.notify(); - })) - .on_action(cx.listener(|this, _: &EnterVisual, _window, cx| this.toggle_visual(cx))) - .on_action(cx.listener(|this, _: &MoveTrackUp, _window, cx| { - let count = this.take_count(); - this.move_selected_track(-count, cx) - })) - .on_action(cx.listener(|this, _: &MoveTrackDown, _window, cx| { - let count = this.take_count(); - this.move_selected_track(count, cx) - })) - .on_action(cx.listener(|this, _: &ToggleLike, _window, cx| this.toggle_like(cx))) - .on_action(cx.listener(|this, _: &FocusLibrary, _window, cx| this.focus_library(cx))) - .on_action(cx.listener(|this, _: &FocusTracks, _window, cx| this.focus_tracks(cx))) - .on_action(cx.listener(|this, _: &ToggleSidebar, _window, cx| this.toggle_sidebar(cx))) - .on_action(cx.listener(|this, _: &HistoryBack, _window, cx| { - // Global binding, so keep the view still while an overlay is on top. - if !this.overlay_open() { - this.history_back(cx); - } - })) - .on_action(cx.listener(|this, _: &HistoryForward, _window, cx| { - if !this.overlay_open() { - this.history_forward(cx); - } - })) - .on_action(cx.listener(|this, _: &NextTrack, _window, cx| this.play_next(cx))) - .on_action(cx.listener(|this, _: &PreviousTrack, _window, cx| this.play_previous(cx))) - .on_action(cx.listener(|this, _: &ToggleShuffle, _window, cx| this.toggle_shuffle(cx))) - .on_action(cx.listener(|this, _: &CycleRepeat, _window, cx| this.cycle_repeat(cx))) - .on_action(cx.listener(|this, _: &ToggleMute, _window, cx| this.toggle_mute(cx))) - .on_action(cx.listener(|this, _: &SeekForward, _window, cx| this.seek_relative(5, cx))) - .on_action( - cx.listener(|this, _: &SeekBackward, _window, cx| this.seek_relative(-5, cx)), - ) - .on_action(cx.listener(|this, _: &ToggleQueue, _window, cx| this.toggle_queue_view(cx))) - .on_action(cx.listener(|this, _: &OpenDevices, _window, cx| this.open_devices(cx))) - .on_action(cx.listener(|this, _: &Dismiss, _window, cx| this.dismiss(cx))) - .on_action(cx.listener(|this, _: &FocusSearch, window, cx| { - window.focus(&this.search_focus, cx); - cx.notify(); - })) - .on_action(cx.listener(|this, _: &ToggleLyrics, _window, cx| this.toggle_lyrics(cx))) - .on_action(cx.listener(|this, _: &ToggleThemes, _window, cx| this.toggle_themes(cx))) - .on_action( - cx.listener(|this, _: &ToggleImmersive, _window, cx| this.toggle_immersive(cx)), - ) - .on_action(cx.listener(|this, _: &HalfPageUp, _window, cx| { + } + + fn bind_actions(root: Div, cx: &mut Context) -> Div { + root.on_action( + cx.listener(|this, _: &TogglePlayback, _window, cx| this.toggle_playback(cx)), + ) + .on_action(cx.listener(|this, _: &MoveUp, _window, cx| { + let count = this.take_count(); + this.move_selection(-count, cx) + })) + .on_action(cx.listener(|this, _: &MoveDown, _window, cx| { + let count = this.take_count(); + this.move_selection(count, cx) + })) + .on_action(cx.listener(|this, _: &PageUp, _window, cx| this.move_selection(-PAGE_ROWS, cx))) + .on_action( + cx.listener(|this, _: &PageDown, _window, cx| this.move_selection(PAGE_ROWS, cx)), + ) + // Takes precedence over the app-level `Quit` handler registered in `main`, which + // cannot see the window, so the ctrl-q binding remembers the window rectangle the + // way the platform's own close request does. The Linux caption button's close + // dispatches `CloseWindow` instead: the same tray-or-quit decision as that request. + .on_action(cx.listener(|this, _: &Quit, window, cx| { + this.persist_window_bounds(window); + cx.quit(); + })) + .on_action(cx.listener(|this, _: &CloseWindow, window, cx| { + if this.on_close_request(window, cx) { + window.remove_window(); + } + })) + // The macOS Window menu's two entries. Handled here rather than app-wide because + // both need the window; `Hide`/`HideOthers`/`ShowAll` do not, so those stay in + // `main` alongside the menu itself. + .on_action(cx.listener(|_, _: &MinimizeWindow, window, _cx| window.minimize_window())) + .on_action(cx.listener(|_, _: &ZoomWindow, window, _cx| window.zoom_window())) + .on_action(cx.listener(|this, _: &SelectFirst, _window, cx| this.set_selection(0, cx))) + .on_action(cx.listener(|this, _: &SelectLast, _window, cx| this.select_last(cx))) + .on_action(cx.listener(|this, _: &Activate, _window, cx| this.activate_selection(cx))) + .on_action(cx.listener(|this, _: &ConfirmPrompt, _window, cx| this.confirm_prompt(cx))) + .on_action(cx.listener(|this, _: &AddToPlaylist, _window, cx| this.add_to_playlist(cx))) + .on_action(cx.listener(|this, _: &OpenActionMenu, _window, cx| this.open_action_menu(cx))) + .on_action(cx.listener(|this, _: &ToggleSettings, _window, cx| this.toggle_settings(cx))) + .on_action(cx.listener(|this, _: &ToggleHelp, _window, cx| { + this.help_open = !this.help_open; + cx.notify(); + })) + .on_action(cx.listener(|this, _: &MarkDelete, _window, cx| { + this.pending_count = None; + if this.multi_selected() { + echo_core::intent::delete_visual_selection(&mut this.state); + } else { + echo_core::intent::mark_selected_for_delete(&mut this.state); + } + cx.notify(); + })) + .on_action(cx.listener(|this, _: &EnterVisual, _window, cx| this.toggle_visual(cx))) + .on_action(cx.listener(|this, _: &MoveTrackUp, _window, cx| { + let count = this.take_count(); + this.move_selected_track(-count, cx) + })) + .on_action(cx.listener(|this, _: &MoveTrackDown, _window, cx| { + let count = this.take_count(); + this.move_selected_track(count, cx) + })) + .on_action(cx.listener(|this, _: &ToggleLike, _window, cx| this.toggle_like(cx))) + .on_action(cx.listener(|this, _: &FocusLibrary, _window, cx| this.focus_library(cx))) + .on_action(cx.listener(|this, _: &FocusTracks, _window, cx| this.focus_tracks(cx))) + .on_action(cx.listener(|this, _: &ToggleSidebar, _window, cx| this.toggle_sidebar(cx))) + .on_action(cx.listener(|this, _: &HistoryBack, _window, cx| { + // Global binding, so keep the view still while an overlay is on top. + if !this.overlay_open() { + this.history_back(cx); + } + })) + .on_action(cx.listener(|this, _: &HistoryForward, _window, cx| { + if !this.overlay_open() { + this.history_forward(cx); + } + })) + .on_action(cx.listener(|this, _: &NextTrack, _window, cx| this.play_next(cx))) + .on_action(cx.listener(|this, _: &PreviousTrack, _window, cx| this.play_previous(cx))) + .on_action(cx.listener(|this, _: &ToggleShuffle, _window, cx| this.toggle_shuffle(cx))) + .on_action(cx.listener(|this, _: &CycleRepeat, _window, cx| this.cycle_repeat(cx))) + .on_action(cx.listener(|this, _: &ToggleMute, _window, cx| this.toggle_mute(cx))) + .on_action(cx.listener(|this, _: &SeekForward, _window, cx| this.seek_relative(5, cx))) + .on_action(cx.listener(|this, _: &SeekBackward, _window, cx| this.seek_relative(-5, cx))) + .on_action(cx.listener(|this, _: &ToggleQueue, _window, cx| this.toggle_queue_view(cx))) + .on_action(cx.listener(|this, _: &OpenDevices, _window, cx| this.open_devices(cx))) + .on_action(cx.listener(|this, _: &Dismiss, _window, cx| this.dismiss(cx))) + .on_action(cx.listener(|this, _: &FocusSearch, window, cx| { + window.focus(&this.search_focus, cx); + cx.notify(); + })) + .on_action(cx.listener(|this, _: &ToggleLyrics, _window, cx| this.toggle_lyrics(cx))) + .on_action(cx.listener(|this, _: &ToggleThemes, _window, cx| this.toggle_themes(cx))) + .on_action(cx.listener(|this, _: &ToggleImmersive, _window, cx| this.toggle_immersive(cx))) + .on_action( + cx.listener(|this, _: &HalfPageUp, _window, cx| { this.move_selection(-PAGE_ROWS / 2, cx) - })) - .on_action(cx.listener(|this, _: &HalfPageDown, _window, cx| { + }), + ) + .on_action( + cx.listener(|this, _: &HalfPageDown, _window, cx| { this.move_selection(PAGE_ROWS / 2, cx) - })) - // `0` extends a pending count (`10j`); bare `0` keeps its seek-to-start role. - .on_action(cx.listener(|this, _: &SeekStart, _window, cx| { - if let Some(count) = this.pending_count { - this.pending_count = Some(count.saturating_mul(10).min(9999)); + }), + ) + // `0` extends a pending count (`10j`); bare `0` keeps its seek-to-start role. + .on_action(cx.listener(|this, _: &SeekStart, _window, cx| { + if let Some(count) = this.pending_count { + this.pending_count = Some(count.saturating_mul(10).min(9999)); + cx.notify(); + } else { + this.seek_start(cx) + } + })) + .on_action(cx.listener(|this, _: &VolumeUp, _window, cx| this.adjust_volume(1, cx))) + .on_action(cx.listener(|this, _: &VolumeDown, _window, cx| this.adjust_volume(-1, cx))) + .on_action(cx.listener(|this, _: &VolumeUpBig, _window, cx| this.adjust_volume(5, cx))) + .on_action(cx.listener(|this, _: &VolumeDownBig, _window, cx| this.adjust_volume(-5, cx))) + .on_action(cx.listener(|this, _: &JumpToCurrent, _window, cx| this.jump_to_current(cx))) + .on_action( + cx.listener(|this, _: &OpenCommand, window, cx| this.open_command("", window, cx)), + ) + .on_action(cx.listener(|this, _: &CommandSearch, window, cx| { + this.open_command("search ", window, cx) + })) + .on_action(cx.listener(|this, _: &NewPlaylistPrompt, window, cx| { + if this.state.ui.active_view == ActiveView::Library { + this.open_command("newplaylist ", window, cx); + } + })) + .on_action(cx.listener(|this, _: &RenamePrompt, window, cx| this.rename_prompt(window, cx))) + .on_action(cx.listener(|this, _: &AddToQueue, _window, cx| this.add_to_queue(cx))) + .on_action(cx.listener(|this, _: &TogglePin, _window, cx| this.toggle_pin(cx))) + .on_action(cx.listener(|this, _: &CycleTab, _window, cx| this.cycle_tab(cx))) + .on_action(cx.listener(|this, _: &Refresh, _window, cx| this.refresh_view(cx))) + .on_action(cx.listener(|this, _: &OpenHome, window, cx| { + this.open_home(cx); + window.focus(&this.focus_handle, cx); + })) + .on_action(cx.listener(|this, _: &OpenFilter, window, cx| this.open_filter(window, cx))) + .on_action(cx.listener(|this, _: &NextMatch, _window, cx| this.next_match(true, cx))) + .on_action(cx.listener(|this, _: &PrevMatch, _window, cx| this.next_match(false, cx))) + .on_action( + cx.listener(|this, _: &ToggleInlineLyrics, _window, cx| this.toggle_inline_lyrics(cx)), + ) + .on_action( + cx.listener(|this, _: &BackOrFocusLibrary, _window, cx| this.back_or_focus_library(cx)), + ) + } + + // Digits are unbound, so they fall through the key bindings to this listener and + // accumulate a vim-style count for j/k. Only while the list itself has focus — + // digits typed into the search/command inputs must not count. + fn handle_count_key( + &mut self, + event: &gpui::KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + if self.handle_playlist_input(event, window, cx) { + return; + } + if !self.focus_handle.is_focused(window) { + return; + } + let keystroke = &event.keystroke; + if keystroke.modifiers.control + || keystroke.modifiers.alt + || keystroke.modifiers.platform + || keystroke.modifiers.shift + { + return; + } + match keystroke.key.as_str() { + digit @ ("1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") => { + let digit = (digit.as_bytes()[0] - b'0') as usize; + let current = self.pending_count.unwrap_or(0); + self.pending_count = + Some(current.saturating_mul(10).saturating_add(digit).min(9999)); + cx.notify(); + } + // Any other unbound key cancels the pending count. + _ => { + if self.pending_count.take().is_some() { cx.notify(); - } else { - this.seek_start(cx) - } - })) - .on_action(cx.listener(|this, _: &VolumeUp, _window, cx| this.adjust_volume(1, cx))) - .on_action(cx.listener(|this, _: &VolumeDown, _window, cx| this.adjust_volume(-1, cx))) - .on_action(cx.listener(|this, _: &VolumeUpBig, _window, cx| this.adjust_volume(5, cx))) - .on_action( - cx.listener(|this, _: &VolumeDownBig, _window, cx| this.adjust_volume(-5, cx)), - ) - .on_action(cx.listener(|this, _: &JumpToCurrent, _window, cx| this.jump_to_current(cx))) - .on_action( - cx.listener(|this, _: &OpenCommand, window, cx| this.open_command("", window, cx)), - ) - .on_action(cx.listener(|this, _: &CommandSearch, window, cx| { - this.open_command("search ", window, cx) - })) - .on_action(cx.listener(|this, _: &NewPlaylistPrompt, window, cx| { - if this.state.ui.active_view == ActiveView::Library { - this.open_command("newplaylist ", window, cx); - } - })) - .on_action( - cx.listener(|this, _: &RenamePrompt, window, cx| this.rename_prompt(window, cx)), - ) - .on_action(cx.listener(|this, _: &AddToQueue, _window, cx| this.add_to_queue(cx))) - .on_action(cx.listener(|this, _: &TogglePin, _window, cx| this.toggle_pin(cx))) - .on_action(cx.listener(|this, _: &CycleTab, _window, cx| this.cycle_tab(cx))) - .on_action(cx.listener(|this, _: &Refresh, _window, cx| this.refresh_view(cx))) - .on_action(cx.listener(|this, _: &OpenHome, window, cx| { - this.open_home(cx); - window.focus(&this.focus_handle, cx); - })) - .on_action(cx.listener(|this, _: &OpenFilter, window, cx| this.open_filter(window, cx))) - .on_action(cx.listener(|this, _: &NextMatch, _window, cx| this.next_match(true, cx))) - .on_action(cx.listener(|this, _: &PrevMatch, _window, cx| this.next_match(false, cx))) - .on_action(cx.listener(|this, _: &ToggleInlineLyrics, _window, cx| { - this.toggle_inline_lyrics(cx) - })) - .on_action(cx.listener(|this, _: &BackOrFocusLibrary, _window, cx| { - this.back_or_focus_library(cx) - })) - // Digits are unbound, so they fall through the key bindings to this listener and - // accumulate a vim-style count for j/k. Only while the list itself has focus — - // digits typed into the search/command inputs must not count. - .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { - if this.handle_playlist_input(event, window, cx) { - return; - } - if !this.focus_handle.is_focused(window) { - return; - } - let keystroke = &event.keystroke; - if keystroke.modifiers.control - || keystroke.modifiers.alt - || keystroke.modifiers.platform - || keystroke.modifiers.shift - { - return; - } - match keystroke.key.as_str() { - digit @ ("1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") => { - let digit = (digit.as_bytes()[0] - b'0') as usize; - let current = this.pending_count.unwrap_or(0); - this.pending_count = - Some(current.saturating_mul(10).saturating_add(digit).min(9999)); - cx.notify(); - } - // Any other unbound key cancels the pending count. - _ => { - if this.pending_count.take().is_some() { - cx.notify(); - } - } - } - })) - .relative() - .flex() - .flex_col() - .size_full() - .bg(backdrop.as_ref().map_or(bg, |b| b.colors.background)) - // The window's backdrop: the one fill covering every corner, so it rounds all four. - .map(|el| views::round_client_corners(el, corners, views::ClientCorners::All)) - .when_some(backdrop.as_ref(), |el, backdrop| { - el.child(views::backdrop_layer(backdrop.clone(), phase, corners)) - }) - .when_some(titlebar, |el, bar| el.child(bar)) - .map(|el| { - if let Some(backdrop) = &backdrop { - el.child(views::immersive_view(self, backdrop, window, cx)) - } else { - el.child( - div() - .flex_grow(1.0) - .flex() - .flex_row() - .overflow_hidden() - .when(!self.sidebar_collapsed, |el| { - el.child(self.regions.sidebar(self.sidebar_width)) - }) - .child(self.regions.main()) - .when(self.right_panel.is_some(), |el| { - let width = self.effective_right_panel_width(window); - el.child(self.regions.right_panel(width)) - }), - ) - .when_some(status_line, |el, line| el.child(line)) } - }) - .when_some(command_bar, |el, bar| el.child(bar)) - .when_some(audio_banner, |el, banner| el.child(banner)) - .when_some(update_banner, |el, banner| el.child(banner)) - .when(!self.immersive, |el| el.child(self.regions.playback_bar())) - .when_some(theme_modal, |el, modal| el.child(modal)) - .when_some(device_modal, |el, modal| el.child(modal)) - .when_some(playlist_add_modal, |el, modal| el.child(modal)) - .when_some(sort_menu, |el, menu| el.child(menu)) - .when_some(settings_modal, |el, modal| el.child(modal)) - .when_some(help_modal, |el, modal| el.child(modal)) - .when_some(context_menu, |el, menu| el.child(menu)) - .when_some(track_menu, |el, menu| el.child(menu)) - .when_some(prompt_modal, |el, modal| el.child(modal)) - .when(self.page_menu.is_some(), |el| { - el.child(views::playlist_page_menu(self, cx)) - }) - .when(self.state.ui.playlist_edit.is_some(), |el| { - el.child(views::playlist_edit_modal(self, cx)) - }); - - // Adds the border and resize edges when the compositor refuses to draw them; a - // pass-through when it does. - views::window_frame(root, window, frame_palette) + } + } } } From c2088235da1b841b225a21b1f03caacd431a4b9f Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:28:53 -0500 Subject: [PATCH 36/44] desktop: split the settings modal into a controls kit and one function per section Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- .../echo-desktop/src/views/modals/settings.rs | 1171 +++++++++-------- 1 file changed, 649 insertions(+), 522 deletions(-) diff --git a/crates/echo-desktop/src/views/modals/settings.rs b/crates/echo-desktop/src/views/modals/settings.rs index b9dcf94..af5b526 100644 --- a/crates/echo-desktop/src/views/modals/settings.rs +++ b/crates/echo-desktop/src/views/modals/settings.rs @@ -1,5 +1,8 @@ use super::*; +const ROW_HEIGHT: f32 = 34.0; +const CONTROL_HEIGHT: f32 = 24.0; + /// The settings sheet. /// /// Booleans are switches, a choice among several is a dropdown (the appearance mode, three @@ -10,396 +13,224 @@ pub fn settings_modal( window: &mut Window, cx: &mut Context, ) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let surface = theme.surface.gpui(crate::theme::PANEL_BG()); - let accent = theme.primary.gpui(WINDOW_FG()); - - let config = app.state.ui.library_config.clone(); - let path_focused = app.settings_path_focus.is_focused(window); - let path_value = app.settings_path_input.clone(); - // Owns its language so translation never borrows `app` across the listener closures below. - let s = { - let lang = config.language.clone(); - move |key: &str| SharedString::from(echo_core::i18n::t(key, &lang)) - }; + let c = Controls::new(app); + let Controls { + palette, + fg, + surface, + .. + } = c; + let config = &app.state.ui.library_config; + + let mut rows = general_section(&c, config, cx); + rows.extend(appearance_section(&c, app, config, cx)); + rows.extend(audio_section(&c, config, cx)); + rows.extend(local_section(&c, app, window, cx)); + rows.extend(updates_section(&c, app, config, cx)); - const ROW_HEIGHT: f32 = 34.0; - const CONTROL_HEIGHT: f32 = 24.0; - let open_dropdown = app.settings_dropdown; - - // A labelled row with its control on the right. Labels and hints arrive translated. A - // disabled row is dimmed: its setting has no effect until another one is turned on. - let row = - |label: SharedString, hint: Option, enabled: bool, control: AnyElement| { + div() + .id("settings-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + // A click outside first closes an open dropdown, then the sheet. + if this.settings_dropdown.take().is_none() { + this.settings_open = false; + } + cx.notify(); + })) + .child( div() + .id("settings-panel") + .w(px(480.0)) + // Never taller than the window: the list below takes what is left and scrolls. + .max_h(px(580.0).min(window.viewport_size().height - px(32.0))) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_4() .flex() - .flex_row() - .items_center() - .justify_between() - .gap_4() - .min_h(px(ROW_HEIGHT)) - .py_0p5() - .when(!enabled, |el| el.opacity(0.4)) + .flex_col() + .overflow_hidden() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + if this.settings_dropdown.take().is_some() { + cx.notify(); + } + cx.stop_propagation(); + })) + .child( + // The rule is where scrolled rows disappear, so they never run up + // under the title. + div() + .flex_none() + .pb_3() + .border_b_1() + .border_color(palette.menu_border) + .text_base() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(fg) + .child(c.t("desktop.settings.title")), + ) .child( div() + .id("settings-list") .flex() .flex_col() - .min_w_0() - .child(div().text_sm().text_color(fg).child(label)) - .when_some(hint, |el, hint| { - el.child(div().text_xs().text_color(muted).child(hint)) - }), - ) - .child(control) - }; + // Sized by its rows, shrinking (and scrolling) once the panel is full. + .min_h_0() + .overflow_y_scroll() + .track_scroll(&app.settings_scroll) + // One child holding every row: the scroll extent is measured across the list's children and + // skips the first one's top margin, which left the last row short of fully scrolling in. + .child(div().flex_none().flex().flex_col().children(rows)), + ), + ) +} - // A section title over a rule, with an optional note that applies to the whole section. - let heading = |label: SharedString, note: Option| { - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap_4() - .mt_4() - .mb_1() - .pb_1() - .border_b_1() - .border_color(palette.menu_border) - .child( - div() - .text_xs() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(muted) - .child(label), - ) - .when_some(note, |el, note| { - el.child(div().text_xs().text_color(muted).child(note)) - }) - }; +fn general_section( + c: &Controls, + config: &echo_core::config::LibraryConfig, + cx: &mut Context, +) -> Vec
{ + let language_row = c.row( + c.t("desktop.settings.language"), + None, + true, + c.dropdown( + "lang", + [("English", "en"), ("简体中文", "zh-CN")] + .into_iter() + .map(|(label, code)| { + ( + label.into(), + SettingChange::Command(format!("lang {code}")), + config.language == code, + ) + }) + .collect(), + true, + cx, + ), + ); - // An on/off switch. - let toggle = |id: &'static str, on: bool, change: SettingChange, cx: &mut Context| { - div() - .id(id) - .flex_none() - .w(px(34.0)) - .h(px(20.0)) - .p(px(2.0)) - .rounded_full() - .flex() - .flex_row() - .items_center() - .when(on, |el| el.justify_end()) - .bg(if on { accent } else { palette.menu_border }) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - change.apply(this, cx); - })) - .child( - div() - .size(px(16.0)) - .rounded_full() - .bg(if on { surface } else { muted }), - ) - .into_any_element() - }; + let tray_row = c.row( + c.t("desktop.settings.tray"), + None, + true, + c.toggle( + "tray", + config.close_to_tray, + SettingChange::Command(format!("tray {}", on_off(!config.close_to_tray))), + cx, + ), + ); - // A segmented control: one joined bar, the active segment filled. - let segmented = |id: &'static str, - options: Vec<(SharedString, String, bool)>, - cx: &mut Context| { - div() - .id(id) - .flex_none() - .h(px(CONTROL_HEIGHT)) - .flex() - .flex_row() - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .overflow_hidden() - .children( - options - .into_iter() - .enumerate() - .map(|(ix, (label, cmd, active))| { - div() - .id(SharedString::from(format!("{id}-{ix}"))) - .h_full() - .px_3() - .flex() - .items_center() - .text_xs() - .text_color(if active { fg } else { muted }) - .when(ix > 0, |el| { - el.border_l_1().border_color(palette.menu_border) - }) - .when(active, |el| el.bg(palette.menu_selected)) - .when(!active, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - }) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - this.run_setting(cmd.clone(), cx); - }, - )) - .child(label) - }), - ) - .into_any_element() + let sort_row = c.row( + c.t("desktop.settings.order"), + None, + true, + c.dropdown( + "libsort", + { + use echo_core::config::SortMode; + [ + // The manual drag-and-drop order. + ("order_custom", "default", SortMode::Default), + ("order_alpha", "alpha", SortMode::Alphabetical), + ("order_creator", "creator", SortMode::Creator), + ] + .into_iter() + .map(|(key, name, mode)| { + ( + c.t(&format!("desktop.settings.{key}")), + SettingChange::Command(format!("sort {name}")), + config.sort_mode == mode, + ) + }) + .collect() + }, + true, + cx, + ), + ); + + let relative_row = c.row( + c.t("desktop.settings.relative"), + None, + true, + c.toggle( + "relative", + config.relative_line_numbers, + SettingChange::Command(format!( + "relative {}", + on_off(!config.relative_line_numbers) + )), + cx, + ), + ); + + let mut rows = vec![ + c.heading(c.t("desktop.settings.general"), None), + language_row, + ]; + if !cfg!(target_os = "macos") { + rows.push(tray_row); + } + rows.extend([sort_row, relative_row]); + rows +} + +fn appearance_section( + c: &Controls, + app: &EchoApp, + config: &echo_core::config::LibraryConfig, + cx: &mut Context, +) -> Vec
{ + let palette = c.palette; + let theme_mode = config + .theme_mode + .unwrap_or(echo_core::config::ThemeMode::Auto); + // The theme in use, or under `Auto` the dark and the light one. + let theme_label = { + use echo_core::config::{Scheme, ThemeMode}; + let chosen = |scheme| echo_core::theme::selected_name(config, &app.state.ui.themes, scheme); + match theme_mode { + ThemeMode::Auto => format!("{} / {}", chosen(Scheme::Dark), chosen(Scheme::Light)), + ThemeMode::Dark => chosen(Scheme::Dark), + ThemeMode::Light => chosen(Scheme::Light), + } }; + let theme_row = c.row( + c.t("desktop.theme"), + None, + true, + c.button("settings-theme", theme_label.into(), false) + .cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.settings_open = false; + this.toggle_themes(cx); + })) + .into_any_element(), + ); - // A dropdown: a button showing the current option, and while open a menu of all of them - // hanging under it. The menu is drawn deferred so the scrolling list does not clip it. - let dropdown = |id: &'static str, - options: Vec<(SharedString, SettingChange, bool)>, - enabled: bool, - cx: &mut Context| { - let current = options - .iter() - .find(|option| option.2) - .map(|option| option.0.clone()) - .unwrap_or_default(); - let is_open = enabled && open_dropdown == Some(id); - let menu = is_open.then(|| { - let items: Vec<_> = options - .into_iter() - .enumerate() - .map(|(ix, (label, change, active))| { - div() - .id(SharedString::from(format!("{id}-option-{ix}"))) - .px_2() - .py_1() - .rounded_sm() - .text_xs() - .text_color(if active { accent } else { fg }) - .when(active, |el| el.bg(palette.menu_selected)) - .cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.settings_dropdown = None; - change.apply(this, cx); - cx.stop_propagation(); - })) - .child(label) - }) - .collect(); - div().absolute().top_full().right_0().child( - gpui::deferred( - gpui::anchored() - .anchor(gpui::Anchor::TopRight) - .snap_to_window() - .child( - div() - .id(SharedString::from(format!("{id}-menu"))) - .occlude() - .mt_1() - .min_w(px(DROPDOWN_WIDTH)) - .p_1() - .flex() - .flex_col() - .rounded_md() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .shadow_md() - .on_click( - cx.listener(|_this, _event, _window, cx| cx.stop_propagation()), - ) - .children(items), - ), - ) - .with_priority(1), - ) - }); - div() - .relative() - .flex_none() - .child( - div() - .id(id) - .h(px(CONTROL_HEIGHT)) - .min_w(px(DROPDOWN_WIDTH)) - .pl_2() - .pr_1p5() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap_2() - .rounded_md() - .border_1() - .border_color(if is_open { accent } else { palette.menu_border }) - .text_xs() - .text_color(fg) - .when(enabled, |el| { - el.cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - this.settings_dropdown = - (this.settings_dropdown != Some(id)).then_some(id); - // The panel behind closes any open dropdown on a click. - cx.stop_propagation(); - cx.notify(); - }, - )) - }) - .child(current) - .child( - svg() - .path("icons/arrow-down.svg") - .size(px(8.0)) - .text_color(muted), - ), - ) - .when_some(menu, |el, menu| el.child(menu)) - .into_any_element() - }; - - // A plain push button; the caller adds the click. `strong` accents the one that matters. - let button = |id: &'static str, label: SharedString, strong: bool| { - div() - .id(id) - .flex_none() - .h(px(CONTROL_HEIGHT)) - .px_2() - .flex() - .items_center() - .rounded_md() - .border_1() - .border_color(if strong { accent } else { palette.menu_border }) - .text_xs() - .text_color(if strong { accent } else { fg }) - .child(label) - }; - - let command = |cmd: String| SettingChange::Command(cmd); - let on_off = |on: bool| if on { "on" } else { "off" }; - - // --- General --------------------------------------------------------------------- - let language_row = row( - s("desktop.settings.language"), - None, - true, - dropdown( - "lang", - [("English", "en"), ("简体中文", "zh-CN")] - .into_iter() - .map(|(label, code)| { - ( - label.into(), - command(format!("lang {code}")), - config.language == code, - ) - }) - .collect(), - true, - cx, - ), - ); - - let tray_row = row( - s("desktop.settings.tray"), - None, - true, - toggle( - "tray", - config.close_to_tray, - command(format!("tray {}", on_off(!config.close_to_tray))), - cx, - ), - ); - - let sort_row = row( - s("desktop.settings.order"), - None, - true, - dropdown( - "libsort", - { - use echo_core::config::SortMode; - [ - // The manual drag-and-drop order. - ("order_custom", "default", SortMode::Default), - ("order_alpha", "alpha", SortMode::Alphabetical), - ("order_creator", "creator", SortMode::Creator), - ] - .into_iter() - .map(|(key, name, mode)| { - ( - s(&format!("desktop.settings.{key}")), - command(format!("sort {name}")), - config.sort_mode == mode, - ) - }) - .collect() - }, - true, - cx, - ), - ); - - let relative_row = row( - s("desktop.settings.relative"), - None, - true, - toggle( - "relative", - config.relative_line_numbers, - command(format!( - "relative {}", - on_off(!config.relative_line_numbers) - )), - cx, - ), - ); - - // --- Appearance ------------------------------------------------------------------ - let theme_mode = config - .theme_mode - .unwrap_or(echo_core::config::ThemeMode::Auto); - // The theme in use, or under `Auto` the dark and the light one. - let theme_label = { - use echo_core::config::{Scheme, ThemeMode}; - let chosen = - |scheme| echo_core::theme::selected_name(&config, &app.state.ui.themes, scheme); - match theme_mode { - ThemeMode::Auto => format!("{} / {}", chosen(Scheme::Dark), chosen(Scheme::Light)), - ThemeMode::Dark => chosen(Scheme::Dark), - ThemeMode::Light => chosen(Scheme::Light), - } - }; - let theme_row = row( - s("desktop.theme"), - None, - true, - button("settings-theme", theme_label.into(), false) - .cursor_pointer() - .hover(move |style| style.bg(palette.menu_hover)) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.settings_open = false; - this.toggle_themes(cx); - })) - .into_any_element(), - ); - - let mode_row = row( - s("desktop.settings.mode"), - None, - true, - segmented( - "mode", - echo_core::config::ThemeMode::ALL + let mode_row = c.row( + c.t("desktop.settings.mode"), + None, + true, + c.segmented( + "mode", + echo_core::config::ThemeMode::ALL .into_iter() .map(|mode| { ( - s(&format!("desktop.theme_mode.{}", mode.name())), + c.t(&format!("desktop.theme_mode.{}", mode.name())), format!("mode {}", mode.name()), theme_mode == mode, ) @@ -409,33 +240,22 @@ pub fn settings_modal( ), ); - // The offered sizes, plus whatever `:pixelate` / `:visbins` set outside them, so the - // button never shows blank. - let with_current = |offered: &[usize], current: usize| { - let mut values = offered.to_vec(); - if !values.contains(¤t) { - values.push(current); - values.sort_unstable(); - } - values - }; - - let pixelate_row = row( - s("desktop.settings.pixelate"), + let pixelate_row = c.row( + c.t("desktop.settings.pixelate"), None, true, - dropdown( + c.dropdown( "pixelate", with_current(&[0, 8, 16, 32], config.cover_img_pixels as usize) .into_iter() .map(|n| { ( if n == 0 { - s("ui.off") + c.t("ui.off") } else { SharedString::from(format!("{n} px")) }, - command(format!("pixelate {n}")), + SettingChange::Command(format!("pixelate {n}")), config.cover_img_pixels as usize == n, ) }) @@ -445,18 +265,18 @@ pub fn settings_modal( ), ); - let backdrop_row = row( - s("desktop.settings.backdrop"), + let backdrop_row = c.row( + c.t("desktop.settings.backdrop"), None, true, - dropdown( + c.dropdown( "backdrop", echo_core::config::BackdropMode::ALL .into_iter() .map(|mode| { ( - s(&format!("desktop.settings.backdrops.{}", mode.name())), - command(format!("backdrop {}", mode.name())), + c.t(&format!("desktop.settings.backdrops.{}", mode.name())), + SettingChange::Command(format!("backdrop {}", mode.name())), config.immersive_backdrop == mode, ) }) @@ -466,26 +286,31 @@ pub fn settings_modal( ), ); - let visualizer_row = row( - s("desktop.settings.visualizer"), + let visualizer_row = c.row( + c.t("desktop.settings.visualizer"), None, true, // `:vis` flips the visualizer; it takes no argument. - toggle("vis", config.enable_visualizer, command("vis".into()), cx), + c.toggle( + "vis", + config.enable_visualizer, + SettingChange::Command("vis".into()), + cx, + ), ); - let bins_row = row( - s("desktop.settings.bins"), + let bins_row = c.row( + c.t("desktop.settings.bins"), None, config.enable_visualizer, - dropdown( + c.dropdown( "visbins", with_current(&[7, 9, 16, 24, 32], config.vis_bins) .into_iter() .map(|n| { ( SharedString::from(n.to_string()), - command(format!("visbins {n}")), + SettingChange::Command(format!("visbins {n}")), config.vis_bins == n, ) }) @@ -495,12 +320,28 @@ pub fn settings_modal( ), ); - // --- Audio quality --------------------------------------------------------------- - let bitrate_row = row( - s("desktop.settings.quality"), + vec![ + c.heading(c.t("desktop.settings.appearance"), None), + theme_row, + mode_row, + pixelate_row, + backdrop_row, + visualizer_row, + bins_row, + ] +} + +fn audio_section( + c: &Controls, + config: &echo_core::config::LibraryConfig, + cx: &mut Context, +) -> Vec
{ + let Controls { palette, fg, .. } = *c; + let bitrate_row = c.row( + c.t("desktop.settings.quality"), None, true, - dropdown( + c.dropdown( "bitrate", [96u32, 160, 320] .into_iter() @@ -518,11 +359,11 @@ pub fn settings_modal( ); let normalisation = config.normalisation; - let normalisation_row = row( - s("desktop.settings.normalisation"), + let normalisation_row = c.row( + c.t("desktop.settings.normalisation"), None, true, - toggle( + c.toggle( "normalisation", normalisation, SettingChange::Normalisation(!normalisation), @@ -561,9 +402,9 @@ pub fn settings_modal( }) .child(label) }; - let pregain_row = row( - s("desktop.settings.pregain"), - Some(s("desktop.settings.pregain_desc")), + let pregain_row = c.row( + c.t("desktop.settings.pregain"), + Some(c.t("desktop.settings.pregain_desc")), normalisation, div() .flex_none() @@ -584,7 +425,32 @@ pub fn settings_modal( .into_any_element(), ); - // --- Local music ----------------------------------------------------------------- + vec![ + c.heading( + c.t("desktop.settings.audio"), + Some(c.t("desktop.settings.next_launch")), + ), + bitrate_row, + normalisation_row, + pregain_row, + ] +} + +fn local_section( + c: &Controls, + app: &EchoApp, + window: &Window, + cx: &mut Context, +) -> Vec
{ + let Controls { + palette, + fg, + muted, + accent, + .. + } = *c; + let path_focused = app.settings_path_focus.is_focused(window); + let path_value = app.settings_path_input.clone(); let path_unsaved = app.local_folder_unsaved(); let local_field = div() .id("settings-localpath") @@ -619,7 +485,7 @@ pub fn settings_modal( .child(SharedString::from(if path_focused { crate::text_with_cursor(&path_value, app.settings_path_cursor) } else if path_value.is_empty() { - s("desktop.settings.folder_empty").to_string() + c.t("desktop.settings.folder_empty").to_string() } else { path_value })); @@ -633,9 +499,9 @@ pub fn settings_modal( .child( // With no folder saved, or a different one typed, the button applies the field; // otherwise there is nothing to set and it rescans. - button( + c.button( "settings-rescan", - s(if path_unsaved { + c.t(if path_unsaved { "desktop.settings.set_folder" } else { "desktop.settings.rescan" @@ -649,11 +515,20 @@ pub fn settings_modal( })), ); - // --- Updates --------------------------------------------------------------------- - // The one control here that is neither a `:` command nor a config write: it runs a network - // call, so its label and action both come from `app.update_state`. - let version_row = row( - s("desktop.settings.updates.version"), + vec![c.heading(c.t("desktop.settings.local"), None), local_row] +} + +// The one control here that is neither a `:` command nor a config write: it runs a network +// call, so its label and action both come from `app.update_state`. +fn updates_section( + c: &Controls, + app: &EchoApp, + config: &echo_core::config::LibraryConfig, + cx: &mut Context, +) -> Vec
{ + let Controls { palette, muted, .. } = *c; + let version_row = c.row( + c.t("desktop.settings.updates.version"), None, true, div() @@ -674,23 +549,23 @@ pub fn settings_modal( let translate = |key: &str, value: &str| -> SharedString { SharedString::from(echo_core::i18n::t(key, &config.language).replace("{}", value)) }; - let auto_update_row = row( - s("desktop.settings.updates.auto"), + let auto_update_row = c.row( + c.t("desktop.settings.updates.auto"), None, true, - toggle( + c.toggle( "autoupdate", config.auto_update, - command(format!("autoupdate {}", on_off(!config.auto_update))), + SettingChange::Command(format!("autoupdate {}", on_off(!config.auto_update))), cx, ), ); // The hint only appears when there is something to report: an installed update waiting // for a restart, or why the last attempt failed. let (update_label, update_hint, update_active) = match &app.update_state { - UpdateState::Idle => (s("desktop.settings.updates.check"), None, true), - UpdateState::Checking => (s("desktop.settings.updates.checking"), None, false), - UpdateState::UpToDate => (s("desktop.settings.updates.uptodate"), None, true), + UpdateState::Idle => (c.t("desktop.settings.updates.check"), None, true), + UpdateState::Checking => (c.t("desktop.settings.updates.checking"), None, false), + UpdateState::UpToDate => (c.t("desktop.settings.updates.uptodate"), None, true), UpdateState::Available(release) => ( translate("desktop.settings.updates.install", release.version()), None, @@ -702,24 +577,25 @@ pub fn settings_modal( false, ), UpdateState::Ready(version) => ( - s("desktop.settings.updates.restart"), + c.t("desktop.settings.updates.restart"), Some(translate("desktop.settings.updates.installed", version)), false, ), UpdateState::Failed(message) => ( - s("desktop.settings.updates.retry"), + c.t("desktop.settings.updates.retry"), Some(SharedString::from(message.clone())), true, ), // Nothing in-app can fix this one, so the button leaves for the releases page. UpdateState::Blocked(message) => ( - s("desktop.settings.updates.open_releases"), + c.t("desktop.settings.updates.open_releases"), Some(SharedString::from(message.clone())), true, ), }; - let update_button = button("settings-update", update_label, update_active) + let update_button = c + .button("settings-update", update_label, update_active) .when(!update_active, |el| el.text_color(muted)) .when(update_active, |el| { el.cursor_pointer() @@ -736,106 +612,357 @@ pub fn settings_modal( }) .into_any_element(); - let update_row = row( - s("desktop.settings.updates.label"), + let update_row = c.row( + c.t("desktop.settings.updates.label"), update_hint, true, update_button, ); - div() - .id("settings-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) - .flex() - .items_center() - .justify_center() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - // A click outside first closes an open dropdown, then the sheet. - if this.settings_dropdown.take().is_none() { - this.settings_open = false; - } - cx.notify(); - })) - .child( - div() - .id("settings-panel") - .w(px(480.0)) - // Never taller than the window: the list below takes what is left and scrolls. - .max_h(px(580.0).min(window.viewport_size().height - px(32.0))) - .rounded_lg() - .border_1() - .border_color(palette.menu_border) - .bg(surface) - .p_4() - .flex() - .flex_col() - .overflow_hidden() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - if this.settings_dropdown.take().is_some() { - cx.notify(); - } - cx.stop_propagation(); - })) - .child( - // The rule is where scrolled rows disappear, so they never run up - // under the title. - div() - .flex_none() - .pb_3() - .border_b_1() - .border_color(palette.menu_border) - .text_base() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(fg) - .child(s("desktop.settings.title")), - ) - .child( + vec![ + c.heading(c.t("desktop.settings.updates.section"), None), + version_row, + auto_update_row, + update_row, + ] +} + +fn on_off(on: bool) -> &'static str { + if on { "on" } else { "off" } +} + +/// The offered sizes, plus whatever `:pixelate` / `:visbins` set outside them, so the +/// button never shows blank. +fn with_current(offered: &[usize], current: usize) -> Vec { + let mut values = offered.to_vec(); + if !values.contains(¤t) { + values.push(current); + values.sort_unstable(); + } + values +} + +/// The colours and building blocks every settings row is made of. +#[derive(Clone, Copy)] +struct Controls<'a> { + palette: DesktopPalette, + fg: Hsla, + muted: Hsla, + surface: Hsla, + accent: Hsla, + open_dropdown: Option<&'static str>, + language: &'a str, +} + +impl<'a> Controls<'a> { + fn new(app: &'a EchoApp) -> Self { + let theme = &app.state.ui.active_theme; + Self { + palette: DesktopPalette::resolve(theme), + fg: theme.text.gpui(WINDOW_FG()), + muted: theme.text_muted.gpui(WINDOW_FG()), + surface: theme.surface.gpui(crate::theme::PANEL_BG()), + accent: theme.primary.gpui(WINDOW_FG()), + open_dropdown: app.settings_dropdown, + language: &app.state.ui.library_config.language, + } + } + + fn t(&self, key: &str) -> SharedString { + SharedString::from(echo_core::i18n::t(key, self.language)) + } + + /// A labelled row with its control on the right. Labels and hints arrive translated. A + /// disabled row is dimmed: its setting has no effect until another one is turned on. + fn row( + &self, + label: SharedString, + hint: Option, + enabled: bool, + control: AnyElement, + ) -> Div { + let Self { fg, muted, .. } = *self; + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap_4() + .min_h(px(ROW_HEIGHT)) + .py_0p5() + .when(!enabled, |el| el.opacity(0.4)) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child(div().text_sm().text_color(fg).child(label)) + .when_some(hint, |el, hint| { + el.child(div().text_xs().text_color(muted).child(hint)) + }), + ) + .child(control) + } + + /// A section title over a rule, with an optional note that applies to the whole section. + fn heading(&self, label: SharedString, note: Option) -> Div { + let Self { palette, muted, .. } = *self; + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap_4() + .mt_4() + .mb_1() + .pb_1() + .border_b_1() + .border_color(palette.menu_border) + .child( + div() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(muted) + .child(label), + ) + .when_some(note, |el, note| { + el.child(div().text_xs().text_color(muted).child(note)) + }) + } + + /// An on/off switch. + fn toggle( + &self, + id: &'static str, + on: bool, + change: SettingChange, + cx: &mut Context, + ) -> AnyElement { + let Self { + palette, + muted, + surface, + accent, + .. + } = *self; + div() + .id(id) + .flex_none() + .w(px(34.0)) + .h(px(20.0)) + .p(px(2.0)) + .rounded_full() + .flex() + .flex_row() + .items_center() + .when(on, |el| el.justify_end()) + .bg(if on { accent } else { palette.menu_border }) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + change.apply(this, cx); + })) + .child( + div() + .size(px(16.0)) + .rounded_full() + .bg(if on { surface } else { muted }), + ) + .into_any_element() + } + + /// A segmented control: one joined bar, the active segment filled. + fn segmented( + &self, + id: &'static str, + options: Vec<(SharedString, String, bool)>, + cx: &mut Context, + ) -> AnyElement { + let Self { + palette, fg, muted, .. + } = *self; + div() + .id(id) + .flex_none() + .h(px(CONTROL_HEIGHT)) + .flex() + .flex_row() + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .overflow_hidden() + .children( + options + .into_iter() + .enumerate() + .map(|(ix, (label, cmd, active))| { + div() + .id(SharedString::from(format!("{id}-{ix}"))) + .h_full() + .px_3() + .flex() + .items_center() + .text_xs() + .text_color(if active { fg } else { muted }) + .when(ix > 0, |el| { + el.border_l_1().border_color(palette.menu_border) + }) + .when(active, |el| el.bg(palette.menu_selected)) + .when(!active, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + this.run_setting(cmd.clone(), cx); + }, + )) + .child(label) + }), + ) + .into_any_element() + } + + /// A dropdown: a button showing the current option, and while open a menu of all of them + /// hanging under it. The menu is drawn deferred so the scrolling list does not clip it. + fn dropdown( + &self, + id: &'static str, + options: Vec<(SharedString, SettingChange, bool)>, + enabled: bool, + cx: &mut Context, + ) -> AnyElement { + let Self { + palette, + fg, + muted, + surface, + accent, + .. + } = *self; + let current = options + .iter() + .find(|option| option.2) + .map(|option| option.0.clone()) + .unwrap_or_default(); + let is_open = enabled && self.open_dropdown == Some(id); + let menu = is_open.then(|| { + let items: Vec<_> = options + .into_iter() + .enumerate() + .map(|(ix, (label, change, active))| { div() - .id("settings-list") - .flex() - .flex_col() - // Sized by its rows, shrinking (and scrolling) once the panel is full. - .min_h_0() - .overflow_y_scroll() - .track_scroll(&app.settings_scroll) - // One child holding every row: the scroll extent is measured across the list's children and - // skips the first one's top margin, which left the last row short of fully scrolling in. + .id(SharedString::from(format!("{id}-option-{ix}"))) + .px_2() + .py_1() + .rounded_sm() + .text_xs() + .text_color(if active { accent } else { fg }) + .when(active, |el| el.bg(palette.menu_selected)) + .cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.settings_dropdown = None; + change.apply(this, cx); + cx.stop_propagation(); + })) + .child(label) + }) + .collect(); + div().absolute().top_full().right_0().child( + gpui::deferred( + gpui::anchored() + .anchor(gpui::Anchor::TopRight) + .snap_to_window() .child( div() - .flex_none() + .id(SharedString::from(format!("{id}-menu"))) + .occlude() + .mt_1() + .min_w(px(DROPDOWN_WIDTH)) + .p_1() .flex() .flex_col() - .child(heading(s("desktop.settings.general"), None)) - .child(language_row) - .when(!cfg!(target_os = "macos"), |el| el.child(tray_row)) - .child(sort_row) - .child(relative_row) - .child(heading(s("desktop.settings.appearance"), None)) - .child(theme_row) - .child(mode_row) - .child(pixelate_row) - .child(backdrop_row) - .child(visualizer_row) - .child(bins_row) - .child(heading( - s("desktop.settings.audio"), - Some(s("desktop.settings.next_launch")), - )) - .child(bitrate_row) - .child(normalisation_row) - .child(pregain_row) - .child(heading(s("desktop.settings.local"), None)) - .child(local_row) - .child(heading(s("desktop.settings.updates.section"), None)) - .child(version_row) - .child(auto_update_row) - .child(update_row), + .rounded_md() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .shadow_md() + .on_click( + cx.listener(|_this, _event, _window, cx| cx.stop_propagation()), + ) + .children(items), ), - ), - ) + ) + .with_priority(1), + ) + }); + div() + .relative() + .flex_none() + .child( + div() + .id(id) + .h(px(CONTROL_HEIGHT)) + .min_w(px(DROPDOWN_WIDTH)) + .pl_2() + .pr_1p5() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap_2() + .rounded_md() + .border_1() + .border_color(if is_open { accent } else { palette.menu_border }) + .text_xs() + .text_color(fg) + .when(enabled, |el| { + el.cursor_pointer() + .hover(move |style| style.bg(palette.menu_hover)) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + this.settings_dropdown = + (this.settings_dropdown != Some(id)).then_some(id); + // The panel behind closes any open dropdown on a click. + cx.stop_propagation(); + cx.notify(); + }, + )) + }) + .child(current) + .child( + svg() + .path("icons/arrow-down.svg") + .size(px(8.0)) + .text_color(muted), + ), + ) + .when_some(menu, |el, menu| el.child(menu)) + .into_any_element() + } + + /// A plain push button; the caller adds the click. `strong` accents the one that matters. + fn button(&self, id: &'static str, label: SharedString, strong: bool) -> Stateful
{ + let Self { + palette, + fg, + accent, + .. + } = *self; + div() + .id(id) + .flex_none() + .h(px(CONTROL_HEIGHT)) + .px_2() + .flex() + .items_center() + .rounded_md() + .border_1() + .border_color(if strong { accent } else { palette.menu_border }) + .text_xs() + .text_color(if strong { accent } else { fg }) + .child(label) + } } /// What a settings control does when used: nearly always a `:` command, so the sheet and the From ccc0b86fb4740e4150ef5affdbabc1d04630d4ca Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:30:01 -0500 Subject: [PATCH 37/44] desktop: split the sidebar into its links, tabs and library rows Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views/sidebar.rs | 1074 ++++++++++++---------- 1 file changed, 596 insertions(+), 478 deletions(-) diff --git a/crates/echo-desktop/src/views/sidebar.rs b/crates/echo-desktop/src/views/sidebar.rs index 3874206..894648a 100644 --- a/crates/echo-desktop/src/views/sidebar.rs +++ b/crates/echo-desktop/src/views/sidebar.rs @@ -17,11 +17,7 @@ fn is_fixed_library_row(id: &str) -> bool { } pub fn sidebar(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let palette = DesktopPalette::resolve(theme); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - + let palette = DesktopPalette::resolve(&app.state.ui.active_theme); let tab = app.state.ui.active_library_tab; let count = match tab { LibraryTab::Albums => app.state.data.saved_albums.len(), @@ -37,26 +33,6 @@ pub fn sidebar(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement .pt_2() .child(nav_button_cluster(app, cx)); - let tab_button = |id: &'static str, label: SharedString, target: LibraryTab, active: bool| { - div() - .id(id) - .px_2() - .py_1() - .rounded_md() - .text_sm() - .text_color(if active { accent } else { muted }) - .hover(move |style| style.bg(palette.row_hover)) - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - this.state.ui.active_library_tab = target; - this.state.ui.selected_playlist_index = 0; - if target == LibraryTab::Artists && this.state.data.followed_artists.is_empty() { - this.dispatch(echo_core::events::AppEvent::FetchFollowedArtists); - } - cx.notify(); - })) - .child(label) - }; - div() .relative() .flex_none() @@ -65,471 +41,38 @@ pub fn sidebar(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement .flex() .flex_col() .child(nav_row) - .child(div().id("home-link").mx_2().mt_2().px_2().py_2().rounded_md().flex().items_center().gap_2().text_sm().text_color(if app.state.ui.active_view == ActiveView::Home { accent } else { muted }).when(app.state.ui.active_view == ActiveView::Home, |el| el.bg(palette.row_selected)).hover(move |style| style.bg(palette.row_hover)).cursor_pointer().on_click(cx.listener(|this: &mut EchoApp, _, window, cx| { this.open_home(cx); window.focus(&this.focus_handle, cx); })).child(svg().path("icons/home.svg").size(px(18.0)).text_color(muted)).child(tr(&app.state, "desktop.home"))) - .child( - div() - .flex() - .flex_row() - .gap_1() - .p_2() - .child(tab_button( - "Playlists", - tr(&app.state, "ui.playlists"), - LibraryTab::Playlists, - tab == LibraryTab::Playlists, - )) - .child(tab_button( - "Albums", - tr(&app.state, "ui.albums"), - LibraryTab::Albums, - tab == LibraryTab::Albums, - )) - .child(tab_button( - "Artists", - tr(&app.state, "ui.artists"), - LibraryTab::Artists, - tab == LibraryTab::Artists, - )), - ) - .child({ - // Browse nodes presented as quick links. - let browse_link = |id: &'static str, - icon: &'static str, - label: SharedString, - open: fn(&mut echo_core::app::AppState) - -> Option| { - div() - .id(id) - .mx_2() - .px_2() - .py_1() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_2() - .text_sm() - .text_color(muted) - .hover(move |style| style.bg(palette.row_hover)) - .cursor_pointer() - .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = open(&mut this.state) { - this.dispatch(event); - } - cx.notify(); - })) - .child( - svg() - .path(icon) - .flex_none() - .w(px(14.0)) - .h(px(14.0)) - .text_color(muted), - ) - .child(label) - }; - div() - .flex_none() - .flex() - .flex_col() - .pb_1() - .child(browse_link( - "top-tracks", - "icons/star.svg", - tr(&app.state, "desktop.top_tracks"), - echo_core::intent::open_top_tracks, - )) - .child(browse_link( - "recently-played", - "icons/clock.svg", - tr(&app.state, "desktop.recently_played"), - echo_core::intent::open_recently_played, - )) - .child(browse_link( - "top-artists", - "icons/mic.svg", - tr(&app.state, "desktop.top_artists"), - echo_core::intent::open_top_artists, - )) - .child(browse_link( - "whats-new", - "icons/sparkles.svg", - tr(&app.state, "desktop.whats_new"), - echo_core::intent::open_whats_new, - )) - }) + .child(home_link(app, cx)) + .child(library_tabs(app, cx)) + .child(browse_links(app, cx)) .child( uniform_list( "library-rows", count, - cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = if this.state.ui.active_view == ActiveView::Library { - palette.row_selected - } else { - palette.row_hover - }; - let drag_colors = DragColors::resolve(theme); - let tab = this.state.ui.active_library_tab; - let selected = this.state.ui.selected_playlist_index; - let visual = visual_range_in(&this.state, ActiveView::Library); - - let rows: Vec<_> = range - .map(|ix| { - // Folders carry no cover; playlists, albums and artists get a - // thumb box even while (or if never) loaded, so the text column - // stays aligned. Folders get a chevron icon, pinned playlists a - // pin icon; artist thumbs are circular. - let (label, label_color, indent_px, thumb_url, has_thumb, chevron, pinned, round_thumb): ( - SharedString, - _, - f32, - Option, - bool, - Option<&'static str>, - bool, - bool, - ) = if tab == LibraryTab::Albums { - let album = &this.state.data.saved_albums[ix]; - let url = album - .thumb_url - .clone() - .or_else(|| album.image_url.clone()); - (album.name.clone().into(), fg, 0.0, url, true, None, false, false) - } else if tab == LibraryTab::Artists { - let artist = &this.state.data.followed_artists[ix]; - ( - artist.name.clone().into(), - fg, - 0.0, - artist.image_url.clone(), - true, - None, - false, - true, - ) - } else { - match &this.state.data.library_view[ix] { - LibraryNode::Folder(f) => ( - f.name.clone().into(), - accent, - 0.0, - None, - false, - Some(if f.is_open { - "icons/arrow-down.svg" - } else { - "icons/arrow-right.svg" - }), - false, - false, - ), - LibraryNode::SpotifyFolder { name, is_open, indent, .. } => ( - name.clone().into(), - accent, - *indent as f32 * 14.0, - None, - false, - Some(if *is_open { - "icons/arrow-down.svg" - } else { - "icons/arrow-right.svg" - }), - false, - false, - ), - LibraryNode::Playlist { playlist, indent } => { - let pinned = this - .state - .ui - .library_config - .pinned - .contains(&playlist.id); - let url = playlist - .thumb_url - .clone() - .or_else(|| playlist.image_url.clone()); - ( - playlist.name.clone().into(), - fg, - *indent as f32 * 14.0, - url, - true, - None, - pinned, - false, - ) - } - } - }; - - // Liked Songs has no cover, so its box holds the heart icon, which - // takes the theme's accent. (An emoji in the name would not: macOS - // draws those in full colour.) - let liked_row = tab == LibraryTab::Playlists - && matches!( - &this.state.data.library_view[ix], - LibraryNode::Playlist { playlist, .. } - if playlist.id == "LIKED_SONGS" - ); - let thumb: Option = has_thumb.then(|| { - let artwork = thumb_url.as_deref().and_then(|url| { - this.state.ui.thumbnails.request(url, ThumbTier::Small); - match this.state.ui.thumbnails.get(url, ThumbTier::Small) { - Some(ThumbState::Ready { artwork }) => { - Some(artwork.clone()) - } - _ => None, - } - }); - match artwork.and_then(|artwork| this.images.get(&artwork)) { - Some(image) => { - let radius = if round_thumb { THUMB_EDGE / 2.0 } else { 4.0 }; - cover_image(image, THUMB_EDGE, radius).into_any_element() - } - None => { - let el = div() - .flex_none() - .w(px(THUMB_EDGE)) - .h(px(THUMB_EDGE)) - .bg(palette.wash) - .flex() - .items_center() - .justify_center() - .child( - svg() - .path(if liked_row { - "icons/heart.svg" - } else { - "icons/music-note.svg" - }) - .w(px(12.0)) - .h(px(12.0)) - .text_color(if liked_row { accent } else { muted }), - ); - if round_thumb { el.rounded_full() } else { el.rounded_sm() } - .into_any_element() - } - } - }); - - // Local playlists and echo's own folders look like Spotify's in the - // sidebar, so they are tagged to keep the distinction visible. - let local_badge: Option = (tab - == LibraryTab::Playlists - && match &this.state.data.library_view[ix] { - LibraryNode::Playlist { playlist, .. } => { - playlist.id.starts_with("local-playlist:") - } - LibraryNode::Folder(_) => true, - LibraryNode::SpotifyFolder { .. } => false, - }) - .then(|| tr(&this.state, "desktop.local_badge")); - - // Playlists can be dragged between folders, the pinned block and the - // loose list, and folders among themselves; every playlist-tab row - // is a drop target (the intent rejects invalid ones). - let drag_source: Option<(String, SharedString)> = - if tab == LibraryTab::Playlists { - match &this.state.data.library_view[ix] { - LibraryNode::Playlist { playlist, .. } - if !is_fixed_library_row(&playlist.id) => - { - Some(( - playlist.id.clone(), - playlist.name.clone().into(), - )) - } - LibraryNode::Playlist { .. } => None, - LibraryNode::Folder(folder) => Some(( - echo_core::models::echo_folder_key(&folder.name), - folder.name.clone().into(), - )), - LibraryNode::SpotifyFolder { id, name, .. } => Some(( - echo_core::models::spotify_folder_key(id), - name.clone().into(), - )), - } - } else { - None - }; - - pill_row(ix, SIDEBAR_PILL, row_selected(ix, selected, visual), selected_bg, palette.row_hover, |row| { - row.pl(px(8.0 + indent_px)) - .gap_2() - .text_color(label_color) - .when(tab != LibraryTab::Artists, |el| { - // Artists have no row actions, so no context menu. - el.on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_playlist_index = ix; - this.track_menu = None; - this.state.ui.playlist_add_filter.clear(); - // Spotify's folders are read-only, so they have no - // row actions to offer. - if this.state.ui.active_library_tab - == LibraryTab::Playlists - && matches!( - this.state.data.library_view.get(ix), - Some(LibraryNode::SpotifyFolder { .. }) - ) - { - this.context_menu = None; - cx.notify(); - return; - } - this.context_menu = Some(crate::ContextMenuState { - index: ix, - position: event.position, - }); - cx.notify(); - }), - ) - }) - .when_some(drag_source, |el, (id, name)| { - el.on_drag( - DraggedPlaylist { id, name }, - move |drag, _offset, _window, cx| { - let name = drag.name.clone(); - cx.new(|_| DragPreview::label(name, drag_colors)) - }, - ) - }) - .when(tab == LibraryTab::Playlists, |el| { - el.drag_over::(move |style, _, _, _| { - style.bg(palette.drag_target) - }) - .on_drop(cx.listener( - move |this: &mut EchoApp, drag: &DraggedPlaylist, _window, cx| { - if echo_core::intent::move_library_row( - &mut this.state, - &drag.id, - ix, - ) { - cx.notify(); - } - }, - )) - .drag_over::(move |style, _, _, _| { - style.bg(palette.drag_target) - }) - .on_drop(cx.listener( - move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { - for event in echo_core::intent::drop_tracks_on_library_row( - &mut this.state, - ix, - drag.tracks.clone(), - ) { - this.dispatch(event); - } - cx.notify(); - }, - )) - }) - .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { - this.state.ui.selected_playlist_index = ix; - let tab = this.state.ui.active_library_tab; - // The first click of a double-click already opened the - // entry; the second one starts it playing. - if event.click_count() >= 2 { - let play = match tab { - LibraryTab::Albums => { - echo_core::intent::play_album_at(&mut this.state, ix) - } - LibraryTab::Artists => None, - _ => echo_core::intent::play_library_entry( - &mut this.state, - ix, - ), - }; - if let Some(event) = play { - this.dispatch(event); - } - cx.notify(); - return; - } - let event = match tab { - LibraryTab::Albums => { - echo_core::intent::open_album(&mut this.state, ix) - } - LibraryTab::Artists => { - echo_core::intent::open_followed_artist( - &mut this.state, - ix, - ) - } - _ => echo_core::intent::open_library_entry( - &mut this.state, - ix, - ), - }; - if let Some(event) = event { - this.dispatch(event); - } - cx.notify(); - })) - .when_some(chevron, |el, icon| { - el.child( - svg() - .path(icon) - .flex_none() - .w(px(12.0)) - .h(px(12.0)) - .text_color(accent), - ) - }) - .when_some(thumb, |el, thumb| el.child(thumb)) - .when(pinned, |el| { - el.child( - svg() - .path("icons/pin.svg") - .flex_none() - .w(px(12.0)) - .h(px(12.0)) - .text_color(muted), - ) - }) - .child( - div() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .child(label), - ) - .when_some(local_badge, |el, badge| { - el.child( - div() - .ml_auto() - .flex_none() - .text_xs() - .text_color(muted) - .child(badge), - ) - }) - }) - }) - .collect(); - - // Kick off fetches for whatever the rows above just requested. - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - - rows - }), + cx.processor( + |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + library_rows(this, range, cx) + }, + ), ) .track_scroll(&app.library_scroll) .on_drag_move(cx.listener( |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { - this.drag_autoscroll(crate::DragList::Library, event.event.position.y, event.bounds, cx); + this.drag_autoscroll( + crate::DragList::Library, + event.event.position.y, + event.bounds, + cx, + ); }, )) .on_drag_move(cx.listener( |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { - this.drag_autoscroll(crate::DragList::Library, event.event.position.y, event.bounds, cx); + this.drag_autoscroll( + crate::DragList::Library, + event.event.position.y, + event.bounds, + cx, + ); }, )) .flex_grow(1.0), @@ -552,3 +95,578 @@ pub fn sidebar(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement ), ) } + +fn home_link(app: &EchoApp, cx: &mut Context) -> impl IntoElement + use<> { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + + div() + .id("home-link") + .mx_2() + .mt_2() + .px_2() + .py_2() + .rounded_md() + .flex() + .items_center() + .gap_2() + .text_sm() + .text_color(if app.state.ui.active_view == ActiveView::Home { + accent + } else { + muted + }) + .when(app.state.ui.active_view == ActiveView::Home, |el| { + el.bg(palette.row_selected) + }) + .hover(move |style| style.bg(palette.row_hover)) + .cursor_pointer() + .on_click(cx.listener(|this: &mut EchoApp, _, window, cx| { + this.open_home(cx); + window.focus(&this.focus_handle, cx); + })) + .child( + svg() + .path("icons/home.svg") + .size(px(18.0)) + .text_color(muted), + ) + .child(tr(&app.state, "desktop.home")) +} + +fn library_tabs(app: &EchoApp, cx: &mut Context) -> Div { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let tab = app.state.ui.active_library_tab; + + let tab_button = |id: &'static str, label: SharedString, target: LibraryTab, active: bool| { + div() + .id(id) + .px_2() + .py_1() + .rounded_md() + .text_sm() + .text_color(if active { accent } else { muted }) + .hover(move |style| style.bg(palette.row_hover)) + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + this.state.ui.active_library_tab = target; + this.state.ui.selected_playlist_index = 0; + if target == LibraryTab::Artists && this.state.data.followed_artists.is_empty() { + this.dispatch(echo_core::events::AppEvent::FetchFollowedArtists); + } + cx.notify(); + })) + .child(label) + }; + + div() + .flex() + .flex_row() + .gap_1() + .p_2() + .child(tab_button( + "Playlists", + tr(&app.state, "ui.playlists"), + LibraryTab::Playlists, + tab == LibraryTab::Playlists, + )) + .child(tab_button( + "Albums", + tr(&app.state, "ui.albums"), + LibraryTab::Albums, + tab == LibraryTab::Albums, + )) + .child(tab_button( + "Artists", + tr(&app.state, "ui.artists"), + LibraryTab::Artists, + tab == LibraryTab::Artists, + )) +} + +/// Browse nodes presented as quick links. +fn browse_links(app: &EchoApp, cx: &mut Context) -> Div { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + + let browse_link = + |id: &'static str, + icon: &'static str, + label: SharedString, + open: fn(&mut echo_core::app::AppState) -> Option| { + div() + .id(id) + .mx_2() + .px_2() + .py_1() + .rounded_md() + .flex() + .flex_row() + .items_center() + .gap_2() + .text_sm() + .text_color(muted) + .hover(move |style| style.bg(palette.row_hover)) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = open(&mut this.state) { + this.dispatch(event); + } + cx.notify(); + })) + .child( + svg() + .path(icon) + .flex_none() + .w(px(14.0)) + .h(px(14.0)) + .text_color(muted), + ) + .child(label) + }; + div() + .flex_none() + .flex() + .flex_col() + .pb_1() + .child(browse_link( + "top-tracks", + "icons/star.svg", + tr(&app.state, "desktop.top_tracks"), + echo_core::intent::open_top_tracks, + )) + .child(browse_link( + "recently-played", + "icons/clock.svg", + tr(&app.state, "desktop.recently_played"), + echo_core::intent::open_recently_played, + )) + .child(browse_link( + "top-artists", + "icons/mic.svg", + tr(&app.state, "desktop.top_artists"), + echo_core::intent::open_top_artists, + )) + .child(browse_link( + "whats-new", + "icons/sparkles.svg", + tr(&app.state, "desktop.whats_new"), + echo_core::intent::open_whats_new, + )) +} + +/// What one sidebar row shows. Folders carry no cover; playlists, albums and artists get a +/// thumb box even while (or if never) loaded, so the text column stays aligned. Folders get a +/// chevron icon, pinned playlists a pin icon; artist thumbs are circular. +struct LibraryRow { + label: SharedString, + label_color: Hsla, + indent_px: f32, + thumb_url: Option, + has_thumb: bool, + chevron: Option<&'static str>, + pinned: bool, + round_thumb: bool, +} + +impl LibraryRow { + fn of( + state: &echo_core::app::AppState, + ix: usize, + tab: LibraryTab, + fg: Hsla, + accent: Hsla, + ) -> Self { + let folder_chevron = |is_open: bool| { + Some(if is_open { + "icons/arrow-down.svg" + } else { + "icons/arrow-right.svg" + }) + }; + if tab == LibraryTab::Albums { + let album = &state.data.saved_albums[ix]; + Self { + label: album.name.clone().into(), + label_color: fg, + indent_px: 0.0, + thumb_url: album.thumb_url.clone().or_else(|| album.image_url.clone()), + has_thumb: true, + chevron: None, + pinned: false, + round_thumb: false, + } + } else if tab == LibraryTab::Artists { + let artist = &state.data.followed_artists[ix]; + Self { + label: artist.name.clone().into(), + label_color: fg, + indent_px: 0.0, + thumb_url: artist.image_url.clone(), + has_thumb: true, + chevron: None, + pinned: false, + round_thumb: true, + } + } else { + match &state.data.library_view[ix] { + LibraryNode::Folder(f) => Self { + label: f.name.clone().into(), + label_color: accent, + indent_px: 0.0, + thumb_url: None, + has_thumb: false, + chevron: folder_chevron(f.is_open), + pinned: false, + round_thumb: false, + }, + LibraryNode::SpotifyFolder { + name, + is_open, + indent, + .. + } => Self { + label: name.clone().into(), + label_color: accent, + indent_px: *indent as f32 * 14.0, + thumb_url: None, + has_thumb: false, + chevron: folder_chevron(*is_open), + pinned: false, + round_thumb: false, + }, + LibraryNode::Playlist { playlist, indent } => Self { + label: playlist.name.clone().into(), + label_color: fg, + indent_px: *indent as f32 * 14.0, + thumb_url: playlist + .thumb_url + .clone() + .or_else(|| playlist.image_url.clone()), + has_thumb: true, + chevron: None, + pinned: state.ui.library_config.pinned.contains(&playlist.id), + round_thumb: false, + }, + } + } + } +} + +fn library_rows( + this: &mut EchoApp, + range: std::ops::Range, + cx: &mut Context, +) -> Vec
{ + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = if this.state.ui.active_view == ActiveView::Library { + palette.row_selected + } else { + palette.row_hover + }; + let drag_colors = DragColors::resolve(theme); + let tab = this.state.ui.active_library_tab; + let selected = this.state.ui.selected_playlist_index; + let visual = visual_range_in(&this.state, ActiveView::Library); + + let rows: Vec<_> = range + .map(|ix| { + let LibraryRow { + label, + label_color, + indent_px, + thumb_url, + has_thumb, + chevron, + pinned, + round_thumb, + } = LibraryRow::of(&this.state, ix, tab, fg, accent); + + // Liked Songs has no cover, so its box holds the heart icon, which + // takes the theme's accent. (An emoji in the name would not: macOS + // draws those in full colour.) + let liked_row = tab == LibraryTab::Playlists + && matches!( + &this.state.data.library_view[ix], + LibraryNode::Playlist { playlist, .. } + if playlist.id == "LIKED_SONGS" + ); + let thumb: Option = has_thumb + .then(|| library_thumb(this, thumb_url.as_deref(), liked_row, round_thumb)); + + // Local playlists and echo's own folders look like Spotify's in the + // sidebar, so they are tagged to keep the distinction visible. + let local_badge: Option = (tab == LibraryTab::Playlists + && match &this.state.data.library_view[ix] { + LibraryNode::Playlist { playlist, .. } => { + playlist.id.starts_with("local-playlist:") + } + LibraryNode::Folder(_) => true, + LibraryNode::SpotifyFolder { .. } => false, + }) + .then(|| tr(&this.state, "desktop.local_badge")); + + // Playlists can be dragged between folders, the pinned block and the + // loose list, and folders among themselves; every playlist-tab row + // is a drop target (the intent rejects invalid ones). + let drag_source = (tab == LibraryTab::Playlists) + .then(|| library_drag_source(&this.state.data.library_view[ix])) + .flatten(); + + pill_row( + ix, + SIDEBAR_PILL, + row_selected(ix, selected, visual), + selected_bg, + palette.row_hover, + |row| { + row.pl(px(8.0 + indent_px)) + .gap_2() + .text_color(label_color) + .when(tab != LibraryTab::Artists, |el| { + // Artists have no row actions, so no context menu. + el.on_mouse_down( + MouseButton::Right, + cx.listener( + move |this: &mut EchoApp, + event: &MouseDownEvent, + _window, + cx| { + open_library_row_menu(this, ix, event.position, cx); + }, + ), + ) + }) + .when_some(drag_source, |el, (id, name)| { + el.on_drag( + DraggedPlaylist { id, name }, + move |drag, _offset, _window, cx| { + let name = drag.name.clone(); + cx.new(|_| DragPreview::label(name, drag_colors)) + }, + ) + }) + .when(tab == LibraryTab::Playlists, |el| { + el.drag_over::(move |style, _, _, _| { + style.bg(palette.drag_target) + }) + .on_drop(cx.listener( + move |this: &mut EchoApp, drag: &DraggedPlaylist, _window, cx| { + if echo_core::intent::move_library_row( + &mut this.state, + &drag.id, + ix, + ) { + cx.notify(); + } + }, + )) + .drag_over::(move |style, _, _, _| { + style.bg(palette.drag_target) + }) + .on_drop(cx.listener( + move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { + for event in echo_core::intent::drop_tracks_on_library_row( + &mut this.state, + ix, + drag.tracks.clone(), + ) { + this.dispatch(event); + } + cx.notify(); + }, + )) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + activate_library_row(this, ix, event.click_count(), cx); + }, + )) + .when_some(chevron, |el, icon| { + el.child( + svg() + .path(icon) + .flex_none() + .w(px(12.0)) + .h(px(12.0)) + .text_color(accent), + ) + }) + .when_some(thumb, |el, thumb| el.child(thumb)) + .when(pinned, |el| { + el.child( + svg() + .path("icons/pin.svg") + .flex_none() + .w(px(12.0)) + .h(px(12.0)) + .text_color(muted), + ) + }) + .child( + div() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .child(label), + ) + .when_some(local_badge, |el, badge| { + el.child( + div() + .ml_auto() + .flex_none() + .text_xs() + .text_color(muted) + .child(badge), + ) + }) + }, + ) + }) + .collect(); + + // Kick off fetches for whatever the rows above just requested. + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + + rows +} + +/// A row's cover, or a placeholder box holding the note icon (the heart for Liked Songs). +fn library_thumb( + this: &mut EchoApp, + url: Option<&str>, + liked_row: bool, + round_thumb: bool, +) -> AnyElement { + let theme = &this.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let artwork = url.and_then(|url| { + this.state.ui.thumbnails.request(url, ThumbTier::Small); + match this.state.ui.thumbnails.get(url, ThumbTier::Small) { + Some(ThumbState::Ready { artwork }) => Some(artwork.clone()), + _ => None, + } + }); + match artwork.and_then(|artwork| this.images.get(&artwork)) { + Some(image) => { + let radius = if round_thumb { THUMB_EDGE / 2.0 } else { 4.0 }; + cover_image(image, THUMB_EDGE, radius).into_any_element() + } + None => { + let el = div() + .flex_none() + .w(px(THUMB_EDGE)) + .h(px(THUMB_EDGE)) + .bg(palette.wash) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path(if liked_row { + "icons/heart.svg" + } else { + "icons/music-note.svg" + }) + .w(px(12.0)) + .h(px(12.0)) + .text_color(if liked_row { accent } else { muted }), + ); + if round_thumb { + el.rounded_full() + } else { + el.rounded_sm() + } + .into_any_element() + } + } +} + +fn library_drag_source(node: &LibraryNode) -> Option<(String, SharedString)> { + match node { + LibraryNode::Playlist { playlist, .. } if !is_fixed_library_row(&playlist.id) => { + Some((playlist.id.clone(), playlist.name.clone().into())) + } + LibraryNode::Playlist { .. } => None, + LibraryNode::Folder(folder) => Some(( + echo_core::models::echo_folder_key(&folder.name), + folder.name.clone().into(), + )), + LibraryNode::SpotifyFolder { id, name, .. } => Some(( + echo_core::models::spotify_folder_key(id), + name.clone().into(), + )), + } +} + +fn open_library_row_menu( + this: &mut EchoApp, + ix: usize, + position: gpui::Point, + cx: &mut Context, +) { + this.state.ui.selected_playlist_index = ix; + this.track_menu = None; + this.state.ui.playlist_add_filter.clear(); + // Spotify's folders are read-only, so they have no + // row actions to offer. + if this.state.ui.active_library_tab == LibraryTab::Playlists + && matches!( + this.state.data.library_view.get(ix), + Some(LibraryNode::SpotifyFolder { .. }) + ) + { + this.context_menu = None; + cx.notify(); + return; + } + this.context_menu = Some(crate::ContextMenuState { + index: ix, + position, + }); + cx.notify(); +} + +fn activate_library_row( + this: &mut EchoApp, + ix: usize, + click_count: usize, + cx: &mut Context, +) { + this.state.ui.selected_playlist_index = ix; + let tab = this.state.ui.active_library_tab; + // The first click of a double-click already opened the + // entry; the second one starts it playing. + if click_count >= 2 { + let play = match tab { + LibraryTab::Albums => echo_core::intent::play_album_at(&mut this.state, ix), + LibraryTab::Artists => None, + _ => echo_core::intent::play_library_entry(&mut this.state, ix), + }; + if let Some(event) = play { + this.dispatch(event); + } + cx.notify(); + return; + } + let event = match tab { + LibraryTab::Albums => echo_core::intent::open_album(&mut this.state, ix), + LibraryTab::Artists => echo_core::intent::open_followed_artist(&mut this.state, ix), + _ => echo_core::intent::open_library_entry(&mut this.state, ix), + }; + if let Some(event) = event { + this.dispatch(event); + } + cx.notify(); +} From dfa93e5995e7b0da1e9a0b4c8aab9d3424c99558 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:30:53 -0500 Subject: [PATCH 38/44] desktop: split the playback bar into its card, caption, visualizer and output controls Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/playback_bar.rs | 729 ++++++++++++------------ 1 file changed, 375 insertions(+), 354 deletions(-) diff --git a/crates/echo-desktop/src/playback_bar.rs b/crates/echo-desktop/src/playback_bar.rs index ef47cf4..a2ae6f5 100644 --- a/crates/echo-desktop/src/playback_bar.rs +++ b/crates/echo-desktop/src/playback_bar.rs @@ -114,43 +114,98 @@ impl EchoApp { pub(crate) fn render_playback_bar(&mut self, cx: &mut Context) -> impl IntoElement { let theme = &self.state.ui.active_theme; let palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); let muted = theme.text_muted.gpui(WINDOW_FG()); let accent = theme.primary.gpui(WINDOW_FG()); - - let playback = &self.state.playback; - let title: SharedString = if playback.playing_track_title.is_empty() { - views::tr(&self.state, "desktop.nothing_playing") - } else { - playback.playing_track_title.clone().into() - }; - let artist: SharedString = playback.playing_track_artist.clone().into(); - let has_track = playback.playing_track_id.is_some(); - let controls = ControlColors { - fg, + fg: theme.text.gpui(WINDOW_FG()), muted, accent, hover: palette.wash, track: palette.border, }; - let volume_fraction = (playback.volume as f32 / 100.0).clamp(0.0, 1.0); - let volume_label: SharedString = format!("{}%", playback.volume).into(); - let mute_icon = if playback.volume == 0 { - "icons/volume-off.svg" - } else { - "icons/volume-high.svg" - }; - let queue_color = if self.right_panel == Some(RightPanel::Queue) { + let lyrics_color = if self.right_panel == Some(RightPanel::Lyrics) { accent } else { muted }; - let lyrics_color = if self.right_panel == Some(RightPanel::Lyrics) { - accent + + div() + .flex() + .flex_col() + .justify_center() + .gap_1() + .h(px(regions::PLAYBACK_BAR_HEIGHT)) + .px_4() + .border_t_1() + .border_color(palette.border) + .child( + // Top row: song card, condensed lyric line, visualizer. Its contents come and go; + // its height doesn't, so nothing here can move the row below. + div() + .flex() + .flex_row() + .items_center() + .gap_3() + .h(px(PLAYBACK_ROW_HEIGHT)) + .child(self.playing_card(controls, cx)) + .child(self.playing_caption(controls)) + .child( + div() + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .flex() + .flex_row() + .items_center() + .justify_end() + .gap_3() + .children(self.playing_on_pill(controls, cx)) + .children(self.visualizer(accent)), + ), + ) + .child( + // Bottom row: transport, seek and volume on one line, so the seek bar sits on the + // buttons' baseline no matter what the row above is doing. + div() + .flex() + .flex_row() + .items_center() + .gap_3() + .h(px(PLAYBACK_ROW_HEIGHT)) + .child( + self.transport_controls(controls, cx) + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .child(icon_button( + "lyrics", + "icons/mic.svg", + lyrics_color, + palette.wash, + cx, + |this, cx| this.toggle_lyrics(cx), + )), + ) + .child(self.seek_bar(controls, cx)) + .child(self.output_controls(controls, cx)), + ) + } + + /// The playing track's cover, title and artist, draggable like a track row. + fn playing_card( + &mut self, + colors: ControlColors, + cx: &mut Context, + ) -> gpui::Stateful
{ + let theme = &self.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let ControlColors { fg, muted, .. } = colors; + let playback = &self.state.playback; + let title: SharedString = if playback.playing_track_title.is_empty() { + views::tr(&self.state, "desktop.nothing_playing") } else { - muted + playback.playing_track_title.clone().into() }; + let artist: SharedString = playback.playing_track_artist.clone().into(); + let has_track = playback.playing_track_id.is_some(); let secondary = theme.secondary.gpui(WINDOW_FG()); let liked_button = playback .playing_track_id @@ -162,22 +217,6 @@ impl EchoApp { let liked = self.state.data.liked_tracks.contains(&track_id); playing_like_button(track_id, liked, secondary, palette.like_dim, cx) }); - // Playback on another Connect device (a phone, a speaker) gets a pill naming it; - // echo's own device and local files are the norm and stay unlabelled. - let playing_on: Option = (has_track - && playback.device_name != echo_core::worker::audio::DEVICE_NAME - && playback.device_name != "Local" - && !playback.device_name.is_empty()) - .then(|| { - views::tr(&self.state, "desktop.playing_on") - .replace("{}", &playback.device_name) - .into() - }); - let visualizer_bands = (self.state.ui.library_config.enable_visualizer - && self.state.playback.is_playing) - .then(|| self.state.playback.audio_visualization.clone()) - .flatten(); - let vis_bins = self.state.ui.vis_bins.clamp(5, 32); // Keep showing the previous cover while the current one refetches after a pixelate // change. @@ -193,10 +232,74 @@ impl EchoApp { let drag_payload = echo_core::history::playing_track(&self.state) .map(|track| views::single_drag_payload(&track, cover.clone())); - // The condensed-lyrics line shows the current lyric accented with the next one below, - // riding the same playback tick that advances the seek bar. - let inline_lyrics = self - .state + div() + .id("playing-card") + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .flex() + .flex_row() + .items_center() + .gap_2() + .when_some(drag_payload, |el, payload| { + el.on_drag(payload, move |drag, _offset, _window, cx| { + views::track_drag_preview(drag, drag_colors, cx) + }) + }) + .child(match cover { + Some(image) => views::cover_image(image, 36.0, 6.0).into_any_element(), + None => div() + .flex_none() + .w(px(36.0)) + .h(px(36.0)) + .rounded_md() + .bg(palette.wash) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path("icons/music-note.svg") + .w(px(16.0)) + .h(px(16.0)) + .text_color(muted), + ) + .into_any_element(), + }) + .child( + div() + .flex_col() + .flex_grow(1.0) + .overflow_hidden() + .child( + playing_track_link( + "playing-title", + title, + fg, + has_track, + echo_core::models::ActionMenuAction::GoToAlbum, + cx, + ) + .text_sm(), + ) + .child( + playing_track_link( + "playing-artist", + artist, + muted, + has_track, + echo_core::models::ActionMenuAction::GoToArtist, + cx, + ) + .text_xs(), + ), + ) + .children(liked_button) + } + + // The condensed-lyrics line shows the current lyric accented with the next one below, + // riding the same playback tick that advances the seek bar. + fn inline_lyrics(&self) -> Option<(String, String)> { + self.state .ui .condensed_lyrics_enabled .then(|| { @@ -226,8 +329,14 @@ impl EchoApp { (String::new(), String::new()) } }) - .filter(|(current, _)| !current.is_empty()); + .filter(|(current, _)| !current.is_empty()) + } + /// The top row's centre slot: the condensed lyric line, or where playback started from. + fn playing_caption(&self, colors: ControlColors) -> Div { + let ControlColors { muted, accent, .. } = colors; + let has_track = self.state.playback.playing_track_id.is_some(); + let inline_lyrics = self.inline_lyrics(); // Inline lyrics keep the top-row center slot; "Playing from X" fills it otherwise. let playing_from = if inline_lyrics.is_none() && has_track { views::playing_context_label(&self.state) @@ -235,336 +344,248 @@ impl EchoApp { None }; - let volume_bounds = self.volume_bounds.clone(); - div() + .flex_grow(1.0) .flex() .flex_col() + .items_center() .justify_center() - .gap_1() - .h(px(regions::PLAYBACK_BAR_HEIGHT)) - .px_4() - .border_t_1() - .border_color(palette.border) - .child( - // Top row: song card, condensed lyric line, visualizer. Its contents come and go; - // its height doesn't, so nothing here can move the row below. - div() - .flex() - .flex_row() - .items_center() - .gap_3() - .h(px(PLAYBACK_ROW_HEIGHT)) - .child( + .overflow_hidden() + .when_some(inline_lyrics, |el, (current, next)| { + el.child( + div() + .text_sm() + .text_color(accent) + .whitespace_nowrap() + .max_w_full() + .overflow_hidden() + .child(SharedString::from(current)), + ) + .when(!next.is_empty(), |el| { + el.child( div() - .id("playing-card") - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .flex() - .flex_row() - .items_center() - .gap_2() - .when_some(drag_payload, |el, payload| { - el.on_drag(payload, move |drag, _offset, _window, cx| { - views::track_drag_preview(drag, drag_colors, cx) - }) - }) - .child(match cover { - Some(image) => { - views::cover_image(image, 36.0, 6.0).into_any_element() - } - None => div() - .flex_none() - .w(px(36.0)) - .h(px(36.0)) - .rounded_md() - .bg(palette.wash) - .flex() - .items_center() - .justify_center() - .child( - svg() - .path("icons/music-note.svg") - .w(px(16.0)) - .h(px(16.0)) - .text_color(muted), - ) - .into_any_element(), - }) - .child( - div() - .flex_col() - .flex_grow(1.0) - .overflow_hidden() - .child( - playing_track_link( - "playing-title", - title, - fg, - has_track, - echo_core::models::ActionMenuAction::GoToAlbum, - cx, - ) - .text_sm(), - ) - .child( - playing_track_link( - "playing-artist", - artist, - muted, - has_track, - echo_core::models::ActionMenuAction::GoToArtist, - cx, - ) - .text_xs(), - ), - ) - .children(liked_button), - ) - .child( - div() - .flex_grow(1.0) - .flex() - .flex_col() - .items_center() - .justify_center() + .text_xs() + .text_color(muted) + .whitespace_nowrap() + .max_w_full() .overflow_hidden() - .when_some(inline_lyrics, |el, (current, next)| { - el.child( - div() - .text_sm() - .text_color(accent) - .whitespace_nowrap() - .max_w_full() - .overflow_hidden() - .child(SharedString::from(current)), - ) - .when(!next.is_empty(), |el| { - el.child( - div() - .text_xs() - .text_color(muted) - .whitespace_nowrap() - .max_w_full() - .overflow_hidden() - .child(SharedString::from(next)), - ) - }) - }) - .when_some(playing_from, |el, label| { - el.child( - div() - .text_xs() - .text_color(muted) - .whitespace_nowrap() - .max_w_full() - .overflow_hidden() - .text_ellipsis() - .child(SharedString::from(label)), - ) - }), + .child(SharedString::from(next)), ) - .child( - div() - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .flex() - .flex_row() - .items_center() - .justify_end() - .gap_3() - .when_some(playing_on, |el, label| { - el.child( - div() - .id("playing-on") - .flex_none() - .max_w(px(160.0)) - .px_2() - .py_1() - .rounded_full() - .border_1() - .border_color(accent) - .flex() - .flex_row() - .items_center() - .gap_1() - .cursor_pointer() - .hover(move |style| style.bg(palette.wash)) - .on_click(cx.listener(|this, _event, _window, cx| { - this.open_devices(cx) - })) - .child( - svg() - .path("icons/computer.svg") - .size(px(12.0)) - .text_color(accent), - ) - .child( - div() - .text_xs() - .text_color(accent) - .whitespace_nowrap() - .text_ellipsis() - .overflow_hidden() - .child(label), - ), - ) - }) - .when_some(visualizer_bands, |el, bands| { - // The engine always fills 32 bands, 0–100; they are averaged down - // to the configured bin count (`:visbins`) and painted as - // bottom-anchored bars. Repaints ride the fast tick. - el.child( - div().flex_none().w(px(120.0)).h(px(32.0)).child( - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let bands = bands.lock(); - let chunk = bands.len() as f32 / vis_bins as f32; - let band_width = - bounds.size.width / vis_bins as f32; - for index in 0..vis_bins { - let start = (index as f32 * chunk) as usize; - let end = if index == vis_bins - 1 { - bands.len() - } else { - ((index + 1) as f32 * chunk) as usize - }; - let slice = &bands[start..end.max(start + 1)]; - let value = slice.iter().sum::() - / slice.len() as f32; - let ratio = (value / 100.0).clamp(0.0, 1.0); - let bar_height = bounds.size.height * ratio; - let origin = gpui::point( - bounds.origin.x + band_width * index as f32, - bounds.origin.y + bounds.size.height - - bar_height, - ); - let bar = Bounds { - origin, - size: size(band_width * 0.8, bar_height), - }; - window.paint_quad(gpui::fill(bar, accent)); - } - }, - ) - .size_full(), - ), - ) - }), - ), + }) + }) + .when_some(playing_from, |el, label| { + el.child( + div() + .text_xs() + .text_color(muted) + .whitespace_nowrap() + .max_w_full() + .overflow_hidden() + .text_ellipsis() + .child(SharedString::from(label)), + ) + }) + } + + // Playback on another Connect device (a phone, a speaker) gets a pill naming it; + // echo's own device and local files are the norm and stay unlabelled. + fn playing_on_pill( + &self, + colors: ControlColors, + cx: &mut Context, + ) -> Option> { + let ControlColors { accent, hover, .. } = colors; + let playback = &self.state.playback; + let has_track = playback.playing_track_id.is_some(); + let playing_on: Option = (has_track + && playback.device_name != echo_core::worker::audio::DEVICE_NAME + && playback.device_name != "Local" + && !playback.device_name.is_empty()) + .then(|| { + views::tr(&self.state, "desktop.playing_on") + .replace("{}", &playback.device_name) + .into() + }); + playing_on.map(|label| { + div() + .id("playing-on") + .flex_none() + .max_w(px(160.0)) + .px_2() + .py_1() + .rounded_full() + .border_1() + .border_color(accent) + .flex() + .flex_row() + .items_center() + .gap_1() + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .on_click(cx.listener(|this, _event, _window, cx| this.open_devices(cx))) + .child( + svg() + .path("icons/computer.svg") + .size(px(12.0)) + .text_color(accent), + ) + .child( + div() + .text_xs() + .text_color(accent) + .whitespace_nowrap() + .text_ellipsis() + .overflow_hidden() + .child(label), + ) + }) + } + + /// The engine always fills 32 bands, 0–100; they are averaged down to the configured bin + /// count (`:visbins`) and painted as bottom-anchored bars. Repaints ride the fast tick. + fn visualizer(&self, accent: Hsla) -> Option
{ + let visualizer_bands = (self.state.ui.library_config.enable_visualizer + && self.state.playback.is_playing) + .then(|| self.state.playback.audio_visualization.clone()) + .flatten(); + let vis_bins = self.state.ui.vis_bins.clamp(5, 32); + visualizer_bands.map(|bands| { + div().flex_none().w(px(120.0)).h(px(32.0)).child( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let bands = bands.lock(); + let chunk = bands.len() as f32 / vis_bins as f32; + let band_width = bounds.size.width / vis_bins as f32; + for index in 0..vis_bins { + let start = (index as f32 * chunk) as usize; + let end = if index == vis_bins - 1 { + bands.len() + } else { + ((index + 1) as f32 * chunk) as usize + }; + let slice = &bands[start..end.max(start + 1)]; + let value = slice.iter().sum::() / slice.len() as f32; + let ratio = (value / 100.0).clamp(0.0, 1.0); + let bar_height = bounds.size.height * ratio; + let origin = gpui::point( + bounds.origin.x + band_width * index as f32, + bounds.origin.y + bounds.size.height - bar_height, + ); + let bar = Bounds { + origin, + size: size(band_width * 0.8, bar_height), + }; + window.paint_quad(gpui::fill(bar, accent)); + } + }, + ) + .size_full(), ) + }) + } + + /// The queue and device buttons, mute, and the volume bar. + fn output_controls(&self, colors: ControlColors, cx: &mut Context) -> Div { + let ControlColors { + fg, + muted, + accent, + hover, + track, + } = colors; + let playback = &self.state.playback; + let volume_fraction = (playback.volume as f32 / 100.0).clamp(0.0, 1.0); + let volume_label: SharedString = format!("{}%", playback.volume).into(); + let mute_icon = if playback.volume == 0 { + "icons/volume-off.svg" + } else { + "icons/volume-high.svg" + }; + let queue_color = if self.right_panel == Some(RightPanel::Queue) { + accent + } else { + muted + }; + let volume_bounds = self.volume_bounds.clone(); + + div() + .flex_none() + .w(px(PLAYBACK_SIDE_WIDTH)) + .flex() + .flex_row() + .items_center() + .justify_end() + .gap_1() + .child(icon_button( + "queue", + "icons/playlist.svg", + queue_color, + hover, + cx, + |this, cx| this.toggle_right_panel(RightPanel::Queue, cx), + )) + .child(icon_button( + "devices", + "icons/computer.svg", + muted, + hover, + cx, + |this, cx| this.open_devices(cx), + )) + .child(icon_button( + "mute", + mute_icon, + muted, + hover, + cx, + |this, cx| this.toggle_mute(cx), + )) .child( - // Bottom row: transport, seek and volume on one line, so the seek bar sits on the - // buttons' baseline no matter what the row above is doing. div() - .flex() - .flex_row() - .items_center() - .gap_3() - .h(px(PLAYBACK_ROW_HEIGHT)) - .child( - self.transport_controls(controls, cx) - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .child(icon_button( - "lyrics", - "icons/mic.svg", - lyrics_color, - palette.wash, - cx, - |this, cx| this.toggle_lyrics(cx), - )), + .id("volume-bar") + .flex_none() + .w(px(90.0)) + .py_2() + .cursor_pointer() + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| { + this.begin_scrub(Scrub::Volume, event.position.x, cx); + }), ) - .child(self.seek_bar(controls, cx)) .child( div() - .flex_none() - .w(px(PLAYBACK_SIDE_WIDTH)) - .flex() - .flex_row() - .items_center() - .justify_end() - .gap_1() - .child(icon_button( - "queue", - "icons/playlist.svg", - queue_color, - palette.wash, - cx, - |this, cx| this.toggle_right_panel(RightPanel::Queue, cx), - )) - .child(icon_button( - "devices", - "icons/computer.svg", - muted, - palette.wash, - cx, - |this, cx| this.open_devices(cx), - )) - .child(icon_button( - "mute", - mute_icon, - muted, - palette.wash, - cx, - |this, cx| this.toggle_mute(cx), - )) + .relative() + .w_full() + .h(px(6.0)) + .rounded_full() + .bg(track) .child( - div() - .id("volume-bar") - .flex_none() - .w(px(90.0)) - .py_2() - .cursor_pointer() - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener( - |this, event: &gpui::MouseDownEvent, _window, cx| { - this.begin_scrub( - Scrub::Volume, - event.position.x, - cx, - ); - }, - ), - ) - .child( - div() - .relative() - .w_full() - .h(px(6.0)) - .rounded_full() - .bg(palette.border) - .child( - canvas( - move |bounds, _window, _cx| { - volume_bounds.set(bounds) - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .child( - div() - .h_full() - .rounded_full() - .bg(fg) - .w(gpui::relative(volume_fraction)), - ), - ), + canvas( + move |bounds, _window, _cx| volume_bounds.set(bounds), + |_, _, _, _| {}, + ) + .absolute() + .size_full(), ) .child( div() - .flex_none() - .w(px(34.0)) - .text_xs() - .text_color(fg) - .child(volume_label), + .h_full() + .rounded_full() + .bg(fg) + .w(gpui::relative(volume_fraction)), ), ), ) + .child( + div() + .flex_none() + .w(px(34.0)) + .text_xs() + .text_color(fg) + .child(volume_label), + ) } /// Shuffle, previous, play/pause, next and repeat in a row, two each side of play so it From 62add9b1687599cd6f08639eb97a36bd4e5bf59f Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 14:31:16 -0500 Subject: [PATCH 39/44] desktop: split the artist page into its header and row builders Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views/artist.rs | 638 ++++++++++++------------ 1 file changed, 321 insertions(+), 317 deletions(-) diff --git a/crates/echo-desktop/src/views/artist.rs b/crates/echo-desktop/src/views/artist.rs index 201aa1a..ccb3419 100644 --- a/crates/echo-desktop/src/views/artist.rs +++ b/crates/echo-desktop/src/views/artist.rs @@ -353,10 +353,7 @@ pub(super) fn whats_new(app: &mut EchoApp, cx: &mut Context) -> impl In } pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyElement { - let theme = &app.state.ui.active_theme; - let outer_palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); + let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); let Some(data) = app.state.data.artist_page_data.clone() else { return div() @@ -369,17 +366,7 @@ pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyEl .into_any_element(); }; - let header_image = app - .state - .ui - .active_library_header_image - .clone() - .and_then(|artwork| app.images.get(&artwork)); let filter = app.state.ui.artist_discography_filter; - let count = data - .chips - .get(&echo_core::models::DiscographyFilter::All) - .map_or(data.albums.len(), |page| page.total); let loading = app.state.data.artist_albums_loading && data.albums.is_empty(); let row_count = data.album_row_count(filter); let top_len = data.top_tracks.len(); @@ -390,64 +377,7 @@ pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyEl .flex() .flex_col() .overflow_hidden() - .child( - div() - .flex_none() - .px_4() - .py_3() - .flex() - .flex_row() - .items_center() - .gap_3() - .child( - div() - .id("artist-back") - .flex_none() - .w(px(28.0)) - .h(px(28.0)) - .flex() - .items_center() - .justify_center() - .rounded_full() - .text_color(muted) - .hover(move |style| style.bg(outer_palette.wash)) - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { - this.close_artist_page(cx); - })) - .child( - svg() - .path("icons/arrow-left.svg") - .w(px(16.0)) - .h(px(16.0)) - .text_color(muted), - ), - ) - .when_some(header_image, |el, image| { - el.child( - cover_image(image, 72.0, 36.0), - ) - }) - .child( - div() - .flex() - .flex_col() - .flex_grow(1.0) - .overflow_hidden() - .child( - div() - .text_lg() - .text_color(fg) - .child(SharedString::from(data.artist_name.clone())), - ) - .child( - div() - .text_xs() - .text_color(muted) - .child(SharedString::from(format!("{count} albums"))), - ), - ) - .child(follow_button(app, &data.artist_id, cx)), - ) + .child(artist_header(app, &data, cx)) .when(top_len > 0 || top_loading, |el| { el.child( div() @@ -473,133 +403,8 @@ pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyEl "artist-top-track-rows", top_len, cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let drag_colors = DragColors::resolve(theme); - let selected_bg = palette.row_selected; - // Combined index space: Popular rows come first, so `ix` compares - // against the page cursor directly. - let selected = this.state.ui.artist_page_album_index; - let playing_id = this.state.playback.playing_track_id.clone(); - - let rows: Vec = range - .map(|ix| { - let Some(track) = this - .state - .data - .artist_page_data - .as_ref() - .and_then(|data| data.top_tracks.get(ix)) - .cloned() - else { - return div().id(ix).into_any_element(); - }; - let is_playing = - playing_id.as_deref() == Some(track.id.as_str()); - let is_liked = this.state.data.liked_tracks.contains(&track.id); - let secondary = - this.state.ui.active_theme.secondary.gpui(WINDOW_FG()); - let title_color = if is_playing { accent } else { fg }; - let thumb = thumb_element( - this, - track.image_url.as_deref(), - 26.0, - false, - muted, - ); - let cover = thumb_image(this, track.image_url.as_deref(), DRAG_COVER_EDGE); - let payload = single_drag_payload(&track, cover); - pill_row( - ix, - LIST_PILL, - ix == selected, - selected_bg, - palette.row_hover, - |row| { - row.gap_3() - .on_drag(payload, move |drag, _offset, _window, cx| { - track_drag_preview(drag, drag_colors, cx) - }) - .on_click(cx.listener( - move |this: &mut EchoApp, - event: &gpui::ClickEvent, - _window, - cx| { - this.state.ui.artist_page_album_index = ix; - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_artist_top_track( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.artist_page_album_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }), - ) - .child(div() - .flex_none() - .w(px(24.0)) - .text_xs() - .text_color(muted) - .child(row_number(&this.state, ix, selected)),) - .child(thumb) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(title_color) - .child(SharedString::from(track.name.clone())), - ) - .child(liked_cell( - "popular", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - .child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(format_time( - track.duration_ms, - ))), - ) - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows + |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + artist_top_track_rows(this, range, cx) }, ), ) @@ -642,124 +447,8 @@ pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyEl "artist-album-rows", row_count, cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - // Album rows sit after the Popular rows in the page's combined index space. - let selected = this.state.ui.artist_page_album_index; - let top_len = this.artist_page_top_len(); - let more_label = tr( - &this.state, - if this.state.data.artist_albums_loading { - "desktop.loading" - } else { - "desktop.load_more" - }, - ); - - let rows: Vec = range - .map(|ix| { - let Some(album) = this - .state - .data - .artist_page_data - .as_ref() - .and_then(|data| data.albums.get(ix)) - .cloned() - else { - // The Load more row after the last album. - return pill_row( - ix, - LIST_PILL, - ix + top_len == selected, - selected_bg, - palette.row_hover, - |row| { - row.justify_center() - .text_color(muted) - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - if let Some(event) = - echo_core::intent::load_more_artist_albums( - &mut this.state, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child(more_label.clone()) - }, - ) - .into_any_element(); - }; - let thumb_url = - album.thumb_url.clone().or_else(|| album.image_url.clone()); - let thumb = - thumb_element(this, thumb_url.as_deref(), 26.0, false, muted); - let tracks_label = album - .track_count - .map(|n| format!("{n} tracks")) - .unwrap_or_default(); - pill_row( - ix, - LIST_PILL, - ix + top_len == selected, - selected_bg, - palette.row_hover, - |row| { - row.gap_3() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - let index = ix + this.artist_page_top_len(); - if let Some(event) = - echo_core::intent::activate_artist_page_row( - &mut this.state, - index, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - .child(thumb) - .child( - div() - .flex_grow(1.0) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(album.name)), - ) - .child( - div() - .flex_none() - .text_xs() - .text_color(muted) - .child(SharedString::from(album.release_year)), - ) - .child( - div() - .flex_none() - .w(px(70.0)) - .text_xs() - .text_color(muted) - .child(SharedString::from(tracks_label)), - ) - }, - ) - .into_any_element() - }) - .collect(); - - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows + |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + artist_album_rows(this, range, cx) }, ), ) @@ -769,3 +458,318 @@ pub(super) fn artist_page(app: &mut EchoApp, cx: &mut Context) -> AnyEl }) .into_any_element() } + +/// The back button, portrait, name and album count, and the follow button. +fn artist_header( + app: &mut EchoApp, + data: &echo_core::models::ArtistPageData, + cx: &mut Context, +) -> Div { + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let header_image = app + .state + .ui + .active_library_header_image + .clone() + .and_then(|artwork| app.images.get(&artwork)); + let count = data + .chips + .get(&echo_core::models::DiscographyFilter::All) + .map_or(data.albums.len(), |page| page.total); + + div() + .flex_none() + .px_4() + .py_3() + .flex() + .flex_row() + .items_center() + .gap_3() + .child( + div() + .id("artist-back") + .flex_none() + .w(px(28.0)) + .h(px(28.0)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .text_color(muted) + .hover(move |style| style.bg(palette.wash)) + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.close_artist_page(cx); + })) + .child( + svg() + .path("icons/arrow-left.svg") + .w(px(16.0)) + .h(px(16.0)) + .text_color(muted), + ), + ) + .when_some(header_image, |el, image| { + el.child(cover_image(image, 72.0, 36.0)) + }) + .child( + div() + .flex() + .flex_col() + .flex_grow(1.0) + .overflow_hidden() + .child( + div() + .text_lg() + .text_color(fg) + .child(SharedString::from(data.artist_name.clone())), + ) + .child( + div() + .text_xs() + .text_color(muted) + .child(SharedString::from(format!("{count} albums"))), + ), + ) + .child(follow_button(app, &data.artist_id, cx)) +} + +fn artist_top_track_rows( + this: &mut EchoApp, + range: std::ops::Range, + cx: &mut Context, +) -> Vec { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let drag_colors = DragColors::resolve(theme); + let selected_bg = palette.row_selected; + // Combined index space: Popular rows come first, so `ix` compares + // against the page cursor directly. + let selected = this.state.ui.artist_page_album_index; + let playing_id = this.state.playback.playing_track_id.clone(); + + let rows: Vec = range + .map(|ix| { + let Some(track) = this + .state + .data + .artist_page_data + .as_ref() + .and_then(|data| data.top_tracks.get(ix)) + .cloned() + else { + return div().id(ix).into_any_element(); + }; + let is_playing = playing_id.as_deref() == Some(track.id.as_str()); + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let secondary = this.state.ui.active_theme.secondary.gpui(WINDOW_FG()); + let title_color = if is_playing { accent } else { fg }; + let thumb = thumb_element(this, track.image_url.as_deref(), 26.0, false, muted); + let cover = thumb_image(this, track.image_url.as_deref(), DRAG_COVER_EDGE); + let payload = single_drag_payload(&track, cover); + pill_row( + ix, + LIST_PILL, + ix == selected, + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .on_drag(payload, move |drag, _offset, _window, cx| { + track_drag_preview(drag, drag_colors, cx) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + this.state.ui.artist_page_album_index = ix; + if event.click_count() >= 2 + && let Some(event) = echo_core::intent::play_artist_top_track( + &mut this.state, + ix, + ) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .on_mouse_down( + MouseButton::Right, + cx.listener( + move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.artist_page_album_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }, + ), + ) + .child( + div() + .flex_none() + .w(px(24.0)) + .text_xs() + .text_color(muted) + .child(row_number(&this.state, ix, selected)), + ) + .child(thumb) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(title_color) + .child(SharedString::from(track.name.clone())), + ) + .child(liked_cell( + "popular", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + .child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(format_time(track.duration_ms))), + ) + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows +} + +fn artist_album_rows( + this: &mut EchoApp, + range: std::ops::Range, + cx: &mut Context, +) -> Vec { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + // Album rows sit after the Popular rows in the page's combined index space. + let selected = this.state.ui.artist_page_album_index; + let top_len = this.artist_page_top_len(); + let more_label = tr( + &this.state, + if this.state.data.artist_albums_loading { + "desktop.loading" + } else { + "desktop.load_more" + }, + ); + + let rows: Vec = range + .map(|ix| { + let Some(album) = this + .state + .data + .artist_page_data + .as_ref() + .and_then(|data| data.albums.get(ix)) + .cloned() + else { + // The Load more row after the last album. + return pill_row( + ix, + LIST_PILL, + ix + top_len == selected, + selected_bg, + palette.row_hover, + |row| { + row.justify_center() + .text_color(muted) + .on_click(cx.listener( + move |this: &mut EchoApp, _event, _window, cx| { + if let Some(event) = + echo_core::intent::load_more_artist_albums(&mut this.state) + { + this.dispatch(event); + } + cx.notify(); + }, + )) + .child(more_label.clone()) + }, + ) + .into_any_element(); + }; + let thumb_url = album.thumb_url.clone().or_else(|| album.image_url.clone()); + let thumb = thumb_element(this, thumb_url.as_deref(), 26.0, false, muted); + let tracks_label = album + .track_count + .map(|n| format!("{n} tracks")) + .unwrap_or_default(); + pill_row( + ix, + LIST_PILL, + ix + top_len == selected, + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + let index = ix + this.artist_page_top_len(); + if let Some(event) = + echo_core::intent::activate_artist_page_row(&mut this.state, index) + { + this.dispatch(event); + } + cx.notify(); + })) + .child(thumb) + .child( + div() + .flex_grow(1.0) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(album.name)), + ) + .child( + div() + .flex_none() + .text_xs() + .text_color(muted) + .child(SharedString::from(album.release_year)), + ) + .child( + div() + .flex_none() + .w(px(70.0)) + .text_xs() + .text_color(muted) + .child(SharedString::from(tracks_label)), + ) + }, + ) + .into_any_element() + }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows +} From 8dbb467f9f74c5694312590690edfdf7f7ae4a6c Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 17:01:27 -0500 Subject: [PATCH 40/44] desktop: split the track list into its header, row builder and row handlers Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views/track_list.rs | 785 ++++++++++++-------- 1 file changed, 464 insertions(+), 321 deletions(-) diff --git a/crates/echo-desktop/src/views/track_list.rs b/crates/echo-desktop/src/views/track_list.rs index bc769fd..c833fcd 100644 --- a/crates/echo-desktop/src/views/track_list.rs +++ b/crates/echo-desktop/src/views/track_list.rs @@ -441,9 +441,7 @@ pub(super) fn track_list( window: &mut Window, cx: &mut Context, ) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); + let muted = app.state.ui.active_theme.text_muted.gpui(WINDOW_FG()); let wide = app.main_content_width(window) >= 640.0; let hero = wide && app @@ -454,6 +452,65 @@ pub(super) fn track_list( .is_some_and(|context| context.requires_worker_load()); let columns = track_columns(&app.state); + let count = app.state.data.tracks.len(); + let loading = count == 0 && app.state.data.active_context_details.is_none(); + + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child(if hero { + context_hero(app, cx).into_any_element() + } else { + track_page_header(app, wide, cx).into_any_element() + }) + .child(track_column_headers(app, columns, cx)) + .child(if loading { + div() + .flex_grow(1.0) + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(tr(&app.state, "desktop.loading")) + .into_any_element() + } else { + uniform_list( + "track-rows", + count, + cx.processor( + move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + track_rows(this, range, columns, cx) + }, + ), + ) + .track_scroll(&app.tracks_scroll) + .on_drag_move(cx.listener( + |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { + this.drag_autoscroll( + crate::DragList::Tracks, + event.event.position.y, + event.bounds, + cx, + ); + }, + )) + .on_drop( + cx.listener(|this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { + drop_tracks_at_end(this, drag, cx); + }), + ) + .flex_grow(1.0) + .into_any_element() + }) +} + +/// The compact page header: cover, title and author, and the page's buttons. +fn track_page_header(app: &mut EchoApp, wide: bool, cx: &mut Context) -> Div { + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); let (context_title, context_author) = app .state .data @@ -468,9 +525,6 @@ pub(super) fn track_list( .active_library_header_image .clone() .and_then(|artwork| app.images.get(&artwork)); - - let count = app.state.data.tracks.len(); - let loading = count == 0 && app.state.data.active_context_details.is_none(); let is_top_tracks = app .state .data @@ -479,341 +533,430 @@ pub(super) fn track_list( .is_some_and(|context| context.id == "TOP_TRACKS"); div() - .flex_grow(1.0) + .flex_none() + .px_4() + .py_3() .flex() - .flex_col() - .overflow_hidden() - .child(if hero { - context_hero(app, cx).into_any_element() - } else { + .flex_row() + .items_center() + .gap_3() + .when_some(header_image.filter(|_| wide), |el, image| { + el.child(cover_image(image, 72.0, 6.0)) + }) + .child( div() - .flex_none() - .px_4() - .py_3() + .flex_grow(1.0) .flex() - .flex_row() - .items_center() - .gap_3() - .when_some(header_image.filter(|_| wide), |el, image| { - el.child( - cover_image(image, 72.0, 6.0), - ) - }) + .flex_col() + .overflow_hidden() .child( div() - .flex_grow(1.0) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .text_lg() - .text_color(fg) - .truncate() - .child(SharedString::from(context_title)), - ) - .when(wide, |el| el.child( - div() - .text_xs() - .text_color(muted) - .truncate() - .child(SharedString::from(context_author)), - )), + .text_lg() + .text_color(fg) + .truncate() + .child(SharedString::from(context_title)), ) - .when(is_top_tracks, |el| el.child(range_switcher(app, cx))) - .child(playlist_edit::page_buttons(app, cx)) - .child(sort_button(app, cx)) - .into_any_element() - }) - .child(track_column_headers(app, columns, cx)) - .child(if loading { - div() - .flex_grow(1.0) - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(tr(&app.state, "desktop.loading")) - .into_any_element() - } else { - uniform_list( - "track-rows", - count, - cx.processor(move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = if this.state.ui.active_view == ActiveView::TrackList { - palette.row_selected - } else { - palette.row_hover - }; - let selected = this.state.ui.selected_track_index; - let visual = visual_range_in(&this.state, ActiveView::TrackList); - let picked = picked_in(&this.state, ActiveView::TrackList); - let context_id = this - .state - .data - .active_tracklist_context - .as_ref() - .map(|context| context.id.clone()); - let playing_id = this.state.playback.playing_track_id.clone(); - let secondary = theme.secondary.gpui(WINDOW_FG()); - // On an album page every row shares the album in the header, so the - // column carries no information. - let in_album = this - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.is_album()); - // Inside Liked Songs every track is liked, so the hearts say nothing. - let in_liked_songs = this - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| context.id == "LIKED_SONGS"); - // Rows are drag-reorderable only where a reorder can be applied: a - // playlist the user can modify, shown in original order. - let reorderable = this.state.ui.track_sort - == echo_core::app::TrackSort::Original - && this.state.ui.track_sort_ascending - && this - .state - .data - .active_tracklist_context - .as_ref() - .is_some_and(|context| { - context.can_modify_playlist(this.state.data.user_id.as_ref()) - }); - let drag_colors = DragColors::resolve(theme); + .when(wide, |el| { + el.child( + div() + .text_xs() + .text_color(muted) + .truncate() + .child(SharedString::from(context_author)), + ) + }), + ) + .when(is_top_tracks, |el| el.child(range_switcher(app, cx))) + .child(playlist_edit::page_buttons(app, cx)) + .child(sort_button(app, cx)) +} - let rows = range - .map(|ix| { - let track = this.state.data.tracks[ix].clone(); - let thumb = thumb_element(this, track.image_url.as_deref(), 32.0, false, muted); - let is_liked = this.state.data.liked_tracks.contains(&track.id); - let is_playing = playing_id.as_deref() == Some(track.id.as_str()); - let title_color = if is_playing { accent } else { fg }; - let payload = drag_payload(this, ActiveView::TrackList, ix, &track); - let over_context = context_id.clone(); - let drop_context = context_id.clone(); +fn track_rows( + this: &mut EchoApp, + range: std::ops::Range, + columns: TrackColumns, + cx: &mut Context, +) -> Vec
{ + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = if this.state.ui.active_view == ActiveView::TrackList { + palette.row_selected + } else { + palette.row_hover + }; + let selected = this.state.ui.selected_track_index; + let visual = visual_range_in(&this.state, ActiveView::TrackList); + let picked = picked_in(&this.state, ActiveView::TrackList); + let context_id = this + .state + .data + .active_tracklist_context + .as_ref() + .map(|context| context.id.clone()); + let playing_id = this.state.playback.playing_track_id.clone(); + let secondary = theme.secondary.gpui(WINDOW_FG()); + // On an album page every row shares the album in the header, so the + // column carries no information. + let in_album = this + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.is_album()); + // Inside Liked Songs every track is liked, so the hearts say nothing. + let in_liked_songs = this + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.id == "LIKED_SONGS"); + // Rows are drag-reorderable only where a reorder can be applied: a + // playlist the user can modify, shown in original order. + let reorderable = this.state.ui.track_sort == echo_core::app::TrackSort::Original + && this.state.ui.track_sort_ascending + && this + .state + .data + .active_tracklist_context + .as_ref() + .is_some_and(|context| context.can_modify_playlist(this.state.data.user_id.as_ref())); + let drag_colors = DragColors::resolve(theme); - pill_row(ix, TRACK_PILL, row_marked(ix, selected, visual, &picked), selected_bg, palette.row_hover, |row| { - row.gap_3().group("track-row") - .on_drag(payload, move |drag, _offset, _window, cx| { - track_drag_preview(drag, drag_colors, cx) - }) - .when(reorderable, |row| { - row.drag_over::(move |style, drag, _, _| { - if drag.source_context == over_context { - style.bg(palette.drag_target) - } else { - style.border_t_2().border_color(accent) + let rows = range + .map(|ix| { + let track = this.state.data.tracks[ix].clone(); + let thumb = thumb_element(this, track.image_url.as_deref(), 32.0, false, muted); + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let is_playing = playing_id.as_deref() == Some(track.id.as_str()); + let title_color = if is_playing { accent } else { fg }; + let payload = drag_payload(this, ActiveView::TrackList, ix, &track); + let over_context = context_id.clone(); + let drop_context = context_id.clone(); + + pill_row( + ix, + TRACK_PILL, + row_marked(ix, selected, visual, &picked), + selected_bg, + palette.row_hover, + |row| { + row.gap_3() + .group("track-row") + .on_drag(payload, move |drag, _offset, _window, cx| { + track_drag_preview(drag, drag_colors, cx) + }) + .when(reorderable, |row| { + row.drag_over::(move |style, drag, _, _| { + if drag.source_context == over_context { + style.bg(palette.drag_target) + } else { + style.border_t_2().border_color(accent) + } + }) + .on_drop( + cx.listener( + move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { + let same_list = drag.source_context == drop_context; + if same_list && drag.tracks.len() > 1 { + return; } - }) - .on_drop(cx.listener( - move |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { - let same_list = drag.source_context == drop_context; - if same_list && drag.tracks.len() > 1 { - return; - } - if let Some(event) = - echo_core::intent::drop_tracks_in_tracklist( - &mut this.state, - drag.tracks.clone(), - same_list.then_some(drag.from_row), - Some(ix), - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )) - }) - .on_click(cx.listener(move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { - // Shift-click selects from the previously focused row to - // this one — the desktop's version of `v` plus motion. - if event.modifiers().shift { - this.extend_selection_to(ix, cx); - return; - } - this.state.ui.active_view = ActiveView::TrackList; - if is_pick_click(event) { - echo_core::intent::toggle_picked_row(&mut this.state, ix); - cx.notify(); - return; - } - this.state.ui.selected_track_index = ix; - if event.click_count() >= 2 - && let Some(event) = - echo_core::intent::play_track_at(&mut this.state, ix) - { - this.dispatch(event); - } - cx.notify(); - })) - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_track_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); + if let Some(event) = + echo_core::intent::drop_tracks_in_tracklist( + &mut this.state, + drag.tracks.clone(), + same_list.then_some(drag.from_row), + Some(ix), + ) + { + this.dispatch(event); } cx.notify(); - }), - ) - .child(track_index_cell(this, ix, selected, is_playing, accent, muted, cx)) + }, + ), + ) + }) + .on_click(cx.listener( + move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + click_track_row(this, ix, event, cx); + }, + )) + .on_mouse_down( + MouseButton::Right, + cx.listener( + move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + open_track_row_menu(this, ix, event.position, cx); + }, + ), + ) + .child(track_index_cell( + this, ix, selected, is_playing, accent, muted, cx, + )) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .min_w_0() + .flex() + .items_center() + .gap_2() + .child(thumb) .child( div() - .flex_grow(2.0) - .flex_basis(px(0.0)) .min_w_0() - .flex().items_center().gap_2() - .child(thumb) - .child(div().min_w_0().flex_1().flex().flex_col() - .child(div() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(title_color) - .child(SharedString::from(track.name.clone()))) - .child(div().flex().items_center().gap_1().text_xs().overflow_hidden() - .when(track.explicit, |el| el.child(div().flex_none().rounded_sm().border_1().border_color(muted).px(px(2.0)).text_size(px(10.0)).text_color(muted).child(tr(&this.state, "desktop.context.explicit")))) - .child({ - let base = div() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_color(muted); - if track.artists.is_empty() { - // Local files and pre-credit caches carry only the - // joined string: one span, go-to-artist fallback. - base.id(("track-artist", ix)) - .text_ellipsis() - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { - cx.stop_propagation(); - if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { - this.go_to(ctx, ActionMenuAction::GoToArtist, cx); - } - })) - .child(SharedString::from(track.artist.clone())) - .into_any_element() - } else { - let mut cell = base.flex().flex_row().items_center(); - for (k, credit) in track.artists.iter().enumerate() { - if k > 0 { - cell = cell.child(div().flex_none().child(SharedString::from(", "))); + .flex_1() + .flex() + .flex_col() + .child( + div() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(title_color) + .child(SharedString::from(track.name.clone())), + ) + .child( + div() + .flex() + .items_center() + .gap_1() + .text_xs() + .overflow_hidden() + .when(track.explicit, |el| { + el.child( + div() + .flex_none() + .rounded_sm() + .border_1() + .border_color(muted) + .px(px(2.0)) + .text_size(px(10.0)) + .text_color(muted) + .child(tr( + &this.state, + "desktop.context.explicit", + )), + ) + }) + .child(track_artist_cell(ix, &track, muted, cx)), + ), + ), + ) + .when(!in_album, |row| { + row.child( + div() + .id(("track-album", ix)) + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener( + move |this: &mut EchoApp, + _event: &gpui::ClickEvent, + _window, + cx| { + cx.stop_propagation(); + if let Some(ctx) = this + .state + .data + .tracks + .get(ix) + .map(ActionMenuContext::from) + { + this.go_to(ctx, ActionMenuAction::GoToAlbum, cx); } - let name = SharedString::from(credit.name.clone()); - cell = cell.child(match credit.id.clone() { - Some(id) => { - let artist_name = credit.name.clone(); - div() - .id(SharedString::from(format!("track-artist-{ix}-{k}"))) - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { - cx.stop_propagation(); - this.open_artist(id.clone(), artist_name.clone(), cx); - })) - .child(name) - .into_any_element() - } - None => div().child(name).into_any_element(), - }); - } - cell.into_any_element() - } - }))), - ) - .when(!in_album, |row| { - row.child( - div() - .id(("track-album", ix)) - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .cursor_pointer() - .hover(|style| style.underline()) - .on_click(cx.listener(move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { - cx.stop_propagation(); - if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { - this.go_to(ctx, ActionMenuAction::GoToAlbum, cx); - } - })) - .child(SharedString::from(track.album.clone())), - ) - }) - .when(columns.added_by, |row| row.child(div().flex_grow(1.0).flex_basis(px(0.0)).min_w_0().truncate().text_color(muted).child(SharedString::from(track.added_by.clone().unwrap_or_default())))) - .when(columns.date, |row| row.child(div().flex_grow(1.0).flex_basis(px(0.0)).min_w_0().truncate().text_color(muted).child(SharedString::from(echo_core::context_details::format_added_at_with(std::time::SystemTime::now().into(), track.added_at.as_deref().unwrap_or_default(), &|key| tr(&this.state, key).to_string()))))) - .when(!in_liked_songs, |row| { - row.child(liked_cell( - "tracks", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, + }, )) - }) - .child( - div() - .flex_none() - .w(px(48.0)) - .text_color(muted) - .child(SharedString::from(format_time(track.duration_ms))), - ) - }) + .child(SharedString::from(track.album.clone())), + ) }) - .collect(); - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }), - ) - .track_scroll(&app.tracks_scroll) - .on_drag_move(cx.listener( - |this: &mut EchoApp, event: &gpui::DragMoveEvent, _window, cx| { - this.drag_autoscroll(crate::DragList::Tracks, event.event.position.y, event.bounds, cx); + .when(columns.added_by, |row| { + row.child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .min_w_0() + .truncate() + .text_color(muted) + .child(SharedString::from( + track.added_by.clone().unwrap_or_default(), + )), + ) + }) + .when(columns.date, |row| { + row.child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .min_w_0() + .truncate() + .text_color(muted) + .child(SharedString::from( + echo_core::context_details::format_added_at_with( + std::time::SystemTime::now().into(), + track.added_at.as_deref().unwrap_or_default(), + &|key| tr(&this.state, key).to_string(), + ), + )), + ) + }) + .when(!in_liked_songs, |row| { + row.child(liked_cell( + "tracks", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + }) + .child( + div() + .flex_none() + .w(px(48.0)) + .text_color(muted) + .child(SharedString::from(format_time(track.duration_ms))), + ) }, - )) - .on_drop(cx.listener( - |this: &mut EchoApp, drag: &DraggedTracks, _window, cx| { - // A drop past the last row appends; drops on rows never reach here. - let same_list = drag.source_context.is_some() - && drag.source_context - == this.state.data.active_tracklist_context.as_ref().map(|c| c.id.clone()); - if same_list && drag.tracks.len() > 1 { - return; - } - if let Some(event) = echo_core::intent::drop_tracks_in_tracklist( - &mut this.state, - drag.tracks.clone(), - same_list.then_some(drag.from_row), - None, - ) { - this.dispatch(event); + ) + }) + .collect(); + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows +} + +fn click_track_row( + this: &mut EchoApp, + ix: usize, + event: &gpui::ClickEvent, + cx: &mut Context, +) { + // Shift-click selects from the previously focused row to + // this one — the desktop's version of `v` plus motion. + if event.modifiers().shift { + this.extend_selection_to(ix, cx); + return; + } + this.state.ui.active_view = ActiveView::TrackList; + if is_pick_click(event) { + echo_core::intent::toggle_picked_row(&mut this.state, ix); + cx.notify(); + return; + } + this.state.ui.selected_track_index = ix; + if event.click_count() >= 2 + && let Some(event) = echo_core::intent::play_track_at(&mut this.state, ix) + { + this.dispatch(event); + } + cx.notify(); +} + +fn open_track_row_menu( + this: &mut EchoApp, + ix: usize, + position: gpui::Point, + cx: &mut Context, +) { + this.state.ui.selected_track_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(position), + selected: 0, + submenu: None, + }); + } + cx.notify(); +} + +/// The row's artist credits, each one linking to its artist page. +fn track_artist_cell( + ix: usize, + track: &echo_core::models::Track, + muted: Hsla, + cx: &mut Context, +) -> AnyElement { + let base = div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_color(muted); + if track.artists.is_empty() { + // Local files and pre-credit caches carry only the + // joined string: one span, go-to-artist fallback. + base.id(("track-artist", ix)) + .text_ellipsis() + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener( + move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { + cx.stop_propagation(); + if let Some(ctx) = this.state.data.tracks.get(ix).map(ActionMenuContext::from) { + this.go_to(ctx, ActionMenuAction::GoToArtist, cx); } - cx.notify(); }, )) - .flex_grow(1.0) + .child(SharedString::from(track.artist.clone())) .into_any_element() - }) + } else { + let mut cell = base.flex().flex_row().items_center(); + for (k, credit) in track.artists.iter().enumerate() { + if k > 0 { + cell = cell.child(div().flex_none().child(SharedString::from(", "))); + } + let name = SharedString::from(credit.name.clone()); + cell = cell.child(match credit.id.clone() { + Some(id) => { + let artist_name = credit.name.clone(); + div() + .id(SharedString::from(format!("track-artist-{ix}-{k}"))) + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(cx.listener( + move |this: &mut EchoApp, _event: &gpui::ClickEvent, _window, cx| { + cx.stop_propagation(); + this.open_artist(id.clone(), artist_name.clone(), cx); + }, + )) + .child(name) + .into_any_element() + } + None => div().child(name).into_any_element(), + }); + } + cell.into_any_element() + } +} + +fn drop_tracks_at_end(this: &mut EchoApp, drag: &DraggedTracks, cx: &mut Context) { + // A drop past the last row appends; drops on rows never reach here. + let same_list = drag.source_context.is_some() + && drag.source_context + == this + .state + .data + .active_tracklist_context + .as_ref() + .map(|c| c.id.clone()); + if same_list && drag.tracks.len() > 1 { + return; + } + if let Some(event) = echo_core::intent::drop_tracks_in_tracklist( + &mut this.state, + drag.tracks.clone(), + same_list.then_some(drag.from_row), + None, + ) { + this.dispatch(event); + } + cx.notify(); } From aed68d16d38273796d3b93e9832696493304fa28 Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 17:01:46 -0500 Subject: [PATCH 41/44] desktop: split the search results into their header, rows and song row Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views/search.rs | 574 ++++++++++++------------ 1 file changed, 277 insertions(+), 297 deletions(-) diff --git a/crates/echo-desktop/src/views/search.rs b/crates/echo-desktop/src/views/search.rs index 584deec..c56b661 100644 --- a/crates/echo-desktop/src/views/search.rs +++ b/crates/echo-desktop/src/views/search.rs @@ -514,12 +514,6 @@ pub(super) fn search_results( window: &mut Window, cx: &mut Context, ) -> impl IntoElement { - let theme = &app.state.ui.active_theme; - let outer_palette = DesktopPalette::resolve(theme); - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let accent = theme.primary.gpui(WINDOW_FG()); - let tab = app.state.ui.active_search_tab; let query = app.state.ui.search_context_query.clone(); let results = &app.state.data.search_results; @@ -537,6 +531,42 @@ pub(super) fn search_results( SearchTab::Playlists => n_playlists, }; + div() + .flex_grow(1.0) + .flex() + .flex_col() + .overflow_hidden() + .child(search_header(app, cx)) + .child(if count == 0 { + search::empty_results(app) + } else if tab == SearchTab::All { + search::all_results(app, window, cx) + } else { + uniform_list( + "search-rows", + count, + cx.processor( + |this: &mut EchoApp, range: std::ops::Range, _window, cx| { + search_rows(this, range, cx) + }, + ), + ) + .track_scroll(&app.search_scroll) + .flex_grow(1.0) + .into_any_element() + }) +} + +/// The query line over the tab pills. +fn search_header(app: &EchoApp, cx: &mut Context) -> Div { + let theme = &app.state.ui.active_theme; + let outer_palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let tab = app.state.ui.active_search_tab; + let query = &app.state.ui.search_context_query; + let tab_button = |id: &'static str, label: String, target: SearchTab, active: bool| { div() .id(id) @@ -557,307 +587,257 @@ pub(super) fn search_results( }; div() - .flex_grow(1.0) + .flex_none() + .px_4() + .py_3() .flex() .flex_col() - .overflow_hidden() + .gap_2() + .child( + div() + .text_lg() + .text_color(fg) + .child(SharedString::from(format!( + "{}{query}", + tr(&app.state, "prompts.search") + ))), + ) .child( div() - .flex_none() - .px_4() - .py_3() .flex() - .flex_col() - .gap_2() - .child( - div() - .text_lg() - .text_color(fg) - .child(SharedString::from(format!( - "{}{query}", - tr(&app.state, "prompts.search") - ))), - ) - .child( - div() - .flex() - .flex_row() - .gap_1() - .flex_wrap() - .child(tab_button( - "search-all", - tr(&app.state, "desktop.search_all").to_string(), - SearchTab::All, - tab == SearchTab::All, - )) - .child(tab_button( - "search-tracks", - tr(&app.state, "desktop.search_songs").to_string(), - SearchTab::Tracks, - tab == SearchTab::Tracks, - )) - .child(tab_button( - "search-albums", - tr(&app.state, "ui.albums").to_string(), - SearchTab::Albums, - tab == SearchTab::Albums, - )) - .child(tab_button( - "search-artists", - tr(&app.state, "ui.artists").to_string(), - SearchTab::Artists, - tab == SearchTab::Artists, - )) - .child(tab_button( - "search-playlists", - tr(&app.state, "ui.playlists").to_string(), - SearchTab::Playlists, - tab == SearchTab::Playlists, - )), - ), + .flex_row() + .gap_1() + .flex_wrap() + .child(tab_button( + "search-all", + tr(&app.state, "desktop.search_all").to_string(), + SearchTab::All, + tab == SearchTab::All, + )) + .child(tab_button( + "search-tracks", + tr(&app.state, "desktop.search_songs").to_string(), + SearchTab::Tracks, + tab == SearchTab::Tracks, + )) + .child(tab_button( + "search-albums", + tr(&app.state, "ui.albums").to_string(), + SearchTab::Albums, + tab == SearchTab::Albums, + )) + .child(tab_button( + "search-artists", + tr(&app.state, "ui.artists").to_string(), + SearchTab::Artists, + tab == SearchTab::Artists, + )) + .child(tab_button( + "search-playlists", + tr(&app.state, "ui.playlists").to_string(), + SearchTab::Playlists, + tab == SearchTab::Playlists, + )), ) - .child(if count == 0 { - search::empty_results(app) - } else if tab == SearchTab::All { - search::all_results(app, window, cx) - } else { - uniform_list( - "search-rows", - count, - cx.processor( - move |this: &mut EchoApp, range: std::ops::Range, _window, cx| { - let theme = &this.state.ui.active_theme; - let fg = theme.text.gpui(WINDOW_FG()); - let muted = theme.text_muted.gpui(WINDOW_FG()); - let palette = DesktopPalette::resolve(theme); - let selected_bg = palette.row_selected; - let tab = this.state.ui.active_search_tab; - let selected = this.state.ui.selected_search_index; - let visual = visual_range_in(&this.state, ActiveView::SearchResults); +} - let rows: Vec = range - .map(|ix| { - pill_row( - ix, - LIST_PILL, - row_selected(ix, selected, visual), - selected_bg, - palette.row_hover, - |row| { - let row = row.gap_3().on_click(cx.listener( - move |this: &mut EchoApp, - event: &gpui::ClickEvent, - _window, - cx| { - this.state.ui.selected_search_index = ix; - if (tab != SearchTab::Tracks - || event.click_count() >= 2) - && let Some(event) = - echo_core::intent::activate_search_result( - &mut this.state, - ix, - ) - { - this.dispatch(event); - } - cx.notify(); - }, - )); +fn search_rows( + this: &mut EchoApp, + range: std::ops::Range, + cx: &mut Context, +) -> Vec { + let theme = &this.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let palette = DesktopPalette::resolve(theme); + let selected_bg = palette.row_selected; + let tab = this.state.ui.active_search_tab; + let selected = this.state.ui.selected_search_index; + let visual = visual_range_in(&this.state, ActiveView::SearchResults); - match tab { - SearchTab::All => row, - SearchTab::Tracks => { - let track = this.state.data.search_results.tracks - [ix] - .clone(); - let is_liked = this - .state - .data - .liked_tracks - .contains(&track.id); - let secondary = this - .state - .ui - .active_theme - .secondary - .gpui(WINDOW_FG()); - row.on_mouse_down( - MouseButton::Right, - cx.listener(move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { - this.state.ui.selected_search_index = ix; - this.context_menu = None; - if let Some(ctx) = this.action_target() { - this.track_menu = Some(crate::TrackMenuState { - ctx, - position: Some(event.position), - selected: 0, - submenu: None, - }); - } - cx.notify(); - }), - ) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(track.name)), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from(track.artist)), - ) - .child( - div() - .flex_grow(1.5) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from(track.album)), - ) - .child(liked_cell( - "search", - ix, - track.id.clone(), - is_liked, - secondary, - palette, - cx, - )) - .child( - div() - .flex_none() - .w(px(48.0)) - .text_color(muted) - .child(SharedString::from(format_time( - track.duration_ms, - ))), - ) - } - SearchTab::Albums => { - let album = this.state.data.search_results.albums - [ix] - .clone(); - let thumb = thumb_element( - this, - album.image_url.as_deref(), - 26.0, - false, - muted, - ); - row.child(thumb) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(album.name)), - ) - .child( - div() - .flex_grow(1.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from( - album.artist, - )), - ) - } - SearchTab::Artists => { - let artist = this.state.data.search_results.artists - [ix] - .clone(); - let thumb = thumb_element( - this, - artist.image_url.as_deref(), - 26.0, - true, - muted, - ); - row.child(thumb).child( - div() - .flex_grow(1.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from(artist.name)), - ) - } - SearchTab::Playlists => { - let playlist = - this.state.data.search_results.playlists[ix] - .clone(); - let thumb_url = playlist - .thumb_url - .clone() - .or_else(|| playlist.image_url.clone()); - let thumb = thumb_element( - this, - thumb_url.as_deref(), - 26.0, - false, - muted, - ); - row.child(thumb) - .child( - div() - .flex_grow(2.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(fg) - .child(SharedString::from( - playlist.name, - )), - ) - .child( - div() - .flex_grow(1.0) - .flex_basis(px(0.0)) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_color(muted) - .child(SharedString::from( - playlist.owner, - )), - ) - } - } - }, - ) - .into_any_element() - }) - .collect(); + let rows: Vec = range + .map(|ix| { + pill_row( + ix, + LIST_PILL, + row_selected(ix, selected, visual), + selected_bg, + palette.row_hover, + |row| { + let row = row.gap_3().on_click(cx.listener( + move |this: &mut EchoApp, event: &gpui::ClickEvent, _window, cx| { + this.state.ui.selected_search_index = ix; + if (tab != SearchTab::Tracks || event.click_count() >= 2) + && let Some(event) = + echo_core::intent::activate_search_result(&mut this.state, ix) + { + this.dispatch(event); + } + cx.notify(); + }, + )); - echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); - rows - }, - ), + match tab { + SearchTab::All => row, + SearchTab::Tracks => { + search_track_row(this, row, ix, fg, muted, palette, cx) + } + SearchTab::Albums => { + let album = this.state.data.search_results.albums[ix].clone(); + let thumb = + thumb_element(this, album.image_url.as_deref(), 26.0, false, muted); + row.child(thumb) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(album.name)), + ) + .child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(album.artist)), + ) + } + SearchTab::Artists => { + let artist = this.state.data.search_results.artists[ix].clone(); + let thumb = + thumb_element(this, artist.image_url.as_deref(), 26.0, true, muted); + row.child(thumb).child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(artist.name)), + ) + } + SearchTab::Playlists => { + let playlist = this.state.data.search_results.playlists[ix].clone(); + let thumb_url = playlist + .thumb_url + .clone() + .or_else(|| playlist.image_url.clone()); + let thumb = + thumb_element(this, thumb_url.as_deref(), 26.0, false, muted); + row.child(thumb) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(playlist.name)), + ) + .child( + div() + .flex_grow(1.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(playlist.owner)), + ) + } + } + }, ) - .track_scroll(&app.search_scroll) - .flex_grow(1.0) .into_any_element() }) + .collect(); + + echo_core::thumbnails::drain_pending(&mut this.state, &this.worker_tx); + rows +} + +fn search_track_row( + this: &mut EchoApp, + row: Stateful
, + ix: usize, + fg: Hsla, + muted: Hsla, + palette: DesktopPalette, + cx: &mut Context, +) -> Stateful
{ + let track = this.state.data.search_results.tracks[ix].clone(); + let is_liked = this.state.data.liked_tracks.contains(&track.id); + let secondary = this.state.ui.active_theme.secondary.gpui(WINDOW_FG()); + row.on_mouse_down( + MouseButton::Right, + cx.listener( + move |this: &mut EchoApp, event: &MouseDownEvent, _window, cx| { + this.state.ui.selected_search_index = ix; + this.context_menu = None; + if let Some(ctx) = this.action_target() { + this.track_menu = Some(crate::TrackMenuState { + ctx, + position: Some(event.position), + selected: 0, + submenu: None, + }); + } + cx.notify(); + }, + ), + ) + .child( + div() + .flex_grow(2.0) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(fg) + .child(SharedString::from(track.name)), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(track.artist)), + ) + .child( + div() + .flex_grow(1.5) + .flex_basis(px(0.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_color(muted) + .child(SharedString::from(track.album)), + ) + .child(liked_cell( + "search", + ix, + track.id.clone(), + is_liked, + secondary, + palette, + cx, + )) + .child( + div() + .flex_none() + .w(px(48.0)) + .text_color(muted) + .child(SharedString::from(format_time(track.duration_ms))), + ) } From 8985375d48e12c1507512ea828acf9ac34d5af7a Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 17:02:23 -0500 Subject: [PATCH 42/44] desktop: split the theme picker into its swatches, mode bar, scheme tabs and rows Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/views/modals/theme.rs | 336 +++++++++++------- 1 file changed, 201 insertions(+), 135 deletions(-) diff --git a/crates/echo-desktop/src/views/modals/theme.rs b/crates/echo-desktop/src/views/modals/theme.rs index a6d39ab..31f01b5 100644 --- a/crates/echo-desktop/src/views/modals/theme.rs +++ b/crates/echo-desktop/src/views/modals/theme.rs @@ -18,7 +18,7 @@ pub fn theme_rows( /// adds a tab for each. A dark/light pair is one row naming both, the listed one first in /// weight; a theme with no sibling is only in its own appearance's list. pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoElement { - use echo_core::config::{Scheme, ThemeMode}; + use echo_core::config::ThemeMode; let theme = &app.state.ui.active_theme; let palette = DesktopPalette::resolve(theme); @@ -34,10 +34,99 @@ pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoEle let chosen = echo_core::theme::selected_name(config, &app.state.ui.themes, tab); let selected = app.theme_modal_index; - // Background, accent and second accent of each listed theme. Choosing does not preview, - // and under `Auto` one of the two lists is never on screen, so this is how they compare. - let swatches: Vec<[gpui::Hsla; 3]> = rows - .iter() + let swatches = theme_swatches(app, &rows, surface); + let mode_control = theme_mode_control(app, mode, cx); + let tabs = theme_scheme_tabs(app, mode, tab, cx); + + div() + .id("theme-backdrop") + .absolute() + .inset_0() + .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + this.theme_modal_open = false; + cx.notify(); + })) + .child( + div() + .id("theme-panel") + .w(px(340.0)) + .max_h(px(480.0)) + .rounded_lg() + .border_1() + .border_color(palette.menu_border) + .bg(surface) + .p_3() + .flex() + .flex_col() + .gap_2() + .overflow_hidden() + .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .child( + div() + .flex_none() + .px_1() + .pb_3() + .border_b_1() + .border_color(palette.menu_border) + .flex() + .flex_row() + .items_center() + .justify_between() + .child( + div() + .text_base() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(fg) + .child(tr(&app.state, "desktop.theme")), + ) + .child(mode_control), + ) + .when_some(tabs, |el, tabs| el.child(tabs)) + .child(if rows.is_empty() { + div() + .py_4() + .text_sm() + .text_color(muted) + .child(tr(&app.state, "desktop.no_themes")) + .into_any_element() + } else { + let row_colors = ThemeRowColors { + palette, + fg, + muted, + accent, + chosen: chosen.clone(), + selected, + }; + div() + .id("theme-list") + .flex() + .flex_col() + // Sized by its rows, shrinking (and scrolling) once the panel is full. + .min_h_0() + .overflow_y_scroll() + .track_scroll(&app.theme_modal_scroll) + .children(rows.into_iter().zip(swatches).enumerate().map( + |(ix, (row, swatch))| theme_list_row(ix, row, swatch, &row_colors, cx), + )) + .into_any_element() + }), + ) +} + +/// Background, accent and second accent of each listed theme. Choosing does not preview, +/// and under `Auto` one of the two lists is never on screen, so this is how they compare. +fn theme_swatches( + app: &EchoApp, + rows: &[echo_core::theme::ThemeRow], + surface: Hsla, +) -> Vec<[Hsla; 3]> { + rows.iter() .map(|row| { let resolved = app .state @@ -54,15 +143,24 @@ pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoEle None => [surface; 3], } }) - .collect(); + .collect() +} +/// One joined bar, the same control as the Mode row in Settings. +fn theme_mode_control( + app: &EchoApp, + mode: echo_core::config::ThemeMode, + cx: &mut Context, +) -> Div { + use echo_core::config::ThemeMode; + let theme = &app.state.ui.active_theme; + let palette = DesktopPalette::resolve(theme); + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); let mode_label = |mode: ThemeMode| tr(&app.state, &format!("desktop.theme_mode.{}", mode.name())); - let scheme_label = - |scheme: Scheme| tr(&app.state, &format!("desktop.theme_mode.{}", scheme.name())); - // One joined bar, the same control as the Mode row in Settings. - let mode_control = div() + div() .flex_none() .h(px(24.0)) .flex() @@ -93,10 +191,25 @@ pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoEle this.set_theme_mode(option, cx); })) .child(mode_label(option)) - })); + })) +} + +/// Under `Auto` only: one tab per appearance, the listed one underlined. +fn theme_scheme_tabs( + app: &EchoApp, + mode: echo_core::config::ThemeMode, + tab: echo_core::config::Scheme, + cx: &mut Context, +) -> Option
{ + use echo_core::config::{Scheme, ThemeMode}; + let theme = &app.state.ui.active_theme; + let fg = theme.text.gpui(WINDOW_FG()); + let muted = theme.text_muted.gpui(WINDOW_FG()); + let accent = theme.primary.gpui(WINDOW_FG()); + let scheme_label = + |scheme: Scheme| tr(&app.state, &format!("desktop.theme_mode.{}", scheme.name())); - // Under `Auto` only: one tab per appearance, the listed one underlined. - let tabs = (mode == ThemeMode::Auto).then(|| { + (mode == ThemeMode::Auto).then(|| { div() .flex_none() .flex() @@ -123,143 +236,96 @@ pub fn theme_modal(app: &mut EchoApp, cx: &mut Context) -> impl IntoEle })) .child(scheme_label(scheme)) })) - }); + }) +} + +/// What every row of the theme list shares. +struct ThemeRowColors { + palette: DesktopPalette, + fg: Hsla, + muted: Hsla, + accent: Hsla, + chosen: String, + selected: usize, +} +fn theme_list_row( + ix: usize, + row: echo_core::theme::ThemeRow, + swatch: [Hsla; 3], + colors: &ThemeRowColors, + cx: &mut Context, +) -> Stateful
{ + let ThemeRowColors { + palette, + fg, + muted, + accent, + ref chosen, + selected, + } = *colors; + let is_chosen = row.name == *chosen; + let is_selected = ix == selected; + let clicked = row.name.clone(); div() - .id("theme-backdrop") - .absolute() - .inset_0() - .bg(gpui::hsla(0.0, 0.0, 0.0, 0.55)) + .id(ix) + .px_2() + .h(px(30.0)) + .flex_none() + .rounded_md() .flex() + .flex_row() .items_center() - .justify_center() - .occlude() - .on_click(cx.listener(|this: &mut EchoApp, _event, _window, cx| { + .gap_3() + .text_sm() + .when(is_selected, |el| el.bg(palette.menu_selected)) + .when(!is_selected, |el| { + el.hover(move |style| style.bg(palette.menu_hover)) + }) + .cursor_pointer() + .on_click(cx.listener(move |this: &mut EchoApp, _event, _window, cx| { + echo_core::intent::apply_theme(&mut this.state, &clicked); this.theme_modal_open = false; cx.notify(); })) .child( + // The theme's background, accent and second accent + // as one joined chip. div() - .id("theme-panel") - .w(px(340.0)) - .max_h(px(480.0)) - .rounded_lg() + .flex_none() + .flex() + .flex_row() + .rounded_sm() .border_1() .border_color(palette.menu_border) - .bg(surface) - .p_3() - .flex() - .flex_col() - .gap_2() .overflow_hidden() - .on_click(cx.listener(|_this, _event, _window, cx| cx.stop_propagation())) + .children( + swatch + .into_iter() + .map(|color| div().w(px(12.0)).h(px(14.0)).bg(color)), + ), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_row() + .gap_1() .child( div() - .flex_none() - .px_1() - .pb_3() - .border_b_1() - .border_color(palette.menu_border) - .flex() - .flex_row() - .items_center() - .justify_between() - .child( - div() - .text_base() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(fg) - .child(tr(&app.state, "desktop.theme")), - ) - .child(mode_control), + .text_color(if is_chosen { accent } else { fg }) + .child(SharedString::from(row.name)), ) - .when_some(tabs, |el, tabs| el.child(tabs)) - .child(if rows.is_empty() { - div() - .py_4() - .text_sm() - .text_color(muted) - .child(tr(&app.state, "desktop.no_themes")) - .into_any_element() - } else { - div() - .id("theme-list") - .flex() - .flex_col() - // Sized by its rows, shrinking (and scrolling) once the panel is full. - .min_h_0() - .overflow_y_scroll() - .track_scroll(&app.theme_modal_scroll) - .children(rows.into_iter().zip(swatches).enumerate().map( - |(ix, (row, swatch))| { - let is_chosen = row.name == chosen; - let is_selected = ix == selected; - let clicked = row.name.clone(); - div() - .id(ix) - .px_2() - .h(px(30.0)) - .flex_none() - .rounded_md() - .flex() - .flex_row() - .items_center() - .gap_3() - .text_sm() - .when(is_selected, |el| el.bg(palette.menu_selected)) - .when(!is_selected, |el| { - el.hover(move |style| style.bg(palette.menu_hover)) - }) - .cursor_pointer() - .on_click(cx.listener( - move |this: &mut EchoApp, _event, _window, cx| { - echo_core::intent::apply_theme( - &mut this.state, - &clicked, - ); - this.theme_modal_open = false; - cx.notify(); - }, - )) - .child( - // The theme's background, accent and second accent - // as one joined chip. - div() - .flex_none() - .flex() - .flex_row() - .rounded_sm() - .border_1() - .border_color(palette.menu_border) - .overflow_hidden() - .children(swatch.into_iter().map(|color| { - div().w(px(12.0)).h(px(14.0)).bg(color) - })), - ) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_row() - .gap_1() - .child( - div() - .text_color(if is_chosen { accent } else { fg }) - .child(SharedString::from(row.name)), - ) - .when_some(row.sibling, |el, sibling| { - el.child(div().text_color(muted).child( - SharedString::from(format!("/ {sibling}")), - )) - }), - ) - .when(is_chosen, |el| { - el.child(div().flex_none().text_color(accent).child("✓")) - }) - }, - )) - .into_any_element() + .when_some(row.sibling, |el, sibling| { + el.child( + div() + .text_color(muted) + .child(SharedString::from(format!("/ {sibling}"))), + ) }), ) + .when(is_chosen, |el| { + el.child(div().flex_none().text_color(accent).child("✓")) + }) } From 38b0455727cb7255fd5168cfab1d555a4011b11d Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 17:02:51 -0500 Subject: [PATCH 43/44] desktop: move the worker bridge and periodic tick out of EchoApp::new Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/main.rs | 164 ++++++++++++++++++-------------- 1 file changed, 90 insertions(+), 74 deletions(-) diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index ff83f0d..dc87453 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -394,7 +394,7 @@ impl EchoApp { mut state, config: _, app_tx, - mut app_rx, + app_rx, worker_tx, } = boot; if state.ui.mode == AppMode::Normal { @@ -403,79 +403,8 @@ impl EchoApp { } } - // Bridge: worker events land here and become repaints. tokio's mpsc futures don't need - // the tokio reactor, so awaiting on GPUI's foreground executor is fine. - cx.spawn(async move |this, cx| { - while let Some(event) = app_rx.recv().await { - let applied = this.update(cx, |app: &mut EchoApp, cx| { - let signed_in = matches!( - &event, - echo_core::events::WorkerEvent::AuthenticationComplete - ); - // Arrives ten times a second during playback and only moves the position. - let position_only = matches!(&event, echo_core::events::WorkerEvent::Tick); - apply_worker_event(event, &mut app.state, &app.app_tx, &app.worker_tx); - if signed_in { - app.open_home(cx); - } - // A tick that reaches the end of the track stops playback, which every - // pane shows. - if position_only && app.state.playback.is_playing { - app.notify_playback_position(cx); - } else { - cx.notify(); - } - }); - if applied.is_err() { - break; // entity dropped — app is shutting down - } - } - }) - .detach(); - - // Progress tick: elapsed time is interpolated at render time, so while playing the bar - // needs a repaint even when no worker event arrives. The visualizer needs a much faster - // cadence, so the interval tightens while it is live; the immersive backdrop's drift - // sets its own, slower one. - cx.spawn(async move |this, cx| { - loop { - let interval = this.update(cx, |app: &mut EchoApp, cx| { - app.maybe_auto_update(cx); - let animating = app.immersive && !cx.reduce_motion(); - if animating { - cx.notify(); - } else if app.state.playback.is_playing { - app.notify_playback_position(cx); - } - // Status messages carry an expiry; the periodic tick retires them. - if app - .state - .ui - .status_message_expiry - .is_some_and(|expiry| expiry <= std::time::Instant::now()) - { - app.state.ui.status_message = None; - app.state.ui.status_message_expiry = None; - cx.notify(); - } - let visualizing = app.state.playback.is_playing - && app.state.ui.library_config.enable_visualizer - && app.state.playback.audio_visualization.is_some(); - if visualizing { - Duration::from_millis(66) - } else if animating { - backdrop::FRAME - } else { - Duration::from_millis(500) - } - }); - let Ok(interval) = interval else { - break; // entity dropped — app is shutting down - }; - cx.background_executor().timer(interval).await; - } - }) - .detach(); + Self::spawn_worker_bridge(app_rx, cx); + Self::spawn_periodic_tick(cx); let focus_handle = cx.focus_handle(); @@ -585,6 +514,93 @@ impl EchoApp { } } + /// Bridge: worker events land here and become repaints. tokio's mpsc futures don't need + /// the tokio reactor, so awaiting on GPUI's foreground executor is fine. + fn spawn_worker_bridge( + mut app_rx: tokio::sync::mpsc::Receiver, + cx: &mut Context, + ) { + cx.spawn(async move |this, cx| { + while let Some(event) = app_rx.recv().await { + let applied = this.update(cx, |app: &mut EchoApp, cx| { + app.on_worker_event(event, cx); + }); + if applied.is_err() { + break; // entity dropped — app is shutting down + } + } + }) + .detach(); + } + + fn on_worker_event(&mut self, event: echo_core::events::WorkerEvent, cx: &mut Context) { + let signed_in = matches!( + &event, + echo_core::events::WorkerEvent::AuthenticationComplete + ); + // Arrives ten times a second during playback and only moves the position. + let position_only = matches!(&event, echo_core::events::WorkerEvent::Tick); + apply_worker_event(event, &mut self.state, &self.app_tx, &self.worker_tx); + if signed_in { + self.open_home(cx); + } + // A tick that reaches the end of the track stops playback, which every + // pane shows. + if position_only && self.state.playback.is_playing { + self.notify_playback_position(cx); + } else { + cx.notify(); + } + } + + /// Progress tick: elapsed time is interpolated at render time, so while playing the bar + /// needs a repaint even when no worker event arrives. The visualizer needs a much faster + /// cadence, so the interval tightens while it is live; the immersive backdrop's drift + /// sets its own, slower one. + fn spawn_periodic_tick(cx: &mut Context) { + cx.spawn(async move |this, cx| { + loop { + let interval = this.update(cx, |app: &mut EchoApp, cx| app.periodic_tick(cx)); + let Ok(interval) = interval else { + break; // entity dropped — app is shutting down + }; + cx.background_executor().timer(interval).await; + } + }) + .detach(); + } + + fn periodic_tick(&mut self, cx: &mut Context) -> Duration { + self.maybe_auto_update(cx); + let animating = self.immersive && !cx.reduce_motion(); + if animating { + cx.notify(); + } else if self.state.playback.is_playing { + self.notify_playback_position(cx); + } + // Status messages carry an expiry; the periodic tick retires them. + if self + .state + .ui + .status_message_expiry + .is_some_and(|expiry| expiry <= std::time::Instant::now()) + { + self.state.ui.status_message = None; + self.state.ui.status_message_expiry = None; + cx.notify(); + } + let visualizing = self.state.playback.is_playing + && self.state.ui.library_config.enable_visualizer + && self.state.playback.audio_visualization.is_some(); + if visualizing { + Duration::from_millis(66) + } else if animating { + backdrop::FRAME + } else { + Duration::from_millis(500) + } + } + /// Binds the entity to a freshly opened window: keyboard focus, the close hook and the /// titlebar drag latch. Runs at launch and every time the window reopens from the tray. fn attach(&mut self, window: &mut Window, cx: &mut Context) { From 5da4e98647b167cc1f30ef3c74009a154c7cd23f Mon Sep 17 00:00:00 2001 From: Andre Sun Date: Thu, 12 Nov 2026 17:03:08 -0500 Subject: [PATCH 44/44] desktop: split main into the panic log, keymap and tray listener Co-authored-by: redsun-agent[bot] <331402388+redsun-agent[bot]@users.noreply.github.com> --- crates/echo-desktop/src/main.rs | 285 +++++++++++++++++--------------- 1 file changed, 152 insertions(+), 133 deletions(-) diff --git a/crates/echo-desktop/src/main.rs b/crates/echo-desktop/src/main.rs index dc87453..2eb7568 100644 --- a/crates/echo-desktop/src/main.rs +++ b/crates/echo-desktop/src/main.rs @@ -744,16 +744,7 @@ pub(crate) fn sort_arg(sort: echo_core::app::TrackSort) -> &'static str { } fn main() { - // Neither launch path has a stderr anyone reads — the Linux .desktop entry sets - // Terminal=false and the Windows build is a windows_subsystem app — so a panic before the - // window opens is indistinguishable from the icon doing nothing at all. First thing in - // main, so it covers the runtime and bootstrap below as well as the UI. - std::panic::set_hook(Box::new(|info| { - let path = echo_core::config::debug_log_path("echo-desktop-panic.log"); - let backtrace = std::backtrace::Backtrace::force_capture(); - let _ = std::fs::write(&path, format!("{info}\n\n{backtrace}\n")); - eprintln!("{info}"); - })); + install_panic_log(); // The worker lives on this runtime; entering it makes bootstrap::init()'s tokio::spawn work. // It must outlive the UI, which `run()` blocks for. @@ -787,120 +778,9 @@ fn main() { // (Start Menu, desktop shortcut, raw exe) groups onto the same pinned button. cx.set_app_identity("com.echo.app", "echo"); cx.on_action(|_: &Quit, cx| cx.quit()); - // The keymap is ctrl-based everywhere. These are the chords a Mac user reaches for - // without thinking, and they are what the menu bar below shows as its accelerators — - // gpui reads them back out of the keymap when it builds the menu. - if cfg!(target_os = "macos") { - cx.bind_keys([ - KeyBinding::new("cmd-q", Quit, None), - KeyBinding::new("cmd-h", Hide, None), - KeyBinding::new("cmd-m", MinimizeWindow, None), - ]); - cx.on_action(|_: &Hide, cx| cx.hide()); - cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps()); - cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps()); - cx.set_menus(mac_menus()); - } - cx.bind_keys([ - KeyBinding::new("ctrl-q", Quit, None), - KeyBinding::new( - if cfg!(target_os = "macos") { - "ctrl-shift-h" - } else { - "ctrl-h" - }, - OpenHome, - None, - ), - // Everything else is scoped to the lists so plain letters can type into the - // search box (whose context adds `search`, defeating the `!search` predicate). - KeyBinding::new("space", TogglePlayback, LIST_KEYS), - KeyBinding::new("up", MoveUp, LIST_KEYS), - KeyBinding::new("k", MoveUp, LIST_KEYS), - KeyBinding::new("down", MoveDown, LIST_KEYS), - KeyBinding::new("j", MoveDown, LIST_KEYS), - KeyBinding::new("pageup", PageUp, LIST_KEYS), - KeyBinding::new("pagedown", PageDown, LIST_KEYS), - KeyBinding::new("home", SelectFirst, LIST_KEYS), - KeyBinding::new("end", SelectLast, LIST_KEYS), - KeyBinding::new("enter", Activate, LIST_KEYS), - // `z` is an Enter alias. - KeyBinding::new("z", Activate, LIST_KEYS), - // `y` answers confirm prompts; Enter reaches the same handler. - KeyBinding::new("y", ConfirmPrompt, LIST_KEYS), - KeyBinding::new("left", FocusLibrary, LIST_KEYS), - KeyBinding::new("right", FocusTracks, LIST_KEYS), - // `l` likes the focused track (or acts as Enter on library rows); - // `right` keeps pane focus for arrow navigation. - KeyBinding::new("l", ToggleLike, LIST_KEYS), - // Vim-style navigation motions. - KeyBinding::new("g g", SelectFirst, LIST_KEYS), - KeyBinding::new("shift-g", SelectLast, LIST_KEYS), - KeyBinding::new("g c", JumpToCurrent, LIST_KEYS), - KeyBinding::new("ctrl-u", HalfPageUp, LIST_KEYS), - KeyBinding::new("ctrl-d", HalfPageDown, LIST_KEYS), - KeyBinding::new("ctrl-b", PageUp, LIST_KEYS), - KeyBinding::new("ctrl-f", PageDown, LIST_KEYS), - // `h` is "back", not "focus sidebar" — the left arrow keeps that role. - KeyBinding::new("h", Dismiss, LIST_KEYS), - // Backspace hops focus back to the sidebar; `h`/escape keep going through history. - KeyBinding::new("backspace", BackOrFocusLibrary, LIST_KEYS), - KeyBinding::new("escape", Dismiss, LIST_KEYS), - KeyBinding::new("tab", CycleTab, LIST_KEYS), - // Playback transport. - KeyBinding::new("ctrl-right", NextTrack, LIST_KEYS), - KeyBinding::new("ctrl-left", PreviousTrack, LIST_KEYS), - KeyBinding::new("]", NextTrack, LIST_KEYS), - KeyBinding::new("[", PreviousTrack, LIST_KEYS), - KeyBinding::new("s", ToggleShuffle, LIST_KEYS), - KeyBinding::new("r", CycleRepeat, LIST_KEYS), - KeyBinding::new("shift-m", ToggleMute, LIST_KEYS), - KeyBinding::new("shift-right", SeekForward, LIST_KEYS), - KeyBinding::new("shift-left", SeekBackward, LIST_KEYS), - KeyBinding::new(".", SeekForward, LIST_KEYS), - KeyBinding::new(",", SeekBackward, LIST_KEYS), - KeyBinding::new("0", SeekStart, LIST_KEYS), - KeyBinding::new("=", VolumeUp, LIST_KEYS), - KeyBinding::new("-", VolumeDown, LIST_KEYS), - KeyBinding::new("shift-=", VolumeUpBig, LIST_KEYS), - KeyBinding::new("shift--", VolumeDownBig, LIST_KEYS), - // Views, prompts and toggles. - KeyBinding::new("q", AddToQueue, LIST_KEYS), - KeyBinding::new("a", AddToPlaylist, LIST_KEYS), - KeyBinding::new("shift-a", OpenActionMenu, LIST_KEYS), - // `dd`: the first press arms, the second stages the confirm prompt. - KeyBinding::new("d", MarkDelete, LIST_KEYS), - KeyBinding::new("shift-q", ToggleQueue, LIST_KEYS), - KeyBinding::new("shift-d", OpenDevices, LIST_KEYS), - KeyBinding::new("shift-r", Refresh, LIST_KEYS), - KeyBinding::new("m", TogglePin, LIST_KEYS), - KeyBinding::new(":", OpenCommand, LIST_KEYS), - KeyBinding::new("f", CommandSearch, LIST_KEYS), - KeyBinding::new("c", NewPlaylistPrompt, LIST_KEYS), - KeyBinding::new("e", RenamePrompt, LIST_KEYS), - // `/` filters the loaded track list; the global search box gets ctrl-k (and stays - // clickable). - KeyBinding::new("/", OpenFilter, LIST_KEYS), - KeyBinding::new("n", NextMatch, LIST_KEYS), - KeyBinding::new("shift-n", PrevMatch, LIST_KEYS), - KeyBinding::new("ctrl-k", FocusSearch, LIST_KEYS), - KeyBinding::new("shift-l", ToggleLyrics, LIST_KEYS), - KeyBinding::new("ctrl-shift-l", ToggleInlineLyrics, LIST_KEYS), - KeyBinding::new("t", ToggleThemes, LIST_KEYS), - KeyBinding::new("shift-f", ToggleImmersive, LIST_KEYS), - // The platform-conventional preferences shortcut; global so it also works while - // the search box has focus. - KeyBinding::new("ctrl-,", ToggleSettings, None), - // Global like ctrl-,: chords type nothing, so they're safe while inputs focus. - KeyBinding::new("ctrl-\\", ToggleSidebar, None), - KeyBinding::new("alt-left", HistoryBack, None), - KeyBinding::new("alt-right", HistoryForward, None), - KeyBinding::new("?", ToggleHelp, LIST_KEYS), - KeyBinding::new("v", EnterVisual, LIST_KEYS), - KeyBinding::new("shift-k", MoveTrackUp, LIST_KEYS), - KeyBinding::new("shift-j", MoveTrackDown, LIST_KEYS), - ]); - let (tray_tx, mut tray_rx) = tokio::sync::mpsc::unbounded_channel(); + bind_platform_keys(cx); + bind_keys(cx); + let (tray_tx, tray_rx) = tokio::sync::mpsc::unbounded_channel(); let instance_task = instance.map(|listener| listener.serve(tray_tx.clone())); let app = cx.new(|cx| EchoApp::new(boot, cx)); cx.set_global(Shell { @@ -909,20 +789,159 @@ fn main() { tray_tx, tray: None, }); - cx.spawn(async move |cx| { - while let Some(event) = tray_rx.recv().await { - cx.update(|cx| match event { - tray::TrayEvent::Show => open_main_window(cx), - tray::TrayEvent::Quit => cx.quit(), - }); - } - }) - .detach(); + spawn_tray_listener(tray_rx, cx); open_main_window(cx); cx.activate(true); }); } +/// Neither launch path has a stderr anyone reads — the Linux .desktop entry sets +/// Terminal=false and the Windows build is a windows_subsystem app — so a panic before the +/// window opens is indistinguishable from the icon doing nothing at all. First thing in +/// main, so it covers the runtime and bootstrap below as well as the UI. +fn install_panic_log() { + std::panic::set_hook(Box::new(|info| { + let path = echo_core::config::debug_log_path("echo-desktop-panic.log"); + let backtrace = std::backtrace::Backtrace::force_capture(); + let _ = std::fs::write(&path, format!("{info}\n\n{backtrace}\n")); + eprintln!("{info}"); + })); +} + +/// The keymap is ctrl-based everywhere. These are the chords a Mac user reaches for +/// without thinking, and they are what the menu bar below shows as its accelerators — +/// gpui reads them back out of the keymap when it builds the menu. +fn bind_platform_keys(cx: &mut App) { + if cfg!(target_os = "macos") { + cx.bind_keys([ + KeyBinding::new("cmd-q", Quit, None), + KeyBinding::new("cmd-h", Hide, None), + KeyBinding::new("cmd-m", MinimizeWindow, None), + ]); + cx.on_action(|_: &Hide, cx| cx.hide()); + cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps()); + cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps()); + cx.set_menus(mac_menus()); + } +} + +fn bind_keys(cx: &mut App) { + cx.bind_keys([ + KeyBinding::new("ctrl-q", Quit, None), + KeyBinding::new( + if cfg!(target_os = "macos") { + "ctrl-shift-h" + } else { + "ctrl-h" + }, + OpenHome, + None, + ), + // Everything else is scoped to the lists so plain letters can type into the + // search box (whose context adds `search`, defeating the `!search` predicate). + KeyBinding::new("space", TogglePlayback, LIST_KEYS), + KeyBinding::new("up", MoveUp, LIST_KEYS), + KeyBinding::new("k", MoveUp, LIST_KEYS), + KeyBinding::new("down", MoveDown, LIST_KEYS), + KeyBinding::new("j", MoveDown, LIST_KEYS), + KeyBinding::new("pageup", PageUp, LIST_KEYS), + KeyBinding::new("pagedown", PageDown, LIST_KEYS), + KeyBinding::new("home", SelectFirst, LIST_KEYS), + KeyBinding::new("end", SelectLast, LIST_KEYS), + KeyBinding::new("enter", Activate, LIST_KEYS), + // `z` is an Enter alias. + KeyBinding::new("z", Activate, LIST_KEYS), + // `y` answers confirm prompts; Enter reaches the same handler. + KeyBinding::new("y", ConfirmPrompt, LIST_KEYS), + KeyBinding::new("left", FocusLibrary, LIST_KEYS), + KeyBinding::new("right", FocusTracks, LIST_KEYS), + // `l` likes the focused track (or acts as Enter on library rows); + // `right` keeps pane focus for arrow navigation. + KeyBinding::new("l", ToggleLike, LIST_KEYS), + // Vim-style navigation motions. + KeyBinding::new("g g", SelectFirst, LIST_KEYS), + KeyBinding::new("shift-g", SelectLast, LIST_KEYS), + KeyBinding::new("g c", JumpToCurrent, LIST_KEYS), + KeyBinding::new("ctrl-u", HalfPageUp, LIST_KEYS), + KeyBinding::new("ctrl-d", HalfPageDown, LIST_KEYS), + KeyBinding::new("ctrl-b", PageUp, LIST_KEYS), + KeyBinding::new("ctrl-f", PageDown, LIST_KEYS), + // `h` is "back", not "focus sidebar" — the left arrow keeps that role. + KeyBinding::new("h", Dismiss, LIST_KEYS), + // Backspace hops focus back to the sidebar; `h`/escape keep going through history. + KeyBinding::new("backspace", BackOrFocusLibrary, LIST_KEYS), + KeyBinding::new("escape", Dismiss, LIST_KEYS), + KeyBinding::new("tab", CycleTab, LIST_KEYS), + // Playback transport. + KeyBinding::new("ctrl-right", NextTrack, LIST_KEYS), + KeyBinding::new("ctrl-left", PreviousTrack, LIST_KEYS), + KeyBinding::new("]", NextTrack, LIST_KEYS), + KeyBinding::new("[", PreviousTrack, LIST_KEYS), + KeyBinding::new("s", ToggleShuffle, LIST_KEYS), + KeyBinding::new("r", CycleRepeat, LIST_KEYS), + KeyBinding::new("shift-m", ToggleMute, LIST_KEYS), + KeyBinding::new("shift-right", SeekForward, LIST_KEYS), + KeyBinding::new("shift-left", SeekBackward, LIST_KEYS), + KeyBinding::new(".", SeekForward, LIST_KEYS), + KeyBinding::new(",", SeekBackward, LIST_KEYS), + KeyBinding::new("0", SeekStart, LIST_KEYS), + KeyBinding::new("=", VolumeUp, LIST_KEYS), + KeyBinding::new("-", VolumeDown, LIST_KEYS), + KeyBinding::new("shift-=", VolumeUpBig, LIST_KEYS), + KeyBinding::new("shift--", VolumeDownBig, LIST_KEYS), + // Views, prompts and toggles. + KeyBinding::new("q", AddToQueue, LIST_KEYS), + KeyBinding::new("a", AddToPlaylist, LIST_KEYS), + KeyBinding::new("shift-a", OpenActionMenu, LIST_KEYS), + // `dd`: the first press arms, the second stages the confirm prompt. + KeyBinding::new("d", MarkDelete, LIST_KEYS), + KeyBinding::new("shift-q", ToggleQueue, LIST_KEYS), + KeyBinding::new("shift-d", OpenDevices, LIST_KEYS), + KeyBinding::new("shift-r", Refresh, LIST_KEYS), + KeyBinding::new("m", TogglePin, LIST_KEYS), + KeyBinding::new(":", OpenCommand, LIST_KEYS), + KeyBinding::new("f", CommandSearch, LIST_KEYS), + KeyBinding::new("c", NewPlaylistPrompt, LIST_KEYS), + KeyBinding::new("e", RenamePrompt, LIST_KEYS), + // `/` filters the loaded track list; the global search box gets ctrl-k (and stays + // clickable). + KeyBinding::new("/", OpenFilter, LIST_KEYS), + KeyBinding::new("n", NextMatch, LIST_KEYS), + KeyBinding::new("shift-n", PrevMatch, LIST_KEYS), + KeyBinding::new("ctrl-k", FocusSearch, LIST_KEYS), + KeyBinding::new("shift-l", ToggleLyrics, LIST_KEYS), + KeyBinding::new("ctrl-shift-l", ToggleInlineLyrics, LIST_KEYS), + KeyBinding::new("t", ToggleThemes, LIST_KEYS), + KeyBinding::new("shift-f", ToggleImmersive, LIST_KEYS), + // The platform-conventional preferences shortcut; global so it also works while + // the search box has focus. + KeyBinding::new("ctrl-,", ToggleSettings, None), + // Global like ctrl-,: chords type nothing, so they're safe while inputs focus. + KeyBinding::new("ctrl-\\", ToggleSidebar, None), + KeyBinding::new("alt-left", HistoryBack, None), + KeyBinding::new("alt-right", HistoryForward, None), + KeyBinding::new("?", ToggleHelp, LIST_KEYS), + KeyBinding::new("v", EnterVisual, LIST_KEYS), + KeyBinding::new("shift-k", MoveTrackUp, LIST_KEYS), + KeyBinding::new("shift-j", MoveTrackDown, LIST_KEYS), + ]); +} + +fn spawn_tray_listener( + mut tray_rx: tokio::sync::mpsc::UnboundedReceiver, + cx: &mut App, +) { + cx.spawn(async move |cx| { + while let Some(event) = tray_rx.recv().await { + cx.update(|cx| match event { + tray::TrayEvent::Show => open_main_window(cx), + tray::TrayEvent::Quit => cx.quit(), + }); + } + }) + .detach(); +} + /// Opens the one main window around the entity `Shell` keeps, at the rectangle saved on the /// last close if it still lands on a display (a window saved on a monitor that is no longer /// attached would otherwise open off-screen with no way to drag it back). Shared by launch,