feat(slint): port keyboard shortcuts + Open Qobuz Link from Tauri

Adds the full keybindings system (26 actions, 5 categories, customizable
and persisted) plus the Ctrl+L "Open Qobuz Link" cross-platform resolver
to the Slint frontend, matching the Tauri implementation 1:1.

- New shared crate qbz-music-link: de-Tauri'd cross-platform link
  resolver (Qobuz/Spotify/Apple/Tidal/Deezer/song.link via Odesli) behind
  a QobuzSearchBridge trait. src-tauri left untouched.
- src/keybindings.rs: action model, winit shortcut grammar, conflict
  detection, ui_prefs persistence, main-window + miniplayer dispatch.
- src/link_resolver.rs: controller + bridge over QbzCore.
- New globals + 3 modals (read-only cheatsheet, customize editor with key
  capture, link resolver), hamburger menu entries, and a UiFocusState
  text-input guard wired across the app's TextInputs.

cc
This commit is contained in:
vicrodh committed 2026-06-25 09:43:50 -06:00
1 parent 14e800ea1f
commit 337062f316
44 files changed
+3360 -40

No files matched your search

+16
View File
@@ -5751,6 +5751,21 @@ dependencies = [
"urlencoding",
]
[[package]]
name = "qbz-music-link"
version = "0.1.0"
dependencies = [
"async-trait",
"log",
"qbz-models",
"qbz-qobuz",
"reqwest",
"serde",
"serde_json",
"thiserror 2.0.18",
"tokio",
]
[[package]]
name = "qbz-offline-cache"
version = "0.1.0"
@@ -5902,6 +5917,7 @@ dependencies = [
"qbz-media-controls",
"qbz-mixtape",
"qbz-models",
"qbz-music-link",
"qbz-offline-cache",
"qbz-player",
"qbz-playlist-import",
+1
View File
@@ -30,6 +30,7 @@ members = [
"qbz-lyrics",
"qbz-booklet",
"qbz-i18n",
"qbz-music-link",
]
[workspace.package]
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "qbz-music-link"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Frontend-agnostic cross-platform music-link resolver for QBZ (Qobuz/Spotify/Apple/Tidal/Deezer/Odesli -> Qobuz)"
[dependencies]
qbz-qobuz = { path = "../qbz-qobuz" }
qbz-models = { path = "../qbz-models" }
# Async
tokio = { workspace = true }
async-trait = { workspace = true }
# HTTP
reqwest = { workspace = true }
# Serialization
serde = { workspace = true }
serde_json = { workspace = true }
# Logging
log = { workspace = true }
# Error handling
thiserror = { workspace = true }
+31
View File
@@ -0,0 +1,31 @@
//! The search bridge that decouples Qobuz search from any frontend.
//!
//! The resolver needs to search Qobuz, but it must not depend on Tauri or any
//! particular frontend's core. Each frontend implements this trait over its own
//! `QbzCore` / `CoreBridge` and passes a `&dyn QobuzSearchBridge` to the resolver.
//!
//! The return types are the REAL `qbz_models` search-result pages:
//! - `SearchResultsPage<Track>` (items have a numeric `id: u64`)
//! - `SearchResultsPage<Album>` (items have a string `id: String` and `title: String`)
use qbz_models::{Album, SearchResultsPage, Track};
/// Searches Qobuz for tracks and albums. Implemented by the frontend.
#[async_trait::async_trait]
pub trait QobuzSearchBridge: Send + Sync {
/// Search Qobuz tracks. `limit`/`offset` mirror the Qobuz search params.
async fn search_tracks(
&self,
query: &str,
limit: usize,
offset: usize,
) -> Result<SearchResultsPage<Track>, String>;
/// Search Qobuz albums. `limit`/`offset` mirror the Qobuz search params.
async fn search_albums(
&self,
query: &str,
limit: usize,
offset: usize,
) -> Result<SearchResultsPage<Album>, String>;
}
+392
View File
@@ -0,0 +1,392 @@
//! Music-URL detection and provider definitions.
//!
//! Ported from `src-tauri/src/playlist_import/providers/{mod,spotify,apple,
//! tidal,deezer}.rs`. Only the URL-detection logic and Spotify's embed-metadata
//! scrape are ported here — the heavy playlist-import machinery (`fetch_playlist`,
//! token plumbing, importer models) is intentionally left in `src-tauri`.
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// Which streaming platform a music link belongs to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MusicProvider {
Spotify,
AppleMusic,
Tidal,
Deezer,
}
/// The kind of resource a music URL points to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MusicResource {
/// A native Qobuz URL — resolve directly.
Qobuz,
/// A single track on a third-party platform.
Track {
provider: MusicProvider,
url: String,
},
/// An album on a third-party platform.
Album {
provider: MusicProvider,
url: String,
},
/// A playlist — should be redirected to the Playlist Importer.
Playlist { provider: MusicProvider },
/// A song.link / album.link / odesli.co URL — resolve via Odesli API.
SongLink { url: String },
}
/// Detect what kind of music resource a URL points to.
///
/// Returns `None` for URLs that don't match any supported platform.
pub fn detect_music_resource(url: &str) -> Option<MusicResource> {
let url = url.trim();
if url.is_empty() {
return None;
}
// 1. Qobuz — resolve_link() handles this natively
if qbz_qobuz::resolve_link(url).is_ok() {
return Some(MusicResource::Qobuz);
}
// 2. song.link / album.link / odesli.co URLs
let lower = url.to_ascii_lowercase();
if lower.contains("song.link/") || lower.contains("album.link/") || lower.contains("odesli.co/")
{
return Some(MusicResource::SongLink {
url: url.to_string(),
});
}
// 3. Per-provider detection (track/album/playlist)
if let Some(resource) = spotify::detect_resource(url) {
return Some(resource);
}
if let Some(resource) = apple::detect_resource(url) {
return Some(resource);
}
if let Some(resource) = tidal::detect_resource(url) {
return Some(resource);
}
if let Some(resource) = deezer::detect_resource(url) {
return Some(resource);
}
None
}
// ── Spotify ──
pub mod spotify {
use super::*;
/// Detect if a URL is a Spotify track, album, or playlist.
pub fn detect_resource(url: &str) -> Option<MusicResource> {
let lower = url.to_ascii_lowercase();
if !lower.contains("spotify.com/") && !lower.starts_with("spotify:") {
return None;
}
// Playlist check first (so parse_playlist_id takes priority for playlists)
if parse_playlist_id(url).is_some() {
return Some(MusicResource::Playlist {
provider: MusicProvider::Spotify,
});
}
// Track: open.spotify.com/track/<id> or spotify:track:<id>
if lower.contains("/track/") || lower.contains(":track:") {
return Some(MusicResource::Track {
provider: MusicProvider::Spotify,
url: url.to_string(),
});
}
// Album: open.spotify.com/album/<id> or spotify:album:<id>
if lower.contains("/album/") || lower.contains(":album:") {
return Some(MusicResource::Album {
provider: MusicProvider::Spotify,
url: url.to_string(),
});
}
None
}
pub fn parse_playlist_id(url: &str) -> Option<String> {
if let Some(rest) = url.strip_prefix("spotify:playlist:") {
if !rest.is_empty() {
return Some(rest.to_string());
}
}
let patterns = [
"open.spotify.com/playlist/",
"open.spotify.com/embed/playlist/",
];
for pattern in patterns {
if let Some(idx) = url.find(pattern) {
let mut part = &url[idx + pattern.len()..];
if let Some(end) = part.find('?') {
part = &part[..end];
}
if !part.is_empty() {
return Some(part.to_string());
}
}
}
None
}
/// Fetch track or album metadata from Spotify embed page.
/// Returns (title, artist) if successful.
pub async fn fetch_embed_metadata(
entity_type: &str,
entity_id: &str,
) -> Option<(String, String)> {
let url = format!(
"https://open.spotify.com/embed/{}/{}",
entity_type, entity_id
);
let html = reqwest::get(&url).await.ok()?.text().await.ok()?;
let json_text = extract_script(&html, "__NEXT_DATA__")?;
let data: Value = serde_json::from_str(&json_text).ok()?;
let entity = data
.get("props")?
.get("pageProps")?
.get("state")?
.get("data")?
.get("entity")?;
let title = entity
.get("title")
.or_else(|| entity.get("name"))
.and_then(|v| v.as_str())?
.to_string();
// Tracks have "artists" array, albums have "subtitle" string
let artist = entity
.get("artists")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|a| a.get("name").and_then(|v| v.as_str()))
.collect::<Vec<_>>()
.join(", ")
})
.or_else(|| {
entity
.get("subtitle")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
.unwrap_or_default();
if title.is_empty() {
return None;
}
Some((title, artist))
}
fn extract_script(html: &str, id: &str) -> Option<String> {
let marker = format!("id=\"{}\"", id);
let start = html.find(&marker)?;
let script_start = html[start..].find('>')? + start + 1;
let script_end = html[script_start..].find("</script>")? + script_start;
Some(html[script_start..script_end].to_string())
}
}
// ── Apple Music ──
pub mod apple {
use super::*;
/// Detect if a URL is an Apple Music track, album, or playlist.
pub fn detect_resource(url: &str) -> Option<MusicResource> {
if !url.contains("music.apple.com/") {
return None;
}
// Playlist
if parse_playlist_id(url).is_some() {
return Some(MusicResource::Playlist {
provider: MusicProvider::AppleMusic,
});
}
// Song page (explicit song URL)
if url.contains("/song/") {
return Some(MusicResource::Track {
provider: MusicProvider::AppleMusic,
url: url.to_string(),
});
}
// Album page — with ?i= parameter means specific track
if url.contains("/album/") {
if url.contains("?i=") || url.contains("&i=") {
return Some(MusicResource::Track {
provider: MusicProvider::AppleMusic,
url: url.to_string(),
});
}
return Some(MusicResource::Album {
provider: MusicProvider::AppleMusic,
url: url.to_string(),
});
}
None
}
pub fn parse_playlist_id(url: &str) -> Option<(String, String)> {
if !url.contains("music.apple.com/") {
return None;
}
let parts: Vec<&str> = url.split('/').collect();
if parts.len() < 6 {
return None;
}
let storefront = parts.get(3)?.to_string();
let playlist_id = parts.last()?.split('?').next()?.to_string();
if playlist_id.starts_with("pl.") || playlist_id.starts_with("pl.u-") {
Some((storefront, playlist_id))
} else {
None
}
}
}
// ── Tidal ──
pub mod tidal {
use super::*;
/// Detect if a URL is a Tidal track, album, or playlist.
pub fn detect_resource(url: &str) -> Option<MusicResource> {
if !url.contains("tidal.com") {
return None;
}
// Playlist
if parse_playlist_id(url).is_some() {
return Some(MusicResource::Playlist {
provider: MusicProvider::Tidal,
});
}
let lower = url.to_ascii_lowercase();
// Track
if lower.contains("/track/") || lower.contains("/browse/track/") {
return Some(MusicResource::Track {
provider: MusicProvider::Tidal,
url: url.to_string(),
});
}
// Album
if lower.contains("/album/") || lower.contains("/browse/album/") {
return Some(MusicResource::Album {
provider: MusicProvider::Tidal,
url: url.to_string(),
});
}
None
}
pub fn parse_playlist_id(url: &str) -> Option<String> {
if !url.contains("tidal.com") {
return None;
}
let patterns = ["/browse/playlist/", "/playlist/"];
for pattern in patterns {
if let Some(idx) = url.find(pattern) {
let mut part = &url[idx + pattern.len()..];
if let Some(end) = part.find('?') {
part = &part[..end];
}
if !part.is_empty() {
return Some(part.to_string());
}
}
}
None
}
}
// ── Deezer ──
pub mod deezer {
use super::*;
/// Detect if a URL is a Deezer track, album, or playlist.
pub fn detect_resource(url: &str) -> Option<MusicResource> {
if !url.contains("deezer.com") {
return None;
}
// Playlist
if parse_playlist_id(url).is_some() {
return Some(MusicResource::Playlist {
provider: MusicProvider::Deezer,
});
}
let parts: Vec<&str> = url.split('/').collect();
for (idx, part) in parts.iter().enumerate() {
match *part {
"track" => {
if parts.get(idx + 1).map(|s| !s.is_empty()).unwrap_or(false) {
return Some(MusicResource::Track {
provider: MusicProvider::Deezer,
url: url.to_string(),
});
}
}
"album" => {
if parts.get(idx + 1).map(|s| !s.is_empty()).unwrap_or(false) {
return Some(MusicResource::Album {
provider: MusicProvider::Deezer,
url: url.to_string(),
});
}
}
_ => {}
}
}
None
}
pub fn parse_playlist_id(url: &str) -> Option<String> {
if !url.contains("deezer.com") {
return None;
}
let parts: Vec<&str> = url.split('/').collect();
for (idx, part) in parts.iter().enumerate() {
if *part == "playlist" {
let id = parts.get(idx + 1)?.split('?').next()?;
if !id.is_empty() {
return Some(id.to_string());
}
}
}
None
}
}
+30
View File
@@ -0,0 +1,30 @@
//! Error types for the music-link resolver.
//!
//! Replaces the Tauri-only `RuntimeError` used by the `src-tauri` original.
use thiserror::Error;
/// Errors that can occur while resolving a cross-platform music link.
#[derive(Debug, Error)]
pub enum MusicLinkError {
/// The input URL was empty after trimming.
#[error("Empty URL")]
EmptyUrl,
/// The URL did not match any supported platform.
#[error("Unsupported or invalid music link")]
Unsupported,
/// A generic internal/resolver error (network, Odesli, search, etc.).
#[error("{0}")]
Internal(String),
}
impl serde::Serialize for MusicLinkError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Direct platform metadata (bypass Odesli for speed).
//!
//! Ported verbatim from the `src-tauri` link resolver. For Tidal/Deezer this
//! calls the platform API directly; for Spotify it scrapes the embed page.
//! Apple Music has no direct API and falls through to Odesli.
use crate::detection::{spotify, MusicProvider};
/// Public Cloudflare-worker proxy base. NOT a secret — this is the same public
/// URL hardcoded in the `src-tauri` original. No API keys are embedded here.
const QBZ_PROXY_BASE: &str = "https://qbz-api-proxy.blitzkriegfc.workers.dev";
/// Try to get title+artist directly from the platform API.
/// Returns None if the platform isn't supported or the request fails.
pub(crate) async fn try_direct_platform_metadata(
url: &str,
provider: &MusicProvider,
is_track: bool,
) -> Option<(String, String)> {
match provider {
MusicProvider::Deezer => try_deezer_metadata(url, is_track).await,
MusicProvider::Spotify => try_spotify_metadata(url, is_track).await,
MusicProvider::Tidal => try_tidal_metadata(url, is_track).await,
MusicProvider::AppleMusic => None, // No direct API available
}
}
/// Extract a numeric or alphanumeric ID after /track/ or /album/ in a URL.
fn extract_entity_id(url: &str, entity_type: &str) -> Option<String> {
let pattern = format!("/{}/", entity_type);
let idx = url.find(&pattern)?;
let rest = &url[idx + pattern.len()..];
let id = rest.split(['?', '/', '#']).next()?;
if id.is_empty() {
None
} else {
Some(id.to_string())
}
}
/// Extract Spotify ID from URL or URI.
fn extract_spotify_entity_id(url: &str, entity_type: &str) -> Option<String> {
// URI format: spotify:track:abc123
let uri_pattern = format!("spotify:{}:", entity_type);
if let Some(rest) = url.strip_prefix(&uri_pattern) {
let id = rest.split(['?', '/']).next()?;
if !id.is_empty() {
return Some(id.to_string());
}
}
extract_entity_id(url, entity_type)
}
async fn try_deezer_metadata(url: &str, is_track: bool) -> Option<(String, String)> {
let entity = if is_track { "track" } else { "album" };
let id = extract_entity_id(url, entity).or_else(|| {
if is_track {
None
} else {
extract_entity_id(url, "track")
}
})?;
let api_url = format!("https://api.deezer.com/{}/{}", entity, id);
log::debug!("Link resolver: Deezer direct API: {}", api_url);
let data: serde_json::Value = reqwest::get(&api_url).await.ok()?.json().await.ok()?;
if data.get("error").is_some() {
return None;
}
let title = data.get("title")?.as_str()?.to_string();
let artist = data
.get("artist")
.and_then(|a| a.get("name"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
Some((title, artist))
}
async fn try_spotify_metadata(url: &str, is_track: bool) -> Option<(String, String)> {
let entity = if is_track { "track" } else { "album" };
let id = extract_spotify_entity_id(url, entity)?;
log::debug!("Link resolver: Spotify embed scrape for {} {}", entity, id);
spotify::fetch_embed_metadata(entity, &id).await
}
async fn try_tidal_metadata(url: &str, is_track: bool) -> Option<(String, String)> {
let entity = if is_track { "track" } else { "album" };
let id = extract_entity_id(url, entity)
// Also try /browse/track/ pattern
.or_else(|| extract_entity_id(url, &format!("browse/{}", entity)))?;
let token = get_proxy_token("tidal").await?;
let api_url = format!(
"https://openapi.tidal.com/v2/{}s/{}?countryCode=US&include=artists",
entity, id
);
log::debug!("Link resolver: Tidal direct API: {}", api_url);
let data: serde_json::Value = reqwest::Client::new()
.get(&api_url)
.header("Authorization", format!("Bearer {}", token))
.send()
.await
.ok()?
.json()
.await
.ok()?;
let title = data
.get("data")
.and_then(|d| d.get("attributes"))
.and_then(|a| a.get("title"))
.and_then(|v| v.as_str())?
.to_string();
// Artist name is in the "included" array
let artist = data
.get("included")
.and_then(|v| v.as_array())
.and_then(|arr| {
arr.iter()
.find(|item| item.get("type").and_then(|v| v.as_str()) == Some("artists"))
})
.and_then(|item| item.get("attributes"))
.and_then(|a| a.get("name"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
Some((title, artist))
}
/// Get an OAuth token from the QBZ proxy for the given platform.
async fn get_proxy_token(platform: &str) -> Option<String> {
let url = format!("{}/{}/token", QBZ_PROXY_BASE, platform);
let data: serde_json::Value = reqwest::Client::builder()
.default_headers({
let mut h = reqwest::header::HeaderMap::new();
h.insert(
reqwest::header::USER_AGENT,
reqwest::header::HeaderValue::from_static("QBZ/1.0.0"),
);
h
})
.build()
.ok()?
.get(&url)
.send()
.await
.ok()?
.json()
.await
.ok()?;
data.get("access_token")
.and_then(|v| v.as_str())
.map(|v| v.to_string())
}
+183
View File
@@ -0,0 +1,183 @@
//! Frontend-agnostic cross-platform music-link resolver.
//!
//! Extracted from `src-tauri/src/commands_v2/link_resolver.rs` so any frontend
//! (Tauri, Slint, TUI/CLI) can resolve music links without depending on
//! `src-tauri` (ADR-006). Accepts URLs from Qobuz, Spotify, Apple Music, Tidal,
//! Deezer, song.link, and album.link. For non-Qobuz tracks/albums it identifies
//! the content (direct platform API fast-path, else the Odesli API) and searches
//! Qobuz by title+artist to find the equivalent. For playlists it returns
//! `PlaylistDetected` so the frontend can redirect to its importer.
//!
//! The Qobuz search itself is decoupled via the [`QobuzSearchBridge`] trait —
//! the frontend implements it over its own core and passes a `&dyn` to
//! [`resolve_music_link`].
mod bridge;
mod detection;
mod errors;
mod fast_path;
mod odesli;
mod qobuz_search;
// ── Public API surface ──
pub use bridge::QobuzSearchBridge;
pub use detection::{detect_music_resource, MusicProvider, MusicResource};
pub use errors::MusicLinkError;
pub use odesli::{ContentType, ShareError, SongLinkClient};
pub use qobuz_search::MusicLinkResult;
// Re-export the native Qobuz parser so frontends can do native parsing too,
// without taking a direct `qbz-qobuz` dependency just for this.
pub use qbz_qobuz::{resolve_link, LinkResolverError, ResolvedLink};
use detection::MusicProvider as Provider;
/// Resolve a cross-platform music link to a Qobuz navigation action.
///
/// Accepts URLs from Qobuz, Spotify, Apple Music, Tidal, Deezer, song.link, and
/// album.link. For non-Qobuz tracks/albums, uses the Odesli API (or a direct
/// platform fast-path) to identify the content, then searches Qobuz by
/// title+artist to find the equivalent album. For playlists, returns
/// `PlaylistDetected` so the frontend can redirect to the importer.
pub async fn resolve_music_link(
url: &str,
songlink: &SongLinkClient,
bridge: &dyn QobuzSearchBridge,
) -> Result<MusicLinkResult, MusicLinkError> {
let url = url.trim().to_string();
if url.is_empty() {
return Err(MusicLinkError::EmptyUrl);
}
// 1. Try Qobuz native resolve first (sync, no network)
if let Ok(resolved) = qbz_qobuz::resolve_link(&url) {
return Ok(MusicLinkResult::Resolved {
link: resolved,
provider: None,
});
}
// 2. Detect what kind of resource this is
let resource = detect_music_resource(&url).ok_or(MusicLinkError::Unsupported)?;
match resource {
MusicResource::Qobuz => {
// Already handled above, but just in case
let resolved = qbz_qobuz::resolve_link(&url)
.map_err(|e| MusicLinkError::Internal(e.to_string()))?;
Ok(MusicLinkResult::Resolved {
link: resolved,
provider: None,
})
}
MusicResource::Playlist { provider } => Ok(MusicLinkResult::PlaylistDetected {
provider: format!("{:?}", provider),
}),
MusicResource::Track {
provider,
url: source_url,
} => {
resolve_via_odesli_and_search(songlink, &source_url, Some(&provider), true, bridge).await
}
MusicResource::Album {
provider,
url: source_url,
} => {
resolve_via_odesli_and_search(songlink, &source_url, Some(&provider), false, bridge)
.await
}
MusicResource::SongLink { url: source_url } => {
// song.link URLs: try to detect track vs album from the URL format
let is_track_hint = source_url.contains("song.link/");
resolve_via_odesli_and_search(songlink, &source_url, None, is_track_hint, bridge).await
}
}
}
/// Identify a cross-platform music URL and search Qobuz for the equivalent.
///
/// Fast path: for Tidal/Deezer calls the platform API directly; for Spotify
/// scrapes the embed page to get title+artist. Fallback: uses Odesli API (~2-3s).
/// Then searches Qobuz with progressively simpler queries.
async fn resolve_via_odesli_and_search(
songlink: &SongLinkClient,
url: &str,
provider: Option<&Provider>,
is_track: bool,
bridge: &dyn QobuzSearchBridge,
) -> Result<MusicLinkResult, MusicLinkError> {
let provider_name = provider.map(|p| format!("{:?}", p));
// 1. Get title + artist: try direct platform API first (fast), fall back to Odesli
let (title, artist) = if let Some(prov) = provider {
match fast_path::try_direct_platform_metadata(url, prov, is_track).await {
Some(meta) => {
log::info!(
"Link resolver: direct API resolved '{}' by '{}'",
meta.0,
meta.1
);
meta
}
None => {
log::info!("Link resolver: direct API failed, falling back to Odesli");
fetch_metadata_via_odesli(songlink, url).await?
}
}
} else {
// No provider (song.link URLs) — use Odesli
fetch_metadata_via_odesli(songlink, url).await?
};
if title.is_empty() {
return Ok(MusicLinkResult::NotOnQobuz {
provider: provider_name,
});
}
// 2. Search Qobuz with progressively simpler queries
if let Some(result) =
qobuz_search::search_qobuz_smart(bridge, &title, &artist, is_track, &provider_name).await?
{
return Ok(result);
}
log::info!(
"Link resolver: '{}' by '{}' not found on Qobuz",
title,
artist
);
Ok(MusicLinkResult::NotOnQobuz {
provider: provider_name,
})
}
/// Fetch metadata from Odesli API (with one retry for transient errors).
async fn fetch_metadata_via_odesli(
songlink: &SongLinkClient,
url: &str,
) -> Result<(String, String), MusicLinkError> {
let response = match songlink.get_by_url(url, ContentType::Track).await {
Ok(r) => r,
Err(first_err) => {
log::warn!(
"Link resolver: Odesli first attempt failed: {}, retrying...",
first_err
);
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
songlink
.get_by_url(url, ContentType::Track)
.await
.map_err(|e| MusicLinkError::Internal(format!("Odesli API error: {}", e)))?
}
};
let title = response.title.unwrap_or_default().trim().to_string();
let artist = response.artist.unwrap_or_default().trim().to_string();
Ok((title, artist))
}
+346
View File
@@ -0,0 +1,346 @@
//! Self-contained Odesli/song.link client.
//!
//! Ported from `src-tauri/src/share/{songlink,models,errors}.rs`. This is a
//! frontend-agnostic copy so the resolver does not depend on the Tauri `share`
//! module. The Odesli endpoint is `https://api.song.link/v1-alpha.1/links`.
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use thiserror::Error;
const ODESLI_API_URL: &str = "https://api.song.link/v1-alpha.1/links";
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
const CACHE_TTL: Duration = Duration::from_secs(3600); // 1 hour
// ── Error type ──
#[derive(Error, Debug)]
pub enum ShareError {
#[error("Network error: {0}")]
NetworkError(#[from] reqwest::Error),
#[error("Odesli API error: {0}")]
OdesliError(String),
#[error("No matches found on Odesli")]
NoMatches,
}
// ── Models ──
/// Response from Odesli API
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)] // wire-shape fields kept for fidelity; not all are read here
pub struct OdesliResponse {
/// The unique ID for the input entity that was supplied in the request
pub entity_unique_id: Option<String>,
/// The userCountry query param that was supplied in the request
pub user_country: Option<String>,
/// The main song.link page URL
pub page_url: String,
/// A map of platform names to their link info
#[serde(default)]
pub links_by_platform: HashMap<String, PlatformLink>,
/// A map of entity unique IDs to entity info
#[serde(default)]
pub entities_by_unique_id: HashMap<String, Entity>,
}
/// Link info for a specific platform
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformLink {
/// The country code for this link
pub country: Option<String>,
/// The URL to this entity on the platform
pub url: String,
/// The native app URI
pub native_app_uri_mobile: Option<String>,
pub native_app_uri_desktop: Option<String>,
/// The unique ID for this entity
pub entity_unique_id: Option<String>,
}
/// Entity info from Odesli
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)] // wire-shape fields kept for fidelity; not all are read here
pub struct Entity {
/// The unique ID (can be a string or number in the API response)
#[serde(deserialize_with = "deserialize_string_or_number")]
pub id: String,
/// Type: "song", "album"
#[serde(rename = "type")]
pub entity_type: Option<String>,
/// Title
pub title: Option<String>,
/// Artist name
pub artist_name: Option<String>,
/// Thumbnail URL
pub thumbnail_url: Option<String>,
/// Thumbnail dimensions
pub thumbnail_width: Option<u32>,
pub thumbnail_height: Option<u32>,
/// API provider
pub api_provider: Option<String>,
/// Platforms this entity is available on
pub platforms: Option<Vec<String>>,
}
/// Simplified response for consumption
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SongLinkResponse {
/// The main song.link URL to share
pub page_url: String,
/// Title of the content (if available)
pub title: Option<String>,
/// Artist name (if available)
pub artist: Option<String>,
/// Thumbnail URL (if available)
pub thumbnail_url: Option<String>,
/// Map of platform names to their direct URLs
pub platforms: HashMap<String, String>,
/// The identifier used (ISRC or UPC)
pub identifier: String,
/// Type of content: "track" or "album"
pub content_type: String,
}
/// Content type for sharing
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentType {
Track,
Album,
}
impl ContentType {
pub fn as_str(&self) -> &'static str {
match self {
ContentType::Track => "track",
ContentType::Album => "album",
}
}
}
/// Deserialize a JSON value that may be a string or a number into a String.
/// Bandcamp's Odesli entities return numeric IDs while others return strings.
fn deserialize_string_or_number<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de;
struct StringOrNumber;
impl<'de> de::Visitor<'de> for StringOrNumber {
type Value = String;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a string or number")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<String, E> {
Ok(v.to_string())
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<String, E> {
Ok(v.to_string())
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<String, E> {
Ok(v.to_string())
}
}
deserializer.deserialize_any(StringOrNumber)
}
// ── Client ──
/// Cached entry with TTL
struct CacheEntry {
response: SongLinkResponse,
created_at: Instant,
}
impl CacheEntry {
fn is_expired(&self) -> bool {
self.created_at.elapsed() > CACHE_TTL
}
}
/// Odesli/song.link client with caching
pub struct SongLinkClient {
client: Client,
cache: Mutex<HashMap<String, CacheEntry>>,
}
impl Default for SongLinkClient {
fn default() -> Self {
Self::new()
}
}
impl SongLinkClient {
pub fn new() -> Self {
Self {
client: Client::builder()
.timeout(REQUEST_TIMEOUT)
.connect_timeout(Duration::from_secs(5))
.build()
.unwrap_or_default(),
cache: Mutex::new(HashMap::new()),
}
}
/// Get song.link URL by URL (fallback when ISRC/UPC are missing)
pub async fn get_by_url(
&self,
url: &str,
content_type: ContentType,
) -> Result<SongLinkResponse, ShareError> {
let cache_key = format!("url:{}", url);
if let Some(cached) = self.get_from_cache(&cache_key) {
log::debug!("Cache hit for URL: {}", url);
return Ok(cached);
}
log::info!("Fetching song.link for URL: {}", url);
let response = self
.client
.get(ODESLI_API_URL)
.query(&[("url", url), ("userCountry", "US")])
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
// Provide a friendlier message for common errors
if status.as_u16() == 400 && text.contains("could_not_resolve_entity") {
return Err(ShareError::OdesliError(
"Track not found on any supported platform. Try a track with an ISRC code."
.to_string(),
));
}
return Err(ShareError::OdesliError(format!(
"HTTP {}: {}",
status, text
)));
}
let odesli: OdesliResponse = response.json().await?;
let result = self.convert_response(odesli, url.to_string(), content_type)?;
self.store_in_cache(cache_key, result.clone());
Ok(result)
}
/// Convert Odesli response to our simplified format
fn convert_response(
&self,
response: OdesliResponse,
identifier: String,
content_type: ContentType,
) -> Result<SongLinkResponse, ShareError> {
// Extract title and artist from the first entity
let (title, artist, thumbnail_url) = response
.entities_by_unique_id
.values()
.next()
.map(|e| {
(
e.title.clone(),
e.artist_name.clone(),
e.thumbnail_url.clone(),
)
})
.unwrap_or((None, None, None));
// Extract platform URLs
let platforms: HashMap<String, String> = response
.links_by_platform
.into_iter()
.map(|(platform, link)| (platform, link.url))
.collect();
if platforms.is_empty() {
return Err(ShareError::NoMatches);
}
Ok(SongLinkResponse {
page_url: response.page_url,
title,
artist,
thumbnail_url,
platforms,
identifier,
content_type: content_type.as_str().to_string(),
})
}
/// Get from cache if not expired
fn get_from_cache(&self, key: &str) -> Option<SongLinkResponse> {
let cache = self.cache.lock().ok()?;
let entry = cache.get(key)?;
if entry.is_expired() {
None
} else {
Some(entry.response.clone())
}
}
/// Store in cache
fn store_in_cache(&self, key: String, response: SongLinkResponse) {
if let Ok(mut cache) = self.cache.lock() {
// Clean up expired entries occasionally
if cache.len() > 100 {
cache.retain(|_, entry| !entry.is_expired());
}
cache.insert(
key,
CacheEntry {
response,
created_at: Instant::now(),
},
);
}
}
/// Clear the cache
pub fn clear_cache(&self) {
if let Ok(mut cache) = self.cache.lock() {
cache.clear();
}
}
}
+161
View File
@@ -0,0 +1,161 @@
//! Smart Qobuz search: progressively simpler queries until a match is found.
//!
//! Ported verbatim from the `src-tauri` link resolver, with the search calls
//! routed through the frontend-agnostic `QobuzSearchBridge`. The 4th
//! `search_type: Option<&str>` arg of the original (always `None`) is dropped
//! from the bridge signature.
use crate::bridge::QobuzSearchBridge;
use crate::errors::MusicLinkError;
/// Result of resolving a cross-platform music link.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "kind")]
pub enum MusicLinkResult {
/// Successfully resolved to a Qobuz entity.
Resolved {
link: qbz_qobuz::ResolvedLink,
provider: Option<String>,
},
/// The URL is a playlist — redirect to the Playlist Importer.
PlaylistDetected { provider: String },
/// The content exists on the source platform but is not available on Qobuz.
NotOnQobuz { provider: Option<String> },
}
/// Search Qobuz with progressively simpler queries until a match is found.
///
/// Strategy:
/// 1. "title artist" (exact)
/// 2. "cleaned_title artist" (remove parenthetical/bracket suffixes)
/// 3. "artist" only with album search (broad)
pub(crate) async fn search_qobuz_smart(
bridge: &dyn QobuzSearchBridge,
title: &str,
artist: &str,
is_track: bool,
provider_name: &Option<String>,
) -> Result<Option<MusicLinkResult>, MusicLinkError> {
let full_query = if artist.is_empty() {
title.to_string()
} else {
format!("{} {}", title, artist)
};
// Attempt 1: full query
if is_track {
let results = bridge
.search_tracks(&full_query, 5, 0)
.await
.map_err(MusicLinkError::Internal)?;
if let Some(track) = results.items.first() {
log::info!(
"Link resolver: found Qobuz track id={} (full query)",
track.id
);
return Ok(Some(MusicLinkResult::Resolved {
link: qbz_qobuz::ResolvedLink::OpenTrack(track.id),
provider: provider_name.clone(),
}));
}
}
let results = bridge
.search_albums(&full_query, 5, 0)
.await
.map_err(MusicLinkError::Internal)?;
if let Some(album) = results.items.first() {
log::info!(
"Link resolver: found Qobuz album id={} (full query)",
album.id
);
return Ok(Some(MusicLinkResult::Resolved {
link: qbz_qobuz::ResolvedLink::OpenAlbum(album.id.clone()),
provider: provider_name.clone(),
}));
}
// Attempt 2: clean title (remove parenthetical/bracket suffixes like "Remastered", "Deluxe")
let cleaned = clean_title(title);
if cleaned != title && !cleaned.is_empty() {
let clean_query = if artist.is_empty() {
cleaned.clone()
} else {
format!("{} {}", cleaned, artist)
};
log::info!(
"Link resolver: retrying with cleaned query '{}'",
clean_query
);
let results = bridge
.search_albums(&clean_query, 5, 0)
.await
.map_err(MusicLinkError::Internal)?;
if let Some(album) = results.items.first() {
log::info!(
"Link resolver: found Qobuz album id={} (cleaned query)",
album.id
);
return Ok(Some(MusicLinkResult::Resolved {
link: qbz_qobuz::ResolvedLink::OpenAlbum(album.id.clone()),
provider: provider_name.clone(),
}));
}
}
// Attempt 3: search by artist name only (broad)
if !artist.is_empty() && artist != title {
log::info!(
"Link resolver: retrying with artist-only query '{}'",
artist
);
let results = bridge
.search_albums(artist, 10, 0)
.await
.map_err(MusicLinkError::Internal)?;
let title_lower = title.to_ascii_lowercase();
let cleaned_lower = clean_title(title).to_ascii_lowercase();
for album in &results.items {
let album_title_lower = album.title.to_ascii_lowercase();
if album_title_lower.contains(&cleaned_lower)
|| cleaned_lower.contains(&album_title_lower)
|| album_title_lower.contains(&title_lower)
{
log::info!(
"Link resolver: found Qobuz album id={} (artist-only + title match)",
album.id
);
return Ok(Some(MusicLinkResult::Resolved {
link: qbz_qobuz::ResolvedLink::OpenAlbum(album.id.clone()),
provider: provider_name.clone(),
}));
}
}
}
Ok(None)
}
/// Remove parenthetical/bracket suffixes from a title.
/// "Senjutsu (2021 Remaster)" → "Senjutsu"
/// "The Number of the Beast [Deluxe Edition]" → "The Number of the Beast"
pub(crate) fn clean_title(title: &str) -> String {
let mut result = title.to_string();
// Remove trailing (...) and [...]
while let Some(pos) = result.rfind('(') {
if result[pos..].contains(')') {
result = result[..pos].trim_end().to_string();
} else {
break;
}
}
while let Some(pos) = result.rfind('[') {
if result[pos..].contains(']') {
result = result[..pos].trim_end().to_string();
} else {
break;
}
}
result.trim().to_string()
}
+1
View File
@@ -44,6 +44,7 @@ slint = { version = "=1.16.1", default-features = false, features = [
# pinned to the exact version Slint resolves (1.16.1) — i-slint-backend-winit
# does not follow semver, and a mismatch makes with_winit_window() return None.
i-slint-backend-winit = "=1.16.1"
qbz-music-link = { path = "../qbz-music-link" }
log = { workspace = true }
env_logger = "0.11"
tokio = { workspace = true }
+620
View File
@@ -0,0 +1,620 @@
//! Keyboard shortcuts (hotkeys) — Rust port of the Tauri `keybindingsStore`.
//!
//! Mirrors the Tauri model 1:1: the same 26 actions, the same default
//! shortcuts, the same shortcut-string grammar, conflict detection, and user
//! overrides. The differences are mechanical:
//!
//! - Persistence is the per-machine `ui_prefs.json` (`keybindings` map) instead
//! of `localStorage` (mirrors every other Slint appearance pref).
//! - Key events come from winit (`on_winit_window_event`) instead of a DOM
//! `keydown` listener. The `isInputTarget` guard becomes `UiFocusState`.
//! - The two modals + the capture widget are Slint (`KeybindingsState` /
//! `KeyboardShortcutsState`); this module owns the model + dispatch.
//!
//! Grammar (identical canonical strings to the TS `eventToShortcut`):
//! `[Ctrl+][Alt+][Shift+]Key`. `Ctrl` covers Ctrl OR Meta/Super. `Shift` is
//! only emitted for letters, digits, and named keys (Arrow*, Space, …) — for a
//! symbol the Shift is already "consumed" by producing the symbol (e.g. `?`).
use std::cell::Cell;
use std::collections::BTreeMap;
use i_slint_backend_winit::{
winit::keyboard::{Key, NamedKey},
EventResult,
};
use slint::ComponentHandle;
use crate::{
AppWindow, ImmersiveActions, ImmersiveState, KeybindingsActions, KeybindingsState,
KeyboardShortcutsState, LinkResolverState, NavState, NowPlayingState, SearchState, ShellState,
};
// ============================================================================
// Action model
// ============================================================================
/// Display/grouping category. Order here is the on-screen order.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Category {
Playback,
Navigation,
Ui,
Immersive,
Mini,
}
impl Category {
const ORDER: [Category; 5] = [
Category::Playback,
Category::Navigation,
Category::Ui,
Category::Immersive,
Category::Mini,
];
/// English source string for the localized category header.
fn label_en(self) -> &'static str {
match self {
Category::Playback => "Playback",
Category::Navigation => "Navigation",
Category::Ui => "Interface",
Category::Immersive => "Immersive",
Category::Mini => "Mini Player",
}
}
}
/// When an action only fires in a specific surface.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Context {
None,
/// Only while the immersive overlay is open (seek shortcuts).
Immersive,
/// Only while the miniplayer window is active (surface 1-5). Dispatched on
/// the mini window's own FocusScope, never on the main window.
Mini,
}
pub struct ActionDef {
pub id: &'static str,
pub label_en: &'static str,
pub category: Category,
pub default: &'static str,
pub context: Context,
}
/// The full action table — a 1:1 port of the Tauri `ACTIONS` array.
pub const ACTIONS: &[ActionDef] = &[
// Playback
ActionDef { id: "playback.toggle", label_en: "Play / Pause", category: Category::Playback, default: "Space", context: Context::None },
ActionDef { id: "playback.next", label_en: "Next Track", category: Category::Playback, default: "Ctrl+ArrowRight", context: Context::None },
ActionDef { id: "playback.prev", label_en: "Previous Track", category: Category::Playback, default: "Ctrl+ArrowLeft", context: Context::None },
// Navigation
ActionDef { id: "nav.back", label_en: "Go Back", category: Category::Navigation, default: "Alt+ArrowLeft", context: Context::None },
ActionDef { id: "nav.forward", label_en: "Go Forward", category: Category::Navigation, default: "Alt+ArrowRight", context: Context::None },
ActionDef { id: "nav.search", label_en: "Search", category: Category::Navigation, default: "Ctrl+f", context: Context::None },
ActionDef { id: "nav.settings", label_en: "Settings", category: Category::Navigation, default: "Ctrl+,", context: Context::None },
// Interface
ActionDef { id: "ui.sidebar", label_en: "Toggle Sidebar", category: Category::Ui, default: "Shift+S", context: Context::None },
ActionDef { id: "ui.focusMode", label_en: "Immersive Mode", category: Category::Ui, default: "Shift+I", context: Context::None },
ActionDef { id: "ui.queue", label_en: "Queue", category: Category::Ui, default: "q", context: Context::None },
ActionDef { id: "ui.escape", label_en: "Close / Dismiss", category: Category::Ui, default: "Escape", context: Context::None },
ActionDef { id: "ui.showShortcuts", label_en: "Show Shortcuts", category: Category::Ui, default: "?", context: Context::None },
ActionDef { id: "ui.openLink", label_en: "Open Qobuz Link", category: Category::Ui, default: "Ctrl+l", context: Context::None },
ActionDef { id: "ui.miniPlayer", label_en: "Toggle Mini Player", category: Category::Ui, default: "Shift+M", context: Context::None },
// Immersive (contextual)
ActionDef { id: "focus.seekForward", label_en: "Seek Forward (5s)", category: Category::Immersive, default: "ArrowRight", context: Context::Immersive },
ActionDef { id: "focus.seekBack", label_en: "Seek Back (5s)", category: Category::Immersive, default: "ArrowLeft", context: Context::Immersive },
ActionDef { id: "focus.seekForwardLong", label_en: "Seek Forward (10s)", category: Category::Immersive, default: "Shift+ArrowRight", context: Context::Immersive },
ActionDef { id: "focus.seekBackLong", label_en: "Seek Back (10s)", category: Category::Immersive, default: "Shift+ArrowLeft", context: Context::Immersive },
// Mini Player (contextual — dispatched on the mini window)
ActionDef { id: "mini.micro", label_en: "Micro View", category: Category::Mini, default: "1", context: Context::Mini },
ActionDef { id: "mini.compact", label_en: "Compact View", category: Category::Mini, default: "2", context: Context::Mini },
ActionDef { id: "mini.artwork", label_en: "Artwork View", category: Category::Mini, default: "3", context: Context::Mini },
ActionDef { id: "mini.queue", label_en: "Queue View", category: Category::Mini, default: "4", context: Context::Mini },
ActionDef { id: "mini.lyrics", label_en: "Lyrics View", category: Category::Mini, default: "5", context: Context::Mini },
];
fn action(id: &str) -> Option<&'static ActionDef> {
ACTIONS.iter().find(|a| a.id == id)
}
// ============================================================================
// Modifier tracking (UI thread only)
// ============================================================================
thread_local! {
static MODS: Cell<(bool, bool, bool)> = const { Cell::new((false, false, false)) };
}
/// Record the current modifier state from a winit `ModifiersChanged` event.
/// `ctrl` already folds in Meta/Super (mirrors the TS `ctrlKey || metaKey`).
pub fn set_mods(ctrl: bool, alt: bool, shift: bool) {
MODS.with(|m| m.set((ctrl, alt, shift)));
}
fn mods() -> (bool, bool, bool) {
MODS.with(|m| m.get())
}
// ============================================================================
// Shortcut-string grammar (port of eventToShortcut / formatShortcutDisplay)
// ============================================================================
/// Normalize a winit logical key to a canonical key token (the part after the
/// modifiers). Returns `None` for bare modifier presses and unrepresentable
/// keys. Letter/symbol casing is taken from winit verbatim (winit already
/// reports the shifted glyph, so Shift+s → "S", Shift+/ → "?").
pub fn token_from_key(key: &Key) -> Option<String> {
match key {
Key::Named(NamedKey::Space) => Some("Space".into()),
Key::Named(NamedKey::ArrowLeft) => Some("ArrowLeft".into()),
Key::Named(NamedKey::ArrowRight) => Some("ArrowRight".into()),
Key::Named(NamedKey::ArrowUp) => Some("ArrowUp".into()),
Key::Named(NamedKey::ArrowDown) => Some("ArrowDown".into()),
Key::Named(NamedKey::Escape) => Some("Escape".into()),
Key::Named(NamedKey::Enter) => Some("Enter".into()),
Key::Named(NamedKey::Tab) => Some("Tab".into()),
Key::Named(NamedKey::Backspace) => Some("Backspace".into()),
Key::Named(NamedKey::Delete) => Some("Delete".into()),
Key::Character(s) => {
let t = s.as_str();
if t.chars().count() != 1 {
return None;
}
Some(t.to_string())
}
_ => None,
}
}
/// Build the canonical shortcut string from modifiers + a key token.
pub fn shortcut_from_parts(ctrl: bool, alt: bool, shift: bool, token: &str) -> Option<String> {
if token.is_empty() {
return None;
}
let mut parts: Vec<String> = Vec::new();
if ctrl {
parts.push("Ctrl".into());
}
if alt {
parts.push("Alt".into());
}
// Shift is emitted only for letters, digits, and named (multi-char) keys.
let is_named = token.chars().count() > 1;
let single = token.chars().next().unwrap();
let is_letter = !is_named && single.is_ascii_alphabetic();
let is_digit = !is_named && single.is_ascii_digit();
if shift && (is_named || is_letter || is_digit) {
parts.push("Shift".into());
}
parts.push(token.to_string());
Some(parts.join("+"))
}
const KEY_DISPLAY: &[(&str, &str)] = &[
("ArrowLeft", "←"),
("ArrowRight", "→"),
("ArrowUp", "↑"),
("ArrowDown", "↓"),
("Space", "Space"),
("Escape", "Esc"),
("Enter", "↵"),
("Backspace", "⌫"),
("Delete", "Del"),
("Tab", "Tab"),
];
/// Format a shortcut string for display (port of `formatShortcutDisplay`).
/// macOS uses ⌘⌥⇧ glyphs joined by spaces; elsewhere "Ctrl + …".
pub fn format_display(shortcut: &str) -> String {
if shortcut.is_empty() {
return String::new();
}
let (mut ctrl, mut alt, mut shift) = (false, false, false);
let mut key = "";
for part in shortcut.split('+') {
match part {
"Ctrl" => ctrl = true,
"Alt" => alt = true,
"Shift" => shift = true,
other => key = other,
}
}
let mac = cfg!(target_os = "macos");
let mut out: Vec<String> = Vec::new();
if ctrl {
out.push(if mac { "⌘" } else { "Ctrl" }.into());
}
if alt {
out.push(if mac { "⌥" } else { "Alt" }.into());
}
if shift {
out.push(if mac { "⇧" } else { "Shift" }.into());
}
let disp = KEY_DISPLAY
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| (*v).to_string())
.unwrap_or_else(|| key.to_uppercase());
out.push(disp);
out.join(if mac { " " } else { " + " })
}
// ============================================================================
// Bindings (defaults + user overrides) + conflict detection
// ============================================================================
/// The active binding map (defaults overlaid with the user's overrides).
pub fn active_bindings() -> BTreeMap<String, String> {
let mut map: BTreeMap<String, String> = BTreeMap::new();
for a in ACTIONS {
map.insert(a.id.to_string(), a.default.to_string());
}
let prefs = crate::ui_prefs::load();
for (id, shortcut) in prefs.keybindings {
if map.contains_key(&id) {
map.insert(id, shortcut);
}
}
map
}
fn action_for_shortcut<'a>(
shortcut: &str,
bindings: &'a BTreeMap<String, String>,
) -> Option<&'static ActionDef> {
let id = bindings
.iter()
.find(|(_, v)| v.as_str() == shortcut)
.map(|(k, _)| k.clone())?;
action(&id)
}
/// The action (other than `exclude`) that already owns `shortcut`, if any.
fn conflicting_action(
shortcut: &str,
exclude: &str,
bindings: &BTreeMap<String, String>,
) -> Option<&'static ActionDef> {
for (id, sc) in bindings {
if sc == shortcut && id != exclude {
return action(id);
}
}
None
}
/// Persist a new binding. Returns false (and writes nothing) on a conflict.
fn set_binding(action_id: &str, shortcut: &str) -> bool {
let bindings = active_bindings();
if conflicting_action(shortcut, action_id, &bindings).is_some() {
return false;
}
let default = action(action_id).map(|a| a.default);
let mut prefs = crate::ui_prefs::load();
if Some(shortcut) == default {
// Back to default → drop the override (keeps the file minimal).
prefs.keybindings.remove(action_id);
} else {
prefs.keybindings.insert(action_id.to_string(), shortcut.to_string());
}
crate::ui_prefs::save(&prefs);
true
}
fn reset_one(action_id: &str) {
let mut prefs = crate::ui_prefs::load();
prefs.keybindings.remove(action_id);
crate::ui_prefs::save(&prefs);
}
fn reset_all() {
let mut prefs = crate::ui_prefs::load();
prefs.keybindings.clear();
crate::ui_prefs::save(&prefs);
}
// ============================================================================
// Slint model (cheatsheet + customize editor share the groups)
// ============================================================================
fn build_groups() -> slint::ModelRc<crate::KeybindingCategoryGroup> {
use slint::{ModelRc, VecModel};
let bindings = active_bindings();
let mut groups: Vec<crate::KeybindingCategoryGroup> = Vec::new();
for cat in Category::ORDER {
let mut rows: Vec<crate::KeybindingRow> = Vec::new();
for a in ACTIONS.iter().filter(|a| a.category == cat) {
let shortcut = bindings.get(a.id).cloned().unwrap_or_default();
let modified = bindings.get(a.id).map(|s| s.as_str()) != Some(a.default);
rows.push(crate::KeybindingRow {
id: a.id.into(),
label: qbz_i18n::t(a.label_en).into(),
shortcut: format_display(&shortcut).into(),
modified,
contextual: a.context != Context::None,
});
}
groups.push(crate::KeybindingCategoryGroup {
label: qbz_i18n::t(cat.label_en()).into(),
rows: ModelRc::new(VecModel::from(rows)),
});
}
ModelRc::new(VecModel::from(groups))
}
fn modified_count() -> i32 {
let bindings = active_bindings();
ACTIONS
.iter()
.filter(|a| bindings.get(a.id).map(|s| s.as_str()) != Some(a.default))
.count() as i32
}
/// Repopulate the Slint state from the persisted bindings. Call at startup and
/// after any change.
pub fn refresh(window: &AppWindow) {
let state = window.global::<KeybindingsState>();
state.set_groups(build_groups());
state.set_modified_count(modified_count());
}
// ============================================================================
// Callback wiring (KeybindingsActions) — called once at startup
// ============================================================================
pub fn wire(window: &AppWindow) {
let actions = window.global::<KeybindingsActions>();
let weak = window.as_weak();
actions.on_start_record(move |id| {
if let Some(w) = weak.upgrade() {
let s = w.global::<KeybindingsState>();
s.set_recording_id(id);
s.set_pending_display("".into());
s.set_conflict_label("".into());
}
});
let weak = window.as_weak();
actions.on_cancel_record(move || {
if let Some(w) = weak.upgrade() {
let s = w.global::<KeybindingsState>();
s.set_recording_id("".into());
s.set_pending_display("".into());
s.set_conflict_label("".into());
}
});
let weak = window.as_weak();
actions.on_reset_one(move |id| {
reset_one(id.as_str());
if let Some(w) = weak.upgrade() {
refresh(&w);
}
});
let weak = window.as_weak();
actions.on_reset_all(move || {
reset_all();
if let Some(w) = weak.upgrade() {
refresh(&w);
}
});
refresh(window);
}
// ============================================================================
// Capture (the customize editor's "press a key" widget)
// ============================================================================
/// Handle a keypress while the customize editor is recording a binding for
/// `action_id`. Always consumes the event.
pub fn handle_capture(window: &AppWindow, action_id: &str, key: &Key) -> EventResult {
let state = window.global::<KeybindingsState>();
// Escape cancels (does not bind — Escape stays the ui.escape default).
if matches!(key, Key::Named(NamedKey::Escape)) {
state.set_recording_id("".into());
state.set_pending_display("".into());
state.set_conflict_label("".into());
return EventResult::PreventDefault;
}
let (ctrl, alt, shift) = mods();
let Some(token) = token_from_key(key) else {
// Bare modifier / unrepresentable — ignore, keep recording.
return EventResult::PreventDefault;
};
let Some(shortcut) = shortcut_from_parts(ctrl, alt, shift, &token) else {
return EventResult::PreventDefault;
};
state.set_pending_display(format_display(&shortcut).into());
let bindings = active_bindings();
if let Some(conflict) = conflicting_action(&shortcut, action_id, &bindings) {
state.set_conflict_label(qbz_i18n::t(conflict.label_en).into());
// Leave recording on so the user can pick a different combo.
} else {
set_binding(action_id, &shortcut);
refresh(window);
state.set_recording_id("".into());
state.set_pending_display("".into());
state.set_conflict_label("".into());
}
EventResult::PreventDefault
}
// ============================================================================
// Dispatch (the global hotkey handler for the MAIN window)
// ============================================================================
/// Resolve + run a hotkey for the main window. Returns `PreventDefault` when an
/// action fired, `Propagate` otherwise. The caller has already ruled out
/// recording mode, an open search dropdown, and text-input focus.
pub fn dispatch(window: &AppWindow, key: &Key) -> EventResult {
let (ctrl, alt, shift) = mods();
let Some(token) = token_from_key(key) else {
return EventResult::Propagate;
};
let Some(shortcut) = shortcut_from_parts(ctrl, alt, shift, &token) else {
return EventResult::Propagate;
};
let bindings = active_bindings();
let Some(action) = action_for_shortcut(&shortcut, &bindings) else {
return EventResult::Propagate;
};
match action.context {
Context::Immersive => {
if !window.global::<ImmersiveState>().get_open() {
return EventResult::Propagate;
}
}
// Mini surfaces are dispatched on the mini window's FocusScope.
Context::Mini => return EventResult::Propagate,
Context::None => {}
}
run_action(window, action.id);
EventResult::PreventDefault
}
fn run_action(window: &AppWindow, id: &str) {
match id {
"playback.toggle" => window.global::<NowPlayingState>().invoke_toggle_play(),
"playback.next" => window.global::<NowPlayingState>().invoke_next(),
"playback.prev" => window.global::<NowPlayingState>().invoke_previous(),
"nav.back" => window.global::<NavState>().invoke_request_back(),
"nav.forward" => window.global::<NavState>().invoke_request_forward(),
"nav.search" => focus_search(window),
"nav.settings" => window.global::<NavState>().invoke_request_settings(),
"ui.sidebar" => window.global::<ShellState>().invoke_cycle_sidebar(),
"ui.focusMode" => toggle_immersive(window),
"ui.queue" => {
let shell = window.global::<ShellState>();
let open = shell.get_queue_open();
shell.set_queue_open(!open);
}
"ui.escape" => handle_escape(window),
"ui.miniPlayer" => toggle_miniplayer(),
"ui.openLink" => open_link_modal(window),
"ui.showShortcuts" => {
window.global::<KeyboardShortcutsState>().set_open(true);
refresh(window);
}
"focus.seekForward" => seek_relative(window, 5),
"focus.seekBack" => seek_relative(window, -5),
"focus.seekForwardLong" => seek_relative(window, 10),
"focus.seekBackLong" => seek_relative(window, -10),
_ => {}
}
}
fn focus_search(window: &AppWindow) {
// Open the header cortinilla; the field grabs focus on open.
window.global::<SearchState>().set_cortinilla_open(true);
}
fn toggle_immersive(window: &AppWindow) {
let imm = window.global::<ImmersiveState>();
let now = imm.get_open();
imm.set_open(!now);
if !now {
window.global::<ImmersiveActions>().invoke_opened();
}
}
fn toggle_miniplayer() {
if crate::miniplayer::is_open() {
crate::miniplayer::exit();
} else {
crate::miniplayer::enter();
}
}
fn open_link_modal(window: &AppWindow) {
let s = window.global::<LinkResolverState>();
s.set_url("".into());
s.set_platform("".into());
s.set_error("".into());
s.set_playlist_detected(false);
s.set_playlist_provider("".into());
s.set_resolving(false);
s.set_open(true);
}
/// Seek by `delta` seconds (clamped) while immersive is open.
fn seek_relative(window: &AppWindow, delta: i32) {
let np = window.global::<NowPlayingState>();
let duration = np.get_duration_secs();
if duration <= 0 {
return;
}
let pos = np.get_position_secs();
let target = (pos + delta).clamp(0, duration);
np.invoke_seek(target as f32 / duration as f32);
}
/// Close the topmost dismissable surface. Text-input focus has already been
/// ruled out by the caller, so this only touches non-text overlays.
fn handle_escape(window: &AppWindow) {
if window.global::<LinkResolverState>().get_open() {
window.global::<LinkResolverState>().set_open(false);
return;
}
if window.global::<KeyboardShortcutsState>().get_customize_open() {
window.global::<KeyboardShortcutsState>().set_customize_open(false);
return;
}
if window.global::<KeyboardShortcutsState>().get_open() {
window.global::<KeyboardShortcutsState>().set_open(false);
return;
}
if window.global::<SearchState>().get_cortinilla_open() {
window.global::<SearchState>().set_cortinilla_open(false);
return;
}
if window.global::<ImmersiveState>().get_open() {
window.global::<ImmersiveState>().set_open(false);
return;
}
let shell = window.global::<ShellState>();
if shell.get_queue_open() {
shell.set_queue_open(false);
}
}
// ============================================================================
// Dispatch for the MINIPLAYER window (a separate winit window). Handles the
// contextual mini surface shortcuts (1-5), the toggle (Shift+M / Escape →
// exit), and shared transport. Respects the user's custom bindings.
// ============================================================================
pub fn dispatch_mini(window: &crate::MiniPlayerWindow, key: &Key) -> EventResult {
let (ctrl, alt, shift) = mods();
let Some(token) = token_from_key(key) else {
return EventResult::Propagate;
};
let Some(shortcut) = shortcut_from_parts(ctrl, alt, shift, &token) else {
return EventResult::Propagate;
};
let bindings = active_bindings();
let Some(action) = action_for_shortcut(&shortcut, &bindings) else {
return EventResult::Propagate;
};
match action.id {
"mini.micro" => window.global::<crate::MiniPlayerState>().invoke_surface_change(0),
"mini.compact" => window.global::<crate::MiniPlayerState>().invoke_surface_change(1),
"mini.artwork" => window.global::<crate::MiniPlayerState>().invoke_surface_change(2),
"mini.queue" => window.global::<crate::MiniPlayerState>().invoke_surface_change(3),
"mini.lyrics" => window.global::<crate::MiniPlayerState>().invoke_surface_change(4),
"ui.miniPlayer" | "ui.escape" => crate::miniplayer::exit(),
"playback.toggle" => window.global::<NowPlayingState>().invoke_toggle_play(),
"playback.next" => window.global::<NowPlayingState>().invoke_next(),
"playback.prev" => window.global::<NowPlayingState>().invoke_previous(),
_ => return EventResult::Propagate,
}
EventResult::PreventDefault
}
+88
View File
@@ -0,0 +1,88 @@
//! "Open Qobuz Link" (Ctrl+L) controller.
//!
//! Bridges the frontend-agnostic `qbz-music-link` crate (the cross-platform
//! resolver extracted out of the Tauri command) to the Slint frontend: it
//! supplies a `QobuzSearchBridge` over `QbzCore`, the instant platform
//! detection for the input icon, and the async resolve entry point. The actual
//! navigation on a `Resolved` result is wired in `main.rs` (where the
//! `navigate_*` helpers live).
use std::sync::Arc;
use async_trait::async_trait;
use qbz_app::shell::AppRuntime;
use qbz_models::{Album, SearchResultsPage, Track};
use qbz_music_link::{resolve_music_link, MusicLinkResult, QobuzSearchBridge, SongLinkClient};
use crate::adapter::SlintAdapter;
/// Instant, network-free platform detection for the modal's leading icon.
/// Mirrors the Tauri `detectPlatform`. Returns "" when unknown.
pub fn detect_platform(url: &str) -> &'static str {
let lower = url.trim().to_ascii_lowercase();
if lower.contains("qobuz.com/") || lower.starts_with("qobuzapp://") {
"qobuz"
} else if lower.contains("spotify.com/") || lower.starts_with("spotify:") {
"spotify"
} else if lower.contains("music.apple.com/") {
"apple"
} else if lower.contains("tidal.com/") {
"tidal"
} else if lower.contains("deezer.com/") {
"deezer"
} else if lower.contains("song.link/")
|| lower.contains("album.link/")
|| lower.contains("odesli.co/")
{
"songlink"
} else {
""
}
}
/// `QobuzSearchBridge` over the live `QbzCore` (the smart-search fallback the
/// cross-platform resolver uses when an Odesli match must be found on Qobuz).
struct CoreSearchBridge {
runtime: Arc<AppRuntime<SlintAdapter>>,
}
#[async_trait]
impl QobuzSearchBridge for CoreSearchBridge {
async fn search_tracks(
&self,
query: &str,
limit: usize,
offset: usize,
) -> Result<SearchResultsPage<Track>, String> {
let core = self.runtime.core();
core.search_tracks(query, limit as u32, offset as u32, None)
.await
.map_err(|e| e.to_string())
}
async fn search_albums(
&self,
query: &str,
limit: usize,
offset: usize,
) -> Result<SearchResultsPage<Album>, String> {
let core = self.runtime.core();
core.search_albums(query, limit as u32, offset as u32, None)
.await
.map_err(|e| e.to_string())
}
}
/// Resolve a pasted URL to a Qobuz entity (or a playlist / not-found verdict).
/// Native Qobuz links resolve offline; cross-platform links hit Odesli + a
/// smart Qobuz search.
pub async fn resolve(
runtime: Arc<AppRuntime<SlintAdapter>>,
url: String,
) -> Result<MusicLinkResult, String> {
let bridge = CoreSearchBridge { runtime };
let songlink = SongLinkClient::new();
resolve_music_link(&url, &songlink, &bridge)
.await
.map_err(|e| e.to_string())
}
+209 -23
View File
@@ -42,7 +42,9 @@ mod dac_wizard;
mod home;
mod immersive;
mod info_modals;
mod keybindings;
mod label;
mod link_resolver;
mod miniplayer;
mod location_view;
mod mix;
@@ -714,6 +716,66 @@ fn update_nav_flags(window: &AppWindow) {
state.set_can_forward(nav::can_forward());
}
/// Navigate to the entity a resolved "Open Qobuz Link" points at. Albums /
/// artists / playlists open their detail view directly; a track is fetched to
/// resolve its album, then that album opens (mirrors the Tauri behavior).
fn apply_resolved_link(
link: qbz_music_link::ResolvedLink,
runtime: &Arc<AppRuntime<SlintAdapter>>,
weak: &slint::Weak<AppWindow>,
handle: &tokio::runtime::Handle,
image_cache: &artwork::ImageCache,
) {
use qbz_music_link::ResolvedLink;
match link {
ResolvedLink::OpenAlbum(id) => {
navigate_album(runtime.clone(), weak.clone(), handle, image_cache.clone(), id);
}
ResolvedLink::OpenArtist(id) => {
navigate_artist(
runtime.clone(),
weak.clone(),
handle,
image_cache.clone(),
id.to_string(),
);
}
ResolvedLink::OpenPlaylist(id) => {
navigate_playlist(
runtime.clone(),
weak.clone(),
handle,
image_cache.clone(),
id.to_string(),
);
}
ResolvedLink::OpenTrack(id) => {
let runtime = runtime.clone();
let weak = weak.clone();
let handle = handle.clone();
let image_cache = image_cache.clone();
handle.clone().spawn(async move {
match runtime.core().get_track(id).await {
Ok(track) => {
if let Some(album_id) = track.album.as_ref().map(|a| a.id.clone()) {
navigate_album(
runtime.clone(),
weak.clone(),
&handle,
image_cache.clone(),
album_id,
);
}
}
Err(e) => {
log::error!("[qbz-slint] open-link: get_track failed: {e}");
}
}
});
}
}
}
/// Capture browser mouse buttons before Slint routes them to the topmost
/// TouchArea, and mirror the cursor position into `ShellState` for passive
/// hover chrome that must not install a TouchArea over interactive content.
@@ -772,41 +834,74 @@ fn install_browser_mouse_nav(window: &AppWindow) {
// the FocusScope. Two surfaces share this hook: the IMMERSIVE dropdown
// takes priority when immersive is open + its search is open (it sits
// on top of everything), otherwise the MAIN header cortinilla.
// Track modifier state for the keybindings dispatcher (winit
// delivers modifiers separately from key presses).
WindowEvent::ModifiersChanged(modifiers) => {
let m = modifiers.state();
crate::keybindings::set_mods(
m.control_key() || m.super_key(),
m.alt_key(),
m.shift_key(),
);
EventResult::Propagate
}
WindowEvent::KeyboardInput { event: key_event, .. }
if key_event.state == ElementState::Pressed =>
{
let Some(window) = weak.upgrade() else {
return EventResult::Propagate;
};
// (A) Customize-shortcuts editor capture: while recording, the
// next combo is captured as a binding instead of dispatched.
let recording = window.global::<KeybindingsState>().get_recording_id();
if !recording.is_empty() {
return crate::keybindings::handle_capture(
&window,
recording.as_str(),
&key_event.logical_key,
);
}
// (B) Steal Up/Down ONLY while a search dropdown is open, BEFORE
// the search input's cursor can eat the first press (lets the
// very first ArrowDown move selection from the input INTO the
// dropdown). Immersive takes priority when its search is open.
let immersive_search_open = window.global::<ImmersiveState>().get_open()
&& window.global::<ImmersiveState>().get_search_open();
let main_cortinilla_open =
window.global::<SearchState>().get_cortinilla_open();
if !immersive_search_open && !main_cortinilla_open {
if immersive_search_open || main_cortinilla_open {
let move_selection = |delta: i32| {
if immersive_search_open {
window
.global::<ImmersiveSearchActions>()
.invoke_move_selection(delta);
} else {
window
.global::<SearchActions>()
.invoke_cortinilla_move_selection(delta);
}
};
return match &key_event.logical_key {
Key::Named(NamedKey::ArrowDown) => {
move_selection(1);
EventResult::PreventDefault
}
Key::Named(NamedKey::ArrowUp) => {
move_selection(-1);
EventResult::PreventDefault
}
_ => EventResult::Propagate,
};
}
// (C) Global hotkeys — never while typing in a text field
// (mirrors the Tauri `isInputTarget` guard).
if window.global::<UiFocusState>().get_text_input_focused() {
return EventResult::Propagate;
}
let move_selection = |delta: i32| {
if immersive_search_open {
window
.global::<ImmersiveSearchActions>()
.invoke_move_selection(delta);
} else {
window
.global::<SearchActions>()
.invoke_cortinilla_move_selection(delta);
}
};
match &key_event.logical_key {
Key::Named(NamedKey::ArrowDown) => {
move_selection(1);
EventResult::PreventDefault
}
Key::Named(NamedKey::ArrowUp) => {
move_selection(-1);
EventResult::PreventDefault
}
_ => EventResult::Propagate,
}
crate::keybindings::dispatch(&window, &key_event.logical_key)
}
// Persist main-window geometry so the next launch restores it
// (mirrors miniplayer.rs). The startup restore clamps to the
@@ -6969,6 +7064,97 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
});
}
// Keyboard shortcuts (hotkeys): seed the cheatsheet/editor model + wire the
// customize-editor capture callbacks. The global key dispatch itself lives
// in `install_browser_mouse_nav`'s winit handler.
keybindings::wire(&window);
// "Open Qobuz Link" (Ctrl+L) — the cross-platform link resolver modal.
{
let weak = window.as_weak();
window
.global::<LinkResolverActions>()
.on_url_changed(move |url| {
if let Some(w) = weak.upgrade() {
w.global::<LinkResolverState>()
.set_platform(link_resolver::detect_platform(&url).into());
}
});
}
{
let weak = window.as_weak();
window.global::<LinkResolverActions>().on_close(move || {
if let Some(w) = weak.upgrade() {
w.global::<LinkResolverState>().set_open(false);
}
});
}
{
let weak = window.as_weak();
window
.global::<LinkResolverActions>()
.on_open_importer(move || {
if let Some(w) = weak.upgrade() {
w.global::<LinkResolverState>().set_open(false);
w.global::<PlaylistImportState>().set_open(true);
}
});
}
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
let image_cache = image_cache.clone();
window.global::<LinkResolverActions>().on_submit(move |url| {
let url = url.trim().to_string();
if url.is_empty() {
return;
}
if let Some(w) = weak.upgrade() {
let s = w.global::<LinkResolverState>();
s.set_resolving(true);
s.set_error("".into());
s.set_playlist_detected(false);
}
let runtime = runtime.clone();
let weak = weak.clone();
let handle = handle.clone();
let image_cache = image_cache.clone();
handle.clone().spawn(async move {
let result = link_resolver::resolve(runtime.clone(), url).await;
let _ = weak.upgrade_in_event_loop(move |w| {
let s = w.global::<LinkResolverState>();
s.set_resolving(false);
match result {
Ok(qbz_music_link::MusicLinkResult::Resolved { link, .. }) => {
s.set_open(false);
apply_resolved_link(
link,
&runtime,
&w.as_weak(),
&handle,
&image_cache,
);
}
Ok(qbz_music_link::MusicLinkResult::PlaylistDetected { provider }) => {
s.set_playlist_detected(true);
s.set_playlist_provider(provider.into());
}
Ok(qbz_music_link::MusicLinkResult::NotOnQobuz { .. }) => {
s.set_error(
qbz_i18n::t("This content is not available on Qobuz").into(),
);
}
Err(e) => {
log::warn!("[qbz-slint] open-link resolve failed: {e}");
s.set_error(qbz_i18n::t("Could not resolve that link").into());
}
}
});
});
});
}
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
+25
View File
@@ -58,6 +58,12 @@ pub fn is_creating_mini() -> bool {
CREATING_MINI.with(|f| *f.borrow())
}
/// Whether the miniplayer window is currently shown (the main window hidden).
/// Read by the hotkey dispatcher to toggle the mini on Shift+M.
pub fn is_open() -> bool {
OPEN.load(std::sync::atomic::Ordering::SeqCst)
}
/// The lyrics sync engine (lyrics_sync.rs) only runs while the MAIN window's
/// lyrics panel is open. When the mini shows its lyrics surface, trigger the
/// fetch and open the (hidden) main panel so the karaoke advances; remember we
@@ -397,6 +403,25 @@ fn install_winit(mini: &MiniPlayerWindow) {
w.global::<MiniPlayerState>().set_window_hovered(false);
}
}
// Keyboard shortcuts on the mini window: surface keys (1-5),
// Shift+M / Escape to exit, shared transport. Respects the
// user's custom bindings (crate::keybindings).
WindowEvent::ModifiersChanged(modifiers) => {
let m = modifiers.state();
crate::keybindings::set_mods(
m.control_key() || m.super_key(),
m.alt_key(),
m.shift_key(),
);
}
WindowEvent::KeyboardInput { event: key_event, .. }
if key_event.state
== i_slint_backend_winit::winit::event::ElementState::Pressed =>
{
if let Some(w) = weak.upgrade() {
return crate::keybindings::dispatch_mini(&w, &key_event.logical_key);
}
}
WindowEvent::Resized(size) => {
if let Some(w) = weak.upgrade() {
let surface = w.global::<MiniPlayerState>().get_surface();
+10
View File
@@ -9,6 +9,7 @@
//! The store is intentionally minimal — read-modify-write the whole file
//! on every set. The file is tiny and writes are rare (a settings change).
use std::collections::BTreeMap;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -323,6 +324,14 @@ pub struct UiPrefs {
#[serde(default = "default_theme")]
pub theme: String,
// ---- Keyboard shortcuts (hotkeys) ----------------------------------
/// User keybinding overrides: action id → shortcut string. Only actions
/// the user re-bound away from their default are stored (mirrors Tauri's
/// `qbz_keybindings` localStorage overrides). A missing entry means the
/// action uses its compiled default (see `crate::keybindings::ACTIONS`).
#[serde(default)]
pub keybindings: BTreeMap<String, String>,
// ---- Miniplayer ----------------------------------------------------
/// Last miniplayer surface: 0 micro · 1 compact · 2 artwork · 3 queue · 4 lyrics.
#[serde(default = "default_mini_surface")]
@@ -450,6 +459,7 @@ impl Default for UiPrefs {
immersive_last_mode: 0,
immersive_last_split_panel: 0,
theme: default_theme(),
keybindings: BTreeMap::new(),
mini_surface: default_mini_surface(),
mini_width: default_mini_width(),
mini_height: default_mini_height(),
@@ -9,7 +9,7 @@ import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { Spacing } from "../foundation/spacing.slint";
import { AlbumState, AlbumActions, ArtworkActions, NavState, ContentView, DragState, NowPlayingState, ShellState, TooltipState, AppearanceState } from "../state.slint";
import { AlbumState, AlbumActions, ArtworkActions, NavState, ContentView, DragState, NowPlayingState, ShellState, TooltipState, AppearanceState, UiFocusState } from "../state.slint";
import { TrackRow } from "../primitives/TrackRow.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { ContextMenu } from "../primitives/ContextMenu.slint";
@@ -644,6 +644,7 @@ export component AlbumPageView inherits Rectangle {
font-size: 13px;
vertical-alignment: center;
single-line: true;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
AlbumActions.search(self.text);
}
@@ -7,7 +7,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { LocalAlbumState, LocalAlbumActions, LocalAlbumVersion, NowPlayingState, NavState, DragState } from "../state.slint";
import { LocalAlbumState, LocalAlbumActions, LocalAlbumVersion, NowPlayingState, NavState, DragState, UiFocusState } from "../state.slint";
import { NavButtons } from "../shell/NavButtons.slint";
import { CircleAction } from "../primitives/CircleAction.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
@@ -410,6 +410,7 @@ export component LocalAlbumView inherits Rectangle {
font-size: 13px;
vertical-alignment: center;
single-line: true;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
LocalAlbumActions.search(self.text);
}
+1 -1
View File
@@ -26,7 +26,7 @@ export { Theme, ThemeColors } from "foundation/semantic-colors.slint";
export { ThemeState } from "foundation/theme-state.slint";
// Re-export the state globals so the Rust layer can populate them.
export { HomeState, HomeActions, DiscoverState, DiscoverActions, SectionDescriptor, ConfigRow, DiscoverBrowseState, DiscoverBrowseActions, ForYouState, MixState, GenreFilterState, GenreFilterActions, AlbumState, ArtistState, NavState, ShellState, SessionState, SettingsState, AlbumActions, ArtistActions, ArtworkActions, NowPlayingState, QueueState, LyricsState, LyricsLineItem, SearchState, SearchActions, NetworkSidebarState, NetworkSidebarActions, MusicianState, MusicianActions, LabelState, LabelActions, AwardState, AwardActions, AwardEntry, ArtistReleasesState, ArtistReleasesActions, LocationViewState, LocationViewActions, FavoritesState, FavoritesActions, PlaylistPickerState, PlaylistPickerActions, DuplicateConfirmState, DuplicateConfirmActions, PlaylistState, PlaylistActions, SidebarState, SidebarActions, SidebarFolderPopupState, CreatePlaylistState, CreatePlaylistActions, EditPlaylistState, EditPlaylistActions, CreateFolderState, CreateFolderActions, MyQbzCreateState, MyQbzCreateActions, DragState, DragActions, PlaylistManagerState, PlaylistManagerActions, OfflineManagerState, OfflineManagerActions, BlacklistState, BlacklistActions, BlacklistedArtistItem, MyQbzState, MyQbzActions, MixtapeCardItem, MyQbzAddState, MyQbzAddActions, MyQbzAddRow, MyQbzDetailState, MyQbzDetailActions, MixtapeDetailItem, MyQbzEditState, MyQbzEditActions, MyQbzMixState, MyQbzMixActions, DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, LocalLibraryState, LocalLibraryActions, LibraryFoldersState, LibFolderEditState, LibraryManageActions, LibraryScanState, LibAlbumFilterState, LocalAlbumState, LocalAlbumActions, TagEditorState, TagEditorActions, FolderEditState, FolderEditActions, ToastState, TextUtil, QconnectDevState, QconnectDevice, CastState, CastDevice, CastActions, AppearanceState, MyQbzBrandingState, EphemeralPlayChoiceState, EphemeralPlayChoiceActions, PlexSettingsState, PlexAuthActions, PlexSectionItem, ScrobbleState, ScrobbleActions, DiscordState, OfflineState, OfflineModeActions, OfflineFavoritesState, OfflineFavoritesActions, ImportLogEntry, PlaylistImportState, PlaylistImportActions, DacWizardState, DacWizardActions, DacCandidateRow, RemediationRow, DacConfigRow, InfoCreditRow, InfoCreditPair, AlbumCreditPerformer, AlbumCreditTrack, TrackInfoState, TrackInfoActions, AlbumInfoState, AlbumInfoActions, BookletState, BookletActions, SuggestionsState, SuggestionsActions, SuggestionCard, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions, PurchasesState, PurchasesActions, PurchaseAlbumItem, PurchaseTrackItem, PurchaseAlbumGroup, PurchaseTrackGroup, PurchaseFormatItem, PurchaseDetailState, PurchaseDetailActions, PurchaseDetailTrack } from "state.slint";
export { HomeState, HomeActions, DiscoverState, DiscoverActions, SectionDescriptor, ConfigRow, DiscoverBrowseState, DiscoverBrowseActions, ForYouState, MixState, GenreFilterState, GenreFilterActions, AlbumState, ArtistState, NavState, ShellState, SessionState, SettingsState, AlbumActions, ArtistActions, ArtworkActions, NowPlayingState, QueueState, LyricsState, LyricsLineItem, SearchState, SearchActions, NetworkSidebarState, NetworkSidebarActions, MusicianState, MusicianActions, LabelState, LabelActions, AwardState, AwardActions, AwardEntry, ArtistReleasesState, ArtistReleasesActions, LocationViewState, LocationViewActions, FavoritesState, FavoritesActions, PlaylistPickerState, PlaylistPickerActions, DuplicateConfirmState, DuplicateConfirmActions, PlaylistState, PlaylistActions, SidebarState, SidebarActions, SidebarFolderPopupState, CreatePlaylistState, CreatePlaylistActions, EditPlaylistState, EditPlaylistActions, CreateFolderState, CreateFolderActions, MyQbzCreateState, MyQbzCreateActions, DragState, DragActions, PlaylistManagerState, PlaylistManagerActions, OfflineManagerState, OfflineManagerActions, BlacklistState, BlacklistActions, BlacklistedArtistItem, MyQbzState, MyQbzActions, MixtapeCardItem, MyQbzAddState, MyQbzAddActions, MyQbzAddRow, MyQbzDetailState, MyQbzDetailActions, MixtapeDetailItem, MyQbzEditState, MyQbzEditActions, MyQbzMixState, MyQbzMixActions, DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, LocalLibraryState, LocalLibraryActions, LibraryFoldersState, LibFolderEditState, LibraryManageActions, LibraryScanState, LibAlbumFilterState, LocalAlbumState, LocalAlbumActions, TagEditorState, TagEditorActions, FolderEditState, FolderEditActions, ToastState, TextUtil, QconnectDevState, QconnectDevice, CastState, CastDevice, CastActions, AppearanceState, MyQbzBrandingState, EphemeralPlayChoiceState, EphemeralPlayChoiceActions, PlexSettingsState, PlexAuthActions, PlexSectionItem, ScrobbleState, ScrobbleActions, DiscordState, OfflineState, OfflineModeActions, OfflineFavoritesState, OfflineFavoritesActions, ImportLogEntry, PlaylistImportState, PlaylistImportActions, DacWizardState, DacWizardActions, DacCandidateRow, RemediationRow, DacConfigRow, InfoCreditRow, InfoCreditPair, AlbumCreditPerformer, AlbumCreditTrack, TrackInfoState, TrackInfoActions, AlbumInfoState, AlbumInfoActions, BookletState, BookletActions, SuggestionsState, SuggestionsActions, SuggestionCard, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions, PurchasesState, PurchasesActions, PurchaseAlbumItem, PurchaseTrackItem, PurchaseAlbumGroup, PurchaseTrackGroup, PurchaseFormatItem, PurchaseDetailState, PurchaseDetailActions, PurchaseDetailTrack, KeybindingRow, KeybindingCategoryGroup, KeybindingsState, KeybindingsActions, KeyboardShortcutsState, LinkResolverState, LinkResolverActions, UiFocusState } from "state.slint";
// Which top-level screen is shown. The app starts on `splash` while it
// restores a saved session, then resolves to `shell` or `login`.
@@ -22,7 +22,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { AwardState, AwardActions, NavState, ShellState } from "../state.slint";
import { AwardState, AwardActions, NavState, ShellState, UiFocusState } from "../state.slint";
import { AlbumCollectionView } from "../discover/AlbumCollectionView.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
import { ListScrollbar } from "../primitives/ListScrollbar.slint";
@@ -63,6 +63,7 @@ component AwardSearch inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> AwardState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
AwardActions.search(self.text);
}
@@ -10,7 +10,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { DiscoverBrowseState, DiscoverBrowseActions, GenreFilterState, GenreFilterActions, NavState, ShellState } from "../state.slint";
import { DiscoverBrowseState, DiscoverBrowseActions, GenreFilterState, GenreFilterActions, NavState, ShellState, UiFocusState } from "../state.slint";
import { AlbumCollectionView } from "AlbumCollectionView.slint";
import { GenreFilterPopup } from "GenreFilterPopup.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
@@ -53,6 +53,7 @@ component BrowseSearch inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> DiscoverBrowseState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
DiscoverBrowseActions.search-changed();
}
@@ -7,7 +7,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { GenreFilterState, GenreFilterActions, GenreChip, GenreTreeRow } from "../state.slint";
import { GenreFilterState, GenreFilterActions, GenreChip, GenreTreeRow, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { QbzToggle } from "../primitives/QbzToggle.slint";
@@ -297,6 +297,7 @@ export component GenreFilterPopup inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> GenreFilterState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
GenreFilterActions.search(self.text);
}
+14
View File
@@ -0,0 +1,14 @@
// Standalone leaf global for the hotkey text-input guard.
//
// Kept OUT of `state.slint` on purpose: `state.slint` imports structs from a
// few low-level primitives (e.g. `JumpNavTab` from `primitives/JumpNavBar.slint`),
// so those primitives CANNOT import `state.slint` back — that is a recursive
// import. This leaf has zero imports, so any file can import `UiFocusState`
// from here without a cycle. `state.slint` re-exports it for everyone else.
// Every free-text TextInput sets this on `changed has-focus`, so the global
// hotkey dispatcher ignores single-key shortcuts (Space, q, ?, 1-5, …) while
// the user is typing (mirrors the Tauri `isInputTarget` check).
export global UiFocusState {
in-out property <bool> text-input-focused: false;
}
@@ -5,7 +5,7 @@
import { Radius } from "../foundation/radius.slint";
import { Typography } from "../foundation/typography.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { NowPlayingState, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, SettingsState, LyricsState, QueueState, TrackInfoActions, SuggestionsActions, WindowControlActions, ShellState } from "../state.slint";
import { NowPlayingState, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, SettingsState, LyricsState, QueueState, TrackInfoActions, SuggestionsActions, WindowControlActions, ShellState, UiFocusState } from "../state.slint";
import { ImmersiveSearchCortinilla } from "ImmersiveSearchCortinilla.slint";
import { ImmersiveAtmosphere } from "ImmersiveAtmosphere.slint";
import { AlbumReactivePanel } from "AlbumReactivePanel.slint";
@@ -839,6 +839,7 @@ component ImmersiveSearchPlaceholder inherits Rectangle {
// route focus back to the scope; `forward-focus: input` immediately
// hands the cursor back here, so typing is unaffected.
changed has-focus => {
UiFocusState.text-input-focused = self.has-focus;
if (self.has-focus) {
search-scope.focus();
if (self.text != "") {
@@ -31,6 +31,7 @@ import { TrackRow } from "../primitives/TrackRow.slint";
import { ToggleButton } from "../primitives/ToggleButton.slint";
import { MultiSelectBar } from "../primitives/MultiSelectBar.slint";
import { TooltipState } from "../state.slint";
import { UiFocusState } from "../state.slint";
import { SegmentedTabBar, SegTab } from "../primitives/SegmentedTabBar.slint";
import { ListView } from "std-widgets.slint";
@@ -1616,6 +1617,7 @@ export component LocalLibraryView inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> LocalLibraryState.folders-tree-search;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
LocalLibraryActions.folders-tree-search(self.text);
}
@@ -1866,6 +1868,7 @@ export component LocalLibraryView inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> LocalLibraryState.folder-detail-search;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
LocalLibraryActions.folder-detail-search(self.text);
}
@@ -18,7 +18,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { MyQbzAddState, MyQbzAddActions, MyQbzAddRow } from "../state.slint";
import { MyQbzAddState, MyQbzAddActions, MyQbzAddRow, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
import { QbzPrimaryButton } from "../primitives/QbzPrimaryButton.slint";
@@ -331,6 +331,7 @@ export component AddToMixtapeModal inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> MyQbzAddState.search;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
MyQbzAddActions.search-changed(self.text);
}
@@ -467,6 +468,7 @@ export component AddToMixtapeModal inherits Rectangle {
single-line: true;
enabled: !MyQbzAddState.create-busy;
text <=> MyQbzAddState.create-name;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
accepted => {
if (root.can-create) {
MyQbzAddActions.create-and-add();
@@ -14,7 +14,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate } from "../state.slint";
import { DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { QualityBadgeFull } from "../primitives/QualityBadgeFull.slint";
import { QbzPrimaryButton } from "../primitives/QbzPrimaryButton.slint";
@@ -513,6 +513,7 @@ export component DiscographyBuilderView inherits Rectangle {
vertical-alignment: center;
single-line: true;
text: DiscoBuilderState.collection-name;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
DiscoBuilderActions.name-changed(self.text);
}
@@ -13,7 +13,7 @@ import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { OfflineManagerState, OfflineManagerActions, OfflineRow, OfflineArtist } from "../state.slint";
import { NavState, TooltipState } from "../state.slint";
import { NavState, TooltipState, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { QbzSelect } from "../primitives/QbzSelect.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
@@ -241,6 +241,7 @@ export component OfflineManagerView inherits Rectangle {
font-size: Typography.body;
input-type: number;
text: OfflineManagerState.limit-gb;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
accepted => {
OfflineManagerActions.set-limit(self.text.to-float());
}
@@ -19,6 +19,7 @@ import {
PmPlaylistItem,
PmTreeRow,
NavState,
UiFocusState,
} from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
@@ -63,6 +64,7 @@ component PmSearch inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> PlaylistManagerState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
PlaylistManagerActions.search-changed(self.text);
}
@@ -11,7 +11,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { DacWizardState, DacWizardActions, NowPlayingState } from "../state.slint";
import { DacWizardState, DacWizardActions, NowPlayingState, UiFocusState } from "../state.slint";
import { QbzIcon } from "QbzIcon.slint";
import { QbzPrimaryButton } from "QbzPrimaryButton.slint";
import { SecondaryButton } from "SecondaryButton.slint";
@@ -442,6 +442,7 @@ export component DacWizardModal inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> DacWizardState.manual-node-name;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
DacWizardActions.validate-manual(self.text);
}
@@ -9,6 +9,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { QbzIcon } from "QbzIcon.slint";
import { UiFocusState } from "../focus-state.slint";
export component ExpandableSearch inherits Rectangle {
in property <string> placeholder: @tr("Search…");
@@ -112,6 +113,7 @@ export component ExpandableSearch inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> root.query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
root.edited(self.text);
}
@@ -17,6 +17,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { QbzIcon } from "QbzIcon.slint";
import { UiFocusState } from "../focus-state.slint";
export struct JumpNavTab {
id: string,
@@ -191,6 +192,7 @@ export component JumpNavBar inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> root.search-text;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
root.search-text-edited(self.text);
}
@@ -23,7 +23,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { PlaylistImportState, PlaylistImportActions, OfflineState } from "../state.slint";
import { PlaylistImportState, PlaylistImportActions, OfflineState, UiFocusState } from "../state.slint";
import { QbzIcon } from "QbzIcon.slint";
import { QbzSelect } from "QbzSelect.slint";
import { LoadingSpinner } from "LoadingSpinner.slint";
@@ -208,6 +208,7 @@ export component PlaylistImportModal inherits Rectangle {
single-line: true;
enabled: !PlaylistImportState.loading;
text <=> PlaylistImportState.url;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
PlaylistImportActions.url-edited(self.text);
}
@@ -329,6 +330,7 @@ export component PlaylistImportModal inherits Rectangle {
enabled: !PlaylistImportState.loading
&& !PlaylistImportState.import-completed;
text <=> PlaylistImportState.custom-name;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
PlaylistImportActions.name-edited(self.text);
}
@@ -14,7 +14,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { PlaylistPickerState, PlaylistPickerActions, PlaylistPickItem } from "../state.slint";
import { PlaylistPickerState, PlaylistPickerActions, PlaylistPickItem, UiFocusState } from "../state.slint";
import { QbzIcon } from "QbzIcon.slint";
import { LoadingSpinner } from "LoadingSpinner.slint";
import { QbzPrimaryButton } from "QbzPrimaryButton.slint";
@@ -333,6 +333,7 @@ export component PlaylistPickerModal inherits Rectangle {
keys.on-enter();
}
changed has-focus => {
UiFocusState.text-input-focused = self.has-focus;
// Tauri: list opens on focus.
if (self.has-focus) {
keys.dropdown-open = true;
@@ -423,6 +424,7 @@ export component PlaylistPickerModal inherits Rectangle {
single-line: true;
enabled: !PlaylistPickerState.creating;
text <=> PlaylistPickerState.create-name;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
accepted => {
if (PlaylistPickerState.create-name != ""
&& !PlaylistPickerState.creating) {
@@ -21,7 +21,7 @@ import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { QbzIcon } from "QbzIcon.slint";
import { TextUtil } from "../state.slint";
import { TextUtil, UiFocusState } from "../state.slint";
// "BP" marker for bit-perfect-capable options. Plain accent text, no
// background — the QBZ UI never uses pill-style chips.
@@ -235,6 +235,7 @@ export component QbzSelect inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> root.filter;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
}
Text {
visible: search-input.text == "";
@@ -29,6 +29,7 @@ import {
PurchaseAlbumGroup,
PurchaseTrackGroup,
PurchaseFormatItem,
UiFocusState,
} from "../state.slint";
// ── A toolbar dropdown button (group / sort) — the favorites toolbar look ──
@@ -730,6 +731,7 @@ component SearchBox inherits Rectangle {
vertical-alignment: center;
single-line: true;
text <=> PurchasesState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
PurchasesActions.search(self.text);
}
@@ -21,7 +21,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { BlacklistState, BlacklistActions } from "../state.slint";
import { BlacklistState, BlacklistActions, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { ListScrollbar } from "../primitives/ListScrollbar.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
@@ -260,6 +260,7 @@ export component BlacklistManagerView inherits Rectangle {
color: Theme.text-primary;
font-size: Typography.legal;
text: BlacklistState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
// Search-as-you-type: every edit re-pushes the
// controller-filtered rows. No debounce (Tauri parity).
edited => {
+20
View File
@@ -40,6 +40,9 @@ import { ImmersiveView } from "../immersive/ImmersiveView.slint";
import { QconnectDevModal } from "QconnectDevModal.slint";
import { CastPicker } from "CastPicker.slint";
import { DiscoverConfigModal } from "../discover/DiscoverConfigModal.slint";
import { KeyboardShortcutsModal } from "KeyboardShortcutsModal.slint";
import { CustomizeShortcutsModal } from "CustomizeShortcutsModal.slint";
import { LinkResolverModal } from "LinkResolverModal.slint";
import { DragGhost } from "../primitives/DragGhost.slint";
import { Toast } from "../primitives/Toast.slint";
import { NowPlayingBar } from "NowPlayingBar.slint";
@@ -678,6 +681,23 @@ export component AppShell inherits Rectangle {
height: 100%;
}
// Keyboard shortcuts: read-only cheatsheet (`?`) + editable customize
// editor. Self-gate on KeyboardShortcutsState.open / .customize-open.
KeyboardShortcutsModal {
width: 100%;
height: 100%;
}
CustomizeShortcutsModal {
width: 100%;
height: 100%;
}
// "Open Qobuz Link" (Ctrl+L) cross-platform link resolver.
LinkResolverModal {
width: 100%;
height: 100%;
}
// Floating track-drag ghost (follows the cursor, on top of all).
DragGhost { }
@@ -0,0 +1,345 @@
// "Customize Shortcuts" — the EDITABLE keybindings editor. 1:1 port of the
// Tauri `KeybindingsSettings.svelte` + `ShortcutInput.svelte`.
//
// Groups actions by category; each row shows its label and a clickable keycap
// button. Clicking the keycap enters RECORDING mode ("Press keys…"): the
// actual key capture happens in RUST (the winit handler reads
// KeybindingsState.recording-id and writes pending-display / conflict-label);
// this modal ONLY flips state via start-record / cancel-record and DISPLAYS
// the live combo + any conflict. A per-row reset appears when the binding is
// modified, a header badge counts modifications, and a footer "Reset All to
// Defaults" button reverts everything.
//
// Self-gated mount (ADR-010): AppShell mounts this with width/height 100%; the
// root fills the window and centers its panel over a dimming scrim. Opened via
// KeyboardShortcutsState.customize-open.
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { Spacing } from "../foundation/spacing.slint";
import {
KeyboardShortcutsState,
KeybindingsState,
KeybindingsActions,
} from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
export component CustomizeShortcutsModal inherits Rectangle {
visible: KeyboardShortcutsState.customize-open;
if KeyboardShortcutsState.customize-open: Rectangle {
background: #000000bf;
// Scrim: a click outside the panel closes the editor (and cancels any
// in-progress recording so we never leave a dangling capture).
TouchArea {
mouse-cursor: default;
clicked => {
KeybindingsState.recording-id = "";
KeybindingsActions.cancel-record();
KeyboardShortcutsState.customize-open = false;
}
}
// The panel is a FocusScope so Escape cancels recording if recording,
// else closes the modal (mirrors the Svelte handler).
keys := FocusScope {
width: Math.min(root.width - 80px, 720px);
height: Math.min(Math.max(420px, panel.preferred-height), root.height - 80px);
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
key-pressed(event) => {
if (event.text == Key.Escape) {
if (KeybindingsState.recording-id != "") {
KeybindingsActions.cancel-record();
} else {
KeyboardShortcutsState.customize-open = false;
}
return accept;
}
return reject;
}
// Deferred mount focus so Escape works immediately (synchronous
// focus during the remount races layout — same idiom as the
// PlaylistPickerModal).
focus-timer := Timer {
interval: 30ms;
running: true;
triggered => {
self.running = false;
keys.focus();
}
}
card := Rectangle {
border-radius: Radius.md;
background: Theme.surface-card;
border-width: 1px;
border-color: Theme.border-subtle;
drop-shadow-blur: 32px;
drop-shadow-color: #00000080;
// Swallow clicks so they don't reach the scrim.
TouchArea { }
panel := VerticalLayout {
padding: 0px;
spacing: 0px;
// ---- Header: title + "N modified" badge + close-x -------
HorizontalLayout {
padding-left: Spacing.lg;
padding-right: Spacing.lg;
padding-top: Spacing.md;
padding-bottom: Spacing.md;
spacing: 10px;
Text {
text: @tr("Customize Shortcuts");
color: Theme.text-primary;
font-size: Typography.section;
font-weight: Typography.semibold;
vertical-alignment: center;
}
if KeybindingsState.modified-count > 0: Rectangle {
width: badge-label.preferred-width + 16px;
height: 20px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
border-radius: Radius.sm;
background: Theme.accent;
badge-label := Text {
text: KeybindingsState.modified-count + " " + @tr("modified");
color: Theme.accent-text;
font-size: Typography.legal;
font-weight: Typography.medium;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
}
// Spacer pushes the close-x to the right edge.
Rectangle { horizontal-stretch: 1; }
close-x := TouchArea {
width: 28px;
height: 28px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
mouse-cursor: pointer;
clicked => {
KeybindingsState.recording-id = "";
KeybindingsActions.cancel-record();
KeyboardShortcutsState.customize-open = false;
}
QbzIcon {
source: @image-url("../assets/icons/x.svg");
width: 17px;
height: 17px;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
tint: close-x.has-hover ? Theme.text-primary : Theme.text-muted;
}
}
}
// Divider under the header.
Rectangle {
height: 1px;
background: Theme.border-subtle;
}
// ---- Scrollable body ------------------------------------
Flickable {
vertical-stretch: 1;
viewport-width: self.width;
viewport-height: groups-col.preferred-height;
groups-col := VerticalLayout {
padding-left: Spacing.lg;
padding-right: Spacing.lg;
padding-top: Spacing.md;
padding-bottom: Spacing.md;
spacing: Spacing.lg;
for group in KeybindingsState.groups: VerticalLayout {
spacing: Spacing.sm;
// Category header.
Text {
text: group.label;
color: Theme.text-muted;
font-size: Typography.legal;
font-weight: Typography.semibold;
}
for entry in group.rows: HorizontalLayout {
spacing: 10px;
min-height: 36px;
// LEFT: action label.
Text {
text: entry.label;
color: Theme.text-primary;
font-size: Typography.body;
vertical-alignment: center;
horizontal-stretch: 1;
}
// RIGHT: keycap capture button + reset.
// A small column so the conflict message
// can sit BELOW the keycap while recording.
VerticalLayout {
spacing: 4px;
alignment: center;
HorizontalLayout {
spacing: 8px;
alignment: end;
// Keycap button — Radius.sm rounded
// rect with a border (NOT a pill,
// ADR-008). Accent border while
// recording; danger border on
// conflict.
capture := Rectangle {
property <bool> recording: KeybindingsState.recording-id == entry.id;
property <bool> conflicting: self.recording && KeybindingsState.conflict-label != "";
width: Math.max(120px, cap-label.preferred-width + 24px);
height: 32px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
border-radius: Radius.sm;
background: capture.recording
? Theme.bg-hover
: (cap-ta.has-hover ? Theme.surface-hover : Theme.surface-elevated);
border-width: (capture.recording || entry.modified) ? 2px : 1px;
border-color: capture.conflicting
? Theme.danger
: (capture.recording
? Theme.accent
: (entry.modified ? Theme.accent : Theme.border-subtle));
cap-label := Text {
text: capture.recording
? (KeybindingsState.pending-display != ""
? KeybindingsState.pending-display
: @tr("Press keys…"))
: entry.shortcut;
color: Theme.text-primary;
font-size: Typography.legal;
font-weight: Typography.medium;
font-family: "monospace";
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
cap-ta := TouchArea {
mouse-cursor: pointer;
clicked => {
KeybindingsActions.start-record(entry.id);
}
}
}
// Per-row reset — only when modified.
if entry.modified: reset-row := Rectangle {
width: 30px;
height: 30px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
border-radius: Radius.sm;
background: reset-ta.has-hover ? Theme.surface-hover : Theme.surface-elevated;
border-width: 1px;
border-color: Theme.border-subtle;
QbzIcon {
source: @image-url("../assets/icons/rotate-ccw.svg");
width: 14px;
height: 14px;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
tint: reset-ta.has-hover ? Theme.text-primary : Theme.text-muted;
}
reset-ta := TouchArea {
mouse-cursor: pointer;
clicked => {
KeybindingsActions.reset-one(entry.id);
}
}
}
}
// Conflict message BELOW the keycap —
// recording stays active so the user can
// pick another combo.
if KeybindingsState.recording-id == entry.id
&& KeybindingsState.conflict-label != "": Text {
text: @tr("Already used by") + " " + KeybindingsState.conflict-label;
color: Theme.danger;
font-size: Typography.legal;
horizontal-alignment: right;
}
}
}
}
}
}
// Divider above the footer.
Rectangle {
height: 1px;
background: Theme.border-subtle;
}
// ---- Footer: "Reset All to Defaults" --------------------
HorizontalLayout {
padding-left: Spacing.lg;
padding-right: Spacing.lg;
padding-top: Spacing.md;
padding-bottom: Spacing.md;
alignment: center;
reset-all := Rectangle {
property <bool> active: KeybindingsState.modified-count > 0;
height: 38px;
horizontal-stretch: 0;
border-radius: Radius.sm;
opacity: reset-all.active ? 1.0 : 0.3;
background: (reset-all.active && reset-all-ta.has-hover) ? Theme.danger-bg : transparent;
border-width: 1px;
border-color: Theme.danger;
reset-all-row := HorizontalLayout {
alignment: center;
spacing: 8px;
padding-left: 16px;
padding-right: 16px;
QbzIcon {
source: @image-url("../assets/icons/rotate-ccw.svg");
width: 14px;
height: 14px;
tint: Theme.danger;
}
Text {
text: @tr("Reset All to Defaults");
color: Theme.danger;
font-size: Typography.body;
vertical-alignment: center;
}
}
reset-all-ta := TouchArea {
mouse-cursor: reset-all.active ? pointer : default;
clicked => {
if (reset-all.active) {
KeybindingsActions.reset-all();
}
}
}
}
}
}
}
}
}
}
+21 -1
View File
@@ -14,7 +14,7 @@ import { Spacing } from "../foundation/spacing.slint";
import { Typography } from "../foundation/typography.slint";
import { Layout } from "../foundation/layout.slint";
import { Radius } from "../foundation/radius.slint";
import { SessionState, NavState, ContentView, ShellState, HeaderMenuState, NavMenuEntry, SearchActions, SearchState, SidebarPlaylistsPopupState, OfflineState, SettingsState, OfflineModeActions, AppearanceState } from "../state.slint";
import { SessionState, NavState, ContentView, ShellState, HeaderMenuState, NavMenuEntry, SearchActions, SearchState, SidebarPlaylistsPopupState, OfflineState, SettingsState, OfflineModeActions, AppearanceState, KeyboardShortcutsState, LinkResolverState, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { SecondaryButton } from "../primitives/SecondaryButton.slint";
import { QbzToggle } from "../primitives/QbzToggle.slint";
@@ -677,6 +677,9 @@ export component HeaderBar inherits Rectangle {
// focus-out (e.g. Tab away) is dismissed via Escape /
// click-outside, matching the menu overlays.
changed has-focus => {
// Hotkey guard: while the search field has focus, the global
// key dispatcher must ignore single-key shortcuts.
UiFocusState.text-input-focused = self.has-focus;
if (self.has-focus) {
// A direct click focuses the TextInput, NOT the wrapping
// FocusScope — and then the scope's key-pressed (the
@@ -1032,9 +1035,26 @@ export component HeaderBar inherits Rectangle {
NavState.request-settings();
}
}
MenuItem {
icon: @image-url("../assets/icons/link.svg");
label: @tr("Open Qobuz Link");
clicked => {
menu.close();
LinkResolverState.url = "";
LinkResolverState.platform = "";
LinkResolverState.error = "";
LinkResolverState.playlist-detected = false;
LinkResolverState.resolving = false;
LinkResolverState.open = true;
}
}
MenuItem {
icon: @image-url("../assets/icons/keyboard.svg");
label: @tr("Keyboard Shortcuts");
clicked => {
menu.close();
KeyboardShortcutsState.open = true;
}
}
MenuItem {
icon: @image-url("../assets/icons/book-open.svg");
@@ -0,0 +1,240 @@
// Keyboard-shortcuts cheatsheet — read-only 1:1 port of the Tauri
// `KeyboardShortcutsModal.svelte`. Lists every keybinding grouped by
// category (Playback / Navigation / Interface / ...), each row showing the
// localized action label (left) and its formatted shortcut keycap (right).
// A footer "Customize Shortcuts" button hands off to the editable editor.
//
// Self-gated mount in AppShell (ADR-010): `if KeyboardShortcutsState.open`.
// Opened with the `?` hotkey. Escape / scrim-click / X all close it.
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { KeyboardShortcutsState, KeybindingsState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
export component KeyboardShortcutsModal inherits Rectangle {
visible: KeyboardShortcutsState.open;
if KeyboardShortcutsState.open: Rectangle {
background: #000000bf;
// Scrim — click outside the panel closes.
TouchArea {
mouse-cursor: default;
clicked => {
KeyboardShortcutsState.open = false;
}
}
// Card-sized FocusScope so Escape closes (grabs focus on mount).
keys := FocusScope {
// Natural height = header + scrollable body content + footer, but
// the Flickable reports only its own (small) preferred height, so
// we add the body's real content height back and cap at ~80vh. The
// Flickable then stretches to whatever room is left and scrolls.
property <length> chrome-height: header-row.preferred-height
+ footer-row.preferred-height + 2px;
property <length> content-height: chrome-height + body.preferred-height + 40px;
width: Math.min(root.width - 80px, 660px);
height: Math.min(self.content-height, root.height - 80px);
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
key-pressed(event) => {
if (event.text == Key.Escape) {
KeyboardShortcutsState.open = false;
return accept;
}
return reject;
}
// Deferred mount focus — synchronous focus during the remount
// races layout; a one-shot timer grabs it a tick later.
focus-timer := Timer {
interval: 30ms;
running: true;
triggered => {
self.running = false;
keys.focus();
}
}
card := Rectangle {
border-radius: Radius.md;
background: Theme.surface-card;
border-width: 1px;
border-color: Theme.border-subtle;
drop-shadow-blur: 32px;
drop-shadow-color: #00000080;
// Swallow clicks so they don't reach the scrim.
TouchArea { }
panel := VerticalLayout {
spacing: 0px;
// --- Header: title + X close --------------------------
header-row := HorizontalLayout {
padding: 20px;
spacing: 10px;
// Fixed-size icon vertically centered in the header row
// via a 1-stretch-free wrapper (Image has no layout
// vertical-alignment property).
Rectangle {
width: 20px;
title-icon := QbzIcon {
source: @image-url("../assets/icons/keyboard.svg");
width: 20px;
height: 20px;
tint: Theme.text-primary;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
}
Text {
text: @tr("Keyboard Shortcuts");
color: Theme.text-primary;
font-size: Typography.heading;
font-weight: Typography.semibold;
horizontal-stretch: 1;
vertical-alignment: center;
}
close-x := TouchArea {
width: 28px;
height: 28px;
mouse-cursor: pointer;
clicked => {
KeyboardShortcutsState.open = false;
}
QbzIcon {
source: @image-url("../assets/icons/x.svg");
width: 17px;
height: 17px;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
tint: close-x.has-hover ? Theme.text-primary : Theme.text-muted;
}
}
}
// Header divider.
Rectangle {
height: 1px;
background: Theme.border-subtle;
}
// --- Body: scrollable grouped list --------------------
Flickable {
vertical-stretch: 1;
viewport-width: self.width;
viewport-height: body.preferred-height;
body := VerticalLayout {
padding: 20px;
spacing: 24px;
for group in KeybindingsState.groups: VerticalLayout {
spacing: 12px;
// Uppercase category header + underline.
VerticalLayout {
spacing: 8px;
Text {
// Already localized in Rust; render as-is.
text: group.label;
color: Theme.text-muted;
font-size: Typography.legal;
font-weight: Typography.semibold;
}
Rectangle {
height: 1px;
background: Theme.border-subtle;
}
}
// One row per binding: label LEFT, keycap RIGHT.
for entry in group.rows: Rectangle {
height: entry-row.preferred-height + 16px;
border-radius: Radius.sm;
background: Theme.surface-elevated;
entry-row := HorizontalLayout {
padding-left: 12px;
padding-right: 12px;
padding-top: 8px;
padding-bottom: 8px;
spacing: 12px;
Text {
text: entry.label;
color: Theme.text-primary;
font-size: Typography.body;
horizontal-stretch: 1;
vertical-alignment: center;
}
// Keycap — a subtle key-like chip
// (Radius.sm, NOT a pill per ADR-008).
Rectangle {
width: keycap-label.preferred-width + 16px;
height: keycap-label.preferred-height + 8px;
border-radius: Radius.sm;
background: Theme.surface-card;
border-width: 1px;
border-color: Theme.border-muted;
keycap-label := Text {
text: entry.shortcut;
color: Theme.text-secondary;
font-size: Typography.legal;
font-family: "monospace";
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
}
}
}
}
}
}
// Footer divider.
Rectangle {
height: 1px;
background: Theme.border-subtle;
}
// --- Footer: Customize Shortcuts ----------------------
footer-row := HorizontalLayout {
padding: 16px;
alignment: center;
customize-btn := Rectangle {
width: customize-label.preferred-width + 40px;
height: 40px;
border-radius: Radius.sm;
background: customize-ta.has-hover ? Theme.surface-hover : Theme.surface-elevated;
border-width: 1px;
border-color: customize-ta.has-hover ? Theme.accent : Theme.border-subtle;
customize-label := Text {
text: @tr("Customize Shortcuts");
color: customize-ta.has-hover ? Theme.text-primary : Theme.text-secondary;
font-size: Typography.body;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
customize-ta := TouchArea {
mouse-cursor: pointer;
clicked => {
KeyboardShortcutsState.open = false;
KeyboardShortcutsState.customize-open = true;
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,287 @@
// "Open Qobuz Link" modal — 1:1 with Tauri's LinkResolverModal.svelte.
//
// Triggered by Ctrl+L (gate: LinkResolverState.open). Paste a Qobuz /
// Spotify / Apple Music / Tidal / Deezer / song.link URL, hit Go, and the
// controller resolves it to an album/track/artist/playlist and navigates.
// A playlist link surfaces a banner that hands off to the Playlist Importer.
//
// Layout (mirrors the Svelte source):
// [ platform icon 36x36 ][ url input (stretch) ][ Go button ]
// error text line (red, when error != "")
// playlist banner (when playlist-detected): text + "Open Playlist Importer"
//
// The url field sets UiFocusState.text-input-focused on `changed has-focus`
// so single-key global hotkeys don't fire while the user types a URL.
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { Spacing } from "../foundation/spacing.slint";
import { LinkResolverState, LinkResolverActions, UiFocusState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
export component LinkResolverModal inherits Rectangle {
width: 100%;
height: 100%;
visible: LinkResolverState.open;
if LinkResolverState.open: Rectangle {
// Scrim — click-outside closes.
background: #000000bf;
TouchArea {
mouse-cursor: default;
clicked => {
LinkResolverActions.close();
}
}
// Card-sized FocusScope so Escape closes and the input can grab
// focus on (deferred) mount. Locals live on the `if open:` subtree
// so each remount resets cleanly.
keys := FocusScope {
width: Math.min(root.width - 80px, 520px);
height: panel.preferred-height;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
forward-focus: url-input;
key-pressed(event) => {
if (event.text == Key.Escape) {
LinkResolverActions.close();
return accept;
}
return reject;
}
// Deferred mount focus — synchronous focus during the remount
// races layout; a one-shot timer grabs it a tick later.
focus-timer := Timer {
interval: 30ms;
running: true;
triggered => {
self.running = false;
keys.focus();
}
}
Rectangle {
border-radius: Radius.md;
background: Theme.surface-card;
border-width: 1px;
border-color: Theme.border-subtle;
drop-shadow-blur: 32px;
drop-shadow-color: #00000080;
// Block scrim click-through.
TouchArea { }
panel := VerticalLayout {
padding: Spacing.lg;
spacing: Spacing.md;
// Header: title + close X.
HorizontalLayout {
Text {
text: @tr("Open Qobuz Link");
color: Theme.text-primary;
font-size: Typography.heading;
font-weight: Typography.semibold;
horizontal-stretch: 1;
vertical-alignment: center;
}
close-x := TouchArea {
width: 28px;
height: 28px;
mouse-cursor: pointer;
clicked => {
LinkResolverActions.close();
}
QbzIcon {
source: @image-url("../assets/icons/x.svg");
width: 17px;
height: 17px;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
tint: close-x.has-hover ? Theme.text-primary : Theme.text-muted;
}
}
}
// Input row: [platform icon][url input][Go].
HorizontalLayout {
spacing: Spacing.sm;
// Leading platform glyph — 36x36 slot, 24x24 logo.
// The image is picked from LinkResolverState.platform,
// which Rust sets on url-changed. song.link and the
// empty/unknown case fall back to the generic link
// icon (Tauri shows a Link2 lucide glyph for songlink
// and nothing for unknown; a quiet link icon reads the
// same and keeps the row width stable).
Rectangle {
width: 36px;
height: 36px;
QbzIcon {
width: 24px;
height: 24px;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
// Tint only the generic fallback link icon; the
// brand logos are full-color SVGs and must NOT
// be recolored.
tint: (LinkResolverState.platform == "qobuz"
|| LinkResolverState.platform == "spotify"
|| LinkResolverState.platform == "apple"
|| LinkResolverState.platform == "tidal"
|| LinkResolverState.platform == "deezer")
? transparent : Theme.text-muted;
source:
LinkResolverState.platform == "qobuz"
? @image-url("../assets/icons/qobuz-logo.svg")
: LinkResolverState.platform == "spotify"
? @image-url("../assets/icons/spotify-logo.svg")
: LinkResolverState.platform == "apple"
? @image-url("../assets/icons/apple-music-logo.svg")
: LinkResolverState.platform == "tidal"
? @image-url("../assets/icons/tidal-tidal.svg")
: LinkResolverState.platform == "deezer"
? @image-url("../assets/icons/deezer-logo.svg")
: @image-url("../assets/icons/link.svg");
}
}
// URL input — custom box (not LineEdit) so we own the
// focus guard + placeholder + disabled styling.
input-box := Rectangle {
horizontal-stretch: 1;
height: 40px;
border-radius: Radius.sm;
background: Theme.surface-elevated;
border-width: 1px;
border-color: url-input.has-focus ? Theme.accent : Theme.border-subtle;
opacity: LinkResolverState.resolving ? 0.6 : 1.0;
HorizontalLayout {
padding-left: 14px;
padding-right: 14px;
Rectangle {
horizontal-stretch: 1;
clip: true;
url-input := TextInput {
width: 100%;
height: 100%;
color: Theme.text-primary;
font-size: Typography.link;
vertical-alignment: center;
single-line: true;
enabled: !LinkResolverState.resolving;
// Two-way bound; `edited` additionally
// fires live platform detection.
text <=> LinkResolverState.url;
edited => {
LinkResolverActions.url-changed(self.text);
}
accepted => {
LinkResolverActions.submit(LinkResolverState.url);
}
// REQUIRED: gate single-key hotkeys
// while typing a URL.
changed has-focus => {
UiFocusState.text-input-focused = self.has-focus;
}
}
// Placeholder — TextInput has no native
// placeholder; a sibling Text gated on empty.
Text {
visible: url-input.text == "";
width: 100%;
height: 100%;
text: @tr("Paste a Qobuz, Spotify, Apple Music, Tidal, Deezer or song.link URL");
color: Theme.text-muted;
font-size: Typography.link;
vertical-alignment: center;
overflow: elide;
}
}
}
}
// Go button — disabled while resolving or url empty.
Rectangle {
property <bool> can-go: LinkResolverState.url != "" && !LinkResolverState.resolving;
width: go-label.preferred-width + 40px;
height: 40px;
border-radius: Radius.sm;
opacity: self.can-go ? 1.0 : 0.5;
background: go-ta.has-hover && self.can-go ? Theme.accent-hover : Theme.accent;
go-label := Text {
text: LinkResolverState.resolving ? @tr("Resolving…") : @tr("Go");
color: Theme.accent-text;
font-size: Typography.body;
font-weight: Typography.semibold;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
go-ta := TouchArea {
mouse-cursor: parent.can-go ? pointer : default;
clicked => {
if (parent.can-go) {
LinkResolverActions.submit(LinkResolverState.url);
}
}
}
}
}
// Error line.
if LinkResolverState.error != "": Text {
text: LinkResolverState.error;
color: Theme.danger;
font-size: Typography.legal;
wrap: word-wrap;
}
// Playlist banner — hand off to the Playlist Importer.
if LinkResolverState.playlist-detected: Rectangle {
height: banner.preferred-height;
border-radius: Radius.sm;
background: Theme.surface-elevated;
border-width: 1px;
border-color: Theme.border-subtle;
banner := VerticalLayout {
padding: 12px;
spacing: Spacing.sm;
Text {
text: @tr("This looks like a playlist.");
color: Theme.text-secondary;
font-size: Typography.legal;
wrap: word-wrap;
}
HorizontalLayout {
alignment: start;
Rectangle {
width: importer-label.preferred-width + 32px;
height: 34px;
border-radius: Radius.sm;
background: importer-ta.has-hover ? Theme.accent-hover : Theme.accent;
importer-label := Text {
text: @tr("Open Playlist Importer");
color: Theme.accent-text;
font-size: Typography.legal;
font-weight: Typography.semibold;
x: Math.round((parent.width - self.width) / 2 / 1px) * 1px;
y: Math.round((parent.height - self.height) / 2 / 1px) * 1px;
}
importer-ta := TouchArea {
mouse-cursor: pointer;
clicked => {
LinkResolverActions.open-importer();
}
}
}
}
}
}
}
}
}
}
}
+2 -1
View File
@@ -16,7 +16,7 @@ import { Radius } from "../foundation/radius.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { ContextMenu } from "../primitives/ContextMenu.slint";
import { ContextMenuItem } from "../primitives/ContextMenuItem.slint";
import { ShellState, QueueState, QueueItem, NowPlayingState } from "../state.slint";
import { ShellState, QueueState, QueueItem, NowPlayingState, UiFocusState } from "../state.slint";
// Close button — mirrors the X control used by LyricsSidebar.
component CloseButton inherits Rectangle {
@@ -815,6 +815,7 @@ export component QueueSidebar inherits Rectangle {
vertical-alignment: center;
single-line: true;
text: QueueState.search-query;
changed has-focus => { UiFocusState.text-input-focused = self.has-focus; }
edited => {
QueueState.search-query = self.text;
QueueState.search-changed();
+90
View File
@@ -6,6 +6,12 @@
import { JumpNavTab } from "primitives/JumpNavBar.slint";
export { JumpNavTab }
// Re-export the hotkey text-input guard from its leaf file so existing
// `import { UiFocusState } from "state.slint"` sites keep working, while
// low-level primitives import it directly from "focus-state.slint" (avoids a
// recursive import — state.slint imports JumpNavBar's JumpNavTab).
export { UiFocusState } from "focus-state.slint";
export struct AlbumCardItem {
id: string,
title: string,
@@ -4908,3 +4914,87 @@ export global DacWizardActions {
callback gen-configs(); // build the per-DAC copy-paste config (Slice 10)
callback toggle-config(int); // collapse/expand one DAC's config accordion
}
// ============================================================================
// Keyboard shortcuts (hotkeys) — port of the Tauri keybindings system.
// ============================================================================
// One action row, prebuilt in Rust (crate::keybindings) with its display
// shortcut already formatted ("Ctrl + →"). Shared by the read-only cheatsheet
// and the editable customize editor.
export struct KeybindingRow {
id: string, // stable action id, e.g. "playback.toggle"
label: string, // localized action label
shortcut: string, // formatted display, e.g. "Ctrl + →" / "Space"
modified: bool, // differs from the default binding
contextual: bool, // only fires in a context (immersive / mini)
}
// A category group (Playback / Navigation / Interface / Immersive / Mini Player)
// with its localized header label and its ordered rows.
export struct KeybindingCategoryGroup {
label: string, // localized category header
rows: [KeybindingRow],
}
export global KeybindingsState {
// Ordered category groups, rebuilt in Rust whenever a binding changes.
in property <[KeybindingCategoryGroup]> groups: [];
// Count of actions whose binding differs from default ("N modified").
in property <int> modified-count: 0;
// --- Customize editor capture state -------------------------------------
// Action id currently being recorded ("" = not recording). The winit key
// handler reads this; while non-empty it captures the next combo instead
// of dispatching a hotkey.
in-out property <string> recording-id: "";
// Live formatted display of the combo being pressed while recording.
in property <string> pending-display: "";
// Localized label of the action that already owns the pressed combo
// ("" = no conflict). When set, the capture is NOT applied.
in property <string> conflict-label: "";
}
export global KeybindingsActions {
callback start-record(string); // begin capturing for an action id
callback cancel-record(); // stop capturing (Escape / click-away)
callback reset-one(string); // reset one action to its default
callback reset-all(); // reset every action to defaults
}
// Open flags for the two keybindings modals. The cheatsheet (read-only, `?`)
// and the editable customize editor. Self-gated mounts in AppShell (ADR-010).
export global KeyboardShortcutsState {
in-out property <bool> open: false; // read-only cheatsheet
in-out property <bool> customize-open: false; // editable customize editor
}
// ============================================================================
// Open Qobuz Link (Ctrl+L) — cross-platform link resolver modal.
// ============================================================================
export global LinkResolverState {
in-out property <bool> open: false;
// Two-way bound to the input field.
in-out property <string> url: "";
// Detected platform id for the leading icon: "qobuz" | "spotify" | "apple"
// | "tidal" | "deezer" | "songlink" | "" (none/unknown). Set by Rust on
// url-changed; reset to "" from the hamburger menu on open (hence in-out).
in-out property <string> platform: "";
in-out property <bool> resolving: false;
// Localized error message ("" = none).
in-out property <string> error: "";
// Playlist banner: the link is a playlist → offer the Playlist Importer.
in-out property <bool> playlist-detected: false;
in property <string> playlist-provider: "";
}
export global LinkResolverActions {
callback submit(string); // resolve + navigate
callback close();
callback url-changed(string); // live platform detection for the icon
callback open-importer(); // playlist banner → open Playlist Importer
}
// UiFocusState (the hotkey text-input guard) lives in the leaf file
// `focus-state.slint` and is re-exported at the top of this file.