Quince: a Material You video player on mpv
libmpv render API into an egui/glow texture, floating controls with a wavy seek bar and morphing play button, track/speed/chapter menus, playlist and adjust sheets, settings, open link, previews, smoke-test harness. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
7a4266b034
22 changed files with 74098 additions and 0 deletions
1011
src/app.rs
Normal file
1011
src/app.rs
Normal file
File diff suppressed because it is too large
Load diff
211
src/config.rs
Normal file
211
src/config.rs
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
//! Settings and recent files, stored as JSON with words for choices (`~/.config/quince/settings.json`).
|
||||
|
||||
use crate::motion::Motion;
|
||||
use crate::theme::{Appearance, Contrast, Scheme};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ColourFrom {
|
||||
#[default]
|
||||
Desktop,
|
||||
Own,
|
||||
/// The film playing.
|
||||
Video,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
pub colour_from: ColourFrom,
|
||||
pub own_colour: String,
|
||||
pub scheme: String,
|
||||
pub appearance: String,
|
||||
pub contrast: String,
|
||||
pub motion: String,
|
||||
/// Seconds before the controls hide while playing.
|
||||
pub hide_after: f32,
|
||||
pub wave: bool,
|
||||
pub resume: bool,
|
||||
pub hwdec: bool,
|
||||
pub use_mpv_conf: bool,
|
||||
pub pass_keys: bool,
|
||||
pub ytdl_quality: String,
|
||||
pub alang: String,
|
||||
pub slang: String,
|
||||
pub screenshot_dir: String,
|
||||
pub volume: f64,
|
||||
pub seek_small: f64,
|
||||
pub seek_large: f64,
|
||||
pub thumbnails: bool,
|
||||
pub remaining_time: bool,
|
||||
pub click_pauses: bool,
|
||||
pub recent: Vec<Recent>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Recent {
|
||||
pub path: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub position: f64,
|
||||
#[serde(default)]
|
||||
pub duration: f64,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Settings {
|
||||
let shots = dirs::picture_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default()).join("Screenshots");
|
||||
Settings {
|
||||
colour_from: ColourFrom::Desktop,
|
||||
own_colour: "#c9a227".into(),
|
||||
scheme: "tonal".into(),
|
||||
appearance: "auto".into(),
|
||||
contrast: "standard".into(),
|
||||
motion: String::new(),
|
||||
hide_after: 2.5,
|
||||
wave: true,
|
||||
resume: true,
|
||||
hwdec: true,
|
||||
use_mpv_conf: true,
|
||||
pass_keys: true,
|
||||
ytdl_quality: "best".into(),
|
||||
alang: String::new(),
|
||||
slang: String::new(),
|
||||
screenshot_dir: shots.to_string_lossy().into_owned(),
|
||||
volume: 100.0,
|
||||
seek_small: 5.0,
|
||||
seek_large: 30.0,
|
||||
thumbnails: true,
|
||||
remaining_time: false,
|
||||
click_pauses: true,
|
||||
recent: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dir() -> PathBuf {
|
||||
dirs::config_dir().unwrap_or_else(std::env::temp_dir).join("quince")
|
||||
}
|
||||
|
||||
fn file() -> PathBuf {
|
||||
if let Some(p) = std::env::var_os("QUINCE_CONFIG") {
|
||||
return PathBuf::from(p);
|
||||
}
|
||||
dir().join("settings.json")
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn load() -> Settings {
|
||||
std::fs::read(file()).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn save(&self) {
|
||||
let f = file();
|
||||
if let Some(d) = f.parent() {
|
||||
let _ = std::fs::create_dir_all(d);
|
||||
}
|
||||
if let Ok(s) = serde_json::to_vec_pretty(self) {
|
||||
let tmp = f.with_extension("tmp");
|
||||
if std::fs::write(&tmp, s).is_ok() {
|
||||
let _ = std::fs::rename(tmp, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scheme(&self) -> Scheme {
|
||||
match self.scheme.as_str() {
|
||||
"vibrant" => Scheme::Vibrant,
|
||||
"expressive" => Scheme::Expressive,
|
||||
"mono" => Scheme::Mono,
|
||||
_ => Scheme::Tonal,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn appearance(&self) -> Appearance {
|
||||
match self.appearance.as_str() {
|
||||
"light" => Appearance::Light,
|
||||
"dark" => Appearance::Dark,
|
||||
"amoled" => Appearance::Amoled,
|
||||
_ => Appearance::Auto,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contrast(&self) -> Contrast {
|
||||
match self.contrast.as_str() {
|
||||
"medium" => Contrast::Medium,
|
||||
"high" => Contrast::High,
|
||||
_ => Contrast::Standard,
|
||||
}
|
||||
}
|
||||
|
||||
/// Unset means: Reduced when the desktop asks for less motion, else Normal.
|
||||
pub fn motion(&self) -> Motion {
|
||||
match self.motion.as_str() {
|
||||
"off" => Motion::Off,
|
||||
"reduced" => Motion::Reduced,
|
||||
"normal" => Motion::Normal,
|
||||
"lively" => Motion::Expressive,
|
||||
_ => {
|
||||
if desktop_wants_less_motion() {
|
||||
Motion::Reduced
|
||||
} else {
|
||||
Motion::Normal
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ytdl_format(&self) -> String {
|
||||
match self.ytdl_quality.as_str() {
|
||||
"2160" | "1440" | "1080" | "720" | "480" => {
|
||||
format!("bestvideo[height<=?{0}]+bestaudio/best[height<=?{0}]", self.ytdl_quality)
|
||||
}
|
||||
"audio" => "bestaudio/best".into(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a file at the top of the recent list, keeping 20.
|
||||
pub fn remember(&mut self, path: &str, title: &str, position: f64, duration: f64) {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.recent.retain(|r| r.path != path);
|
||||
self.recent.insert(0, Recent { path: path.into(), title: title.into(), position, duration });
|
||||
self.recent.truncate(20);
|
||||
}
|
||||
}
|
||||
|
||||
pub const SCHEMES: [&str; 4] = ["tonal", "vibrant", "expressive", "mono"];
|
||||
pub const APPEARANCES: [&str; 4] = ["auto", "light", "dark", "amoled"];
|
||||
pub const CONTRASTS: [&str; 3] = ["standard", "medium", "high"];
|
||||
pub const MOTIONS: [&str; 4] = ["off", "reduced", "normal", "lively"];
|
||||
pub const QUALITIES: [(&str, &str); 6] =
|
||||
[("best", "Best"), ("2160", "4K"), ("1080", "1080p"), ("720", "720p"), ("480", "480p"), ("audio", "Sound only")];
|
||||
|
||||
fn desktop_wants_less_motion() -> bool {
|
||||
static ASKED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ASKED.get_or_init(ask_desktop_motion)
|
||||
}
|
||||
|
||||
fn ask_desktop_motion() -> bool {
|
||||
let kde = dirs::config_dir().unwrap_or_default().join("kdeglobals");
|
||||
if let Ok(t) = std::fs::read_to_string(kde) {
|
||||
for l in t.lines() {
|
||||
if let Some(v) = l.trim().strip_prefix("AnimationDurationFactor=") {
|
||||
return v.trim().parse::<f32>().map(|f| f == 0.0).unwrap_or(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
// GNOME only; elsewhere gsettings may wait on a bus that isn't there
|
||||
if !std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_lowercase().contains("gnome") {
|
||||
return false;
|
||||
}
|
||||
std::process::Command::new("timeout")
|
||||
.args(["1", "gsettings", "get", "org.gnome.desktop.interface", "enable-animations"])
|
||||
.output()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim() == "false")
|
||||
.unwrap_or(false)
|
||||
}
|
||||
55
src/fonts.rs
Normal file
55
src/fonts.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
//! Rubik (variable, embedded) in three weights, Material Symbols Rounded (subset, outlined and filled), and egui's and
|
||||
//! the system's fonts behind them for other scripts.
|
||||
|
||||
use crate::tokens;
|
||||
use eframe::egui::{self, FontData, FontDefinitions, FontFamily, FontId, TextStyle};
|
||||
use eframe::epaint::text::{FontTweak, VariationCoords};
|
||||
use std::sync::Arc;
|
||||
|
||||
static RUBIK: &[u8] = include_bytes!("../assets/Rubik.ttf");
|
||||
static SYMBOLS: &[u8] = include_bytes!("../assets/symbols.ttf");
|
||||
static SYMBOLS_FILL: &[u8] = include_bytes!("../assets/symbols-fill.ttf");
|
||||
|
||||
pub fn install(ctx: &egui::Context) {
|
||||
let mut defs = FontDefinitions::default();
|
||||
let fallback = defs.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
for (key, family, weight) in [
|
||||
("rubik", FontFamily::Proportional, 400.0),
|
||||
("med", FontFamily::Name("med".into()), 500.0),
|
||||
("semi", FontFamily::Name("semi".into()), 600.0),
|
||||
] {
|
||||
let tweak = FontTweak { coords: VariationCoords::new([(b"wght", weight)]), ..FontTweak::default() };
|
||||
defs.font_data.insert(key.into(), Arc::new(FontData::from_static(RUBIK).tweak(tweak)));
|
||||
let names = std::iter::once(key.to_string()).chain(fallback.iter().cloned()).collect();
|
||||
defs.families.insert(family, names);
|
||||
}
|
||||
// Icons sit centred on their line box.
|
||||
let icon_tweak = FontTweak { y_offset_factor: 0.0, ..FontTweak::default() };
|
||||
defs.font_data.insert("icons".into(), Arc::new(FontData::from_static(SYMBOLS).tweak(icon_tweak.clone())));
|
||||
defs.font_data.insert("icons_fill".into(), Arc::new(FontData::from_static(SYMBOLS_FILL).tweak(icon_tweak)));
|
||||
defs.families.insert(FontFamily::Name("icons".into()), vec!["icons".into()]);
|
||||
defs.families.insert(FontFamily::Name("icons_fill".into()), vec!["icons_fill".into()]);
|
||||
ctx.set_fonts(defs);
|
||||
ctx.all_styles_mut(|s| {
|
||||
s.text_styles = [
|
||||
(TextStyle::Small, FontId::proportional(tokens::text::LABEL)),
|
||||
(TextStyle::Body, FontId::proportional(tokens::text::BODY)),
|
||||
(TextStyle::Button, med(tokens::text::BODY)),
|
||||
(TextStyle::Heading, semi(tokens::text::TITLE)),
|
||||
(TextStyle::Monospace, FontId::monospace(tokens::text::BODY)),
|
||||
]
|
||||
.into();
|
||||
});
|
||||
}
|
||||
|
||||
pub fn ui(size: f32) -> FontId {
|
||||
FontId::proportional(size)
|
||||
}
|
||||
|
||||
pub fn med(size: f32) -> FontId {
|
||||
FontId::new(size, FontFamily::Name("med".into()))
|
||||
}
|
||||
|
||||
pub fn semi(size: f32) -> FontId {
|
||||
FontId::new(size, FontFamily::Name("semi".into()))
|
||||
}
|
||||
44
src/inhibit.rs
Normal file
44
src/inhibit.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
//! Keeps the screen awake while a video plays (mpv can't do it when it isn't drawing its own window). Uses the
|
||||
//! freedesktop ScreenSaver interface on a worker thread, so a slow bus never stalls the UI.
|
||||
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
pub struct Inhibitor {
|
||||
tx: Option<Sender<bool>>,
|
||||
on: bool,
|
||||
}
|
||||
|
||||
impl Inhibitor {
|
||||
pub fn new() -> Inhibitor {
|
||||
let (tx, rx) = channel::<bool>();
|
||||
let ok = std::thread::Builder::new()
|
||||
.name("inhibit".into())
|
||||
.spawn(move || {
|
||||
let Ok(conn) = zbus::blocking::Connection::session() else { return };
|
||||
let mut cookie: Option<u32> = None;
|
||||
while let Ok(want) = rx.recv() {
|
||||
let proxy = zbus::blocking::Proxy::new(&conn, "org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver");
|
||||
let Ok(proxy) = proxy else { continue };
|
||||
match (want, cookie) {
|
||||
(true, None) => cookie = proxy.call::<_, _, u32>("Inhibit", &("quince", "Playing a video")).ok(),
|
||||
(false, Some(c)) => {
|
||||
let _ = proxy.call::<_, _, ()>("UnInhibit", &(c,));
|
||||
cookie = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.is_ok();
|
||||
Inhibitor { tx: ok.then_some(tx), on: false }
|
||||
}
|
||||
|
||||
pub fn set(&mut self, on: bool) {
|
||||
if on != self.on {
|
||||
self.on = on;
|
||||
if let Some(tx) = &self.tx {
|
||||
let _ = tx.send(on);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
62
src/main.rs
Normal file
62
src/main.rs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
//! Quince: a Material You video player for Linux, built on mpv.
|
||||
|
||||
mod app;
|
||||
mod config;
|
||||
mod fonts;
|
||||
mod inhibit;
|
||||
mod motion;
|
||||
mod mpv;
|
||||
mod script;
|
||||
mod shape;
|
||||
mod theme;
|
||||
mod thumbs;
|
||||
mod tokens;
|
||||
mod ui;
|
||||
mod wave;
|
||||
mod widgets;
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.iter().any(|a| a == "--help" || a == "-h") {
|
||||
println!("Usage: quince [FILE or LINK]...\n\nPlays videos and sound with mpv. Settings live in ~/.config/quince.");
|
||||
return Ok(());
|
||||
}
|
||||
if args.iter().any(|a| a == "--version") {
|
||||
println!("quince {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
let files: Vec<String> = args
|
||||
.into_iter()
|
||||
.filter(|a| !a.starts_with("--"))
|
||||
.map(|a| if a.contains("://") { a } else { std::fs::canonicalize(&a).map(|p| p.to_string_lossy().into_owned()).unwrap_or(a) })
|
||||
.collect();
|
||||
// libmpv needs the C locale for numbers
|
||||
unsafe { libc_setlocale() };
|
||||
let size = std::env::var("QUINCE_SIZE").ok().and_then(|s| {
|
||||
let (w, h) = s.split_once('x')?;
|
||||
Some([w.parse().ok()?, h.parse().ok()?])
|
||||
});
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_app_id("quince")
|
||||
.with_title("Quince")
|
||||
.with_inner_size(size.unwrap_or(tokens::size::WINDOW))
|
||||
.with_min_inner_size(tokens::size::WINDOW_MIN)
|
||||
.with_drag_and_drop(true),
|
||||
renderer: eframe::Renderer::Glow,
|
||||
..Default::default()
|
||||
};
|
||||
eframe::run_native("Quince", options, Box::new(move |cc| Ok(Box::new(app::App::new(cc, files)))))
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn setlocale(category: i32, locale: *const std::ffi::c_char) -> *mut std::ffi::c_char;
|
||||
}
|
||||
|
||||
/// LC_NUMERIC must be "C" or mpv refuses to start.
|
||||
unsafe fn libc_setlocale() {
|
||||
const LC_NUMERIC: i32 = 1;
|
||||
unsafe { setlocale(LC_NUMERIC, c"C".as_ptr()) };
|
||||
}
|
||||
324
src/motion.rs
Normal file
324
src/motion.rs
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
//! Spring physics for all motion. `spring(id, target, preset)` is the immediate-mode form: call it each frame with where
|
||||
//! the value should be and it gives back where it is now. Presets are in `tokens::spring`. (From Medlar and Damson.)
|
||||
//!
|
||||
//! Each frame: `motion::begin_frame(dt, level)` first, draw, then `if motion::busy() { ctx.request_repaint() }`.
|
||||
|
||||
use eframe::egui::{Color32, Id};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// The motion setting. Store it in the config as a word ("off", "reduced", "normal", "lively").
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Motion {
|
||||
/// Everything snaps.
|
||||
Off,
|
||||
/// No overshoot; travelling decoration stops.
|
||||
Reduced,
|
||||
#[default]
|
||||
Normal,
|
||||
/// More bounce.
|
||||
Expressive,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Preset {
|
||||
pub stiffness: f32,
|
||||
pub damping: f32,
|
||||
}
|
||||
|
||||
/// A spring nobody asked for in this many frames is forgotten.
|
||||
const KEEP_FRAMES: u64 = 600;
|
||||
|
||||
thread_local! {
|
||||
static BUSY: Cell<bool> = const { Cell::new(false) };
|
||||
static LEVEL: Cell<Motion> = const { Cell::new(Motion::Normal) };
|
||||
static DT: Cell<f32> = const { Cell::new(1.0 / 60.0) };
|
||||
static FRAME: Cell<u64> = const { Cell::new(0) };
|
||||
static MAP: RefCell<HashMap<Id, Slot>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
s: Spring,
|
||||
frame: u64,
|
||||
}
|
||||
|
||||
/// Starts a frame; `level` is the motion choice in settings.
|
||||
pub fn begin_frame(dt: f32, level: Motion) {
|
||||
DT.set(dt.clamp(0.001, 0.05));
|
||||
LEVEL.set(level);
|
||||
BUSY.set(false);
|
||||
let frame = FRAME.get() + 1;
|
||||
FRAME.set(frame);
|
||||
if frame.is_multiple_of(KEEP_FRAMES) {
|
||||
MAP.with_borrow_mut(|m| m.retain(|_, slot| slot.frame + KEEP_FRAMES > frame));
|
||||
}
|
||||
}
|
||||
|
||||
/// Did anything move this frame? If so the next frame must be drawn.
|
||||
pub fn busy() -> bool {
|
||||
BUSY.get()
|
||||
}
|
||||
|
||||
/// For motion that isn't a spring, such as a wave that travels while bytes arrive.
|
||||
pub fn keep_alive() {
|
||||
BUSY.set(true);
|
||||
}
|
||||
|
||||
pub fn dt() -> f32 {
|
||||
DT.get()
|
||||
}
|
||||
|
||||
pub fn level() -> Motion {
|
||||
LEVEL.get()
|
||||
}
|
||||
|
||||
fn adjusted(p: Preset) -> Preset {
|
||||
match level() {
|
||||
Motion::Reduced => Preset { damping: p.damping.max(1.0), ..p },
|
||||
// What must not overshoot stays that way.
|
||||
Motion::Expressive if p.damping < 1.0 => Preset { stiffness: p.stiffness * 0.8, damping: p.damping * 0.62 },
|
||||
_ => p,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Spring {
|
||||
pub x: f32,
|
||||
pub v: f32,
|
||||
pub target: f32,
|
||||
}
|
||||
|
||||
impl Spring {
|
||||
pub fn new(x: f32) -> Spring {
|
||||
Spring { x, v: 0.0, target: x }
|
||||
}
|
||||
|
||||
pub fn settled(&self) -> bool {
|
||||
self.x == self.target && self.v == 0.0
|
||||
}
|
||||
|
||||
pub fn snap(&mut self, x: f32) {
|
||||
*self = Spring::new(x);
|
||||
}
|
||||
|
||||
/// Advances one frame and returns the new value. Changing `target` in flight keeps position and velocity.
|
||||
pub fn step(&mut self, p: Preset) -> f32 {
|
||||
if self.settled() {
|
||||
return self.x;
|
||||
}
|
||||
if level() == Motion::Off {
|
||||
self.snap(self.target);
|
||||
return self.x;
|
||||
}
|
||||
let p = adjusted(p);
|
||||
let c = 2.0 * p.damping * p.stiffness.sqrt();
|
||||
let range = (self.target - self.x).abs().clamp(1.0, 50.0);
|
||||
let mut left = dt();
|
||||
while left > 0.0 {
|
||||
let h = left.min(0.002);
|
||||
let a = -p.stiffness * (self.x - self.target) - c * self.v;
|
||||
self.v += a * h;
|
||||
self.x += self.v * h;
|
||||
left -= h;
|
||||
}
|
||||
if (self.x - self.target).abs() < 0.002 * range && self.v.abs() < 0.05 * range {
|
||||
self.snap(self.target);
|
||||
} else {
|
||||
keep_alive();
|
||||
}
|
||||
self.x
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the spring called `id`, heading for `target`. A new one starts there.
|
||||
pub fn spring(id: impl Hash + std::fmt::Debug, target: f32, p: Preset) -> f32 {
|
||||
spring_from(id, target, target, p)
|
||||
}
|
||||
|
||||
/// Like `spring`, but a new one starts at `from`, so the value animates in.
|
||||
pub fn spring_from(id: impl Hash + std::fmt::Debug, from: f32, target: f32, p: Preset) -> f32 {
|
||||
let frame = FRAME.get();
|
||||
MAP.with_borrow_mut(|m| {
|
||||
let slot = m.entry(Id::unique(id)).or_insert(Slot { s: Spring::new(from), frame: 0 });
|
||||
slot.s.target = target;
|
||||
// Asking twice in a frame must not move it twice.
|
||||
if slot.frame != frame {
|
||||
slot.frame = frame;
|
||||
slot.s.step(p);
|
||||
}
|
||||
slot.s.x
|
||||
})
|
||||
}
|
||||
|
||||
/// Gives a spring a shove, such as on a key press.
|
||||
pub fn kick(id: impl Hash + std::fmt::Debug, velocity: f32) {
|
||||
MAP.with_borrow_mut(|m| {
|
||||
if let Some(slot) = m.get_mut(&Id::unique(id)) {
|
||||
slot.s.v += velocity;
|
||||
keep_alive();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Forgets a spring, so the next use starts fresh.
|
||||
pub fn forget(id: impl Hash + std::fmt::Debug) {
|
||||
MAP.with_borrow_mut(|m| m.remove(&Id::unique(id)));
|
||||
}
|
||||
|
||||
/// A colour on its way to another, on a spring that never overshoots. Keep one per thing that changes colour.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Fade {
|
||||
from: Color32,
|
||||
to: Color32,
|
||||
t: Spring,
|
||||
}
|
||||
|
||||
impl Fade {
|
||||
pub fn new(c: Color32) -> Fade {
|
||||
Fade { from: c, to: c, t: Spring::new(1.0) }
|
||||
}
|
||||
|
||||
/// One frame towards `to`; a new `to` starts from wherever the colour is now.
|
||||
pub fn step(&mut self, to: Color32, p: Preset) -> Color32 {
|
||||
if to != self.to {
|
||||
*self = Fade { from: self.now(), to, t: Spring { target: 100.0, ..Spring::new(0.0) } };
|
||||
}
|
||||
self.t.step(p);
|
||||
self.now()
|
||||
}
|
||||
|
||||
pub fn now(&self) -> Color32 {
|
||||
if self.t.settled() {
|
||||
return self.to;
|
||||
}
|
||||
let t = (self.t.x / 100.0).clamp(0.0, 1.0);
|
||||
let l = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;
|
||||
let (a, b) = (self.from.to_srgba_unmultiplied(), self.to.to_srgba_unmultiplied());
|
||||
Color32::from_rgba_unmultiplied(l(a[0], b[0]), l(a[1], b[1]), l(a[2], b[2]), l(a[3], b[3]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Eased 0..1 for lists appearing one after another: `t` seconds since the start, `delay` for this item, `dur` each.
|
||||
/// Overshoots a little (back-out), except under Reduced; 1 at once under Off.
|
||||
pub fn stagger(t: f32, delay: f32, dur: f32) -> f32 {
|
||||
let x = ((t - delay) / dur.max(0.001)).clamp(0.0, 1.0);
|
||||
match level() {
|
||||
Motion::Off => 1.0,
|
||||
Motion::Reduced => 1.0 - (1.0 - x).powi(3),
|
||||
_ => {
|
||||
if x < 1.0 {
|
||||
keep_alive();
|
||||
}
|
||||
let c = 1.70158;
|
||||
1.0 + (c + 1.0) * (x - 1.0).powi(3) + c * (x - 1.0).powi(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT, FAST, SLOW};
|
||||
|
||||
const DT60: f32 = 1.0 / 60.0;
|
||||
|
||||
fn run(s: &mut Spring, p: Preset, level: Motion, frames: usize) -> f32 {
|
||||
let mut peak = f32::MIN;
|
||||
for _ in 0..frames {
|
||||
begin_frame(DT60, level);
|
||||
peak = peak.max(s.step(p));
|
||||
}
|
||||
peak
|
||||
}
|
||||
|
||||
fn towards_100() -> Spring {
|
||||
Spring { target: 100.0, ..Spring::new(0.0) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overshoots_then_settles() {
|
||||
let mut s = towards_100();
|
||||
let peak = run(&mut s, DEFAULT, Motion::Normal, 240);
|
||||
assert!(peak > 100.5, "peak {peak}");
|
||||
assert!(s.settled() && s.x == 100.0);
|
||||
let peak_expressive = run(&mut towards_100(), DEFAULT, Motion::Expressive, 240);
|
||||
assert!(peak_expressive > peak);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduced_never_overshoots_and_off_snaps() {
|
||||
for p in [FAST, DEFAULT, SLOW] {
|
||||
assert!(run(&mut towards_100(), p, Motion::Reduced, 240) <= 100.0);
|
||||
}
|
||||
let mut s = towards_100();
|
||||
assert_eq!(run(&mut s, DEFAULT, Motion::Off, 1), 100.0);
|
||||
assert!(!busy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_never_overshoot() {
|
||||
for level in [Motion::Reduced, Motion::Normal, Motion::Expressive] {
|
||||
assert!(run(&mut towards_100(), EFFECT, level, 240) <= 100.0, "{level:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retarget_keeps_position_and_velocity() {
|
||||
let mut s = towards_100();
|
||||
run(&mut s, DEFAULT, Motion::Normal, 3);
|
||||
let (x, v) = (s.x, s.v);
|
||||
assert!(x > 1.0 && v > 100.0);
|
||||
s.target = 0.0;
|
||||
assert_eq!((s.x, s.v), (x, v), "a new target changes nothing by itself");
|
||||
begin_frame(0.001, Motion::Normal);
|
||||
s.step(DEFAULT);
|
||||
assert!(s.x > x, "still carried on by its speed: {} after {x}", s.x);
|
||||
assert!(s.v < v, "but already slowing");
|
||||
run(&mut s, DEFAULT, Motion::Normal, 240);
|
||||
assert!(s.settled() && s.x == 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retarget_onto_the_current_place_does_not_freeze_it() {
|
||||
let mut s = towards_100();
|
||||
run(&mut s, DEFAULT, Motion::Normal, 3);
|
||||
s.target = s.x;
|
||||
assert!(!s.settled());
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
assert!(s.step(DEFAULT) > s.target);
|
||||
assert!(busy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_springs_move_once_a_frame_and_stop_asking_for_frames() {
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
assert_eq!(spring("named", 0.0, DEFAULT), 0.0);
|
||||
assert!(!busy());
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
let x = spring("named", 1.0, DEFAULT);
|
||||
assert!(x > 0.0 && busy());
|
||||
assert_eq!(spring("named", 1.0, DEFAULT), x);
|
||||
for _ in 0..240 {
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
spring("named", 1.0, DEFAULT);
|
||||
}
|
||||
assert!(!busy());
|
||||
assert_eq!(spring_from("fresh", 5.0, 5.0, DEFAULT), 5.0);
|
||||
kick("named", 10.0);
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
assert!(spring("named", 1.0, DEFAULT) > 1.0);
|
||||
forget("named");
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
assert_eq!(spring("named", 3.0, DEFAULT), 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_springs_are_dropped() {
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
spring("gone", 0.0, DEFAULT);
|
||||
for _ in 0..KEEP_FRAMES * 2 {
|
||||
begin_frame(DT60, Motion::Normal);
|
||||
}
|
||||
MAP.with_borrow(|m| assert!(!m.contains_key(&Id::unique("gone"))));
|
||||
}
|
||||
}
|
||||
770
src/mpv.rs
Normal file
770
src/mpv.rs
Normal file
|
|
@ -0,0 +1,770 @@
|
|||
//! mpv: one libmpv handle, its OpenGL render context, and the properties the UI shows.
|
||||
//!
|
||||
//! The video is rendered into our own framebuffer texture (libmpv's render API) and drawn by egui like any image, so
|
||||
//! every control can sit on top of it. Property changes arrive as events; `pump` drains them into `State` each frame.
|
||||
|
||||
use libmpv2::{Format, Mpv, events::Event, events::PropertyData};
|
||||
use libmpv2_sys as sys;
|
||||
use serde::Deserialize;
|
||||
use std::ffi::{CStr, CString, c_char, c_void};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type GetProc = Arc<dyn Fn(&CStr) -> *const c_void + Send + Sync>;
|
||||
|
||||
/// What mpv is starting with; most can change while it runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Init {
|
||||
pub use_mpv_conf: bool,
|
||||
pub hwdec: bool,
|
||||
pub resume: bool,
|
||||
pub ytdl_format: String,
|
||||
pub alang: String,
|
||||
pub slang: String,
|
||||
pub screenshot_dir: String,
|
||||
pub volume: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Track {
|
||||
pub id: i64,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
#[serde(default)]
|
||||
pub lang: Option<String>,
|
||||
#[serde(default)]
|
||||
pub codec: Option<String>,
|
||||
#[serde(default)]
|
||||
pub selected: bool,
|
||||
#[serde(default)]
|
||||
pub external: bool,
|
||||
#[serde(default, rename = "default")]
|
||||
pub is_default: bool,
|
||||
#[serde(default, rename = "demux-channel-count")]
|
||||
pub channels: Option<i64>,
|
||||
#[serde(default, rename = "demux-w")]
|
||||
pub w: Option<i64>,
|
||||
#[serde(default, rename = "demux-h")]
|
||||
pub h: Option<i64>,
|
||||
#[serde(default, rename = "demux-fps")]
|
||||
pub fps: Option<f64>,
|
||||
#[serde(default, rename = "demux-samplerate")]
|
||||
pub samplerate: Option<i64>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
/// "English · AAC 5.1" style name for menus.
|
||||
pub fn label(&self) -> String {
|
||||
let mut parts = vec![];
|
||||
if let Some(t) = self.title.as_deref().filter(|t| !t.is_empty()) {
|
||||
parts.push(t.to_string());
|
||||
}
|
||||
if let Some(l) = self.lang.as_deref() {
|
||||
let name = lang_name(l);
|
||||
if !parts.iter().any(|p| p.eq_ignore_ascii_case(&name)) {
|
||||
parts.push(name);
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
parts.push(format!("Track {}", self.id));
|
||||
}
|
||||
parts.join(" · ")
|
||||
}
|
||||
|
||||
pub fn detail(&self) -> String {
|
||||
let mut d = vec![];
|
||||
if let Some(c) = &self.codec {
|
||||
d.push(c.to_uppercase());
|
||||
}
|
||||
match self.kind.as_str() {
|
||||
"video" => {
|
||||
if let (Some(w), Some(h)) = (self.w, self.h) {
|
||||
d.push(format!("{w}×{h}"));
|
||||
}
|
||||
if let Some(f) = self.fps {
|
||||
d.push(format!("{} fps", trim_num(f, 3)));
|
||||
}
|
||||
}
|
||||
"audio" => {
|
||||
if let Some(c) = self.channels {
|
||||
d.push(match c {
|
||||
1 => "mono".into(),
|
||||
2 => "stereo".into(),
|
||||
6 => "5.1".into(),
|
||||
8 => "7.1".into(),
|
||||
n => format!("{n} ch"),
|
||||
});
|
||||
}
|
||||
if let Some(s) = self.samplerate {
|
||||
d.push(format!("{} kHz", trim_num(s as f64 / 1000.0, 1)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if self.external {
|
||||
d.push("external".into());
|
||||
}
|
||||
if self.is_default {
|
||||
d.push("default".into());
|
||||
}
|
||||
d.join(" · ")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trim_num(v: f64, places: usize) -> String {
|
||||
let s = format!("{v:.places$}");
|
||||
if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
|
||||
}
|
||||
|
||||
fn lang_name(code: &str) -> String {
|
||||
let n = match code.to_ascii_lowercase().as_str() {
|
||||
"en" | "eng" => "English",
|
||||
"ja" | "jpn" => "Japanese",
|
||||
"de" | "ger" | "deu" => "German",
|
||||
"fr" | "fre" | "fra" => "French",
|
||||
"es" | "spa" => "Spanish",
|
||||
"it" | "ita" => "Italian",
|
||||
"pt" | "por" => "Portuguese",
|
||||
"ru" | "rus" => "Russian",
|
||||
"zh" | "chi" | "zho" => "Chinese",
|
||||
"ko" | "kor" => "Korean",
|
||||
"nl" | "dut" | "nld" => "Dutch",
|
||||
"sv" | "swe" => "Swedish",
|
||||
"pl" | "pol" => "Polish",
|
||||
"ar" | "ara" => "Arabic",
|
||||
"hi" | "hin" => "Hindi",
|
||||
"tr" | "tur" => "Turkish",
|
||||
"und" => "Unknown language",
|
||||
_ => return code.to_string(),
|
||||
};
|
||||
n.into()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Chapter {
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
pub time: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub filename: String,
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
#[serde(default)]
|
||||
pub current: bool,
|
||||
#[serde(default)]
|
||||
pub id: i64,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub fn name(&self) -> String {
|
||||
if let Some(t) = self.title.as_deref().filter(|t| !t.is_empty()) {
|
||||
return t.to_string();
|
||||
}
|
||||
display_name(&self.filename)
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name of a path or URL, without the folder.
|
||||
pub fn display_name(path: &str) -> String {
|
||||
if path.contains("://") {
|
||||
let p = path.split(['?', '#']).next().unwrap_or(path);
|
||||
let last = p.trim_end_matches('/').rsplit('/').next().unwrap_or(p);
|
||||
let last = urlencoding::decode(last).map(|s| s.into_owned()).unwrap_or_else(|_| last.to_string());
|
||||
return if last.is_empty() || last.contains(':') { path.to_string() } else { last };
|
||||
}
|
||||
std::path::Path::new(path).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
/// What the UI shows, as mpv last said it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct State {
|
||||
pub idle: bool,
|
||||
pub pause: bool,
|
||||
pub time: f64,
|
||||
pub duration: f64,
|
||||
pub volume: f64,
|
||||
pub mute: bool,
|
||||
pub speed: f64,
|
||||
pub title: String,
|
||||
pub path: String,
|
||||
pub tracks: Vec<Track>,
|
||||
pub chapters: Vec<Chapter>,
|
||||
pub chapter: i64,
|
||||
pub playlist: Vec<Entry>,
|
||||
pub playlist_pos: i64,
|
||||
pub cache_time: f64,
|
||||
pub buffering: bool,
|
||||
pub seeking: bool,
|
||||
pub eof: bool,
|
||||
pub loop_file: bool,
|
||||
pub loop_playlist: bool,
|
||||
pub ab_a: Option<f64>,
|
||||
pub ab_b: Option<f64>,
|
||||
pub sub_delay: f64,
|
||||
pub audio_delay: f64,
|
||||
pub sub_scale: f64,
|
||||
pub sub_pos: f64,
|
||||
pub sub_visible: bool,
|
||||
pub sub_ass_override: String,
|
||||
pub secondary_sid: String,
|
||||
pub vid: String,
|
||||
pub aid: String,
|
||||
pub sid: String,
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
pub hwdec_current: String,
|
||||
pub hwdec: String,
|
||||
pub aspect_override: String,
|
||||
pub rotate: i64,
|
||||
pub zoom: f64,
|
||||
pub brightness: f64,
|
||||
pub contrast: f64,
|
||||
pub saturation: f64,
|
||||
pub gamma: f64,
|
||||
pub hue: f64,
|
||||
pub deinterlace: bool,
|
||||
pub audio_pitch_correction: bool,
|
||||
pub audio_device: String,
|
||||
pub af: String,
|
||||
pub vf: String,
|
||||
pub shuffle: bool,
|
||||
pub file_format: String,
|
||||
pub video_codec: String,
|
||||
pub audio_codec: String,
|
||||
pub fps: f64,
|
||||
pub panscan: f64,
|
||||
pub devices: Vec<Device>,
|
||||
pub audio_channels: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Device {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn tracks_of(&self, kind: &str) -> impl Iterator<Item = &Track> {
|
||||
self.tracks.iter().filter(move |t| t.kind == kind)
|
||||
}
|
||||
|
||||
pub fn has_video(&self) -> bool {
|
||||
self.width > 0 && self.height > 0
|
||||
}
|
||||
|
||||
pub fn loaded(&self) -> bool {
|
||||
!self.idle && !self.path.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Things that happened, for the app to react to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Happened {
|
||||
FileLoaded,
|
||||
StartFile,
|
||||
EndFile,
|
||||
/// A command or a file failed; the app knows which from what it was doing.
|
||||
Error(String),
|
||||
VideoReconfig,
|
||||
PlaybackRestart,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
const PROPS: &[(&str, Format)] = &[
|
||||
("idle-active", Format::Flag),
|
||||
("pause", Format::Flag),
|
||||
("time-pos", Format::Double),
|
||||
("duration", Format::Double),
|
||||
("volume", Format::Double),
|
||||
("mute", Format::Flag),
|
||||
("speed", Format::Double),
|
||||
("media-title", Format::String),
|
||||
("path", Format::String),
|
||||
("track-list", Format::String),
|
||||
("chapter-list", Format::String),
|
||||
("chapter", Format::Int64),
|
||||
("playlist", Format::String),
|
||||
("playlist-pos", Format::Int64),
|
||||
("demuxer-cache-time", Format::Double),
|
||||
("paused-for-cache", Format::Flag),
|
||||
("seeking", Format::Flag),
|
||||
("eof-reached", Format::Flag),
|
||||
("loop-file", Format::String),
|
||||
("loop-playlist", Format::String),
|
||||
("ab-loop-a", Format::String),
|
||||
("ab-loop-b", Format::String),
|
||||
("sub-delay", Format::Double),
|
||||
("audio-delay", Format::Double),
|
||||
("sub-scale", Format::Double),
|
||||
("sub-pos", Format::Double),
|
||||
("sub-visibility", Format::Flag),
|
||||
("sub-ass-override", Format::String),
|
||||
("secondary-sid", Format::String),
|
||||
("vid", Format::String),
|
||||
("aid", Format::String),
|
||||
("sid", Format::String),
|
||||
("dwidth", Format::Int64),
|
||||
("dheight", Format::Int64),
|
||||
("hwdec-current", Format::String),
|
||||
("hwdec", Format::String),
|
||||
("video-aspect-override", Format::String),
|
||||
("video-rotate", Format::Int64),
|
||||
("video-zoom", Format::Double),
|
||||
("brightness", Format::Double),
|
||||
("contrast", Format::Double),
|
||||
("saturation", Format::Double),
|
||||
("gamma", Format::Double),
|
||||
("hue", Format::Double),
|
||||
("deinterlace", Format::Flag),
|
||||
("audio-pitch-correction", Format::Flag),
|
||||
("audio-device", Format::String),
|
||||
("af", Format::String),
|
||||
("vf", Format::String),
|
||||
("shuffle", Format::Flag),
|
||||
("file-format", Format::String),
|
||||
("video-codec", Format::String),
|
||||
("audio-codec-name", Format::String),
|
||||
("container-fps", Format::Double),
|
||||
("panscan", Format::Double),
|
||||
("audio-device-list", Format::String),
|
||||
("audio-channels", Format::String),
|
||||
];
|
||||
|
||||
fn json<T: for<'de> Deserialize<'de> + Default>(s: &str) -> T {
|
||||
serde_json::from_str(s).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn opt_time(s: &str) -> Option<f64> {
|
||||
s.parse::<f64>().ok()
|
||||
}
|
||||
|
||||
pub struct Player {
|
||||
pub mpv: Mpv,
|
||||
pub state: State,
|
||||
render: *mut sys::mpv_render_context,
|
||||
_get_proc: Box<GetProc>,
|
||||
fbo: Option<Target>,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
struct Target {
|
||||
fbo: glow::Framebuffer,
|
||||
tex: glow::Texture,
|
||||
w: i32,
|
||||
h: i32,
|
||||
id: Option<eframe::egui::TextureId>,
|
||||
}
|
||||
|
||||
unsafe extern "C" fn get_proc_cb(ctx: *mut c_void, name: *const c_char) -> *mut c_void {
|
||||
let f = unsafe { &*(ctx as *const GetProc) };
|
||||
f(unsafe { CStr::from_ptr(name) }) as *mut c_void
|
||||
}
|
||||
|
||||
fn ctx_free(_id: eframe::egui::TextureId) {
|
||||
// native textures are only a name for our GL texture; deleting the texture below is enough
|
||||
}
|
||||
|
||||
unsafe extern "C" fn on_update(ctx: *mut c_void) {
|
||||
let egui = unsafe { &*(ctx as *const eframe::egui::Context) };
|
||||
egui.request_repaint();
|
||||
}
|
||||
|
||||
/// Display pointers mpv needs for hardware decoding interop.
|
||||
pub enum Display {
|
||||
Wayland(*mut c_void),
|
||||
X11(*mut c_void),
|
||||
None,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
pub fn new(init: &Init, get_proc_address: GetProc, display: Display, egui: eframe::egui::Context) -> Result<Player, String> {
|
||||
let config_dir = dirs::config_dir().unwrap_or_default().join("mpv");
|
||||
let watch_later = dirs::state_dir().unwrap_or_else(std::env::temp_dir).join("quince/watch_later");
|
||||
let _ = std::fs::create_dir_all(&watch_later);
|
||||
let log = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join("quince/mpv.log");
|
||||
let _ = std::fs::create_dir_all(log.parent().unwrap());
|
||||
let init = init.clone();
|
||||
let mut mpv = Mpv::with_initializer(move |i| {
|
||||
i.set_property("vo", "libmpv")?;
|
||||
i.set_property("config", if init.use_mpv_conf { "yes" } else { "no" })?;
|
||||
i.set_property("config-dir", config_dir.to_string_lossy().as_ref())?;
|
||||
i.set_property("input-default-bindings", "yes")?;
|
||||
i.set_property("input-vo-keyboard", "no")?;
|
||||
i.set_property("osc", "no")?;
|
||||
i.set_property("osd-bar", "no")?;
|
||||
i.set_property("idle", "yes")?;
|
||||
i.set_property("keep-open", "yes")?;
|
||||
i.set_property("force-window", "no")?;
|
||||
i.set_property("terminal", "no")?;
|
||||
i.set_property("log-file", log.to_string_lossy().as_ref())?;
|
||||
i.set_property("msg-level", "all=info")?;
|
||||
i.set_property("audio-client-name", "quince")?;
|
||||
i.set_property("volume-max", "150")?;
|
||||
i.set_property("volume", init.volume)?;
|
||||
i.set_property("hwdec", if init.hwdec { "auto-safe" } else { "no" })?;
|
||||
i.set_property("ytdl", "yes")?;
|
||||
if !init.ytdl_format.is_empty() {
|
||||
i.set_property("ytdl-format", init.ytdl_format.as_str())?;
|
||||
}
|
||||
i.set_property("sub-auto", "fuzzy")?;
|
||||
if !init.alang.is_empty() {
|
||||
i.set_property("alang", init.alang.as_str())?;
|
||||
}
|
||||
if !init.slang.is_empty() {
|
||||
i.set_property("slang", init.slang.as_str())?;
|
||||
}
|
||||
i.set_property("save-position-on-quit", init.resume)?;
|
||||
i.set_property("watch-later-directory", watch_later.to_string_lossy().as_ref())?;
|
||||
i.set_property("screenshot-directory", init.screenshot_dir.as_str())?;
|
||||
i.set_property("screenshot-template", "Quince %F %wH-%wM-%wS")?;
|
||||
i.set_property("screenshot-format", "png")?;
|
||||
i.set_property("cache", "auto")?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| format!("Couldn't start mpv: {e}"))?;
|
||||
// mpv.conf may name another video output; ours must stay.
|
||||
let _ = mpv.set_property("vo", "libmpv");
|
||||
let _ = mpv.disable_deprecated_events();
|
||||
for (n, (name, fmt)) in PROPS.iter().enumerate() {
|
||||
let _ = mpv.observe_property(name, *fmt, n as u64);
|
||||
}
|
||||
let wake = egui.clone();
|
||||
mpv.set_wakeup_callback(move || wake.request_repaint());
|
||||
|
||||
let get_proc = Box::new(get_proc_address);
|
||||
let mut init_params = sys::mpv_opengl_init_params {
|
||||
get_proc_address: Some(get_proc_cb),
|
||||
get_proc_address_ctx: &*get_proc as *const GetProc as *mut c_void,
|
||||
};
|
||||
let mut params = vec![
|
||||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_API_TYPE, data: sys::MPV_RENDER_API_TYPE_OPENGL.as_ptr() as *mut c_void },
|
||||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, data: &mut init_params as *mut _ as *mut c_void },
|
||||
];
|
||||
match display {
|
||||
Display::Wayland(p) => params.push(sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_WL_DISPLAY, data: p }),
|
||||
Display::X11(p) => params.push(sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_X11_DISPLAY, data: p }),
|
||||
Display::None => {}
|
||||
}
|
||||
params.push(sys::mpv_render_param { type_: 0, data: std::ptr::null_mut() });
|
||||
let mut render: *mut sys::mpv_render_context = std::ptr::null_mut();
|
||||
let err = unsafe { sys::mpv_render_context_create(&mut render, mpv.ctx.as_ptr(), params.as_mut_ptr()) };
|
||||
if err < 0 {
|
||||
return Err(format!("Couldn't set up video output: {}", sys::mpv_error_str(err)));
|
||||
}
|
||||
// The context lives as long as the app (we leak one clone of it on purpose).
|
||||
let ctx_ptr = Box::into_raw(Box::new(egui)) as *mut c_void;
|
||||
unsafe { sys::mpv_render_context_set_update_callback(render, Some(on_update), ctx_ptr) };
|
||||
Ok(Player { mpv, state: State { idle: true, speed: 1.0, volume: 100.0, sub_visible: true, sub_scale: 1.0, sub_pos: 100.0, zoom: 0.0, ..State::default() }, render, _get_proc: get_proc, fbo: None, dirty: true })
|
||||
}
|
||||
|
||||
/// Runs a command without waiting for it.
|
||||
pub fn cmd(&self, args: &[&str]) {
|
||||
let owned: Vec<CString> = args.iter().map(|a| CString::new(*a).unwrap_or_default()).collect();
|
||||
let mut ptrs: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();
|
||||
ptrs.push(std::ptr::null());
|
||||
unsafe { sys::mpv_command_async(self.mpv.ctx.as_ptr(), 0, ptrs.as_mut_ptr()) };
|
||||
}
|
||||
|
||||
pub fn set<T: libmpv2::SetData>(&self, name: &str, v: T) {
|
||||
let _ = self.mpv.set_property(name, v);
|
||||
}
|
||||
|
||||
pub fn get_str(&self, name: &str) -> Option<String> {
|
||||
self.mpv.get_property::<String>(name).ok()
|
||||
}
|
||||
|
||||
pub fn get_f64(&self, name: &str) -> Option<f64> {
|
||||
self.mpv.get_property::<f64>(name).ok()
|
||||
}
|
||||
|
||||
/// Drains mpv's events into `state` and returns what happened.
|
||||
pub fn pump(&mut self) -> Vec<Happened> {
|
||||
let mut out = vec![];
|
||||
while let Some(ev) = self.mpv.wait_event(0.0) {
|
||||
match ev {
|
||||
Ok(Event::PropertyChange { name, change, .. }) => apply(&mut self.state, name, change),
|
||||
Ok(Event::FileLoaded) => out.push(Happened::FileLoaded),
|
||||
Ok(Event::StartFile) => out.push(Happened::StartFile),
|
||||
Ok(Event::EndFile(_)) => out.push(Happened::EndFile),
|
||||
Err(e) => out.push(Happened::Error(err_words(&e))),
|
||||
Ok(Event::VideoReconfig) => out.push(Happened::VideoReconfig),
|
||||
Ok(Event::PlaybackRestart) => out.push(Happened::PlaybackRestart),
|
||||
Ok(Event::Shutdown) => out.push(Happened::Shutdown),
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders the newest video frame into our texture, `w`×`h` physical pixels, if mpv has one or the size changed.
|
||||
/// Returns the texture to draw.
|
||||
pub fn render(&mut self, gl: &glow::Context, frame: &mut eframe::Frame, w: i32, h: i32) -> Option<eframe::egui::TextureId> {
|
||||
use glow::HasContext;
|
||||
let (w, h) = (w.max(1), h.max(1));
|
||||
if self.render.is_null() {
|
||||
return None;
|
||||
}
|
||||
let flags = unsafe { sys::mpv_render_context_update(self.render) };
|
||||
if flags & sys::mpv_render_update_flag_MPV_RENDER_UPDATE_FRAME as u64 != 0 {
|
||||
self.dirty = true;
|
||||
}
|
||||
let resized = self.fbo.as_ref().is_none_or(|t| t.w != w || t.h != h);
|
||||
unsafe {
|
||||
if resized {
|
||||
if let Some(old) = self.fbo.take() {
|
||||
if let Some(id) = old.id {
|
||||
let _ = frame;
|
||||
ctx_free(id);
|
||||
}
|
||||
gl.delete_framebuffer(old.fbo);
|
||||
gl.delete_texture(old.tex);
|
||||
}
|
||||
let tex = gl.create_texture().ok()?;
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
|
||||
gl.tex_image_2d(glow::TEXTURE_2D, 0, glow::RGBA8 as i32, w, h, 0, glow::RGBA, glow::UNSIGNED_BYTE, glow::PixelUnpackData::Slice(None));
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
|
||||
gl.bind_texture(glow::TEXTURE_2D, None);
|
||||
let fbo = gl.create_framebuffer().ok()?;
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo));
|
||||
gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(tex), 0);
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
|
||||
let id = frame.register_native_glow_texture(tex);
|
||||
self.fbo = Some(Target { fbo, tex, w, h, id: Some(id) });
|
||||
self.dirty = true;
|
||||
}
|
||||
let t = self.fbo.as_ref()?;
|
||||
if self.dirty {
|
||||
self.dirty = false;
|
||||
let mut fbo = sys::mpv_opengl_fbo { fbo: t.fbo.0.get() as i32, w, h, internal_format: 0 };
|
||||
let mut flip: i32 = 0;
|
||||
let mut block: i32 = 0;
|
||||
let mut params = [
|
||||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_OPENGL_FBO, data: &mut fbo as *mut _ as *mut c_void },
|
||||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_FLIP_Y, data: &mut flip as *mut _ as *mut c_void },
|
||||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME, data: &mut block as *mut _ as *mut c_void },
|
||||
sys::mpv_render_param { type_: 0, data: std::ptr::null_mut() },
|
||||
];
|
||||
sys::mpv_render_context_render(self.render, params.as_mut_ptr());
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
|
||||
gl.bind_texture(glow::TEXTURE_2D, None);
|
||||
gl.use_program(None);
|
||||
sys::mpv_render_context_report_swap(self.render);
|
||||
}
|
||||
t.id
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Player {
|
||||
/// Frees the render context and our GL objects; must run while the GL context is current.
|
||||
pub fn shutdown(&mut self, gl: Option<&glow::Context>) {
|
||||
use glow::HasContext;
|
||||
if !self.render.is_null() {
|
||||
unsafe { sys::mpv_render_context_free(self.render) };
|
||||
self.render = std::ptr::null_mut();
|
||||
}
|
||||
if let (Some(gl), Some(t)) = (gl, self.fbo.take()) {
|
||||
unsafe {
|
||||
gl.delete_framebuffer(t.fbo);
|
||||
gl.delete_texture(t.tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Player {
|
||||
fn drop(&mut self) {
|
||||
if !self.render.is_null() {
|
||||
unsafe { sys::mpv_render_context_free(self.render) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// mpv's error, in words a person can use.
|
||||
fn err_words(e: &libmpv2::Error) -> String {
|
||||
let raw = match e {
|
||||
libmpv2::Error::Raw(code) => sys::mpv_error_str(*code).to_string(),
|
||||
other => format!("{other}"),
|
||||
};
|
||||
match raw.as_str() {
|
||||
"loading failed" => "the file couldn't be read".into(),
|
||||
"unrecognized file format" => "it isn't a format mpv can play".into(),
|
||||
"no audio or video data played" => "it has no sound or picture mpv can play".into(),
|
||||
"error running command" => "mpv couldn't do that".into(),
|
||||
"property unavailable" => "that isn't available for this file".into(),
|
||||
r => r.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(s: &mut State, name: &str, v: PropertyData) {
|
||||
let f = |v: &PropertyData| match v {
|
||||
PropertyData::Double(d) => *d,
|
||||
PropertyData::Int64(i) => *i as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
let b = |v: &PropertyData| matches!(v, PropertyData::Flag(true));
|
||||
let st = |v: &PropertyData| match v {
|
||||
PropertyData::Str(s) | PropertyData::OsdStr(s) => s.to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let i = |v: &PropertyData| match v {
|
||||
PropertyData::Int64(i) => *i,
|
||||
PropertyData::Double(d) => *d as i64,
|
||||
_ => 0,
|
||||
};
|
||||
match name {
|
||||
"idle-active" => s.idle = b(&v),
|
||||
"pause" => s.pause = b(&v),
|
||||
"time-pos" => s.time = f(&v),
|
||||
"duration" => s.duration = f(&v),
|
||||
"volume" => s.volume = f(&v),
|
||||
"mute" => s.mute = b(&v),
|
||||
"speed" => s.speed = f(&v),
|
||||
"media-title" => s.title = st(&v),
|
||||
"path" => s.path = st(&v),
|
||||
"track-list" => s.tracks = json(&st(&v)),
|
||||
"chapter-list" => s.chapters = json(&st(&v)),
|
||||
"chapter" => s.chapter = i(&v),
|
||||
"playlist" => s.playlist = json(&st(&v)),
|
||||
"playlist-pos" => s.playlist_pos = i(&v),
|
||||
"demuxer-cache-time" => s.cache_time = f(&v),
|
||||
"paused-for-cache" => s.buffering = b(&v),
|
||||
"seeking" => s.seeking = b(&v),
|
||||
"eof-reached" => s.eof = b(&v),
|
||||
"loop-file" => s.loop_file = st(&v) != "no",
|
||||
"loop-playlist" => s.loop_playlist = st(&v) != "no",
|
||||
"ab-loop-a" => s.ab_a = opt_time(&st(&v)),
|
||||
"ab-loop-b" => s.ab_b = opt_time(&st(&v)),
|
||||
"sub-delay" => s.sub_delay = f(&v),
|
||||
"audio-delay" => s.audio_delay = f(&v),
|
||||
"sub-scale" => s.sub_scale = f(&v),
|
||||
"sub-pos" => s.sub_pos = f(&v),
|
||||
"sub-visibility" => s.sub_visible = b(&v),
|
||||
"sub-ass-override" => s.sub_ass_override = st(&v),
|
||||
"secondary-sid" => s.secondary_sid = st(&v),
|
||||
"vid" => s.vid = st(&v),
|
||||
"aid" => s.aid = st(&v),
|
||||
"sid" => s.sid = st(&v),
|
||||
"dwidth" => s.width = i(&v),
|
||||
"dheight" => s.height = i(&v),
|
||||
"hwdec-current" => s.hwdec_current = st(&v),
|
||||
"hwdec" => s.hwdec = st(&v),
|
||||
"video-aspect-override" => {
|
||||
let a = st(&v);
|
||||
s.aspect_override = if a.parse::<f64>().is_ok_and(|x| x <= 0.0) || a == "no" { "-1".into() } else { a };
|
||||
}
|
||||
"video-rotate" => s.rotate = i(&v),
|
||||
"video-zoom" => s.zoom = f(&v),
|
||||
"brightness" => s.brightness = f(&v),
|
||||
"contrast" => s.contrast = f(&v),
|
||||
"saturation" => s.saturation = f(&v),
|
||||
"gamma" => s.gamma = f(&v),
|
||||
"hue" => s.hue = f(&v),
|
||||
"deinterlace" => s.deinterlace = b(&v),
|
||||
"audio-pitch-correction" => s.audio_pitch_correction = b(&v),
|
||||
"audio-device" => s.audio_device = st(&v),
|
||||
"af" => s.af = st(&v),
|
||||
"vf" => s.vf = st(&v),
|
||||
"shuffle" => s.shuffle = b(&v),
|
||||
"file-format" => s.file_format = st(&v),
|
||||
"video-codec" => s.video_codec = st(&v),
|
||||
"audio-codec-name" => s.audio_codec = st(&v),
|
||||
"container-fps" => s.fps = f(&v),
|
||||
"panscan" => s.panscan = f(&v),
|
||||
"audio-device-list" => s.devices = json(&st(&v)),
|
||||
"audio-channels" => s.audio_channels = st(&v),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// mpv's name for an egui key, for passing keys the app doesn't use on to mpv (input.conf, scripts, the console).
|
||||
pub fn key_name(key: eframe::egui::Key, m: eframe::egui::Modifiers) -> Option<String> {
|
||||
use eframe::egui::Key as K;
|
||||
let base = match key {
|
||||
K::ArrowDown => "DOWN".into(),
|
||||
K::ArrowLeft => "LEFT".into(),
|
||||
K::ArrowRight => "RIGHT".into(),
|
||||
K::ArrowUp => "UP".into(),
|
||||
K::Escape => "ESC".into(),
|
||||
K::Tab => "TAB".into(),
|
||||
K::Backspace => "BS".into(),
|
||||
K::Enter => "ENTER".into(),
|
||||
K::Space => "SPACE".into(),
|
||||
K::Insert => "INS".into(),
|
||||
K::Delete => "DEL".into(),
|
||||
K::Home => "HOME".into(),
|
||||
K::End => "END".into(),
|
||||
K::PageUp => "PGUP".into(),
|
||||
K::PageDown => "PGDWN".into(),
|
||||
K::F1 => "F1".into(),
|
||||
K::F2 => "F2".into(),
|
||||
K::F3 => "F3".into(),
|
||||
K::F4 => "F4".into(),
|
||||
K::F5 => "F5".into(),
|
||||
K::F6 => "F6".into(),
|
||||
K::F7 => "F7".into(),
|
||||
K::F8 => "F8".into(),
|
||||
K::F9 => "F9".into(),
|
||||
K::F10 => "F10".into(),
|
||||
K::F11 => "F11".into(),
|
||||
K::F12 => "F12".into(),
|
||||
_ => {
|
||||
let s = key.symbol_or_name();
|
||||
if s.chars().count() != 1 {
|
||||
return None;
|
||||
}
|
||||
let c = s.chars().next()?;
|
||||
if c.is_ascii_alphabetic() {
|
||||
// mpv tells letters apart by case, not by Shift.
|
||||
let c = if m.shift { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() };
|
||||
let mut out = String::new();
|
||||
if m.ctrl {
|
||||
out.push_str("Ctrl+");
|
||||
}
|
||||
if m.alt {
|
||||
out.push_str("Alt+");
|
||||
}
|
||||
out.push(c);
|
||||
return Some(out);
|
||||
}
|
||||
s.to_string()
|
||||
}
|
||||
};
|
||||
let mut out = String::new();
|
||||
if m.ctrl {
|
||||
out.push_str("Ctrl+");
|
||||
}
|
||||
if m.alt {
|
||||
out.push_str("Alt+");
|
||||
}
|
||||
if m.shift {
|
||||
out.push_str("Shift+");
|
||||
}
|
||||
out.push_str(&base);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_and_tracks_read_well() {
|
||||
assert_eq!(display_name("/home/a/Films/The Film (2020).mkv"), "The Film (2020).mkv");
|
||||
assert_eq!(display_name("https://example.com/v/My%20clip.mp4?x=1"), "My clip.mp4");
|
||||
assert_eq!(trim_num(23.976, 3), "23.976");
|
||||
assert_eq!(trim_num(48.0, 1), "48");
|
||||
let t: Vec<Track> = json(r#"[{"id":1,"type":"audio","lang":"jpn","codec":"aac","demux-channel-count":6,"demux-samplerate":48000,"selected":true}]"#);
|
||||
assert_eq!(t[0].label(), "Japanese");
|
||||
assert_eq!(t[0].detail(), "AAC · 5.1 · 48 kHz");
|
||||
}
|
||||
}
|
||||
125
src/script.rs
Normal file
125
src/script.rs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
//! A tiny driver for smoke tests and screenshots: `QUINCE_SCRIPT` names a file of steps, one per line:
|
||||
//! `wait 1.5`, `move x y`, `click x y`, `rclick x y`, `dclick x y`, `key Space`, `text a`, `shot name`, `quit`.
|
||||
//! Pointer and key events are pushed into egui's input; `shot` saves the window to `QUINCE_SHOTS/<name>.png`.
|
||||
|
||||
use eframe::egui::{self, Event, Key, Modifiers, PointerButton, RawInput, pos2};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct Script {
|
||||
steps: Vec<String>,
|
||||
at: usize,
|
||||
wait_until: f64,
|
||||
dir: PathBuf,
|
||||
shot_pending: Option<String>,
|
||||
pos: egui::Pos2,
|
||||
done: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl Script {
|
||||
pub fn from_env() -> Option<Script> {
|
||||
let path = std::env::var_os("QUINCE_SCRIPT")?;
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let dir = std::env::var_os("QUINCE_SHOTS").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
Some(Script { steps: text.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty() && !l.starts_with('#')).collect(), at: 0, wait_until: 0.0, dir, shot_pending: None, pos: pos2(0.0, 0.0), done: Default::default() })
|
||||
}
|
||||
|
||||
pub fn feed(&mut self, ctx: &egui::Context, raw: &mut RawInput) {
|
||||
if self.shot_pending.is_some() && self.done.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
self.shot_pending = None;
|
||||
}
|
||||
let now = raw.time.unwrap_or(0.0);
|
||||
if self.shot_pending.is_some() || now < self.wait_until {
|
||||
return;
|
||||
}
|
||||
while let Some(step) = self.steps.get(self.at).cloned() {
|
||||
self.at += 1;
|
||||
let w: Vec<&str> = step.split_whitespace().collect();
|
||||
let num = |i: usize| w.get(i).and_then(|s| s.parse::<f32>().ok()).unwrap_or(0.0);
|
||||
match w[0] {
|
||||
"wait" => {
|
||||
self.wait_until = now + num(1) as f64;
|
||||
return;
|
||||
}
|
||||
"move" => {
|
||||
self.pos = pos2(num(1), num(2));
|
||||
raw.events.push(Event::PointerMoved(self.pos));
|
||||
self.wait_until = now + 0.05;
|
||||
return;
|
||||
}
|
||||
"click" | "rclick" | "dclick" => {
|
||||
self.pos = pos2(num(1), num(2));
|
||||
let button = if w[0] == "rclick" { PointerButton::Secondary } else { PointerButton::Primary };
|
||||
raw.events.push(Event::PointerMoved(self.pos));
|
||||
let times = if w[0] == "dclick" { 2 } else { 1 };
|
||||
for _ in 0..times {
|
||||
raw.events.push(Event::PointerButton { pos: self.pos, button, pressed: true, modifiers: Modifiers::NONE });
|
||||
raw.events.push(Event::PointerButton { pos: self.pos, button, pressed: false, modifiers: Modifiers::NONE });
|
||||
}
|
||||
self.wait_until = now + 0.1;
|
||||
return;
|
||||
}
|
||||
"press" => {
|
||||
self.pos = pos2(num(1), num(2));
|
||||
raw.events.push(Event::PointerMoved(self.pos));
|
||||
raw.events.push(Event::PointerButton { pos: self.pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
self.wait_until = now + 0.05;
|
||||
return;
|
||||
}
|
||||
"release" => {
|
||||
raw.events.push(Event::PointerButton { pos: self.pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
}
|
||||
"key" => {
|
||||
let mut mods = Modifiers::NONE;
|
||||
let mut name = w.get(1).copied().unwrap_or("");
|
||||
if let Some(rest) = name.strip_prefix("Ctrl+") {
|
||||
mods = Modifiers::COMMAND;
|
||||
name = rest;
|
||||
} else if let Some(rest) = name.strip_prefix("Shift+") {
|
||||
mods = Modifiers::SHIFT;
|
||||
name = rest;
|
||||
}
|
||||
if let Some(key) = Key::from_name(name) {
|
||||
raw.events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods });
|
||||
if name.chars().count() == 1 && mods.is_none() {
|
||||
raw.events.push(Event::Text(name.to_lowercase()));
|
||||
} else if name == "Space" {
|
||||
raw.events.push(Event::Text(" ".into()));
|
||||
}
|
||||
raw.events.push(Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: mods });
|
||||
}
|
||||
self.wait_until = now + 0.1;
|
||||
return;
|
||||
}
|
||||
"text" => raw.events.push(Event::Text(w[1..].join(" "))),
|
||||
"shot" => {
|
||||
let name = w.get(1).unwrap_or(&"shot").to_string();
|
||||
self.shot_pending = Some(name.clone());
|
||||
self.done.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let (done, file, c2) = (self.done.clone(), self.dir.join(format!("{name}.png")), ctx.clone());
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::ScreenshotCallback::new(move |image| {
|
||||
let [w, h] = image.size;
|
||||
let bytes: Vec<u8> = image.pixels.iter().flat_map(|c| c.to_array()).collect();
|
||||
if let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, bytes) {
|
||||
let _ = img.save(&file);
|
||||
}
|
||||
done.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
c2.request_repaint();
|
||||
})));
|
||||
return;
|
||||
}
|
||||
"quit" => {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn after_frame(&mut self, ctx: &egui::Context, _state: Option<&crate::mpv::State>) {
|
||||
// keep the steps going while the app itself is still, but leave a wait's frames to the app
|
||||
let now = ctx.input(|i| i.time);
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64((self.wait_until - now).max(0.05)));
|
||||
}
|
||||
}
|
||||
205
src/shape.rs
Normal file
205
src/shape.rs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
//! M3 Expressive shapes as polar outlines: circle, square, pill, cookies, clover, burst, pentagon, triangle, blob.
|
||||
//! Morph between them, spin them, fill them with a colour or clip a texture (cover art) into them. (From Mulberry
|
||||
//! `ui/shape.rs`; Medlar `ui/shape.rs` has a point-pair version that can also become a tick.)
|
||||
//!
|
||||
//! Uses: the loading indicator (`Morpher` cycling through `LOADING`), covers and avatars, empty-state pictures, the play
|
||||
//! button that turns into a cookie while playing, a blob that reacts to the music.
|
||||
|
||||
use crate::motion::{self, Motion, Spring};
|
||||
use crate::tokens::spring::{DEFAULT, FAST};
|
||||
use eframe::egui::{Color32, Mesh, Painter, Pos2, Rect, TextureId, Vec2, pos2};
|
||||
use std::f32::consts::{PI, TAU};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// Points round an outline.
|
||||
pub const N: usize = 120;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Form {
|
||||
Circle,
|
||||
Square,
|
||||
Pill,
|
||||
Triangle,
|
||||
Pentagon,
|
||||
Clover,
|
||||
Burst,
|
||||
Cookie4,
|
||||
Cookie6,
|
||||
Cookie9,
|
||||
Cookie12,
|
||||
Blob,
|
||||
}
|
||||
|
||||
impl Form {
|
||||
pub const ALL: [Form; 12] = [
|
||||
Form::Circle, Form::Square, Form::Pill, Form::Triangle, Form::Pentagon, Form::Clover,
|
||||
Form::Burst, Form::Cookie4, Form::Cookie6, Form::Cookie9, Form::Cookie12, Form::Blob,
|
||||
];
|
||||
/// What the loading indicator goes through.
|
||||
pub const LOADING: [Form; 6] = [Form::Cookie9, Form::Pentagon, Form::Pill, Form::Burst, Form::Cookie6, Form::Clover];
|
||||
|
||||
/// Radii at `N` evenly spaced angles, mean 1.
|
||||
pub fn radii(self) -> &'static [f32; N] {
|
||||
static ALL: LazyLock<Vec<[f32; N]>> = LazyLock::new(|| Form::ALL.iter().map(|f| f.make()).collect());
|
||||
&ALL[Form::ALL.iter().position(|f| *f == self).unwrap_or(0)]
|
||||
}
|
||||
|
||||
fn make(self) -> [f32; N] {
|
||||
let at = |i: usize| i as f32 / N as f32 * TAU;
|
||||
let cookie = |amp: f32, k: f32| std::array::from_fn(|i| 1.0 + amp * (k * at(i)).cos());
|
||||
let polygon = |k: f32, round: f32| -> [f32; N] {
|
||||
let seg = TAU / k;
|
||||
let raw: [f32; N] = std::array::from_fn(|i| (PI / k).cos() / ((at(i) % seg) - PI / k).cos());
|
||||
let mean = raw.iter().sum::<f32>() / N as f32;
|
||||
raw.map(|r| r * (1.0 - round) + round * mean)
|
||||
};
|
||||
let r: [f32; N] = match self {
|
||||
Form::Circle => [1.0; N],
|
||||
Form::Square => std::array::from_fn(|i| {
|
||||
let n = 4.2;
|
||||
(at(i).cos().abs().powf(n) + at(i).sin().abs().powf(n)).powf(-1.0 / n)
|
||||
}),
|
||||
Form::Pill => std::array::from_fn(|i| 1.0 / ((at(i).cos()).powi(2) + (at(i).sin() / 0.74).powi(2)).sqrt()),
|
||||
Form::Triangle => polygon(3.0, 0.55),
|
||||
Form::Pentagon => polygon(5.0, 0.45),
|
||||
Form::Clover => std::array::from_fn(|i| 1.0 + 0.26 * (2.0 * at(i)).cos().abs()),
|
||||
Form::Burst => cookie(0.1, 8.0),
|
||||
Form::Cookie4 => cookie(0.13, 4.0),
|
||||
Form::Cookie6 => cookie(0.09, 6.0),
|
||||
Form::Cookie9 => cookie(0.065, 9.0),
|
||||
Form::Cookie12 => cookie(0.05, 12.0),
|
||||
Form::Blob => std::array::from_fn(|i| 1.0 + 0.08 * (3.0 * at(i) + 1.1).cos() + 0.05 * (5.0 * at(i) + 2.3).cos()),
|
||||
};
|
||||
let mean = r.iter().sum::<f32>() / N as f32;
|
||||
r.map(|x| x / mean)
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape on its way from one form to another, with its own rotation and size kick.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Morpher {
|
||||
from: [f32; N],
|
||||
to: Form,
|
||||
t: Spring,
|
||||
pub rotation: Spring,
|
||||
/// Extra scale from kicks (beats, clicks), springs back to 0.
|
||||
pub kick: Spring,
|
||||
}
|
||||
|
||||
impl Morpher {
|
||||
pub fn new(form: Form) -> Morpher {
|
||||
Morpher { from: *form.radii(), to: form, t: Spring::new(1.0), rotation: Spring::new(0.0), kick: Spring::new(0.0) }
|
||||
}
|
||||
|
||||
pub fn form(&self) -> Form {
|
||||
self.to
|
||||
}
|
||||
|
||||
/// Starts morphing to `form` from wherever the outline is now, and turns it a little on the way.
|
||||
pub fn morph_to(&mut self, form: Form) {
|
||||
if form == self.to {
|
||||
return;
|
||||
}
|
||||
self.from = self.radii_now();
|
||||
self.to = form;
|
||||
self.t = Spring { target: 1.0, ..Spring::new(0.0) };
|
||||
self.rotation.target += 0.6;
|
||||
}
|
||||
|
||||
/// A shove for a hit: the shape swells and springs back.
|
||||
pub fn hit(&mut self, strength: f32) {
|
||||
if motion::level() != Motion::Off {
|
||||
self.kick.v += 2.0 + 3.0 * strength;
|
||||
self.kick.x += 0.0001;
|
||||
motion::keep_alive();
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame on.
|
||||
pub fn step(&mut self) {
|
||||
self.t.step(DEFAULT);
|
||||
self.rotation.step(DEFAULT);
|
||||
self.kick.target = 0.0;
|
||||
self.kick.step(FAST);
|
||||
}
|
||||
|
||||
fn radii_now(&self) -> [f32; N] {
|
||||
let (a, b, k) = (&self.from, self.to.radii(), self.t.x);
|
||||
std::array::from_fn(|i| a[i] + (b[i] - a[i]) * k)
|
||||
}
|
||||
|
||||
/// The outline round `c` with mean radius `r`.
|
||||
pub fn points(&self, c: Pos2, r: f32) -> Vec<Pos2> {
|
||||
let radii = self.radii_now();
|
||||
let scale = r * (1.0 + 0.12 * self.kick.x.max(-0.5));
|
||||
(0..N).map(|i| c + Vec2::angled(i as f32 / N as f32 * TAU + self.rotation.x) * radii[i] * scale).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills an outline (from `Morpher::points` or `outline`) as a fan from its centre: fine for every form above, which are
|
||||
/// all star-shaped round the centre.
|
||||
pub fn fill(p: &Painter, c: Pos2, pts: &[Pos2], color: Color32) {
|
||||
let mut m = Mesh::default();
|
||||
m.colored_vertex(c, color);
|
||||
for q in pts {
|
||||
m.colored_vertex(*q, color);
|
||||
}
|
||||
let n = pts.len() as u32;
|
||||
for i in 0..n {
|
||||
m.add_triangle(0, 1 + i, 1 + (i + 1) % n);
|
||||
}
|
||||
p.add(m);
|
||||
}
|
||||
|
||||
/// Clips a texture (cover art, a thumbnail) into the outline: the square `rect` of the texture maps onto the outline's
|
||||
/// bounding square, so the image isn't stretched.
|
||||
pub fn fill_texture(p: &Painter, c: Pos2, r_box: f32, pts: &[Pos2], tex: TextureId, tint: Color32) {
|
||||
let mut m = Mesh::with_texture(tex);
|
||||
let uv = |q: Pos2| pos2(0.5 + (q.x - c.x) / (2.0 * r_box), 0.5 + (q.y - c.y) / (2.0 * r_box));
|
||||
m.vertices.push(eframe::egui::epaint::Vertex { pos: c, uv: uv(c), color: tint });
|
||||
for q in pts {
|
||||
m.vertices.push(eframe::egui::epaint::Vertex { pos: *q, uv: uv(*q), color: tint });
|
||||
}
|
||||
let n = pts.len() as u32;
|
||||
for i in 0..n {
|
||||
m.add_triangle(0, 1 + i, 1 + (i + 1) % n);
|
||||
}
|
||||
p.add(m);
|
||||
}
|
||||
|
||||
/// The still outline of a form, for when no morph is needed.
|
||||
pub fn outline(form: Form, c: Pos2, r: f32, rotation: f32) -> Vec<Pos2> {
|
||||
let radii = form.radii();
|
||||
(0..N).map(|i| c + Vec2::angled(i as f32 / N as f32 * TAU + rotation) * radii[i] * r).collect()
|
||||
}
|
||||
|
||||
/// Dots just outside an outline, like the ring round Mulberry's cover. `levels` (0..1 each, for example a spectrum)
|
||||
/// push each dot outwards; pass an empty slice for a still ring.
|
||||
pub fn dot_ring(p: &Painter, c: Pos2, pts: &[Pos2], dots: usize, gap: f32, radius: f32, levels: &[f32], color: Color32) {
|
||||
for k in 0..dots {
|
||||
let q = pts[k * pts.len() / dots.max(1)];
|
||||
let out = (q - c).normalized();
|
||||
let lift = levels.get(k * levels.len().max(1) / dots.max(1)).copied().unwrap_or(0.0) * gap * 2.0;
|
||||
p.circle_filled(q + out * (gap + lift), radius, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// A loading indicator in `rect`: a shape that morphs through `Form::LOADING` and turns. Draws nothing for the first
|
||||
/// 300 ms of waiting (`since` = seconds waited). Under Off it is a still cookie.
|
||||
pub fn loading(p: &Painter, m: &mut Morpher, rect: Rect, since: f32, color: Color32) {
|
||||
if since < 0.3 {
|
||||
motion::keep_alive();
|
||||
return;
|
||||
}
|
||||
if motion::level() != Motion::Off {
|
||||
let step = ((since - 0.3) / 0.65) as usize;
|
||||
let next = Form::LOADING[step % Form::LOADING.len()];
|
||||
m.morph_to(next);
|
||||
m.rotation.target += motion::dt() * 2.4;
|
||||
m.step();
|
||||
motion::keep_alive();
|
||||
}
|
||||
let c = rect.center();
|
||||
let pts = m.points(c, rect.width().min(rect.height()) * 0.38);
|
||||
fill(p, c, &pts, color);
|
||||
}
|
||||
562
src/theme.rs
Normal file
562
src/theme.rs
Normal file
|
|
@ -0,0 +1,562 @@
|
|||
//! Material You colour roles, built from a seed in OKLCH space (tone == CIE L*). (From Medlar, Damson and Mulberry.)
|
||||
//!
|
||||
//! Every text role reaches the contrast level's ratio on every surface it may sit on: `fit` moves its tone until it does.
|
||||
//! Seeds come from the user's own colour, the desktop (`desktop_seed`) or an image (`art_seed`).
|
||||
|
||||
use crate::motion::Motion;
|
||||
use crate::tokens;
|
||||
use eframe::egui::{self, Color32, Stroke};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// How colourful the scheme is. Store as a word in the config.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Scheme {
|
||||
#[default]
|
||||
Tonal,
|
||||
Vibrant,
|
||||
Expressive,
|
||||
Mono,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Contrast {
|
||||
#[default]
|
||||
Standard,
|
||||
Medium,
|
||||
High,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Appearance {
|
||||
/// Follow the desktop, dark when it doesn't say.
|
||||
#[default]
|
||||
Auto,
|
||||
Light,
|
||||
Dark,
|
||||
/// Dark with black surfaces.
|
||||
Amoled,
|
||||
}
|
||||
|
||||
fn srgb_to_lin(c: f64) -> f64 {
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
fn lin_to_srgb(c: f64) -> f64 {
|
||||
if c <= 0.0031308 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
fn lin(c: Color32) -> [f64; 3] {
|
||||
[c.r(), c.g(), c.b()].map(|x| srgb_to_lin(x as f64 / 255.0))
|
||||
}
|
||||
|
||||
fn oklch_of(c: Color32) -> (f64, f64, f64) {
|
||||
let [r, g, b] = lin(c);
|
||||
let l = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b).cbrt();
|
||||
let m = (0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b).cbrt();
|
||||
let s = (0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b).cbrt();
|
||||
let ll = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
|
||||
let a = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
|
||||
let bb = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
|
||||
(ll, a.hypot(bb), bb.atan2(a).to_degrees().rem_euclid(360.0))
|
||||
}
|
||||
|
||||
/// 0 black, 1 white, as the eye sees it.
|
||||
pub fn lightness(c: Color32) -> f64 {
|
||||
oklch_of(c).0
|
||||
}
|
||||
|
||||
fn oklch_to_lin(l: f64, c: f64, h: f64) -> [f64; 3] {
|
||||
let (a, b) = (c * h.to_radians().cos(), c * h.to_radians().sin());
|
||||
let l_ = (l + 0.3963377774 * a + 0.2158037573 * b).powi(3);
|
||||
let m_ = (l - 0.1055613458 * a - 0.0638541728 * b).powi(3);
|
||||
let s_ = (l - 0.0894841775 * a - 1.2914855480 * b).powi(3);
|
||||
[
|
||||
4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,
|
||||
-1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,
|
||||
-0.0041960863 * l_ - 0.7034186147 * m_ + 1.7076147010 * s_,
|
||||
]
|
||||
}
|
||||
|
||||
/// The colour, with less chroma where the screen can't show it.
|
||||
fn oklch(l: f64, c: f64, h: f64) -> Color32 {
|
||||
let in_gamut = |rgb: [f64; 3]| rgb.iter().all(|v| (-1e-4..=1.0001).contains(v));
|
||||
let mut rgb = oklch_to_lin(l, c, h);
|
||||
if !in_gamut(rgb) {
|
||||
let (mut lo, mut hi) = (0.0, c);
|
||||
for _ in 0..18 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if in_gamut(oklch_to_lin(l, mid, h)) { lo = mid } else { hi = mid }
|
||||
}
|
||||
rgb = oklch_to_lin(l, lo, h);
|
||||
}
|
||||
let [r, g, b] = rgb.map(|x| (lin_to_srgb(x.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
Color32::from_rgb(r, g, b)
|
||||
}
|
||||
|
||||
/// Hue in degrees and colourfulness of a seed.
|
||||
pub fn hue_of(c: Color32) -> (f64, f64) {
|
||||
let (_, chroma, hue) = oklch_of(c);
|
||||
(hue, chroma)
|
||||
}
|
||||
|
||||
/// A seed of this hue and colourfulness.
|
||||
pub fn seed(hue: f64, chroma: f64) -> Color32 {
|
||||
oklch(0.62, chroma, hue)
|
||||
}
|
||||
|
||||
fn luminance(c: Color32) -> f64 {
|
||||
let [r, g, b] = lin(c);
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/// WCAG contrast ratio, 1 to 21.
|
||||
pub fn contrast(a: Color32, b: Color32) -> f64 {
|
||||
let (x, y) = (luminance(a), luminance(b));
|
||||
(x.max(y) + 0.05) / (x.min(y) + 0.05)
|
||||
}
|
||||
|
||||
pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
let l = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round() as u8;
|
||||
Color32::from_rgba_premultiplied(l(a.r(), b.r()), l(a.g(), b.g()), l(a.b(), b.b()), l(a.a(), b.a()))
|
||||
}
|
||||
|
||||
pub fn alpha(c: Color32, a: f32) -> Color32 {
|
||||
c.gamma_multiply(a.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// `#rrggbb` or `rrggbb`.
|
||||
pub fn hex(s: &str) -> Option<Color32> {
|
||||
let s = s.trim().trim_start_matches('#');
|
||||
if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let v = u32::from_str_radix(s, 16).ok()?;
|
||||
Some(Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Tonal {
|
||||
h: f64,
|
||||
c: f64,
|
||||
}
|
||||
|
||||
impl Tonal {
|
||||
fn at(self, tone: f64) -> Color32 {
|
||||
let l = if tone <= 8.0 { (tone / 903.2963).cbrt() } else { (tone + 16.0) / 116.0 };
|
||||
oklch(l, self.c, self.h)
|
||||
}
|
||||
|
||||
/// `tone`, or the nearest one further from the backgrounds that reaches `ratio` on all of them.
|
||||
fn fit(self, tone: f64, dark_ground: bool, grounds: &[Color32], ratio: f64) -> Color32 {
|
||||
let step = if dark_ground { 1.0 } else { -1.0 };
|
||||
let mut t = tone;
|
||||
loop {
|
||||
let c = self.at(t);
|
||||
if grounds.iter().all(|g| contrast(c, *g) >= ratio) || !(0.0..=100.0).contains(&(t + step)) {
|
||||
return c;
|
||||
}
|
||||
t += step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Theme {
|
||||
pub dark: bool,
|
||||
pub primary: Color32,
|
||||
pub on_primary: Color32,
|
||||
pub primary_container: Color32,
|
||||
pub on_primary_container: Color32,
|
||||
pub secondary: Color32,
|
||||
pub on_secondary: Color32,
|
||||
pub secondary_container: Color32,
|
||||
pub on_secondary_container: Color32,
|
||||
pub tertiary: Color32,
|
||||
pub on_tertiary: Color32,
|
||||
pub tertiary_container: Color32,
|
||||
pub on_tertiary_container: Color32,
|
||||
pub error: Color32,
|
||||
pub on_error: Color32,
|
||||
pub error_container: Color32,
|
||||
pub on_error_container: Color32,
|
||||
/// Finished and checked.
|
||||
pub success: Color32,
|
||||
/// Slowed down, or needs a look.
|
||||
pub warning: Color32,
|
||||
pub surface: Color32,
|
||||
pub lowest: Color32,
|
||||
pub low: Color32,
|
||||
pub container: Color32,
|
||||
pub high: Color32,
|
||||
pub highest: Color32,
|
||||
pub on_surface: Color32,
|
||||
/// Second lines, hints and icons at rest.
|
||||
pub on_variant: Color32,
|
||||
/// Borders that must be seen.
|
||||
pub outline: Color32,
|
||||
/// Hairlines between things.
|
||||
pub outline_variant: Color32,
|
||||
/// Toasts.
|
||||
pub inverse_surface: Color32,
|
||||
pub inverse_on_surface: Color32,
|
||||
pub inverse_primary: Color32,
|
||||
}
|
||||
|
||||
impl Theme {
|
||||
/// D-012: the desktop's colour or the user's own; undecided means the desktop's when it has one.
|
||||
/// The theme for these choices. `seed` is already picked (own colour, desktop or artwork); `desktop_dark` is what
|
||||
/// the desktop says, if anything.
|
||||
pub fn build(seed: Color32, appearance: Appearance, desktop_dark: Option<bool>, scheme: Scheme, level: Contrast) -> Theme {
|
||||
let dark = match appearance {
|
||||
Appearance::Auto => desktop_dark.unwrap_or(true),
|
||||
Appearance::Light => false,
|
||||
Appearance::Dark | Appearance::Amoled => true,
|
||||
};
|
||||
Theme::from_seed(seed, dark, appearance == Appearance::Amoled, scheme, level)
|
||||
}
|
||||
|
||||
pub fn from_seed(seed: Color32, dark: bool, amoled: bool, scheme: Scheme, level: Contrast) -> Theme {
|
||||
let (_, sc, h) = oklch_of(seed);
|
||||
// A grey seed has no hue worth boosting.
|
||||
let scheme = if sc < 0.02 { Scheme::Mono } else { scheme };
|
||||
let (pc, sec_c, ter_c, ter_shift, neutral_c) = match scheme {
|
||||
Scheme::Tonal => (sc.clamp(0.085, 0.15), 0.04, 0.075, 60.0, 0.014),
|
||||
Scheme::Vibrant => (sc.clamp(0.13, 0.19), 0.08, 0.11, 45.0, 0.022),
|
||||
Scheme::Expressive => (sc.clamp(0.10, 0.16), 0.07, 0.12, 130.0, 0.026),
|
||||
Scheme::Mono => (0.012, 0.008, 0.012, 0.0, 0.004),
|
||||
};
|
||||
let p = Tonal { h, c: pc };
|
||||
let sec = Tonal { h, c: sec_c };
|
||||
let ter = Tonal { h: (h + ter_shift) % 360.0, c: ter_c };
|
||||
let err = Tonal { h: 25.0, c: 0.17 };
|
||||
let good = Tonal { h: 150.0, c: 0.13 };
|
||||
let warn = Tonal { h: 75.0, c: 0.13 };
|
||||
let n = Tonal { h, c: neutral_c };
|
||||
let nv = Tonal { h, c: (neutral_c * 1.8).max(if scheme == Scheme::Mono { 0.004 } else { 0.016 }) };
|
||||
// Lowest ratio of text, and of borders and icons.
|
||||
let (text, line) = match level {
|
||||
Contrast::Standard => (4.5, 3.0),
|
||||
Contrast::Medium => (7.0, 4.5),
|
||||
Contrast::High => (10.0, 7.0),
|
||||
};
|
||||
let hairline = if level == Contrast::High { 3.0 } else { 1.0 };
|
||||
let d = |dk: f64, lt: f64| if dark { dk } else { lt };
|
||||
|
||||
let surfaces = match (dark, amoled) {
|
||||
(true, true) => [0.0, 0.0, 5.0, 8.0, 12.0, 17.0],
|
||||
(true, false) => [6.0, 4.0, 10.0, 12.0, 17.0, 22.0],
|
||||
(false, _) => [98.0, 100.0, 96.0, 94.0, 92.0, 90.0],
|
||||
}
|
||||
.map(|t| n.at(t));
|
||||
let [surface, lowest, low, container, high, highest] = surfaces;
|
||||
let on = |t: Tonal, dk: f64, lt: f64, ratio: f64| t.fit(d(dk, lt), dark, &surfaces, ratio);
|
||||
let accent = |t: Tonal| {
|
||||
let c = on(t, 80.0, 40.0, text);
|
||||
(c, t.fit(d(20.0, 100.0), !dark, &[c], text))
|
||||
};
|
||||
let (primary, on_primary) = accent(p);
|
||||
let (secondary, on_secondary) = accent(sec);
|
||||
let (tertiary, on_tertiary) = accent(ter);
|
||||
let (error, on_error) = accent(err);
|
||||
let boxed = |t: Tonal| {
|
||||
let c = t.at(d(30.0, 90.0));
|
||||
(c, t.fit(d(90.0, 10.0), dark, &[c], text))
|
||||
};
|
||||
let (primary_container, on_primary_container) = boxed(p);
|
||||
let (secondary_container, on_secondary_container) = boxed(sec);
|
||||
let (tertiary_container, on_tertiary_container) = boxed(ter);
|
||||
let (error_container, on_error_container) = boxed(err);
|
||||
let inverse_surface = n.at(d(90.0, 20.0));
|
||||
Theme {
|
||||
dark,
|
||||
primary,
|
||||
on_primary,
|
||||
primary_container,
|
||||
on_primary_container,
|
||||
secondary,
|
||||
on_secondary,
|
||||
secondary_container,
|
||||
on_secondary_container,
|
||||
tertiary,
|
||||
on_tertiary,
|
||||
tertiary_container,
|
||||
on_tertiary_container,
|
||||
error,
|
||||
on_error,
|
||||
error_container,
|
||||
on_error_container,
|
||||
success: on(good, 80.0, 40.0, text),
|
||||
warning: on(warn, 80.0, 40.0, text),
|
||||
surface,
|
||||
lowest,
|
||||
low,
|
||||
container,
|
||||
high,
|
||||
highest,
|
||||
on_surface: on(n, 90.0, 10.0, text),
|
||||
on_variant: on(nv, 80.0, 30.0, text),
|
||||
outline: on(nv, 60.0, 50.0, line),
|
||||
outline_variant: on(nv, 30.0, 80.0, hairline),
|
||||
inverse_surface,
|
||||
inverse_on_surface: n.fit(d(20.0, 95.0), !dark, &[inverse_surface], text),
|
||||
inverse_primary: p.fit(d(40.0, 80.0), !dark, &[inverse_surface], text),
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes egui's own widgets (text fields, menus, tooltips) follow the theme.
|
||||
pub fn apply(&self, ctx: &egui::Context, motion: Motion) {
|
||||
ctx.set_theme(if self.dark { egui::Theme::Dark } else { egui::Theme::Light });
|
||||
ctx.global_style_mut(|s| {
|
||||
let v = &mut s.visuals;
|
||||
*v = if self.dark { egui::Visuals::dark() } else { egui::Visuals::light() };
|
||||
v.override_text_color = Some(self.on_surface);
|
||||
v.weak_text_color = Some(self.on_variant);
|
||||
v.panel_fill = self.surface;
|
||||
v.window_fill = self.container;
|
||||
v.window_stroke = Stroke::NONE;
|
||||
v.window_corner_radius = tokens::radius::XL.into();
|
||||
v.menu_corner_radius = tokens::radius::M.into();
|
||||
v.window_shadow = tokens::elevation::floating(self.dark);
|
||||
v.popup_shadow = v.window_shadow;
|
||||
v.extreme_bg_color = self.lowest;
|
||||
v.faint_bg_color = self.low;
|
||||
v.code_bg_color = self.high;
|
||||
v.hyperlink_color = self.primary;
|
||||
v.error_fg_color = self.error;
|
||||
v.warn_fg_color = self.warning;
|
||||
v.selection.bg_fill = self.primary_container;
|
||||
v.selection.stroke = Stroke::new(1.0, self.on_primary_container);
|
||||
v.text_cursor.stroke = Stroke::new(2.0, self.primary);
|
||||
// A blinking cursor draws frames for as long as a field has focus.
|
||||
v.text_cursor.blink = !matches!(motion, Motion::Off | Motion::Reduced);
|
||||
let w = &mut v.widgets;
|
||||
for (state, fill, line) in [
|
||||
(&mut w.noninteractive, self.surface, self.outline_variant),
|
||||
(&mut w.inactive, self.high, self.outline),
|
||||
(&mut w.hovered, self.highest, self.on_variant),
|
||||
(&mut w.active, self.highest, self.primary),
|
||||
(&mut w.open, self.high, self.outline),
|
||||
] {
|
||||
state.bg_fill = fill;
|
||||
state.weak_bg_fill = fill;
|
||||
state.bg_stroke = Stroke::new(tokens::size::HAIRLINE, line);
|
||||
state.fg_stroke = Stroke::new(1.5, self.on_surface);
|
||||
state.corner_radius = tokens::radius::S.into();
|
||||
state.expansion = 0.0;
|
||||
}
|
||||
s.animation_time = if motion == Motion::Off { 0.0 } else { 0.12 };
|
||||
s.spacing.item_spacing = [tokens::space::S; 2].into();
|
||||
s.spacing.interact_size.y = tokens::size::HIT;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ where seeds come from
|
||||
|
||||
/// The desktop's colour and dark mode, if it shares them: Caelestia's scheme first, then KDE's kdeglobals.
|
||||
/// (The XDG portal's `org.freedesktop.appearance` `accent-color` and `color-scheme` are the other source; read them with
|
||||
/// zbus where the app already depends on it.)
|
||||
pub fn desktop_seed() -> (Option<Color32>, Option<bool>) {
|
||||
if let Some(v) = std::fs::read(caelestia_path()).ok().and_then(|b| serde_json_lite(&b)) {
|
||||
return (Some(v.0), Some(v.1));
|
||||
}
|
||||
kde_accent()
|
||||
}
|
||||
|
||||
/// Paths to watch: when one's modified time changes, call `desktop_seed` again and rebuild the theme.
|
||||
pub fn desktop_sources() -> Vec<PathBuf> {
|
||||
vec![caelestia_path(), config_dir().join("kdeglobals")]
|
||||
}
|
||||
|
||||
fn config_dir() -> PathBuf {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".config"))
|
||||
}
|
||||
|
||||
fn caelestia_path() -> PathBuf {
|
||||
std::env::var_os("XDG_STATE_HOME")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".local/state"))
|
||||
.join("caelestia/scheme.json")
|
||||
}
|
||||
|
||||
/// Reads `"primary": "rrggbb"` inside `"colours"` and `"mode"` from Caelestia's scheme.json without a JSON crate.
|
||||
/// Swap for serde_json if the app has it.
|
||||
fn serde_json_lite(bytes: &[u8]) -> Option<(Color32, bool)> {
|
||||
let s = std::str::from_utf8(bytes).ok()?;
|
||||
let value_after = |from: usize, key: &str| -> Option<String> {
|
||||
let at = from + s[from..].find(&format!("\"{key}\""))?;
|
||||
let rest = &s[at + key.len() + 2..];
|
||||
let start = rest.find('"')? + 1;
|
||||
let end = start + rest[start..].find('"')?;
|
||||
Some(rest[start..end].to_string())
|
||||
};
|
||||
let colours = s.find("\"colours\"")?;
|
||||
let seed = hex(&value_after(colours, "primary")?)?;
|
||||
let dark = value_after(0, "mode").as_deref() != Some("light");
|
||||
Some((seed, dark))
|
||||
}
|
||||
|
||||
fn kde_accent() -> (Option<Color32>, Option<bool>) {
|
||||
let Ok(txt) = std::fs::read_to_string(config_dir().join("kdeglobals")) else { return (None, None) };
|
||||
let parse = |v: &str| -> Option<Color32> {
|
||||
let p: Vec<u8> = v.split(',').take(3).filter_map(|x| x.trim().parse().ok()).collect();
|
||||
if p.len() == 3 { Some(Color32::from_rgb(p[0], p[1], p[2])) } else { hex(v) }
|
||||
};
|
||||
let (mut sec, mut accent, mut sel, mut win) = (String::new(), None, None, None);
|
||||
for line in txt.lines() {
|
||||
let line = line.trim();
|
||||
if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
sec = s.to_string();
|
||||
} else if let Some((k, v)) = line.split_once('=') {
|
||||
match (sec.as_str(), k.trim()) {
|
||||
("General", "AccentColor") => accent = parse(v),
|
||||
("Colors:Selection", "BackgroundNormal") => sel = parse(v),
|
||||
("Colors:Window", "BackgroundNormal") => win = parse(v),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
(accent.or(sel), win.map(|w| lightness(w) < 0.6))
|
||||
}
|
||||
|
||||
/// Colour spotting: a vivid seed that represents an image (album art, a video frame, a wallpaper), or None when it is
|
||||
/// all greys. `rgba` is 8-bit RGBA, `width` × `height`. Downscale big images first (48×48 is plenty); run it off the UI
|
||||
/// thread and cache the result. (From Mulberry's `dominant_color`.)
|
||||
pub fn art_seed(rgba: &[u8], width: usize, height: usize) -> Option<Color32> {
|
||||
if width == 0 || height == 0 || rgba.len() < width * height * 4 {
|
||||
return None;
|
||||
}
|
||||
// Look at about 48×48 pixels whatever the size.
|
||||
let step = ((width * height) as f64 / 2304.0).sqrt().max(1.0) as usize;
|
||||
let mut bins = [[0.0f64; 4]; 24];
|
||||
let mut any = false;
|
||||
for y in (0..height).step_by(step) {
|
||||
for x in (0..width).step_by(step) {
|
||||
let i = (y * width + x) * 4;
|
||||
if rgba[i + 3] < 128 {
|
||||
continue;
|
||||
}
|
||||
let (l, c, h) = oklch_of(Color32::from_rgb(rgba[i], rgba[i + 1], rgba[i + 2]));
|
||||
if c < 0.03 || !(0.2..=0.95).contains(&l) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
// Vivid pixels count far more than big dull areas.
|
||||
let w = c * c;
|
||||
let b = &mut bins[((h / 15.0) as usize).min(23)];
|
||||
b[0] += w;
|
||||
b[1] += h.to_radians().cos() * w;
|
||||
b[2] += h.to_radians().sin() * w;
|
||||
b[3] += c * w;
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
let best = bins.iter().max_by(|a, b| a[0].total_cmp(&b[0]))?;
|
||||
let hue = best[2].atan2(best[1]).to_degrees().rem_euclid(360.0);
|
||||
Some(oklch(0.65, (best[3] / best[0]).max(0.1), hue))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SEEDS: [&str; 12] = [
|
||||
"#b5622b", "#7f5fc4", "#d0485e", "#3f9c6b", "#c8a020", "#2b7fd4", "#f5b2e1", "#00ffff", "#ffff00", "#0000ff", "#000000",
|
||||
"#808080",
|
||||
];
|
||||
|
||||
fn every_theme(mut check: impl FnMut(&Theme, Contrast, &str)) {
|
||||
for seed in SEEDS {
|
||||
for (dark, amoled) in [(false, false), (true, false), (true, true)] {
|
||||
for scheme in [Scheme::Tonal, Scheme::Vibrant, Scheme::Expressive, Scheme::Mono] {
|
||||
for level in [Contrast::Standard, Contrast::Medium, Contrast::High] {
|
||||
let t = Theme::from_seed(hex(seed).unwrap(), dark, amoled, scheme, level);
|
||||
check(&t, level, &format!("{seed} dark={dark} amoled={amoled} {scheme:?} {level:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_and_icons_are_readable_in_every_mode() {
|
||||
every_theme(|t, level, name| {
|
||||
let (text, icon) = match level {
|
||||
Contrast::Standard => (4.5, 3.0),
|
||||
Contrast::Medium => (7.0, 4.5),
|
||||
Contrast::High => (10.0, 7.0),
|
||||
};
|
||||
let surfaces = [t.surface, t.lowest, t.low, t.container, t.high, t.highest];
|
||||
for (role, c, least) in [
|
||||
("on_surface", t.on_surface, text),
|
||||
("on_variant", t.on_variant, text),
|
||||
("primary", t.primary, text),
|
||||
("secondary", t.secondary, text),
|
||||
("tertiary", t.tertiary, text),
|
||||
("error", t.error, text),
|
||||
("success", t.success, text),
|
||||
("warning", t.warning, text),
|
||||
("outline", t.outline, icon),
|
||||
] {
|
||||
for (i, ground) in surfaces.iter().enumerate() {
|
||||
let c = contrast(c, *ground);
|
||||
assert!(c >= least, "{name}: {role} on surface {i} is {c:.2}");
|
||||
}
|
||||
}
|
||||
for (role, c, ground) in [
|
||||
("on_primary", t.on_primary, t.primary),
|
||||
("on_secondary", t.on_secondary, t.secondary),
|
||||
("on_tertiary", t.on_tertiary, t.tertiary),
|
||||
("on_error", t.on_error, t.error),
|
||||
("on_primary_container", t.on_primary_container, t.primary_container),
|
||||
("on_secondary_container", t.on_secondary_container, t.secondary_container),
|
||||
("on_tertiary_container", t.on_tertiary_container, t.tertiary_container),
|
||||
("on_error_container", t.on_error_container, t.error_container),
|
||||
("inverse_on_surface", t.inverse_on_surface, t.inverse_surface),
|
||||
("inverse_primary", t.inverse_primary, t.inverse_surface),
|
||||
] {
|
||||
let c = contrast(c, ground);
|
||||
// What stands on a colour reaches at least 7, even at the high level.
|
||||
assert!(c >= text.min(7.0), "{name}: {role} is {c:.2}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surfaces_step_the_right_way_and_amoled_is_black() {
|
||||
every_theme(|t, _, name| {
|
||||
let steps = [t.surface, t.low, t.container, t.high, t.highest].map(luminance);
|
||||
let ok = if t.dark { steps.is_sorted() } else { steps.iter().rev().is_sorted() };
|
||||
assert!(ok, "{name}");
|
||||
});
|
||||
let t = Theme::from_seed(hex("#b5622b").unwrap(), true, true, Scheme::Tonal, Contrast::Standard);
|
||||
assert_eq!(t.surface, Color32::BLACK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_seed_finds_the_vivid_colour() {
|
||||
// Mostly grey with a red patch: red wins.
|
||||
let mut px = vec![128u8; 64 * 64 * 4];
|
||||
for i in 0..64 * 8 {
|
||||
px[i * 4..i * 4 + 4].copy_from_slice(&[200, 40, 40, 255]);
|
||||
}
|
||||
let (h, _) = hue_of(art_seed(&px, 64, 64).unwrap());
|
||||
assert!(!(60.0..340.0).contains(&h), "hue {h}");
|
||||
assert_eq!(art_seed(&[128u8; 16 * 16 * 4], 16, 16), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_takes_only_colours() {
|
||||
assert_eq!(hex(" #0a0B0c "), Some(Color32::from_rgb(10, 11, 12)));
|
||||
for bad in ["", "#fff", "#gggggg", "+12345", "ééé"] {
|
||||
assert_eq!(hex(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
72
src/thumbs.rs
Normal file
72
src/thumbs.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
//! Seek-bar previews: a small frame at the hovered time, cut by ffmpeg on a worker thread, cached per file and per few
|
||||
//! seconds. Local files only; nothing runs while the pointer isn't over the bar.
|
||||
|
||||
use eframe::egui::{self, ColorImage, TextureHandle, TextureOptions};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
|
||||
pub const HEIGHT: u32 = 90;
|
||||
|
||||
pub struct Thumbs {
|
||||
path: String,
|
||||
step: f64,
|
||||
cache: HashMap<u64, Option<TextureHandle>>,
|
||||
asked: Option<u64>,
|
||||
busy: bool,
|
||||
tx: Sender<(String, u64, Option<ColorImage>)>,
|
||||
rx: Receiver<(String, u64, Option<ColorImage>)>,
|
||||
pub available: bool,
|
||||
}
|
||||
|
||||
impl Thumbs {
|
||||
pub fn new() -> Thumbs {
|
||||
let (tx, rx) = channel();
|
||||
let available = std::process::Command::new("ffmpeg").arg("-version").stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().is_ok();
|
||||
Thumbs { path: String::new(), step: 5.0, cache: HashMap::new(), asked: None, busy: false, tx, rx, available }
|
||||
}
|
||||
|
||||
/// A preview near `time` of `path`, if one is ready; asks for it otherwise.
|
||||
pub fn get(&mut self, ctx: &egui::Context, path: &str, duration: f64, time: f64) -> Option<TextureHandle> {
|
||||
if !self.available || path.is_empty() || path.contains("://") || duration <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if path != self.path {
|
||||
self.path = path.to_string();
|
||||
self.cache.clear();
|
||||
self.step = (duration / 200.0).clamp(2.0, 30.0);
|
||||
}
|
||||
while let Ok((p, k, img)) = self.rx.try_recv() {
|
||||
self.busy = false;
|
||||
if p == self.path {
|
||||
let tex = img.map(|i| ctx.load_texture(format!("thumb-{k}"), i, TextureOptions::LINEAR));
|
||||
self.cache.insert(k, tex);
|
||||
}
|
||||
}
|
||||
let key = (time / self.step).floor() as u64;
|
||||
if let Some(t) = self.cache.get(&key) {
|
||||
return t.clone();
|
||||
}
|
||||
if !self.busy && self.asked != Some(key) {
|
||||
self.asked = Some(key);
|
||||
self.busy = true;
|
||||
let (tx, path, at, ctx) = (self.tx.clone(), self.path.clone(), key as f64 * self.step + self.step / 2.0, ctx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let img = grab(&path, at.min(duration - 0.5).max(0.0));
|
||||
let _ = tx.send((path, key, img));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
// the nearest one we have stands in while the right one is cut
|
||||
(0..6u64).find_map(|d| self.cache.get(&key.saturating_sub(d)).cloned().flatten())
|
||||
}
|
||||
}
|
||||
|
||||
fn grab(path: &str, at: f64) -> Option<ColorImage> {
|
||||
let out = std::process::Command::new("nice")
|
||||
.args(["-n", "10", "ffmpeg", "-v", "error", "-nostdin", "-ss", &format!("{at:.2}"), "-i", path, "-frames:v", "1", "-an", "-sn"])
|
||||
.args(["-vf", &format!("scale=-2:{HEIGHT}"), "-f", "image2pipe", "-vcodec", "png", "-"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let img = image::load_from_memory(&out.stdout).ok()?.to_rgba8();
|
||||
Some(ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw()))
|
||||
}
|
||||
129
src/tokens.rs
Normal file
129
src/tokens.rs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
//! The only place for sizes, radii, type, shadows and spring presets. Colours are in `theme`. (From Medlar.)
|
||||
|
||||
/// Gaps and padding, on a 4 px grid.
|
||||
pub mod space {
|
||||
pub const XS: f32 = 4.0;
|
||||
pub const S: f32 = 8.0;
|
||||
pub const M: f32 = 12.0;
|
||||
pub const L: f32 = 16.0;
|
||||
pub const XL: f32 = 24.0;
|
||||
pub const XXL: f32 = 32.0;
|
||||
}
|
||||
|
||||
/// Corner radii. A shape inside another takes `inner(outer, padding)` so the corners stay concentric.
|
||||
pub mod radius {
|
||||
pub const XS: f32 = 4.0;
|
||||
pub const S: f32 = 8.0;
|
||||
pub const M: f32 = 12.0;
|
||||
pub const L: f32 = 16.0;
|
||||
pub const XL: f32 = 28.0;
|
||||
/// Clamped to half the height by egui.
|
||||
pub const FULL: f32 = 255.0;
|
||||
|
||||
pub fn inner(outer: f32, padding: f32) -> f32 {
|
||||
(outer - padding).max(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Text sizes. Weight comes from `fonts::{ui, med, semi}`. Digits are tabular in every weight.
|
||||
pub mod text {
|
||||
pub const LABEL: f32 = 12.0;
|
||||
pub const BODY: f32 = 14.0;
|
||||
pub const TITLE: f32 = 18.0;
|
||||
pub const HEADLINE: f32 = 24.0;
|
||||
/// Only for the big speed number.
|
||||
pub const DISPLAY: f32 = 45.0;
|
||||
}
|
||||
|
||||
/// Drawn icon sizes.
|
||||
pub mod icon {
|
||||
pub const S: f32 = 16.0;
|
||||
pub const M: f32 = 20.0;
|
||||
pub const L: f32 = 24.0;
|
||||
pub const XL: f32 = 40.0;
|
||||
/// An empty state's picture.
|
||||
pub const HERO: f32 = 96.0;
|
||||
pub const ALL: [f32; 5] = [S, M, L, XL, HERO];
|
||||
}
|
||||
|
||||
/// Control sizes.
|
||||
pub mod size {
|
||||
/// Smallest thing that can be clicked.
|
||||
pub const HIT: f32 = 32.0;
|
||||
pub const CONTROL: f32 = 40.0;
|
||||
pub const HAIRLINE: f32 = 1.0;
|
||||
pub const FOCUS_RING: f32 = 2.0;
|
||||
/// The big button, the FAB, and a slider's handle.
|
||||
pub const LARGE: f32 = 56.0;
|
||||
pub const SWITCH: [f32; 2] = [52.0, 32.0];
|
||||
/// A row of a menu.
|
||||
pub const ROW: f32 = 36.0;
|
||||
pub const MENU_MIN: f32 = 176.0;
|
||||
pub const MENU_MAX: f32 = 336.0;
|
||||
pub const DIALOG_S: f32 = 360.0;
|
||||
pub const DIALOG_M: f32 = 480.0;
|
||||
pub const DIALOG_L: f32 = 640.0;
|
||||
pub const SHEET: f32 = 360.0;
|
||||
pub const TOAST: f32 = 440.0;
|
||||
pub const WINDOW: [f32; 2] = [1080.0, 720.0];
|
||||
pub const WINDOW_MIN: [f32; 2] = [480.0, 360.0];
|
||||
}
|
||||
|
||||
/// Opacity of the on-colour laid over a control.
|
||||
pub mod state {
|
||||
pub const HOVER: f32 = 0.08;
|
||||
pub const PRESS: f32 = 0.12;
|
||||
pub const DRAG: f32 = 0.16;
|
||||
pub const DISABLED: f32 = 0.38;
|
||||
/// The fill of a disabled control.
|
||||
pub const DISABLED_FILL: f32 = 0.12;
|
||||
}
|
||||
|
||||
/// Waits, in seconds.
|
||||
pub mod time {
|
||||
/// A spinner shows only after this.
|
||||
pub const LOADING: f64 = 0.3;
|
||||
/// A pointer rests this long before a submenu opens or closes, so it can cross other rows on its way.
|
||||
pub const SUBMENU: f64 = 0.18;
|
||||
pub const TOAST: f64 = 5.0;
|
||||
/// A toast with a button stays longer.
|
||||
pub const TOAST_ACTION: f64 = 9.0;
|
||||
}
|
||||
|
||||
/// Resting surfaces have no shadow. Menus, dialogs and toasts have this one.
|
||||
pub mod elevation {
|
||||
use eframe::egui::{Color32, Shadow};
|
||||
|
||||
pub const SCRIM: f32 = 0.45;
|
||||
|
||||
pub fn floating(dark: bool) -> Shadow {
|
||||
Shadow { offset: [0, 6], blur: 20, spread: 0, color: Color32::from_black_alpha(if dark { 110 } else { 50 }) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Springs, from Material 3 Expressive's spatial tokens.
|
||||
pub mod spring {
|
||||
use crate::motion::Preset;
|
||||
|
||||
/// Presses and small controls.
|
||||
pub const FAST: Preset = Preset { stiffness: 1400.0, damping: 0.62 };
|
||||
/// Panels and movement.
|
||||
pub const DEFAULT: Preset = Preset { stiffness: 700.0, damping: 0.68 };
|
||||
/// Big transitions.
|
||||
pub const SLOW: Preset = Preset { stiffness: 300.0, damping: 0.74 };
|
||||
/// Colours, opacity and anything else that must not overshoot.
|
||||
pub const EFFECT: Preset = Preset { stiffness: 900.0, damping: 1.0 };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn spacing_is_on_the_grid_and_inner_radii_never_go_negative() {
|
||||
for gap in [space::XS, space::S, space::M, space::L, space::XL, space::XXL] {
|
||||
assert_eq!(gap % 4.0, 0.0);
|
||||
}
|
||||
assert_eq!((radius::inner(radius::L, space::S), radius::inner(radius::XS, space::S)), (8.0, 0.0));
|
||||
}
|
||||
}
|
||||
579
src/ui/chrome.rs
Normal file
579
src/ui/chrome.rs
Normal file
|
|
@ -0,0 +1,579 @@
|
|||
//! What floats over the video: the top bar, the control dock with the wavy seek bar, the on-screen messages, toasts,
|
||||
//! and the screens shown when nothing is playing or a file has only sound.
|
||||
|
||||
use crate::app::{Act, MenuKind, Sheet, Toast, cmd, set};
|
||||
use crate::fonts;
|
||||
use crate::motion::{spring, spring_from};
|
||||
use crate::mpv::{self, trim_num};
|
||||
use crate::shape::{self, Form};
|
||||
use crate::theme::{alpha, mix};
|
||||
use crate::thumbs::Thumbs;
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{radius, size, space, text, time};
|
||||
use crate::ui::View;
|
||||
use crate::ui::controls::{self, clock, play_button, seek_bar, slider};
|
||||
use crate::ui::glyphs as g;
|
||||
use crate::widgets::{Kind, button, cr, feel, floating_shadow, icon, icon_button, line, scale_rect};
|
||||
use eframe::egui::{self, Align2, Area, Color32, Id, Order, Pos2, Rect, Sense, Ui, pos2, vec2};
|
||||
|
||||
const DOCK_MAX: f32 = 1040.0;
|
||||
const DOCK_H: f32 = 116.0;
|
||||
const BAR_H: f32 = 56.0;
|
||||
|
||||
fn area(ctx: &egui::Context, name: &str, rect: Rect, order: Order, f: impl FnOnce(&mut Ui)) {
|
||||
Area::new(Id::new(name)).order(order).fixed_pos(rect.min).constrain(false).show(ctx, |ui| {
|
||||
ui.set_min_size(rect.size());
|
||||
ui.set_max_size(rect.size());
|
||||
f(ui)
|
||||
});
|
||||
}
|
||||
|
||||
fn ib(ui: &mut Ui, v: &View, key: &str, at: Pos2, side: f32, glyph: &str, name: &str, keys: &str, on: bool) -> egui::Response {
|
||||
let _ = v;
|
||||
icon_button(ui, v.t, Id::new(("ib", key)), Rect::from_center_size(at, vec2(side, side)), glyph, name, keys, Kind::Standard, on)
|
||||
}
|
||||
|
||||
/// The bar along the top: what is playing, and buttons to open and for the menu.
|
||||
pub fn top_bar(ctx: &egui::Context, v: &mut View, sheet_w: f32) -> Vec<Rect> {
|
||||
let screen = ctx.content_rect();
|
||||
let t = v.t;
|
||||
let lift = (1.0 - v.vis) * -12.0;
|
||||
let right_w = 3.0 * size::CONTROL + 2.0 * space::S;
|
||||
let right = Rect::from_min_size(pos2(screen.right() - space::L - sheet_w - right_w, screen.top() + space::L + lift), vec2(right_w, BAR_H));
|
||||
// title pill
|
||||
let title = if v.s.title.is_empty() { mpv::display_name(&v.s.path) } else { v.s.title.clone() };
|
||||
let mut detail = vec![];
|
||||
if v.s.width > 0 {
|
||||
detail.push(format!("{}×{}", v.s.width, v.s.height));
|
||||
}
|
||||
if !v.s.video_codec.is_empty() {
|
||||
detail.push(v.s.video_codec.split_whitespace().next().unwrap_or("").to_uppercase());
|
||||
}
|
||||
if v.s.fps > 0.0 {
|
||||
detail.push(format!("{} fps", trim_num(v.s.fps, 3)));
|
||||
}
|
||||
if !v.s.hwdec_current.is_empty() && v.s.hwdec_current != "no" {
|
||||
detail.push(format!("hardware ({})", v.s.hwdec_current));
|
||||
}
|
||||
if v.s.playlist.len() > 1 {
|
||||
detail.push(format!("{} of {}", v.s.playlist_pos + 1, v.s.playlist.len()));
|
||||
}
|
||||
let detail = detail.join(" · ");
|
||||
let room = (right.left() - space::S - (screen.left() + space::L)).max(120.0);
|
||||
let p = ctx.layer_painter(egui::LayerId::new(Order::Middle, Id::new("top-measure")));
|
||||
let tw = p.layout_no_wrap(title.clone(), fonts::semi(text::BODY + 2.0), t.on_surface).size().x;
|
||||
let dw = p.layout_no_wrap(detail.clone(), fonts::ui(text::LABEL), t.on_variant).size().x;
|
||||
let w = (tw.max(dw) + 2.0 * space::XL).min(room).max(120.0);
|
||||
let left = Rect::from_min_size(pos2(screen.left() + space::L, screen.top() + space::L + lift), vec2(w, BAR_H));
|
||||
let vis = v.vis;
|
||||
area(ctx, "top-left", left, Order::Middle, |ui| {
|
||||
ui.multiply_opacity(vis);
|
||||
let p = ui.painter();
|
||||
floating_shadow(p, left, cr(radius::XL), t.dark);
|
||||
p.rect_filled(left, cr(radius::XL), t.container);
|
||||
let inner = left.shrink2(vec2(space::XL, 0.0));
|
||||
let a = line(p, &title, fonts::semi(text::BODY + 2.0), t.on_surface, inner.width());
|
||||
let b = line(p, &detail, fonts::ui(text::LABEL), t.on_variant, inner.width());
|
||||
let total = a.size().y + if detail.is_empty() { 0.0 } else { b.size().y };
|
||||
let y = left.center().y - total / 2.0;
|
||||
p.galley(pos2(inner.left(), y), a.clone(), t.on_surface);
|
||||
if !detail.is_empty() {
|
||||
p.galley(pos2(inner.left(), y + a.size().y), b, t.on_variant);
|
||||
}
|
||||
});
|
||||
let acts = &mut *v.acts;
|
||||
let vv = View { t: v.t, s: v.s, cfg: v.cfg, acts, now: v.now, vis: v.vis };
|
||||
let mut out_acts = vec![];
|
||||
area(ctx, "top-right", right, Order::Middle, |ui| {
|
||||
ui.multiply_opacity(vis);
|
||||
let p = ui.painter();
|
||||
floating_shadow(p, right, cr(radius::XL), t.dark);
|
||||
p.rect_filled(right, cr(radius::XL), t.container);
|
||||
let y = right.center().y;
|
||||
let mut x = right.left() + space::S + size::CONTROL / 2.0;
|
||||
if ib(ui, &vv, "open", pos2(x, y), size::CONTROL, g::FOLDER_OPEN, "Open file", "Ctrl+O", false).clicked() {
|
||||
out_acts.push(Act::OpenFiles);
|
||||
}
|
||||
x += size::CONTROL;
|
||||
if ib(ui, &vv, "link", pos2(x, y), size::CONTROL, g::LINK, "Open link", "Ctrl+L", false).clicked() {
|
||||
out_acts.push(Act::OpenUrl);
|
||||
}
|
||||
x += size::CONTROL;
|
||||
let r = ib(ui, &vv, "more", pos2(x, y), size::CONTROL, g::MORE_VERT, "Menu", "", false);
|
||||
if r.clicked() {
|
||||
out_acts.push(Act::Menu(MenuKind::Context, pos2(r.rect.right(), r.rect.bottom() + space::XS), false));
|
||||
}
|
||||
});
|
||||
v.acts.extend(out_acts);
|
||||
vec![left, right]
|
||||
}
|
||||
|
||||
/// Buttons in the corner of the empty screen.
|
||||
pub fn top_bar_idle(ctx: &egui::Context, v: &mut View) -> Vec<Rect> {
|
||||
let screen = ctx.content_rect();
|
||||
let w = 2.0 * size::CONTROL + 2.0 * space::S;
|
||||
let r = Rect::from_min_size(pos2(screen.right() - space::L - w, screen.top() + space::L), vec2(w, BAR_H));
|
||||
let mut out = vec![];
|
||||
let t = v.t;
|
||||
area(ctx, "idle-top", r, Order::Middle, |ui| {
|
||||
let y = r.center().y;
|
||||
let x = r.left() + space::S + size::CONTROL / 2.0;
|
||||
if icon_button(ui, t, Id::new("idle-settings"), Rect::from_center_size(pos2(x, y), vec2(40.0, 40.0)), g::SETTINGS, "Settings", "Ctrl+,", Kind::Standard, false).clicked() {
|
||||
out.push(Act::Settings);
|
||||
}
|
||||
let m = icon_button(ui, t, Id::new("idle-more"), Rect::from_center_size(pos2(x + size::CONTROL, y), vec2(40.0, 40.0)), g::MORE_VERT, "Menu", "", Kind::Standard, false);
|
||||
if m.clicked() {
|
||||
out.push(Act::Menu(MenuKind::Context, pos2(m.rect.right(), m.rect.bottom() + space::XS), false));
|
||||
}
|
||||
});
|
||||
v.acts.extend(out);
|
||||
vec![r]
|
||||
}
|
||||
|
||||
/// The control dock: seek bar with times, transport, volume, tracks, speed, sheets and fullscreen.
|
||||
/// Returns its rect and whether the seek bar is being dragged.
|
||||
pub fn dock(ctx: &egui::Context, v: &mut View, thumbs: &mut Thumbs, sheet_w: f32) -> (Rect, bool) {
|
||||
let screen = ctx.content_rect();
|
||||
let t = v.t;
|
||||
let s = v.s;
|
||||
let avail_l = screen.left() + space::L;
|
||||
let avail_r = screen.right() - space::L - sheet_w;
|
||||
let w = (avail_r - avail_l).min(DOCK_MAX).max(320.0);
|
||||
let x0 = avail_l + ((avail_r - avail_l) - w) / 2.0;
|
||||
let y0 = screen.bottom() - space::L - DOCK_H + (1.0 - v.vis) * 16.0;
|
||||
let rect = Rect::from_min_size(pos2(x0, y0), vec2(w, DOCK_H));
|
||||
let narrow = w < 640.0;
|
||||
let vis = v.vis;
|
||||
let mut acts = vec![];
|
||||
let mut dragging = false;
|
||||
let mut hover: Option<(f64, f32)> = None;
|
||||
let chapters: Vec<f64> = s.chapters.iter().map(|c| c.time).collect();
|
||||
let playing = !s.pause && !s.eof;
|
||||
area(ctx, "dock", rect, Order::Middle, |ui| {
|
||||
ui.multiply_opacity(vis);
|
||||
let p = ui.painter().clone();
|
||||
floating_shadow(&p, rect, cr(radius::XL), t.dark);
|
||||
p.rect_filled(rect, cr(radius::XL), t.container);
|
||||
// row 1: times and seek bar
|
||||
let r1 = Rect::from_min_size(pos2(rect.left() + space::L, rect.top() + space::M), vec2(w - 2.0 * space::L, 32.0));
|
||||
let time_w = if s.duration >= 3600.0 { 64.0 } else { 48.0 };
|
||||
let shown_time = if v.cfg.remaining_time { s.time } else { s.time };
|
||||
p.text(pos2(r1.left(), r1.center().y), Align2::LEFT_CENTER, clock(shown_time), fonts::med(text::LABEL + 1.0), t.on_surface);
|
||||
let right_txt = if v.cfg.remaining_time { format!("-{}", clock((s.duration - s.time).max(0.0) / s.speed.max(0.01))) } else { clock(s.duration) };
|
||||
let rt = Rect::from_min_size(pos2(r1.right() - time_w, r1.top()), vec2(time_w, 32.0));
|
||||
let rr = ui.interact(rt, Id::new("dock-remaining"), Sense::click());
|
||||
let rf = feel(&rr, true);
|
||||
if rf.tint > 0.001 {
|
||||
p.rect_filled(rt, cr(radius::S), alpha(t.on_surface, rf.tint));
|
||||
}
|
||||
p.text(pos2(rt.right(), rt.center().y), Align2::RIGHT_CENTER, right_txt, fonts::med(text::LABEL + 1.0), t.on_variant);
|
||||
if rr.clicked() {
|
||||
acts.push(Act::ToggleRemaining);
|
||||
}
|
||||
let rr = rr.on_hover_text(if v.cfg.remaining_time { "Show length" } else { "Show time left" });
|
||||
let _ = rr;
|
||||
let bar = Rect::from_min_max(pos2(r1.left() + time_w + space::S, r1.top()), pos2(rt.left() - space::S, r1.bottom()));
|
||||
let sk = seek_bar(ui, t, Id::new("seek"), bar, s.time, s.duration, s.cache_time, &chapters, playing, v.cfg.wave);
|
||||
if let Some(to) = sk.seek {
|
||||
acts.push(Act::Seek(to));
|
||||
}
|
||||
dragging = sk.dragging.is_some();
|
||||
hover = sk.hover.or(sk.dragging.map(|d| (d, bar.left() + 8.0 + (bar.width() - 16.0) * (d / s.duration.max(1.0)) as f32)));
|
||||
|
||||
// row 2
|
||||
let y = rect.top() + space::M + 32.0 + space::XS + BAR_H / 2.0;
|
||||
let mut x = rect.left() + space::M + size::CONTROL / 2.0;
|
||||
let has_list = s.playlist.len() > 1;
|
||||
let prev = ui.add_enabled_ui(has_list || s.chapters.len() > 1, |ui| ib(ui, v, "prev", pos2(x, y), size::CONTROL, g::SKIP_PREVIOUS, "Previous", "P", false)).inner;
|
||||
if prev.clicked() {
|
||||
acts.push(if has_list { cmd(&["playlist-prev"]) } else { cmd(&["add", "chapter", "-1"]) });
|
||||
}
|
||||
x += size::CONTROL / 2.0 + space::XS + size::LARGE / 2.0;
|
||||
if play_button(ui, t, Id::new("play"), Rect::from_center_size(pos2(x, y), vec2(size::LARGE, size::LARGE)), playing).clicked() {
|
||||
acts.push(Act::TogglePause);
|
||||
}
|
||||
x += size::LARGE / 2.0 + space::XS + size::CONTROL / 2.0;
|
||||
let next = ui.add_enabled_ui(has_list || s.chapters.len() > 1, |ui| ib(ui, v, "next", pos2(x, y), size::CONTROL, g::SKIP_NEXT, "Next", "N", false)).inner;
|
||||
if next.clicked() {
|
||||
acts.push(if has_list { cmd(&["playlist-next"]) } else { cmd(&["add", "chapter", "1"]) });
|
||||
}
|
||||
x += size::CONTROL / 2.0 + space::S + size::CONTROL / 2.0;
|
||||
let vol_glyph = if s.mute || s.volume <= 0.0 { g::VOLUME_OFF } else if s.volume < 50.0 { g::VOLUME_DOWN } else { g::VOLUME_UP };
|
||||
if ib(ui, v, "mute", pos2(x, y), size::CONTROL, vol_glyph, if s.mute { "Sound on" } else { "Mute" }, "M", s.mute).clicked() {
|
||||
acts.push(cmd(&["cycle", "mute"]));
|
||||
}
|
||||
let mut left_end = x + size::CONTROL / 2.0;
|
||||
if !narrow {
|
||||
let sr = Rect::from_min_size(pos2(left_end + space::XS, y - 16.0), vec2(120.0, 32.0));
|
||||
let mut vol = if s.mute { 0.0 } else { s.volume };
|
||||
if slider(ui, t, Id::new("volume"), sr, &mut vol, 0.0, 150.0, 1.0, None, &|v| format!("{} %", v.round())) {
|
||||
acts.push(Act::Volume(vol));
|
||||
}
|
||||
left_end = sr.right();
|
||||
}
|
||||
|
||||
// right side, from the right edge
|
||||
let mut rx = rect.right() - space::M - size::CONTROL / 2.0;
|
||||
let fs = ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
|
||||
if ib(ui, v, "fs", pos2(rx, y), size::CONTROL, if fs { g::FULLSCREEN_EXIT } else { g::FULLSCREEN }, if fs { "Leave full screen" } else { "Full screen" }, "F", false).clicked() {
|
||||
acts.push(Act::Fullscreen);
|
||||
}
|
||||
rx -= size::CONTROL;
|
||||
if ib(ui, v, "playlist", pos2(rx, y), size::CONTROL, g::PLAYLIST_PLAY, "Playlist", "Ctrl+P", false).clicked() {
|
||||
acts.push(Act::Sheet(Sheet::Playlist));
|
||||
}
|
||||
rx -= size::CONTROL;
|
||||
if !narrow {
|
||||
if ib(ui, v, "adjust", pos2(rx, y), size::CONTROL, g::TUNE, "Picture, sound and subtitles", "Ctrl+E", false).clicked() {
|
||||
acts.push(Act::Sheet(Sheet::Adjust));
|
||||
}
|
||||
rx -= size::CONTROL;
|
||||
}
|
||||
let subs_on = s.sid != "no" && !s.sid.is_empty() && s.sub_visible;
|
||||
let sr = ib(ui, v, "subs", pos2(rx, y), size::CONTROL, if subs_on { g::SUBTITLES } else { g::SUBTITLES_OFF }, "Subtitles", "J", false);
|
||||
if sr.clicked() {
|
||||
acts.push(Act::Menu(MenuKind::Subtitles, pos2(sr.rect.left(), rect.top() - space::S), true));
|
||||
}
|
||||
rx -= size::CONTROL;
|
||||
let ar = ib(ui, v, "audio", pos2(rx, y), size::CONTROL, g::MUSIC_NOTE, "Sound track", "A", false);
|
||||
if ar.clicked() {
|
||||
acts.push(Act::Menu(MenuKind::Audio, pos2(ar.rect.left(), rect.top() - space::S), true));
|
||||
}
|
||||
rx -= size::CONTROL / 2.0 + space::XS;
|
||||
// speed as a small pill showing the value
|
||||
let label = format!("{}×", trim_num(s.speed, 2));
|
||||
let gw = p.layout_no_wrap(label.clone(), fonts::med(text::BODY), t.on_variant).size().x;
|
||||
let pw = (gw + 2.0 * space::M).max(48.0);
|
||||
let pr = Rect::from_min_size(pos2(rx - pw, y - 16.0), vec2(pw, 32.0));
|
||||
let changed_speed = (s.speed - 1.0).abs() > 0.001;
|
||||
let resp = ui.interact(pr, Id::new("speed"), Sense::click());
|
||||
let f = feel(&resp, true);
|
||||
let look_fill = if changed_speed { t.secondary_container } else { Color32::TRANSPARENT };
|
||||
let ink = if changed_speed { t.on_secondary_container } else { t.on_variant };
|
||||
let shape = scale_rect(pr, 1.0 - 0.05 * f.press);
|
||||
p.rect_filled(shape, cr(radius::S), look_fill);
|
||||
if !changed_speed {
|
||||
p.rect_stroke(shape, cr(radius::S), egui::Stroke::new(1.0, t.outline_variant), egui::StrokeKind::Inside);
|
||||
}
|
||||
if f.tint > 0.001 {
|
||||
p.rect_filled(shape, cr(radius::S), alpha(ink, f.tint));
|
||||
}
|
||||
if f.focus {
|
||||
crate::widgets::ring(&p, t, shape, cr(radius::S));
|
||||
}
|
||||
p.text(pr.center(), Align2::CENTER_CENTER, &label, fonts::med(text::BODY), ink);
|
||||
if resp.clicked() {
|
||||
acts.push(Act::Menu(MenuKind::Speed, pos2(pr.left(), rect.top() - space::S), true));
|
||||
}
|
||||
if resp.secondary_clicked() {
|
||||
acts.push(set("speed", "1"));
|
||||
}
|
||||
let _ = resp.on_hover_text("Speed ([ and ])");
|
||||
rx = pr.left() - space::XS;
|
||||
if !s.chapters.is_empty() {
|
||||
rx -= size::CONTROL / 2.0;
|
||||
let cr_ = ib(ui, v, "chapters", pos2(rx, y), size::CONTROL, g::BOOKMARKS, "Chapters", "PgUp, PgDn", false);
|
||||
if cr_.clicked() {
|
||||
acts.push(Act::Menu(MenuKind::Chapters, pos2(cr_.rect.left(), rect.top() - space::S), true));
|
||||
}
|
||||
rx -= size::CONTROL / 2.0;
|
||||
}
|
||||
// the middle: chapter name, or loop state
|
||||
let mid_l = left_end + space::L;
|
||||
let mid_r = rx - space::M;
|
||||
if !narrow && mid_r - mid_l > 80.0 {
|
||||
let mut what = String::new();
|
||||
if let Some(c) = usize::try_from(s.chapter).ok().and_then(|i| s.chapters.get(i)) {
|
||||
what = c.title.clone().unwrap_or_else(|| format!("Chapter {}", s.chapter + 1));
|
||||
}
|
||||
if let (Some(a), b) = (s.ab_a, s.ab_b) {
|
||||
what = match b {
|
||||
Some(b) => format!("Looping {} to {}", clock(a), clock(b)),
|
||||
None => format!("Loop from {}", clock(a)),
|
||||
};
|
||||
} else if s.loop_file {
|
||||
what = if what.is_empty() { "Repeating".into() } else { format!("{what} · repeating") };
|
||||
}
|
||||
if s.buffering {
|
||||
what = "Loading".into();
|
||||
}
|
||||
let gal = line(&p, &what, fonts::ui(text::BODY), t.on_variant, mid_r - mid_l);
|
||||
p.galley(pos2((mid_l + mid_r) / 2.0 - gal.size().x / 2.0, y - gal.size().y / 2.0), gal, t.on_variant);
|
||||
}
|
||||
});
|
||||
// preview above the bar
|
||||
if let Some((at, x)) = hover {
|
||||
preview(ctx, v, thumbs, at, x, rect.top() - space::S);
|
||||
}
|
||||
v.acts.extend(acts);
|
||||
(rect, dragging)
|
||||
}
|
||||
|
||||
fn preview(ctx: &egui::Context, v: &View, thumbs: &mut Thumbs, at: f64, x: f32, bottom: f32) {
|
||||
let t = v.t;
|
||||
let s = v.s;
|
||||
let tex = if v.cfg.thumbnails && s.has_video() { thumbs.get(ctx, &s.path, s.duration, at) } else { None };
|
||||
let chapter = s.chapters.iter().rev().find(|c| c.time <= at).and_then(|c| c.title.clone());
|
||||
let p = ctx.layer_painter(egui::LayerId::new(Order::Tooltip, Id::new("seek-preview")));
|
||||
let label = clock(at);
|
||||
let tg = p.layout_no_wrap(label, fonts::med(text::BODY), t.on_surface);
|
||||
let cg = chapter.as_ref().map(|c| line(&p, c, fonts::ui(text::LABEL), t.on_variant, 200.0));
|
||||
let (tw, th) = tex.as_ref().map(|tx| {
|
||||
let sz = tx.size_vec2();
|
||||
(sz.x * (90.0 / sz.y.max(1.0)), 90.0)
|
||||
}).unwrap_or((0.0, 0.0));
|
||||
let w = tw.max(tg.size().x + 2.0 * space::M).max(cg.as_ref().map(|c| c.size().x + 2.0 * space::M).unwrap_or(0.0));
|
||||
let h = th + if th > 0.0 { space::S } else { 0.0 } + tg.size().y + cg.as_ref().map(|c| c.size().y).unwrap_or(0.0) + 2.0 * space::S;
|
||||
let screen = ctx.content_rect();
|
||||
let left = (x - w / 2.0).clamp(screen.left() + space::S, screen.right() - space::S - w);
|
||||
let r = Rect::from_min_size(pos2(left, bottom - h), vec2(w, h));
|
||||
let rise = spring_from("preview-rise", 6.0, 0.0, DEFAULT);
|
||||
let r = r.translate(vec2(0.0, rise));
|
||||
floating_shadow(&p, r, cr(radius::M), t.dark);
|
||||
p.rect_filled(r, cr(radius::M), t.high);
|
||||
let mut y = r.top() + space::S;
|
||||
if let Some(tx) = &tex {
|
||||
let ir = Rect::from_min_size(pos2(r.center().x - tw / 2.0, y), vec2(tw, th)).shrink2(vec2(space::S, 0.0));
|
||||
p.add(egui::epaint::RectShape::filled(ir, cr(radius::S), Color32::WHITE).with_texture(tx.id(), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))));
|
||||
y += th + space::S;
|
||||
}
|
||||
p.galley(pos2(r.center().x - tg.size().x / 2.0, y), tg.clone(), t.on_surface);
|
||||
y += tg.size().y;
|
||||
if let Some(c) = cg {
|
||||
p.galley(pos2(r.center().x - c.size().x / 2.0, y), c, t.on_variant);
|
||||
}
|
||||
}
|
||||
|
||||
/// Short message at the top for volume, seeking, speed and the like. A level shows as a bar under the words.
|
||||
pub fn osd(ctx: &egui::Context, v: &mut View, o: Option<&crate::app::Osd>) {
|
||||
let Some(o) = o else { return };
|
||||
let age = v.now - o.at;
|
||||
let alive = age < 1.3;
|
||||
let k = spring_from(("osd", (o.at * 1000.0) as i64), 0.0, f32::from(alive), EFFECT);
|
||||
if alive {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(1.31 - age));
|
||||
}
|
||||
if k < 0.01 {
|
||||
return;
|
||||
}
|
||||
let t = v.t;
|
||||
let screen = ctx.content_rect();
|
||||
let p = ctx.layer_painter(egui::LayerId::new(Order::Foreground, Id::new("osd")));
|
||||
let gal = p.layout_no_wrap(o.text.clone(), fonts::med(text::BODY), t.on_surface);
|
||||
let w = (gal.size().x + 2.0 * space::XL).max(if o.level.is_some() { 200.0 } else { 0.0 });
|
||||
let h = if o.level.is_some() { 64.0 } else { 44.0 };
|
||||
let top = screen.top() + if v.vis > 0.5 { space::L + BAR_H + space::M } else { space::XL };
|
||||
let rise = spring_from(("osd-rise", (o.at * 1000.0) as i64), -8.0, 0.0, DEFAULT);
|
||||
let r = Rect::from_min_size(pos2(screen.center().x - w / 2.0, top + rise), vec2(w, h));
|
||||
let mut p = p.clone();
|
||||
p.set_opacity(k);
|
||||
floating_shadow(&p, r, cr(radius::FULL), t.dark);
|
||||
p.rect_filled(r, cr(radius::FULL), t.high);
|
||||
if let Some(l) = o.level {
|
||||
p.galley(pos2(r.center().x - gal.size().x / 2.0, r.top() + 10.0), gal.clone(), t.on_surface);
|
||||
let bar = Rect::from_min_size(pos2(r.left() + space::XL, r.bottom() - 22.0), vec2(w - 2.0 * space::XL, 12.0));
|
||||
crate::wave::bar(&egui::Ui::new(ctx.clone(), Id::new("osd-ui"), egui::UiBuilder::new().layer_id(egui::LayerId::new(Order::Foreground, Id::new("osd"))).max_rect(r)), t, Id::new("osd-bar"), bar, l.clamp(0.0, 1.0), 0.0, t.primary, t.secondary_container);
|
||||
} else {
|
||||
p.galley(r.center() - gal.size() / 2.0, gal, t.on_surface);
|
||||
}
|
||||
}
|
||||
|
||||
/// Toasts at the bottom centre, above the dock when it shows. Newest at the bottom, older ones pushed up.
|
||||
pub fn toasts(ctx: &egui::Context, v: &mut View, list: &mut Vec<Toast>) {
|
||||
let now = v.now;
|
||||
list.retain(|t| now - t.at < if t.action.is_some() { time::TOAST_ACTION } else { time::TOAST } + 0.4);
|
||||
if list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let t = v.t;
|
||||
let screen = ctx.content_rect();
|
||||
let mut bottom = screen.bottom() - space::L - if v.vis > 0.5 && v.s.loaded() { DOCK_H + space::M } else { 0.0 };
|
||||
let mut acts = vec![];
|
||||
let n = list.len();
|
||||
for (i, to) in list.iter().enumerate().rev() {
|
||||
let life = if to.action.is_some() { time::TOAST_ACTION } else { time::TOAST };
|
||||
let age = now - to.at;
|
||||
let alive = age < life;
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64((life - age).max(0.0) + 0.02));
|
||||
let key = (to.at * 1000.0) as i64;
|
||||
let k = spring_from(("toast", key), 0.0, f32::from(alive), EFFECT).clamp(0.0, 1.0);
|
||||
let rise = spring_from(("toast-rise", key), 24.0, 0.0, DEFAULT);
|
||||
let p = ctx.layer_painter(egui::LayerId::new(Order::Foreground, Id::new(("toast", key))));
|
||||
let max_w = size::TOAST.min(screen.width() - 2.0 * space::L);
|
||||
let action_w = to.action.as_ref().map(|(l, _)| p.layout_no_wrap(l.clone(), fonts::med(text::BODY), t.inverse_primary).size().x + 2.0 * space::M + space::S).unwrap_or(0.0);
|
||||
let job = {
|
||||
let mut j = egui::text::LayoutJob::simple(to.text.clone(), fonts::ui(text::BODY), t.inverse_on_surface, max_w - 2.0 * space::L - action_w);
|
||||
j.wrap.max_rows = 3;
|
||||
j
|
||||
};
|
||||
let gal = p.layout_job(job);
|
||||
let w = (gal.size().x + 2.0 * space::L + action_w).min(max_w);
|
||||
let h = (gal.size().y + 2.0 * space::M + 4.0).max(48.0);
|
||||
let r = Rect::from_min_size(pos2(screen.center().x - w / 2.0, bottom - h + rise), vec2(w, h));
|
||||
bottom = r.top() - space::S;
|
||||
let mut p2 = p.clone();
|
||||
p2.set_opacity(k);
|
||||
floating_shadow(&p2, r, cr(radius::M), t.dark);
|
||||
p2.rect_filled(r, cr(radius::M), t.inverse_surface);
|
||||
p2.galley(pos2(r.left() + space::L, r.center().y - gal.size().y / 2.0), gal, t.inverse_on_surface);
|
||||
if let Some((label, act)) = &to.action {
|
||||
let br = Rect::from_min_size(pos2(r.right() - action_w, r.center().y - 18.0), vec2(action_w - space::S, 36.0));
|
||||
let mut clicked = false;
|
||||
area(ctx, &format!("toast-btn-{key}"), br, Order::Foreground, |ui| {
|
||||
let resp = ui.interact(br, Id::new(("toast-btn", key)), Sense::click());
|
||||
let f = feel(&resp, true);
|
||||
if f.tint > 0.001 {
|
||||
ui.painter().rect_filled(br, cr(radius::FULL), alpha(t.inverse_primary, f.tint));
|
||||
}
|
||||
ui.painter().text(br.center(), Align2::CENTER_CENTER, label, fonts::med(text::BODY), t.inverse_primary);
|
||||
clicked = resp.clicked();
|
||||
});
|
||||
if clicked {
|
||||
acts.push(act.clone());
|
||||
}
|
||||
}
|
||||
let _ = (i, n);
|
||||
}
|
||||
v.acts.extend(acts);
|
||||
}
|
||||
|
||||
/// What shows when nothing is open: a shape, a line of what to do, two buttons, and the recent files.
|
||||
pub fn empty(ctx: &egui::Context, v: &mut View, error: Option<&str>) {
|
||||
let t = v.t;
|
||||
let screen = ctx.content_rect();
|
||||
let recent: Vec<_> = v.cfg.recent.iter().take(5).cloned().collect();
|
||||
let col_w = 440.0f32.min(screen.width() - 2.0 * space::L);
|
||||
let recent_h = if recent.is_empty() { 0.0 } else { space::XXL + 32.0 + recent.len() as f32 * 56.0 + 2.0 * space::S };
|
||||
let err_h = if error.is_some() { 72.0 + space::L } else { 0.0 };
|
||||
let total = err_h + 96.0 + space::XL + 32.0 + space::S + 20.0 + space::XL + 40.0 + recent_h;
|
||||
let top = (screen.center().y - total / 2.0).max(screen.top() + 80.0);
|
||||
let rect = Rect::from_min_size(pos2(screen.center().x - col_w / 2.0, top), vec2(col_w, total));
|
||||
let mut acts = vec![];
|
||||
area(ctx, "empty", rect, Order::Middle, |ui| {
|
||||
let p = ui.painter().clone();
|
||||
let mut y = rect.top();
|
||||
if let Some(e) = error {
|
||||
let er = Rect::from_min_size(pos2(rect.left(), y), vec2(col_w, 72.0));
|
||||
p.rect_filled(er, cr(radius::L), t.error_container);
|
||||
icon(&p, pos2(er.left() + space::L + 12.0, er.center().y), 24.0, g::ERROR, t.on_error_container);
|
||||
let gal = p.layout(e.to_string(), fonts::ui(text::BODY), t.on_error_container, col_w - 3.0 * space::L - 24.0);
|
||||
p.galley(pos2(er.left() + 2.0 * space::L + 24.0, er.center().y - gal.size().y / 2.0), gal, t.on_error_container);
|
||||
y += 72.0 + space::L;
|
||||
}
|
||||
// the shape: turns a little when hovered, opens files when clicked
|
||||
let c = pos2(rect.center().x, y + 48.0);
|
||||
let sr = Rect::from_center_size(c, vec2(96.0, 96.0));
|
||||
let resp = ui.interact(sr, Id::new("empty-shape"), Sense::click());
|
||||
let f = feel(&resp, true);
|
||||
let turn = spring("empty-turn", if resp.hovered() { 0.35 } else { 0.0 }, DEFAULT);
|
||||
let pts = shape::outline(Form::Cookie12, c, 48.0 * (1.0 - 0.06 * f.press), turn);
|
||||
shape::fill(&p, c, &pts, t.primary_container);
|
||||
if f.tint > 0.001 {
|
||||
shape::fill(&p, c, &pts, alpha(t.on_primary_container, f.tint));
|
||||
}
|
||||
icon(&p, c, 40.0, g::MOVIE, t.on_primary_container);
|
||||
if resp.clicked() {
|
||||
acts.push(Act::OpenFiles);
|
||||
}
|
||||
y += 96.0 + space::XL;
|
||||
p.text(pos2(rect.center().x, y), Align2::CENTER_TOP, "Nothing playing", fonts::semi(text::HEADLINE), t.on_surface);
|
||||
y += 32.0 + space::S;
|
||||
p.text(pos2(rect.center().x, y), Align2::CENTER_TOP, "Open a video or a link, or drop files here.", fonts::ui(text::BODY), t.on_variant);
|
||||
y += 20.0 + space::XL;
|
||||
let bw = 148.0;
|
||||
let b1 = Rect::from_min_size(pos2(rect.center().x - bw - space::S / 2.0, y), vec2(bw, 40.0));
|
||||
let b2 = Rect::from_min_size(pos2(rect.center().x + space::S / 2.0, y), vec2(bw, 40.0));
|
||||
if button(ui, t, Id::new("empty-open"), b1, g::FOLDER_OPEN, "Open file", Kind::Filled).on_hover_text("Open file (Ctrl+O)").clicked() {
|
||||
acts.push(Act::OpenFiles);
|
||||
}
|
||||
if button(ui, t, Id::new("empty-link"), b2, g::LINK, "Open link", Kind::Tonal).on_hover_text("Open link (Ctrl+L)").clicked() {
|
||||
acts.push(Act::OpenUrl);
|
||||
}
|
||||
y += 40.0 + space::XXL;
|
||||
if !recent.is_empty() {
|
||||
p.text(pos2(rect.left() + space::S, y + 16.0), Align2::LEFT_CENTER, "Recent", fonts::med(text::BODY), t.primary);
|
||||
let cl = Rect::from_min_size(pos2(rect.right() - 72.0, y), vec2(72.0, 32.0));
|
||||
if button(ui, t, Id::new("recent-clear"), cl, "", "Clear", Kind::Text).clicked() {
|
||||
acts.push(Act::ClearRecent);
|
||||
}
|
||||
y += 32.0;
|
||||
let card = Rect::from_min_size(pos2(rect.left(), y), vec2(col_w, recent.len() as f32 * 56.0 + 2.0 * space::S));
|
||||
p.rect_filled(card, cr(radius::L), t.low);
|
||||
let mut ry = card.top() + space::S;
|
||||
for r in &recent {
|
||||
let row_r = Rect::from_min_size(pos2(card.left() + space::S, ry), vec2(col_w - 2.0 * space::S, 56.0));
|
||||
let name = if r.title.is_empty() || r.title == mpv::display_name(&r.path) { mpv::display_name(&r.path) } else { r.title.clone() };
|
||||
let detail = if r.duration > 0.0 && r.position > 5.0 && r.position < r.duration - 10.0 {
|
||||
format!("Stopped at {} of {}", clock(r.position), clock(r.duration))
|
||||
} else if r.path.contains("://") {
|
||||
r.path.split('/').nth(2).unwrap_or("").to_string()
|
||||
} else {
|
||||
std::path::Path::new(&r.path).parent().map(|d| short(&d.to_string_lossy())).unwrap_or_default()
|
||||
};
|
||||
let id = Id::new(("recent", &r.path));
|
||||
let resp = controls::row(ui, t, id, row_r.shrink2(vec2(0.0, 2.0)), if r.path.contains("://") { g::PUBLIC } else { g::VIDEO_FILE }, &name, &detail, false);
|
||||
// the remove button shows on hover without moving anything
|
||||
let xr = Rect::from_center_size(pos2(row_r.right() - 24.0, row_r.center().y), vec2(32.0, 32.0));
|
||||
let show_x = spring((id, "x"), f32::from(resp.hovered() || ui.rect_contains_pointer(xr)), EFFECT);
|
||||
let mut removed = false;
|
||||
if show_x > 0.01 {
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(xr));
|
||||
child.multiply_opacity(show_x);
|
||||
if icon_button(&mut child, t, id.with("x"), xr, g::CLOSE, "Remove from recent", "", Kind::Standard, false).clicked() {
|
||||
acts.push(Act::ForgetRecent(r.path.clone()));
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
if resp.clicked() && !removed {
|
||||
acts.push(Act::Load(r.path.clone()));
|
||||
}
|
||||
ry += 56.0;
|
||||
}
|
||||
}
|
||||
});
|
||||
v.acts.extend(acts);
|
||||
}
|
||||
|
||||
fn short(p: &str) -> String {
|
||||
let home = dirs::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
if !home.is_empty() && p.starts_with(&home) { format!("~{}", &p[home.len()..]) } else { p.to_string() }
|
||||
}
|
||||
|
||||
/// A file with sound and no picture: a shape that is round while paused and a cookie while playing, and the title.
|
||||
pub fn sound_only(ctx: &egui::Context, v: &mut View) {
|
||||
let t = v.t;
|
||||
let screen = ctx.content_rect();
|
||||
let c = pos2(screen.center().x, screen.center().y - 60.0);
|
||||
let playing = !v.s.pause && !v.s.eof;
|
||||
let p = ctx.layer_painter(egui::LayerId::background());
|
||||
p.rect_filled(screen, 0.0, t.surface);
|
||||
let m = crate::wave::with_state(ctx, Id::new("sound-shape"), |m: &mut Option<shape::Morpher>, _| {
|
||||
let m = m.get_or_insert_with(|| shape::Morpher::new(Form::Circle));
|
||||
m.morph_to(if playing { Form::Cookie12 } else { Form::Circle });
|
||||
if playing && controls::travels() {
|
||||
m.rotation.target += crate::motion::dt() * 0.25;
|
||||
crate::motion::keep_alive();
|
||||
}
|
||||
m.step();
|
||||
m.clone()
|
||||
});
|
||||
let r = (screen.height() * 0.18).clamp(56.0, 120.0);
|
||||
let pts = m.points(c, r);
|
||||
shape::fill(&p, c, &pts, t.primary_container);
|
||||
icon(&p, c, r * 0.7, g::MUSIC_NOTE, t.on_primary_container);
|
||||
let title = if v.s.title.is_empty() { mpv::display_name(&v.s.path) } else { v.s.title.clone() };
|
||||
let gal = line(&p, &title, fonts::semi(text::HEADLINE), t.on_surface, screen.width() - 64.0);
|
||||
p.galley(pos2(screen.center().x - gal.size().x / 2.0, c.y + r * 1.25 + space::L), gal, t.on_surface);
|
||||
let detail = [v.s.audio_codec.to_uppercase(), v.s.file_format.clone()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
p.text(pos2(screen.center().x, c.y + r * 1.25 + space::L + 36.0), Align2::CENTER_TOP, detail, fonts::ui(text::BODY), t.on_variant);
|
||||
let _ = mix(t.surface, t.surface, 0.0);
|
||||
}
|
||||
|
||||
/// Quince's logo, the same drawing as the app icon: a leaf-green clover with a dark play mark. `spin` turns it.
|
||||
pub fn logo(p: &egui::Painter, c: Pos2, r: f32, spin: f32) {
|
||||
let base = Color32::from_rgb(0x94, 0xbb, 0x3b);
|
||||
let ink = Color32::from_rgb(0x2b, 0x39, 0x0b);
|
||||
let pts = shape::outline(Form::Clover, c, r, std::f32::consts::FRAC_PI_4 + spin);
|
||||
shape::fill(p, c, &pts, base);
|
||||
controls::play_pause_glyph(p, c + vec2(r * 0.06, 0.0), r * 0.95, 0.0, ink);
|
||||
}
|
||||
424
src/ui/controls.rs
Normal file
424
src/ui/controls.rs
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
//! Quince's own controls on top of the kit: the morphing play button, the expressive slider, the seek bar with
|
||||
//! chapters and a preview, list rows, tabs, a text field and keycaps.
|
||||
|
||||
use crate::fonts;
|
||||
use crate::motion::{self, spring};
|
||||
use crate::shape::{self, Form};
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT, FAST};
|
||||
use crate::tokens::{radius, size, space, state, text};
|
||||
use crate::wave::{self, Drive, with_state};
|
||||
use crate::widgets::{Feel, Look, cr, feel, icon, icon_filled, line, ring, scale_rect};
|
||||
use eframe::egui::{
|
||||
self, Align2, Color32, CursorIcon, Id, Painter, Pos2, Rect, Response, Role, Sense, Shape, Stroke, StrokeKind, Ui, Vec2,
|
||||
WidgetInfo, pos2, vec2,
|
||||
};
|
||||
|
||||
pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
/// The big play button: a circle while paused that turns into a soft cookie while playing, with the play triangle
|
||||
/// folding into the pause bars. Both changes ride springs and can be interrupted.
|
||||
pub fn play_button(ui: &mut Ui, t: &Theme, id: Id, rect: Rect, playing: bool) -> Response {
|
||||
let r = ui.interact(rect, id, Sense::click());
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::Button, ui.is_enabled(), if playing { "Pause" } else { "Play" }));
|
||||
let live = ui.is_enabled();
|
||||
let f = feel(&r, live);
|
||||
let k = spring((id, "k"), f32::from(playing), DEFAULT);
|
||||
let c = rect.center();
|
||||
let rad = rect.width() / 2.0 * (1.0 - 0.08 * f.press);
|
||||
let morph = with_state(ui.ctx(), id.with("shape"), |m: &mut Option<shape::Morpher>, _| {
|
||||
let m = m.get_or_insert_with(|| shape::Morpher::new(if playing { Form::Cookie9 } else { Form::Circle }));
|
||||
m.morph_to(if playing { Form::Cookie9 } else { Form::Circle });
|
||||
m.step();
|
||||
m.clone()
|
||||
});
|
||||
let pts = morph.points(c, rad);
|
||||
let look = if live { Look::new(t.primary, t.on_primary) } else { Look::new(t.primary, t.on_primary).disabled(t) };
|
||||
let p = ui.painter();
|
||||
shape::fill(p, c, &pts, look.fill);
|
||||
if f.tint > 0.001 {
|
||||
shape::fill(p, c, &pts, alpha(look.ink, f.tint));
|
||||
}
|
||||
if f.focus {
|
||||
ring(p, t, rect, cr(rect.height() / 2.0));
|
||||
}
|
||||
play_pause_glyph(p, c, rect.height() * 0.5, k, look.ink);
|
||||
if live && r.hovered() {
|
||||
ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
|
||||
}
|
||||
r.on_hover_text(if playing { "Pause (Space)" } else { "Play (Space)" })
|
||||
}
|
||||
|
||||
/// Play triangle (k = 0) folding into pause bars (k = 1). Draws sensibly past 1 so a spring's overshoot shows.
|
||||
pub fn play_pause_glyph(p: &Painter, c: Pos2, s: f32, k: f32, color: Color32) {
|
||||
let play = [
|
||||
[(-0.30, -0.40), (0.07, -0.20), (0.07, 0.20), (-0.30, 0.40)],
|
||||
[(0.07, -0.20), (0.44, 0.0), (0.44, 0.0), (0.07, 0.20)],
|
||||
];
|
||||
let pause = [
|
||||
[(-0.30, -0.36), (-0.08, -0.36), (-0.08, 0.36), (-0.30, 0.36)],
|
||||
[(0.08, -0.36), (0.30, -0.36), (0.30, 0.36), (0.08, 0.36)],
|
||||
];
|
||||
for (a, b) in play.iter().zip(pause.iter()) {
|
||||
let pts: Vec<Pos2> = a
|
||||
.iter()
|
||||
.zip(b.iter())
|
||||
.map(|(x, y)| c + vec2(lerp(x.0, y.0, k), lerp(x.1, y.1, k)) * s)
|
||||
.collect();
|
||||
p.add(Shape::convex_polygon(pts, color, Stroke::new(s * 0.06, color)));
|
||||
}
|
||||
}
|
||||
|
||||
/// How a slider reads its value aloud and in its bubble.
|
||||
pub type Fmt<'a> = &'a dyn Fn(f64) -> String;
|
||||
|
||||
/// M3 Expressive slider: a thick round track split around a tall thin handle, a stop dot at the end, a value bubble
|
||||
/// while dragging. A click jumps, a drag keeps the value under the pointer, the wheel and arrow keys step (PgUp and PgDn
|
||||
/// by ten). `origin` fills from there instead of from the start (for delays). True when the value changed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn slider(ui: &mut Ui, t: &Theme, id: Id, rect: Rect, value: &mut f64, min: f64, max: f64, step: f64, origin: Option<f64>, fmt: Fmt) -> bool {
|
||||
let r = ui.interact(rect, id, Sense::click_and_drag());
|
||||
let label = fmt(*value);
|
||||
r.widget_info(|| WidgetInfo::slider(ui.is_enabled(), *value, &label));
|
||||
let live = ui.is_enabled();
|
||||
let f = feel(&r, live);
|
||||
let small = rect.height() < 36.0;
|
||||
let track_h = if small { 12.0 } else { 16.0 };
|
||||
let handle_h = if small { 24.0 } else { 36.0 } + 4.0 * f.press;
|
||||
let gap = 4.0;
|
||||
let (a, b) = (rect.left() + 2.0, rect.right() - 2.0);
|
||||
let to_v = |x: f32| min + ((x - a) / (b - a).max(1.0)).clamp(0.0, 1.0) as f64 * (max - min);
|
||||
let snap = |v: f64| if step > 0.0 { ((v - min) / step).round() * step + min } else { v }.clamp(min, max);
|
||||
let mut changed = false;
|
||||
if live {
|
||||
if (r.dragged() || r.is_pointer_button_down_on() || r.clicked())
|
||||
&& let Some(p) = r.interact_pointer_pos()
|
||||
{
|
||||
let v = snap(to_v(p.x));
|
||||
if v != *value {
|
||||
*value = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if r.hovered() {
|
||||
let d = crate::widgets::wheel(ui);
|
||||
let notch = if d.y.abs() > d.x.abs() { d.y } else { -d.x };
|
||||
if notch.abs() > 0.5 {
|
||||
let v = snap(*value + step.max((max - min) / 100.0) * notch.signum() as f64);
|
||||
if v != *value {
|
||||
*value = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.has_focus() {
|
||||
let k = |key| ui.input(|i| i.key_pressed(key));
|
||||
let mut d = 0.0;
|
||||
if k(egui::Key::ArrowRight) || k(egui::Key::ArrowUp) {
|
||||
d = 1.0;
|
||||
} else if k(egui::Key::ArrowLeft) || k(egui::Key::ArrowDown) {
|
||||
d = -1.0;
|
||||
} else if k(egui::Key::PageUp) {
|
||||
d = 10.0;
|
||||
} else if k(egui::Key::PageDown) {
|
||||
d = -10.0;
|
||||
}
|
||||
if d != 0.0 {
|
||||
*value = snap(*value + d * step.max((max - min) / 100.0));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if r.hovered() {
|
||||
ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
|
||||
}
|
||||
}
|
||||
let frac = (((*value - min) / (max - min).max(1e-9)).clamp(0.0, 1.0)) as f32;
|
||||
let fx = spring((id, "x"), frac, FAST);
|
||||
let x = lerp(a, b, fx);
|
||||
let y = rect.center().y;
|
||||
let p = ui.painter();
|
||||
let (on, off) = if live { (t.primary, t.secondary_container) } else { (alpha(t.on_surface, state::DISABLED), alpha(t.on_surface, state::DISABLED_FILL)) };
|
||||
let o = origin.map(|o| lerp(a, b, ((o - min) / (max - min)) as f32)).unwrap_or(a);
|
||||
let tr = |l: f32, rgt: f32| Rect::from_min_max(pos2(l, y - track_h / 2.0), pos2(rgt, y + track_h / 2.0));
|
||||
let rr = cr(track_h / 2.0);
|
||||
let small_r = cr(radius::XS / 2.0);
|
||||
// Inactive track on both sides of the handle, active part between origin and handle.
|
||||
let left_end = x - gap - 2.0;
|
||||
let right_start = x + gap + 2.0;
|
||||
if left_end > a {
|
||||
let full = tr(a, left_end);
|
||||
p.rect_filled(full, egui::CornerRadius { nw: rr.nw, sw: rr.sw, ne: small_r.ne, se: small_r.se }, off);
|
||||
}
|
||||
if right_start < b {
|
||||
let full = tr(right_start, b);
|
||||
p.rect_filled(full, egui::CornerRadius { nw: small_r.nw, sw: small_r.sw, ne: rr.ne, se: rr.se }, off);
|
||||
p.circle_filled(pos2(b - track_h / 2.0, y), 2.0, on);
|
||||
}
|
||||
if origin.is_none() {
|
||||
if left_end > a {
|
||||
p.rect_filled(tr(a, left_end), egui::CornerRadius { nw: rr.nw, sw: rr.sw, ne: small_r.ne, se: small_r.se }, on);
|
||||
}
|
||||
} else {
|
||||
let (l, rgt) = if x > o { (o, left_end) } else { (right_start, o) };
|
||||
if rgt > l {
|
||||
p.rect_filled(tr(l, rgt), small_r, on);
|
||||
}
|
||||
p.circle_filled(pos2(o, y), 2.0, if (x - o).abs() < gap + 4.0 { on } else { t.on_secondary_container });
|
||||
}
|
||||
let handle = Rect::from_center_size(pos2(x, y), vec2(4.0, handle_h));
|
||||
p.rect_filled(handle, cr(2.0), on);
|
||||
if f.focus {
|
||||
ring(p, t, handle, cr(2.0));
|
||||
}
|
||||
let dragging = r.dragged() || r.is_pointer_button_down_on();
|
||||
let bubble = spring((id, "bubble"), f32::from(dragging || f.focus), EFFECT);
|
||||
if bubble > 0.01 {
|
||||
let g = p.layout_no_wrap(label.clone(), fonts::med(text::LABEL), t.inverse_on_surface);
|
||||
let w = g.size().x + 2.0 * space::M;
|
||||
let br = Rect::from_center_size(pos2(x, rect.top() - 18.0 + 6.0 * (1.0 - bubble)), vec2(w.max(40.0), 28.0));
|
||||
let p2 = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, id.with("bubble")));
|
||||
p2.rect_filled(br, cr(radius::FULL), alpha(t.inverse_surface, bubble));
|
||||
p2.galley(br.center() - g.size() / 2.0, g, alpha(t.inverse_on_surface, bubble));
|
||||
}
|
||||
let _ = Feel::default();
|
||||
changed
|
||||
}
|
||||
|
||||
/// What the seek bar wants.
|
||||
pub struct SeekOut {
|
||||
pub seek: Option<f64>,
|
||||
/// Pointer over the bar, as a time: for the preview.
|
||||
pub hover: Option<(f64, f32)>,
|
||||
pub dragging: Option<f64>,
|
||||
}
|
||||
|
||||
/// The seek bar: a wave while playing (flat and still when paused or when the wave setting is off), chapter marks on
|
||||
/// the track, the buffered part a step brighter, a tall thin handle. The value follows the hand while dragging and the
|
||||
/// seek is sent as the hand moves (throttled by mpv's own keyframe seeking) and exactly on release.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn seek_bar(ui: &mut Ui, t: &Theme, id: Id, rect: Rect, time: f64, duration: f64, cached: f64, chapters: &[f64], playing: bool, wave_on: bool) -> SeekOut {
|
||||
let r = ui.interact(rect, id, Sense::click_and_drag());
|
||||
r.widget_info(|| WidgetInfo::slider(ui.is_enabled(), time, "Position"));
|
||||
let live = ui.is_enabled() && duration > 0.0;
|
||||
let pad = 8.0;
|
||||
let (a, b) = (rect.left() + pad, rect.right() - pad);
|
||||
let at = |x: f32| ((x - a) / (b - a).max(1.0)).clamp(0.0, 1.0) as f64 * duration;
|
||||
let mut out = SeekOut { seek: None, hover: None, dragging: None };
|
||||
with_state(ui.ctx(), id, |s: &mut SeekState, seen| {
|
||||
let life = if playing && wave_on { 0.55 } else { 0.0 };
|
||||
if !seen {
|
||||
s.drive.snap(life);
|
||||
}
|
||||
if live {
|
||||
if r.is_pointer_button_down_on() || r.dragged() {
|
||||
if let Some(p) = r.interact_pointer_pos() {
|
||||
let v = at(p.x);
|
||||
if s.drag.is_none_or(|d| (d - v).abs() > duration / 2000.0) {
|
||||
out.seek = Some(v);
|
||||
}
|
||||
s.drag = Some(v);
|
||||
}
|
||||
} else if let Some(v) = s.drag.take() {
|
||||
out.seek = Some(v);
|
||||
s.exact = true;
|
||||
}
|
||||
} else {
|
||||
s.drag = None;
|
||||
}
|
||||
out.dragging = s.drag;
|
||||
let v = if duration > 0.0 { (s.drag.unwrap_or(time) / duration).clamp(0.0, 1.0) as f32 } else { 0.0 };
|
||||
let (amp, _) = s.drive.step(life);
|
||||
let p = ui.painter();
|
||||
let x = lerp(a, b, v);
|
||||
let y = rect.center().y;
|
||||
let bar = Rect::from_min_max(pos2(a, y - wave::HEIGHT / 2.0), pos2(b, y + wave::HEIGHT / 2.0));
|
||||
let track = if live { t.secondary_container } else { t.highest };
|
||||
wave::paint_bar(p, t, bar, v, amp, s.drive.phase, if live { t.primary } else { t.outline }, track);
|
||||
// buffered part, over the flat track only
|
||||
if live && cached > time {
|
||||
let cx = lerp(a, b, (cached / duration).clamp(0.0, 1.0) as f32);
|
||||
let from = x + wave::GAP + 4.0;
|
||||
if cx > from + 1.0 {
|
||||
p.rect_filled(Rect::from_min_max(pos2(from, y - 2.0), pos2(cx.min(b - 6.0), y + 2.0)), cr(2.0), mix(track, t.on_secondary_container, 0.35));
|
||||
}
|
||||
}
|
||||
for &c in chapters {
|
||||
if c <= 0.0 || duration <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let cx = lerp(a, b, (c / duration).clamp(0.0, 1.0) as f32);
|
||||
if (cx - x).abs() < 8.0 {
|
||||
continue;
|
||||
}
|
||||
let col = if cx < x { t.on_primary } else { t.on_secondary_container };
|
||||
p.circle_filled(pos2(cx, y), 1.5, col);
|
||||
}
|
||||
let hot = r.hovered() || s.drag.is_some();
|
||||
let h = spring((id, "handle"), if hot { 24.0 } else { 18.0 }, FAST);
|
||||
let handle = Rect::from_center_size(pos2(x, y), vec2(5.0, h));
|
||||
p.rect_filled(handle, cr(2.5), if live { t.primary } else { t.outline });
|
||||
if r.has_focus() {
|
||||
ring(p, t, handle, cr(2.5));
|
||||
}
|
||||
});
|
||||
if live && let Some(hp) = r.hover_pos() {
|
||||
out.hover = Some((at(hp.x), hp.x));
|
||||
ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
|
||||
}
|
||||
if live && r.has_focus() {
|
||||
ui.input(|i| {
|
||||
if i.key_pressed(egui::Key::ArrowRight) {
|
||||
out.seek = Some((time + 5.0).min(duration));
|
||||
} else if i.key_pressed(egui::Key::ArrowLeft) {
|
||||
out.seek = Some((time - 5.0).max(0.0));
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct SeekState {
|
||||
drive: Drive,
|
||||
drag: Option<f64>,
|
||||
exact: bool,
|
||||
}
|
||||
|
||||
/// "1:02:03" or "4:05".
|
||||
pub fn clock(s: f64) -> String {
|
||||
let s = if s.is_finite() { s.max(0.0) as u64 } else { 0 };
|
||||
let (h, m, sec) = (s / 3600, (s / 60) % 60, s % 60);
|
||||
if h > 0 { format!("{h}:{m:02}:{sec:02}") } else { format!("{m}:{sec:02}") }
|
||||
}
|
||||
|
||||
/// A list row: rounded, inset, tinted on hover, filled when chosen. Icon, title and detail stay on their columns.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn row(ui: &mut Ui, t: &Theme, id: Id, rect: Rect, glyph: &str, title: &str, detail: &str, chosen: bool) -> Response {
|
||||
let r = ui.interact(rect, id, Sense::click());
|
||||
r.widget_info(|| WidgetInfo::selected(Role::ListItem, ui.is_enabled(), chosen, title));
|
||||
let f = feel(&r, ui.is_enabled());
|
||||
let c = spring((id, "chosen"), f32::from(chosen), EFFECT);
|
||||
let look = Look::new(alpha(t.secondary_container, c), mix(t.on_surface, t.on_secondary_container, c));
|
||||
let shape = scale_rect(rect, 1.0 - 0.01 * f.press);
|
||||
look.paint(ui.painter(), t, shape, cr(radius::FULL), f);
|
||||
let p = ui.painter();
|
||||
let mut x = rect.left() + space::L;
|
||||
if !glyph.is_empty() {
|
||||
let at = pos2(x + 10.0, rect.center().y);
|
||||
if chosen { icon_filled(p, at, 20.0, glyph, look.ink) } else { icon(p, at, 20.0, glyph, mix(t.on_variant, look.ink, c)) }
|
||||
x += 20.0 + space::M;
|
||||
}
|
||||
let w = rect.right() - x - space::L;
|
||||
if detail.is_empty() {
|
||||
let g = line(p, title, fonts::ui(text::BODY), look.ink, w);
|
||||
p.galley(pos2(x, rect.center().y - g.size().y / 2.0), g, look.ink);
|
||||
} else {
|
||||
let g = line(p, title, fonts::ui(text::BODY), look.ink, w);
|
||||
let d = line(p, detail, fonts::ui(text::LABEL), t.on_variant, w);
|
||||
let total = g.size().y + d.size().y;
|
||||
let top = rect.center().y - total / 2.0;
|
||||
p.galley(pos2(x, top), g.clone(), look.ink);
|
||||
p.galley(pos2(x, top + g.size().y), d, t.on_variant);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Tabs with an underline that stretches from the old tab to the new one: its two ends ride different springs.
|
||||
pub fn tabs(ui: &mut Ui, t: &Theme, id: Id, rect: Rect, labels: &[&str], chosen: &mut usize) -> bool {
|
||||
let n = labels.len().max(1);
|
||||
let w = rect.width() / n as f32;
|
||||
let mut changed = false;
|
||||
let p = ui.painter().clone();
|
||||
for (i, l) in labels.iter().enumerate() {
|
||||
let cell = Rect::from_min_size(pos2(rect.left() + w * i as f32, rect.top()), vec2(w, rect.height()));
|
||||
let r = ui.interact(cell, id.with(i), Sense::click());
|
||||
r.widget_info(|| WidgetInfo::selected(Role::Tab, true, *chosen == i, *l));
|
||||
let f = feel(&r, true);
|
||||
if r.clicked() && *chosen != i {
|
||||
*chosen = i;
|
||||
changed = true;
|
||||
}
|
||||
if f.tint > 0.001 {
|
||||
p.rect_filled(cell, cr(radius::S), alpha(t.on_surface, f.tint));
|
||||
}
|
||||
if f.focus {
|
||||
ring(&p, t, cell, cr(radius::S));
|
||||
}
|
||||
let near = spring((id, "near", i), f32::from(*chosen == i), EFFECT);
|
||||
let ink = mix(t.on_variant, t.primary, near);
|
||||
let g = line(&p, l, fonts::med(text::BODY), ink, w - space::S);
|
||||
p.galley(cell.center() - g.size() / 2.0, g, ink);
|
||||
}
|
||||
let target_l = rect.left() + w * *chosen as f32 + w * 0.2;
|
||||
let target_r = target_l + w * 0.6;
|
||||
let moving_right = spring((id, "dir"), *chosen as f32, EFFECT) < *chosen as f32;
|
||||
let (lp, rp) = if moving_right { (crate::tokens::spring::SLOW, FAST) } else { (FAST, crate::tokens::spring::SLOW) };
|
||||
let l = spring((id, "l"), target_l, lp);
|
||||
let rr = spring((id, "r"), target_r, rp);
|
||||
p.rect_filled(Rect::from_min_max(pos2(l, rect.bottom() - 3.0), pos2(rr.max(l + 4.0), rect.bottom())), egui::CornerRadius { nw: 3, ne: 3, sw: 0, se: 0 }, t.primary);
|
||||
p.rect_filled(Rect::from_min_max(pos2(rect.left(), rect.bottom()), pos2(rect.right(), rect.bottom() + size::HAIRLINE)), 0.0, t.outline_variant);
|
||||
changed
|
||||
}
|
||||
|
||||
/// A filled pill text field with a leading icon; the outline turns primary while focused. Enter gives `submitted`.
|
||||
pub fn text_field(ui: &mut Ui, t: &Theme, id: Id, rect: Rect, value: &mut String, hint: &str, glyph: &str) -> (Response, bool) {
|
||||
let focused = ui.memory(|m| m.has_focus(id));
|
||||
let fcs = spring((id, "focus"), f32::from(focused), EFFECT);
|
||||
let p = ui.painter().clone();
|
||||
p.rect_filled(rect, cr(radius::FULL), t.highest);
|
||||
p.rect_stroke(rect, cr(radius::FULL), Stroke::new(1.0 + fcs, mix(t.outline_variant, t.primary, fcs)), StrokeKind::Inside);
|
||||
let mut inner = rect.shrink2(vec2(space::L, 0.0));
|
||||
if !glyph.is_empty() {
|
||||
icon(&p, pos2(inner.left() + 10.0, rect.center().y), 20.0, glyph, t.on_variant);
|
||||
inner.min.x += 20.0 + space::M;
|
||||
}
|
||||
let inner = Rect::from_min_max(pos2(inner.left(), rect.center().y - 10.0), pos2(inner.right(), rect.center().y + 10.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
let te = egui::TextEdit::singleline(value)
|
||||
.id(id)
|
||||
.frame(egui::Frame::NONE)
|
||||
.hint_text(egui::RichText::new(hint).color(t.on_variant))
|
||||
.font(fonts::ui(text::BODY))
|
||||
.text_color(t.on_surface)
|
||||
.margin(egui::Margin::ZERO)
|
||||
.desired_width(inner.width());
|
||||
let out = child.add(te);
|
||||
let submitted = out.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
(out, submitted)
|
||||
}
|
||||
|
||||
/// A key drawn as a cap, for menus, tooltips and the shortcuts list. Returns its width.
|
||||
pub fn keycap(p: &Painter, t: &Theme, right_center: Pos2, keys: &str) -> f32 {
|
||||
let mut x = right_center.x;
|
||||
for k in keys.split('+').rev() {
|
||||
let g = p.layout_no_wrap(k.to_string(), fonts::med(text::LABEL), t.on_variant);
|
||||
let w = (g.size().x + 2.0 * 6.0).max(20.0);
|
||||
let r = Rect::from_min_size(pos2(x - w, right_center.y - 11.0), vec2(w, 22.0));
|
||||
p.rect_stroke(r, cr(radius::XS + 2.0), Stroke::new(1.0, t.outline_variant), StrokeKind::Inside);
|
||||
p.galley(r.center() - g.size() / 2.0, g, t.on_variant);
|
||||
x -= w + 4.0;
|
||||
}
|
||||
right_center.x - x - 4.0
|
||||
}
|
||||
|
||||
/// A small label above a group of settings.
|
||||
pub fn heading(p: &Painter, t: &Theme, at: Pos2, what: &str) {
|
||||
p.text(at, Align2::LEFT_TOP, what, fonts::med(text::BODY), t.primary);
|
||||
}
|
||||
|
||||
/// Text of the label style, for a slider's name and value on one line.
|
||||
pub fn label_row(p: &Painter, t: &Theme, rect: Rect, name: &str, value: &str) {
|
||||
p.text(pos2(rect.left(), rect.center().y), Align2::LEFT_CENTER, name, fonts::ui(text::BODY), t.on_surface);
|
||||
p.text(pos2(rect.right(), rect.center().y), Align2::RIGHT_CENTER, value, fonts::ui(text::BODY), t.on_variant);
|
||||
}
|
||||
|
||||
/// Pins things that move by time to the motion setting: true if decoration may travel.
|
||||
pub fn travels() -> bool {
|
||||
!matches!(motion::level(), motion::Motion::Off | motion::Motion::Reduced)
|
||||
}
|
||||
|
||||
pub fn v2(x: f32, y: f32) -> Vec2 {
|
||||
vec2(x, y)
|
||||
}
|
||||
103
src/ui/glyphs.rs
Normal file
103
src/ui/glyphs.rs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
//! Material Symbols Rounded codepoints (subset in assets/symbols*.ttf, made by tools/icons.py).
|
||||
#![allow(dead_code)]
|
||||
|
||||
pub const PLAY_ARROW: &str = "\u{e037}";
|
||||
pub const PAUSE: &str = "\u{e034}";
|
||||
pub const SKIP_NEXT: &str = "\u{e044}";
|
||||
pub const SKIP_PREVIOUS: &str = "\u{e045}";
|
||||
pub const FAST_FORWARD: &str = "\u{e01f}";
|
||||
pub const FAST_REWIND: &str = "\u{e020}";
|
||||
pub const REPLAY_10: &str = "\u{e059}";
|
||||
pub const FORWARD_10: &str = "\u{e056}";
|
||||
pub const VOLUME_UP: &str = "\u{e050}";
|
||||
pub const VOLUME_DOWN: &str = "\u{e04d}";
|
||||
pub const VOLUME_MUTE: &str = "\u{e04e}";
|
||||
pub const VOLUME_OFF: &str = "\u{e04f}";
|
||||
pub const FULLSCREEN: &str = "\u{e5d0}";
|
||||
pub const FULLSCREEN_EXIT: &str = "\u{e5d1}";
|
||||
pub const BLOCK: &str = "\u{e033}";
|
||||
pub const SUBTITLES: &str = "\u{e048}";
|
||||
pub const SUBTITLES_OFF: &str = "\u{ef72}";
|
||||
pub const MUSIC_NOTE: &str = "\u{e3a1}";
|
||||
pub const QUEUE_MUSIC: &str = "\u{e03d}";
|
||||
pub const PLAYLIST_PLAY: &str = "\u{e05f}";
|
||||
pub const PLAYLIST_ADD: &str = "\u{e03b}";
|
||||
pub const SETTINGS: &str = "\u{e8b8}";
|
||||
pub const TUNE: &str = "\u{e429}";
|
||||
pub const MORE_VERT: &str = "\u{e5d4}";
|
||||
pub const FOLDER_OPEN: &str = "\u{e2c8}";
|
||||
pub const FILE_OPEN: &str = "\u{eaf3}";
|
||||
pub const LINK: &str = "\u{e157}";
|
||||
pub const MOVIE: &str = "\u{e02c}";
|
||||
pub const CLOSE: &str = "\u{e14c}";
|
||||
pub const ADD: &str = "\u{e145}";
|
||||
pub const DELETE: &str = "\u{e872}";
|
||||
pub const CHECK: &str = "\u{e5ca}";
|
||||
pub const CHEVRON_RIGHT: &str = "\u{e409}";
|
||||
pub const CHEVRON_LEFT: &str = "\u{e408}";
|
||||
pub const EXPAND_MORE: &str = "\u{e5cf}";
|
||||
pub const EXPAND_LESS: &str = "\u{e5ce}";
|
||||
pub const SPEED: &str = "\u{e9e4}";
|
||||
pub const ASPECT_RATIO: &str = "\u{e85b}";
|
||||
pub const ROTATE_RIGHT: &str = "\u{e41a}";
|
||||
pub const ROTATE_LEFT: &str = "\u{e419}";
|
||||
pub const ZOOM_IN: &str = "\u{e8ff}";
|
||||
pub const ZOOM_OUT: &str = "\u{e900}";
|
||||
pub const PHOTO_CAMERA: &str = "\u{e3b0}";
|
||||
pub const REPEAT: &str = "\u{e040}";
|
||||
pub const REPEAT_ONE: &str = "\u{e041}";
|
||||
pub const SHUFFLE: &str = "\u{e043}";
|
||||
pub const BOOKMARKS: &str = "\u{e98b}";
|
||||
pub const HISTORY: &str = "\u{e28e}";
|
||||
pub const KEYBOARD: &str = "\u{e312}";
|
||||
pub const INFO: &str = "\u{e88e}";
|
||||
pub const PALETTE: &str = "\u{e3b7}";
|
||||
pub const VIDEO_SETTINGS: &str = "\u{ea75}";
|
||||
pub const CLOSED_CAPTION: &str = "\u{e01c}";
|
||||
pub const DRAG_INDICATOR: &str = "\u{e945}";
|
||||
pub const CROP: &str = "\u{e3be}";
|
||||
pub const FLIP: &str = "\u{e3e8}";
|
||||
pub const BRIGHTNESS_6: &str = "\u{e3ab}";
|
||||
pub const CONTRAST: &str = "\u{eb37}";
|
||||
pub const TIMER: &str = "\u{e425}";
|
||||
pub const SYNC: &str = "\u{e627}";
|
||||
pub const RESTART_ALT: &str = "\u{f053}";
|
||||
pub const STOP: &str = "\u{e047}";
|
||||
pub const REMOVE: &str = "\u{e15b}";
|
||||
pub const CLEAR_ALL: &str = "\u{e0b8}";
|
||||
pub const VIDEO_FILE: &str = "\u{eb87}";
|
||||
pub const LANGUAGE: &str = "\u{e894}";
|
||||
pub const LIGHT_MODE: &str = "\u{e518}";
|
||||
pub const DARK_MODE: &str = "\u{e51c}";
|
||||
pub const BRIGHTNESS_AUTO: &str = "\u{e1ab}";
|
||||
pub const ANIMATION: &str = "\u{e71c}";
|
||||
pub const TEXT_FIELDS: &str = "\u{e262}";
|
||||
pub const FORMAT_SIZE: &str = "\u{e245}";
|
||||
pub const VERTICAL_ALIGN_BOTTOM: &str = "\u{e258}";
|
||||
pub const VISIBILITY: &str = "\u{e417}";
|
||||
pub const VISIBILITY_OFF: &str = "\u{e8f5}";
|
||||
pub const GRAPHIC_EQ: &str = "\u{e1b8}";
|
||||
pub const EQUALIZER: &str = "\u{e01d}";
|
||||
pub const SWAP_VERT: &str = "\u{e0c3}";
|
||||
pub const SLOW_MOTION_VIDEO: &str = "\u{e068}";
|
||||
pub const MEMORY: &str = "\u{e322}";
|
||||
pub const TERMINAL: &str = "\u{eb8e}";
|
||||
pub const PUBLIC: &str = "\u{e80b}";
|
||||
pub const SORT: &str = "\u{e164}";
|
||||
pub const SEARCH: &str = "\u{e8b6}";
|
||||
pub const OPEN_IN_NEW: &str = "\u{e895}";
|
||||
pub const HEARING: &str = "\u{e023}";
|
||||
pub const ARROW_BACK: &str = "\u{e5c4}";
|
||||
pub const ARROW_FORWARD: &str = "\u{e5c8}";
|
||||
pub const LOW_PRIORITY: &str = "\u{e16d}";
|
||||
pub const RADIO_BUTTON_CHECKED: &str = "\u{e837}";
|
||||
pub const RADIO_BUTTON_UNCHECKED: &str = "\u{e836}";
|
||||
pub const CHECK_CIRCLE: &str = "\u{e86c}";
|
||||
pub const ERROR: &str = "\u{e000}";
|
||||
pub const WARNING: &str = "\u{e002}";
|
||||
pub const CONTENT_COPY: &str = "\u{e14d}";
|
||||
pub const SYNC_ALT: &str = "\u{ea18}";
|
||||
pub const SPLITSCREEN: &str = "\u{f06d}";
|
||||
pub const FRAME_SOURCE: &str = "\u{f770}";
|
||||
pub const PICTURE_IN_PICTURE_ALT: &str = "\u{e911}";
|
||||
pub const HD: &str = "\u{e052}";
|
||||
365
src/ui/menu.rs
Normal file
365
src/ui/menu.rs
Normal file
|
|
@ -0,0 +1,365 @@
|
|||
//! Menus with submenus: container surface, radius 16, one shadow, rows 36 px with a radius 8 tint. They open by
|
||||
//! growing from 0.92 at the anchor with their rows fading in, submenus open after a 180 ms rest (or at once on click or
|
||||
//! Right), and keyboard works: arrows, Enter, Escape. They stay inside the window, flipping up or left when needed, and
|
||||
//! scroll when longer than it.
|
||||
|
||||
use crate::app::Act;
|
||||
use crate::fonts;
|
||||
use crate::motion::{spring, spring_from};
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{radius, size, space, state, text, time};
|
||||
use crate::ui::controls::keycap;
|
||||
use crate::widgets::{cr, feel, floating_shadow, icon, icon_filled, line, ring};
|
||||
use eframe::egui::{self, Align2, Color32, Id, Order, Pos2, Rect, Sense, pos2, vec2};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Item {
|
||||
pub glyph: &'static str,
|
||||
pub label: String,
|
||||
pub keys: String,
|
||||
/// Shown at the right in place of keys (a current value).
|
||||
pub detail: String,
|
||||
pub check: Option<bool>,
|
||||
pub act: Option<Act>,
|
||||
pub sub: Vec<Item>,
|
||||
pub enabled: bool,
|
||||
pub divider: bool,
|
||||
pub heading: bool,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
pub fn new(glyph: &'static str, label: impl Into<String>, act: Act) -> Item {
|
||||
Item { glyph, label: label.into(), act: Some(act), enabled: true, ..Item::default() }
|
||||
}
|
||||
|
||||
pub fn sub(glyph: &'static str, label: impl Into<String>, sub: Vec<Item>) -> Item {
|
||||
let enabled = !sub.is_empty();
|
||||
Item { glyph, label: label.into(), sub, enabled, ..Item::default() }
|
||||
}
|
||||
|
||||
pub fn divider() -> Item {
|
||||
Item { divider: true, ..Item::default() }
|
||||
}
|
||||
|
||||
pub fn heading(label: impl Into<String>) -> Item {
|
||||
Item { heading: true, label: label.into(), ..Item::default() }
|
||||
}
|
||||
|
||||
pub fn keys(mut self, k: &str) -> Item {
|
||||
self.keys = k.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn detail(mut self, d: impl Into<String>) -> Item {
|
||||
self.detail = d.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn check(mut self, on: bool) -> Item {
|
||||
self.check = Some(on);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, on: bool) -> Item {
|
||||
self.enabled = on;
|
||||
self
|
||||
}
|
||||
|
||||
fn height(&self) -> f32 {
|
||||
if self.divider {
|
||||
space::L + 1.0
|
||||
} else if self.heading {
|
||||
32.0
|
||||
} else {
|
||||
size::ROW + space::XS
|
||||
}
|
||||
}
|
||||
|
||||
fn clickable(&self) -> bool {
|
||||
!self.divider && !self.heading && self.enabled
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Menu {
|
||||
pub id: Id,
|
||||
pub anchor: Pos2,
|
||||
/// Opens above the anchor (for buttons at the bottom of the window).
|
||||
pub above: bool,
|
||||
/// Open submenus: index of the row at each depth.
|
||||
path: Vec<usize>,
|
||||
/// Row under the pointer and since when, per depth.
|
||||
rest: Option<(usize, usize, f64)>,
|
||||
focus: Option<(usize, usize)>,
|
||||
scroll: Vec<f32>,
|
||||
pub closing: bool,
|
||||
rows: Vec<Vec<Rect>>,
|
||||
frames: Vec<Rect>,
|
||||
}
|
||||
|
||||
impl Menu {
|
||||
pub fn new(name: &str, anchor: Pos2, above: bool) -> Menu {
|
||||
Menu { id: Id::new(("menu", name, anchor.x as i32, anchor.y as i32)), anchor, above, path: vec![], rest: None, focus: None, scroll: vec![], closing: false, rows: vec![], frames: vec![] }
|
||||
}
|
||||
|
||||
/// True if `p` is over any open level.
|
||||
pub fn contains(&self, p: Pos2) -> bool {
|
||||
self.frames.iter().any(|r| r.contains(p))
|
||||
}
|
||||
}
|
||||
|
||||
fn level_items<'a>(items: &'a [Item], path: &[usize]) -> Vec<&'a [Item]> {
|
||||
let mut out = vec![items];
|
||||
let mut cur = items;
|
||||
for &i in path {
|
||||
match cur.get(i) {
|
||||
Some(it) if !it.sub.is_empty() => {
|
||||
cur = &it.sub;
|
||||
out.push(cur);
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Draws the menu and returns what was chosen. `None` from `open` means it closed by itself (click outside, Escape).
|
||||
pub fn show(ctx: &egui::Context, t: &Theme, m: &mut Menu, items: &[Item], open: &mut bool) -> Option<Act> {
|
||||
let screen = ctx.content_rect().shrink(space::S);
|
||||
let now = ctx.input(|i| i.time);
|
||||
let mut chosen = None;
|
||||
// Keep the path valid if the items changed under it.
|
||||
let levels_len = level_items(items, &m.path).len();
|
||||
m.path.truncate(levels_len - 1);
|
||||
let levels = level_items(items, &m.path);
|
||||
m.rows.resize(levels.len(), vec![]);
|
||||
m.frames.resize(levels.len(), Rect::NOTHING);
|
||||
m.scroll.resize(levels.len(), 0.0);
|
||||
|
||||
// keyboard
|
||||
if !m.closing {
|
||||
let (up, down, left, right, enter, esc) = ctx.input(|i| {
|
||||
(
|
||||
i.key_pressed(egui::Key::ArrowUp),
|
||||
i.key_pressed(egui::Key::ArrowDown),
|
||||
i.key_pressed(egui::Key::ArrowLeft),
|
||||
i.key_pressed(egui::Key::ArrowRight),
|
||||
i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Space),
|
||||
i.key_pressed(egui::Key::Escape),
|
||||
)
|
||||
});
|
||||
let depth = levels.len() - 1;
|
||||
let list = levels[depth];
|
||||
let clickable: Vec<usize> = (0..list.len()).filter(|&i| list[i].clickable()).collect();
|
||||
let cur = m.focus.filter(|f| f.0 == depth).map(|f| f.1);
|
||||
if (up || down) && !clickable.is_empty() {
|
||||
let pos = cur.and_then(|c| clickable.iter().position(|&i| i == c));
|
||||
let next = match (pos, down) {
|
||||
(None, true) => 0,
|
||||
(None, false) => clickable.len() - 1,
|
||||
(Some(p), true) => (p + 1) % clickable.len(),
|
||||
(Some(p), false) => (p + clickable.len() - 1) % clickable.len(),
|
||||
};
|
||||
m.focus = Some((depth, clickable[next]));
|
||||
}
|
||||
if right && let Some(c) = cur && !list[c].sub.is_empty() {
|
||||
m.path.push(c);
|
||||
m.focus = list[c].sub.iter().position(|i| i.clickable()).map(|i| (depth + 1, i));
|
||||
}
|
||||
if (left && depth > 0) || (esc && depth > 0) {
|
||||
let back = m.path.pop();
|
||||
m.focus = back.map(|b| (depth - 1, b));
|
||||
} else if esc {
|
||||
m.closing = true;
|
||||
}
|
||||
if enter && let Some(c) = cur {
|
||||
let it = &list[c];
|
||||
if !it.sub.is_empty() {
|
||||
m.path.push(c);
|
||||
m.focus = it.sub.iter().position(|i| i.clickable()).map(|i| (depth + 1, i));
|
||||
} else if let Some(a) = &it.act {
|
||||
chosen = Some(a.clone());
|
||||
m.closing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let levels = level_items(items, &m.path);
|
||||
|
||||
let mut new_path: Option<Vec<usize>> = None;
|
||||
let mut any_hovered = false;
|
||||
for (d, list) in levels.iter().enumerate() {
|
||||
// size
|
||||
let p = ctx.layer_painter(egui::LayerId::new(Order::Foreground, m.id.with(d)));
|
||||
let mut w: f32 = size::MENU_MIN;
|
||||
for it in list.iter() {
|
||||
if it.divider {
|
||||
continue;
|
||||
}
|
||||
let g = p.layout_no_wrap(it.label.clone(), fonts::ui(text::BODY), t.on_surface);
|
||||
let right = if !it.sub.is_empty() { 28.0 } else { 0.0 }
|
||||
+ if it.keys.is_empty() { 0.0 } else { 24.0 * it.keys.split('+').count() as f32 + 12.0 * it.keys.len() as f32 / 2.0 }
|
||||
+ if it.detail.is_empty() { 0.0 } else { p.layout_no_wrap(it.detail.clone(), fonts::ui(text::BODY), t.on_variant).size().x + space::M };
|
||||
w = w.max(space::M + 20.0 + space::M + g.size().x + space::L + right + space::M + 2.0 * space::S);
|
||||
}
|
||||
let w = w.min(size::MENU_MAX + 64.0).min(screen.width());
|
||||
let content_h: f32 = list.iter().map(|i| i.height()).sum::<f32>() + 2.0 * space::S;
|
||||
let h = content_h.min(screen.height());
|
||||
// place
|
||||
let origin = if d == 0 {
|
||||
m.anchor
|
||||
} else {
|
||||
let parent = m.rows[d - 1].get(m.path[d - 1]).copied().unwrap_or(Rect::from_min_size(m.anchor, vec2(1.0, 1.0)));
|
||||
pos2(parent.right() + space::XS, parent.top() - space::S)
|
||||
};
|
||||
let mut x = origin.x;
|
||||
let mut y = if d == 0 && m.above { origin.y - h } else { origin.y };
|
||||
if x + w > screen.right() {
|
||||
x = if d == 0 { (screen.right() - w).max(screen.left()) } else {
|
||||
let parent = m.frames[d - 1];
|
||||
(parent.left() - w - space::XS).max(screen.left())
|
||||
};
|
||||
}
|
||||
if y + h > screen.bottom() {
|
||||
y = if d == 0 && !m.above && origin.y - h > screen.top() { origin.y - h } else { (screen.bottom() - h).max(screen.top()) };
|
||||
}
|
||||
if y < screen.top() {
|
||||
y = screen.top();
|
||||
}
|
||||
let frame = Rect::from_min_size(pos2(x, y), vec2(w, h));
|
||||
m.frames[d] = frame;
|
||||
// open animation: grow from 0.92 at the anchor's side and fade in
|
||||
let key = (m.id, d, m.path.get(..d).map(|p| p.to_vec()).unwrap_or_default());
|
||||
let grow = spring_from((key.clone(), "grow"), 0.92, if m.closing { 0.96 } else { 1.0 }, DEFAULT);
|
||||
let fade = spring_from((key, "fade"), 0.0, if m.closing { 0.0 } else { 1.0 }, EFFECT).clamp(0.0, 1.0);
|
||||
let pivot = pos2(if x < origin.x - 1.0 { frame.right() } else { frame.left() }, if y < origin.y - 1.0 { frame.bottom() } else { frame.top() });
|
||||
let shown = Rect::from_min_max(pivot + (frame.min - pivot) * grow, pivot + (frame.max - pivot) * grow);
|
||||
if fade < 0.01 && m.closing {
|
||||
continue;
|
||||
}
|
||||
let area = egui::Area::new(m.id.with(("area", d))).order(Order::Foreground).fixed_pos(frame.min).constrain(false);
|
||||
area.show(ctx, |ui| {
|
||||
ui.set_min_size(frame.size());
|
||||
let mut p = ui.painter().clone();
|
||||
p.set_opacity(fade);
|
||||
floating_shadow(&p, shown, cr(radius::L), t.dark);
|
||||
p.rect_filled(shown, cr(radius::L), t.container);
|
||||
let clip = shown.shrink(1.0);
|
||||
let p = p.with_clip_rect(clip);
|
||||
// scroll when longer than the window
|
||||
let overflow = (content_h - h).max(0.0);
|
||||
if overflow > 0.0 && ui.rect_contains_pointer(frame) {
|
||||
let d_y = crate::widgets::wheel(ui).y;
|
||||
m.scroll[d] = (m.scroll[d] - d_y).clamp(0.0, overflow);
|
||||
}
|
||||
let off = spring((m.id, "scroll", d), m.scroll[d], EFFECT);
|
||||
let mut ry = frame.top() + space::S - off;
|
||||
let mut rects = Vec::with_capacity(list.len());
|
||||
for (i, it) in list.iter().enumerate() {
|
||||
let rh = it.height();
|
||||
let rr = Rect::from_min_size(pos2(frame.left() + space::S, ry), vec2(w - 2.0 * space::S, rh));
|
||||
ry += rh;
|
||||
rects.push(rr);
|
||||
if it.divider {
|
||||
p.rect_filled(Rect::from_center_size(rr.center(), vec2(rr.width(), 1.0)), 0.0, t.outline_variant);
|
||||
continue;
|
||||
}
|
||||
if it.heading {
|
||||
p.text(pos2(rr.left() + space::M, rr.center().y + 2.0), Align2::LEFT_CENTER, &it.label, fonts::med(text::LABEL), t.primary);
|
||||
continue;
|
||||
}
|
||||
let row = Rect::from_center_size(rr.center(), vec2(rr.width(), size::ROW));
|
||||
if !clip.intersects(row) {
|
||||
continue;
|
||||
}
|
||||
let resp = ui.interact(row.intersect(clip), m.id.with(("row", d, i, m.path.get(..d).map(|p| p.to_vec()))), Sense::click());
|
||||
let live = it.enabled && !m.closing;
|
||||
let f = feel(&resp, live);
|
||||
let open_here = m.path.get(d) == Some(&i);
|
||||
let focused = m.focus == Some((d, i));
|
||||
let tint = if open_here { state::HOVER.max(f.tint) } else { f.tint };
|
||||
if tint > 0.001 {
|
||||
p.rect_filled(row, cr(radius::S), alpha(t.on_surface, tint));
|
||||
}
|
||||
if focused && !resp.hovered() {
|
||||
ring(&p, t, row.shrink(2.0), cr(radius::S));
|
||||
}
|
||||
let ink = if live { t.on_surface } else { alpha(t.on_surface, state::DISABLED) };
|
||||
let soft = if live { t.on_variant } else { alpha(t.on_surface, state::DISABLED) };
|
||||
let mut lx = row.left() + space::M;
|
||||
let ic = pos2(lx + 10.0, row.center().y);
|
||||
match it.check {
|
||||
Some(true) => icon_filled(&p, ic, 20.0, crate::ui::glyphs::CHECK, if live { t.primary } else { ink }),
|
||||
Some(false) if it.glyph.is_empty() => {}
|
||||
_ if !it.glyph.is_empty() => icon(&p, ic, 20.0, it.glyph, soft),
|
||||
_ => {}
|
||||
}
|
||||
lx += 20.0 + space::M;
|
||||
let mut right = row.right() - space::M;
|
||||
if !it.sub.is_empty() {
|
||||
icon(&p, pos2(right - 10.0, row.center().y), 20.0, crate::ui::glyphs::CHEVRON_RIGHT, soft);
|
||||
right -= 20.0 + space::S;
|
||||
}
|
||||
if !it.keys.is_empty() {
|
||||
let kw = keycap(&p, t, pos2(right, row.center().y), &it.keys);
|
||||
right -= kw + space::S;
|
||||
} else if !it.detail.is_empty() {
|
||||
let g = line(&p, &it.detail, fonts::ui(text::BODY), soft, 160.0);
|
||||
p.galley(pos2(right - g.size().x, row.center().y - g.size().y / 2.0), g.clone(), soft);
|
||||
right -= g.size().x + space::M;
|
||||
}
|
||||
let g = line(&p, &it.label, fonts::ui(text::BODY), ink, right - lx);
|
||||
p.galley(pos2(lx, row.center().y - g.size().y / 2.0), g, ink);
|
||||
if !live {
|
||||
continue;
|
||||
}
|
||||
if resp.hovered() {
|
||||
any_hovered = true;
|
||||
m.focus = Some((d, i));
|
||||
match m.rest {
|
||||
Some((rd, ri, since)) if rd == d && ri == i => {
|
||||
let rested = now - since >= time::SUBMENU;
|
||||
let want: Vec<usize> = m.path[..d.min(m.path.len())].iter().copied().chain((!it.sub.is_empty()).then_some(i)).collect();
|
||||
if rested && want != m.path {
|
||||
new_path = Some(want);
|
||||
} else if !rested {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(time::SUBMENU - (now - since) + 0.01));
|
||||
}
|
||||
}
|
||||
_ => m.rest = Some((d, i, now)),
|
||||
}
|
||||
}
|
||||
if resp.clicked() {
|
||||
if !it.sub.is_empty() {
|
||||
let mut want: Vec<usize> = m.path[..d.min(m.path.len())].to_vec();
|
||||
want.push(i);
|
||||
new_path = Some(want);
|
||||
} else if let Some(a) = &it.act {
|
||||
chosen = Some(a.clone());
|
||||
m.closing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
m.rows[d] = rects;
|
||||
let _ = Color32::TRANSPARENT;
|
||||
});
|
||||
}
|
||||
if let Some(p) = new_path {
|
||||
m.path = p;
|
||||
}
|
||||
if !any_hovered {
|
||||
m.rest = None;
|
||||
}
|
||||
// A click outside every level closes it.
|
||||
let pressed_outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !m.frames.iter().any(|f| f.contains(p))));
|
||||
if pressed_outside && !m.closing {
|
||||
m.closing = true;
|
||||
}
|
||||
if m.closing {
|
||||
let still = spring_from(((m.id, 0usize, Vec::<usize>::new()), "fade"), 0.0, 0.0, EFFECT);
|
||||
if still < 0.01 {
|
||||
*open = false;
|
||||
}
|
||||
}
|
||||
chosen
|
||||
}
|
||||
196
src/ui/menus.rs
Normal file
196
src/ui/menus.rs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
//! What each menu holds, built fresh each frame from mpv's state so ticks are always right.
|
||||
|
||||
use crate::app::{Act, MenuKind, Sheet, cmd, set};
|
||||
use crate::config::Settings;
|
||||
use crate::mpv::{State, trim_num};
|
||||
use crate::ui::controls::clock;
|
||||
use crate::ui::glyphs as g;
|
||||
use crate::ui::menu::Item;
|
||||
|
||||
pub fn build(kind: MenuKind, s: &State, cfg: &Settings) -> Vec<Item> {
|
||||
match kind {
|
||||
MenuKind::Context => context(s, cfg),
|
||||
MenuKind::Audio => audio(s),
|
||||
MenuKind::Subtitles => subtitles(s),
|
||||
MenuKind::Speed => speed(s),
|
||||
MenuKind::Chapters => chapters(s),
|
||||
MenuKind::Video => video(s),
|
||||
}
|
||||
}
|
||||
|
||||
fn context(s: &State, cfg: &Settings) -> Vec<Item> {
|
||||
let loaded = s.loaded();
|
||||
let mut v = vec![
|
||||
Item::new(g::FOLDER_OPEN, "Open file", Act::OpenFiles).keys("Ctrl+O"),
|
||||
Item::new(g::LINK, "Open link", Act::OpenUrl).keys("Ctrl+L"),
|
||||
Item::new(g::FOLDER_OPEN, "Open folder", Act::OpenFolder),
|
||||
Item::sub(g::HISTORY, "Recent", recent(cfg)),
|
||||
Item::divider(),
|
||||
];
|
||||
if loaded {
|
||||
v.extend([
|
||||
Item::new(if s.pause { g::PLAY_ARROW } else { g::PAUSE }, if s.pause { "Play" } else { "Pause" }, Act::TogglePause).keys("Space"),
|
||||
Item::sub(g::SPEED, "Speed", speed(s)).detail(format!("{}×", trim_num(s.speed, 2))),
|
||||
Item::sub(g::REPEAT, "Repeat", vec![
|
||||
Item::new("", "Off", Act::Cmd(vec!["set".into(), "loop-file".into(), "no".into()])).check(!s.loop_file && !s.loop_playlist && s.ab_a.is_none()),
|
||||
Item::new("", "This video", set("loop-file", "inf")).check(s.loop_file).keys("Shift+L"),
|
||||
Item::new("", "Playlist", set("loop-playlist", "inf")).check(s.loop_playlist && !s.loop_file),
|
||||
Item::divider(),
|
||||
Item::new(g::SYNC_ALT, ab_label(s), cmd(&["ab-loop"])).keys("L"),
|
||||
]),
|
||||
Item::sub(g::BOOKMARKS, "Chapters", chapters(s)),
|
||||
Item::divider(),
|
||||
Item::sub(g::MOVIE, "Video", video(s)),
|
||||
Item::sub(g::MUSIC_NOTE, "Sound", audio(s)),
|
||||
Item::sub(g::SUBTITLES, "Subtitles", subtitles(s)),
|
||||
Item::new(g::TUNE, "Adjust picture and sound", Act::Sheet(Sheet::Adjust)).keys("Ctrl+E"),
|
||||
Item::divider(),
|
||||
Item::new(g::PHOTO_CAMERA, "Take screenshot", Act::Screenshot(true)).keys("S"),
|
||||
Item::new(g::PHOTO_CAMERA, "Screenshot without subtitles", Act::Screenshot(false)).keys("Shift+S"),
|
||||
Item::new(g::PLAYLIST_PLAY, "Playlist", Act::Sheet(Sheet::Playlist)).keys("Ctrl+P"),
|
||||
Item::new(g::CONTENT_COPY, "Copy file location", Act::CopyPath),
|
||||
Item::new(g::STOP, "Stop", cmd(&["stop"])).keys("Ctrl+W"),
|
||||
Item::divider(),
|
||||
]);
|
||||
}
|
||||
v.extend([
|
||||
Item::new(g::TERMINAL, "mpv console", cmd(&["script-binding", "console/enable"])).keys("`").enabled(cfg.use_mpv_conf || true),
|
||||
Item::new(g::INFO, "Playback statistics", cmd(&["script-binding", "stats/display-stats-toggle"])).keys("Shift+I").enabled(loaded),
|
||||
Item::new(g::SETTINGS, "Settings", Act::Settings).keys("Ctrl+,"),
|
||||
Item::new(g::CLOSE, "Quit", Act::Quit).keys("Q"),
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
fn ab_label(s: &State) -> String {
|
||||
match (s.ab_a, s.ab_b) {
|
||||
(None, _) => "Set loop start".into(),
|
||||
(Some(a), None) => format!("Set loop end (from {})", clock(a)),
|
||||
(Some(a), Some(b)) => format!("Clear loop {} to {}", clock(a), clock(b)),
|
||||
}
|
||||
}
|
||||
|
||||
fn recent(cfg: &Settings) -> Vec<Item> {
|
||||
let mut v: Vec<Item> = cfg
|
||||
.recent
|
||||
.iter()
|
||||
.take(12)
|
||||
.map(|r| {
|
||||
let name = if r.title.is_empty() { crate::mpv::display_name(&r.path) } else { r.title.clone() };
|
||||
Item::new(if r.path.contains("://") { g::PUBLIC } else { g::VIDEO_FILE }, name, Act::Load(r.path.clone()))
|
||||
})
|
||||
.collect();
|
||||
if !v.is_empty() {
|
||||
v.push(Item::divider());
|
||||
v.push(Item::new(g::CLEAR_ALL, "Clear recent files", Act::ClearRecent));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub const SPEEDS: [f64; 10] = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 3.0, 4.0];
|
||||
|
||||
fn speed(s: &State) -> Vec<Item> {
|
||||
let mut v: Vec<Item> = SPEEDS
|
||||
.iter()
|
||||
.map(|&x| Item::new("", if x == 1.0 { "Normal".to_string() } else { format!("{}×", trim_num(x, 2)) }, set("speed", x)).check((s.speed - x).abs() < 0.001))
|
||||
.collect();
|
||||
v.push(Item::divider());
|
||||
v.push(Item::new(g::REMOVE, "Slower", cmd(&["multiply", "speed", "1/1.1"])).keys("["));
|
||||
v.push(Item::new(g::ADD, "Faster", cmd(&["multiply", "speed", "1.1"])).keys("]"));
|
||||
v.push(Item::new(g::RESTART_ALT, "Reset", set("speed", "1")).keys("Backspace"));
|
||||
v.push(Item::new(g::GRAPHIC_EQ, "Keep the pitch", set("audio-pitch-correction", if s.audio_pitch_correction { "no" } else { "yes" })).check(s.audio_pitch_correction));
|
||||
v
|
||||
}
|
||||
|
||||
fn track_items(s: &State, kind: &str, prop: &str, current: &str) -> Vec<Item> {
|
||||
s.tracks_of(kind)
|
||||
.map(|t| {
|
||||
let it = Item::new("", t.label(), set(prop, t.id)).check(current == t.id.to_string());
|
||||
let d = t.detail();
|
||||
if d.is_empty() { it } else { it.detail(d) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn audio(s: &State) -> Vec<Item> {
|
||||
let mut v = vec![Item::heading("Sound track")];
|
||||
v.extend(track_items(s, "audio", "aid", &s.aid));
|
||||
v.push(Item::new("", "None", set("aid", "no")).check(s.aid == "no"));
|
||||
v.extend([
|
||||
Item::divider(),
|
||||
Item::new(g::ADD, "Load sound track", Act::LoadAudio),
|
||||
Item::new(g::REMOVE, "Delay 100 ms less", cmd(&["add", "audio-delay", "-0.1"])).keys("Ctrl+-"),
|
||||
Item::new(g::ADD, "Delay 100 ms more", cmd(&["add", "audio-delay", "0.1"])).keys("Ctrl++"),
|
||||
Item::new(g::TUNE, "More sound settings", Act::Sheet(Sheet::Adjust)),
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
fn subtitles(s: &State) -> Vec<Item> {
|
||||
let mut v = vec![Item::heading("Subtitles")];
|
||||
v.push(Item::new("", "Off", set("sid", "no")).check(s.sid == "no" || s.sid.is_empty()));
|
||||
v.extend(track_items(s, "sub", "sid", &s.sid));
|
||||
let secondary: Vec<Item> = std::iter::once(Item::new("", "Off", set("secondary-sid", "no")).check(s.secondary_sid == "no" || s.secondary_sid.is_empty()))
|
||||
.chain(track_items(s, "sub", "secondary-sid", &s.secondary_sid))
|
||||
.collect();
|
||||
v.extend([
|
||||
Item::divider(),
|
||||
Item::new(g::ADD, "Load subtitles", Act::LoadSub),
|
||||
Item::sub(g::SUBTITLES, "Second subtitles", secondary),
|
||||
Item::new(g::VISIBILITY, "Show subtitles", cmd(&["cycle", "sub-visibility"])).check(s.sub_visible).keys("V"),
|
||||
Item::new(g::REMOVE, "Show 100 ms earlier", cmd(&["add", "sub-delay", "-0.1"])).keys("Z"),
|
||||
Item::new(g::ADD, "Show 100 ms later", cmd(&["add", "sub-delay", "0.1"])).keys("X"),
|
||||
Item::new(g::TUNE, "More subtitle settings", Act::Sheet(Sheet::Adjust)),
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
fn chapters(s: &State) -> Vec<Item> {
|
||||
s.chapters
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let title = c.title.clone().filter(|t| !t.is_empty()).unwrap_or_else(|| format!("Chapter {}", i + 1));
|
||||
Item::new("", title, set("chapter", i)).detail(clock(c.time)).check(s.chapter == i as i64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub const ASPECTS: [(&str, &str); 7] = [("-1", "Original"), ("16:9", "16:9"), ("4:3", "4:3"), ("2.35:1", "2.35:1"), ("1.85:1", "1.85:1"), ("21:9", "21:9"), ("1:1", "1:1")];
|
||||
|
||||
fn video(s: &State) -> Vec<Item> {
|
||||
let mut v = vec![Item::heading("Video track")];
|
||||
v.extend(track_items(s, "video", "vid", &s.vid));
|
||||
let aspect = s.aspect_override.as_str();
|
||||
let aspects: Vec<Item> = ASPECTS
|
||||
.iter()
|
||||
.map(|(val, label)| {
|
||||
let on = if *val == "-1" { aspect == "-1" || aspect == "no" || aspect.is_empty() } else { aspect_eq(aspect, val) };
|
||||
Item::new("", *label, set("video-aspect-override", val)).check(on)
|
||||
})
|
||||
.collect();
|
||||
v.extend([
|
||||
Item::divider(),
|
||||
Item::sub(g::ASPECT_RATIO, "Aspect ratio", aspects),
|
||||
Item::new(g::CROP, "Fill the window", set("panscan", if s.panscan > 0.5 { "0" } else { "1" })).check(s.panscan > 0.5),
|
||||
Item::new(g::ROTATE_RIGHT, "Rotate", set("video-rotate", (s.rotate + 90) % 360)).detail(format!("{}°", s.rotate)),
|
||||
Item::new(g::FLIP, "Mirror", cmd(&["vf", "toggle", "hflip"])).check(s.vf.contains("hflip")),
|
||||
Item::new(g::ANIMATION, "Deinterlace", set("deinterlace", if s.deinterlace { "no" } else { "yes" })).check(s.deinterlace),
|
||||
Item::new(g::MEMORY, "Hardware decoding", set("hwdec", if s.hwdec == "no" { "auto-safe" } else { "no" })).check(s.hwdec != "no").keys("Ctrl+H"),
|
||||
Item::divider(),
|
||||
Item::new(g::SKIP_NEXT, "Next frame", cmd(&["frame-step"])).keys("."),
|
||||
Item::new(g::SKIP_PREVIOUS, "Previous frame", cmd(&["frame-back-step"])).keys(","),
|
||||
Item::new(g::RESTART_ALT, "Reset picture", Act::ResetVideo),
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
fn aspect_eq(cur: &str, want: &str) -> bool {
|
||||
let parse = |s: &str| -> Option<f64> {
|
||||
if let Some((a, b)) = s.split_once(':') { Some(a.parse::<f64>().ok()? / b.parse::<f64>().ok()?) } else { s.parse().ok() }
|
||||
};
|
||||
match (parse(cur), parse(want)) {
|
||||
(Some(a), Some(b)) => (a - b).abs() < 0.01,
|
||||
_ => cur == want,
|
||||
}
|
||||
}
|
||||
30
src/ui/mod.rs
Normal file
30
src/ui/mod.rs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
//! Screens and overlays. Each piece draws from a `View` and pushes `Act`s for the app to apply.
|
||||
|
||||
pub mod chrome;
|
||||
pub mod controls;
|
||||
pub mod glyphs;
|
||||
pub mod menu;
|
||||
pub mod menus;
|
||||
pub mod settings;
|
||||
pub mod sheets;
|
||||
|
||||
use crate::app::Act;
|
||||
use crate::config::Settings;
|
||||
use crate::mpv::State;
|
||||
use crate::theme::Theme;
|
||||
|
||||
pub struct View<'a> {
|
||||
pub t: &'a Theme,
|
||||
pub s: &'a State,
|
||||
pub cfg: &'a Settings,
|
||||
pub acts: &'a mut Vec<Act>,
|
||||
pub now: f64,
|
||||
/// How visible the controls are, 0..1.
|
||||
pub vis: f32,
|
||||
}
|
||||
|
||||
impl View<'_> {
|
||||
pub fn act(&mut self, a: Act) {
|
||||
self.acts.push(a);
|
||||
}
|
||||
}
|
||||
563
src/ui/settings.rs
Normal file
563
src/ui/settings.rs
Normal file
|
|
@ -0,0 +1,563 @@
|
|||
//! Dialogs: Settings (appearance with a live preview, playback, languages, mpv, keys, about) and Open link.
|
||||
|
||||
use crate::app::{Act, App, Dialog};
|
||||
use crate::config::{self, ColourFrom};
|
||||
use crate::fonts;
|
||||
use crate::motion::{spring, spring_from};
|
||||
use crate::shape;
|
||||
use crate::theme::{self, alpha, mix};
|
||||
use crate::tokens::elevation::SCRIM;
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT, FAST};
|
||||
use crate::tokens::{radius, size, space, text};
|
||||
use crate::ui::controls::{self, heading, keycap, play_pause_glyph, slider, text_field};
|
||||
use crate::ui::glyphs as g;
|
||||
use crate::widgets::{Kind, button, cr, feel, floating_shadow, icon, icon_button, line, ring, segmented, switch};
|
||||
use eframe::egui::{self, Align2, Color32, Id, Order, Rect, Sense, Ui, pos2, vec2};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Changed {
|
||||
pub theme: bool,
|
||||
pub mpv: bool,
|
||||
pub any: bool,
|
||||
}
|
||||
|
||||
const PAGES: [(&str, &str); 6] = [
|
||||
(g::PALETTE, "Appearance"),
|
||||
(g::PLAY_ARROW, "Playback"),
|
||||
(g::LANGUAGE, "Languages"),
|
||||
(g::TERMINAL, "mpv"),
|
||||
(g::KEYBOARD, "Keyboard"),
|
||||
(g::INFO, "About"),
|
||||
];
|
||||
|
||||
pub const SWATCHES: [&str; 8] = ["#c9a227", "#d0583b", "#3f8f5a", "#1f8a92", "#4a77c4", "#8a6d3b", "#b84a73", "#6b7b8c"];
|
||||
|
||||
fn scrim(ctx: &egui::Context, open: bool) -> bool {
|
||||
let k = spring_from("dialog-scrim", 0.0, f32::from(open), EFFECT);
|
||||
let screen = ctx.content_rect();
|
||||
let mut clicked = false;
|
||||
egui::Area::new(Id::new("scrim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
|
||||
let r = ui.interact(screen, Id::new("scrim-hit"), Sense::click());
|
||||
ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha((SCRIM * 255.0 * k) as u8));
|
||||
clicked = r.clicked();
|
||||
});
|
||||
clicked
|
||||
}
|
||||
|
||||
/// Draws the open dialog. Settings are changed in place; what changed comes back.
|
||||
pub fn dialog(ctx: &egui::Context, app: &mut App, acts: &mut Vec<Act>) -> Changed {
|
||||
let mut ch = Changed::default();
|
||||
DESKTOP.with(|d| d.set(app.desktop_has_colour()));
|
||||
let outside = scrim(ctx, true);
|
||||
match app.dialog {
|
||||
Dialog::Url => url(ctx, app, acts, outside),
|
||||
Dialog::Settings => {
|
||||
settings(ctx, app, &mut ch);
|
||||
if outside {
|
||||
app.dialog = Dialog::None;
|
||||
}
|
||||
}
|
||||
Dialog::None => {}
|
||||
}
|
||||
ch
|
||||
}
|
||||
|
||||
fn frame(ctx: &egui::Context, name: &str, w: f32, h: f32, f: impl FnOnce(&mut Ui, Rect)) {
|
||||
let screen = ctx.content_rect();
|
||||
let w = w.min(screen.width() - 2.0 * space::L);
|
||||
let h = h.min(screen.height() - 2.0 * space::L);
|
||||
let rect = Rect::from_center_size(screen.center(), vec2(w, h));
|
||||
let grow = spring_from((name, "grow"), 0.92, 1.0, DEFAULT);
|
||||
let fade = spring_from((name, "fade"), 0.0, 1.0, EFFECT).clamp(0.0, 1.0);
|
||||
egui::Area::new(Id::new(("dialog", name))).order(Order::Foreground).fixed_pos(rect.min).constrain(false).show(ctx, |ui| {
|
||||
ui.set_min_size(rect.size());
|
||||
ui.set_max_size(rect.size());
|
||||
ui.multiply_opacity(fade);
|
||||
let shown = Rect::from_center_size(rect.center(), rect.size() * grow);
|
||||
floating_shadow(ui.painter(), shown, cr(radius::XL), app_dark(ui));
|
||||
let _ = ui.interact(rect, Id::new((name, "bg")), Sense::click());
|
||||
ui.painter().rect_filled(shown, cr(radius::XL), ui.visuals().window_fill);
|
||||
f(ui, rect);
|
||||
});
|
||||
}
|
||||
|
||||
fn app_dark(ui: &Ui) -> bool {
|
||||
ui.visuals().dark_mode
|
||||
}
|
||||
|
||||
fn url(ctx: &egui::Context, app: &mut App, acts: &mut Vec<Act>, outside: bool) {
|
||||
let t = app.theme.clone();
|
||||
let mut close = outside;
|
||||
let mut go: Option<bool> = None;
|
||||
frame(ctx, "url", size::DIALOG_M, 260.0, |ui, r| {
|
||||
let p = ui.painter().clone();
|
||||
let x = r.left() + space::XL;
|
||||
let w = r.width() - 2.0 * space::XL;
|
||||
p.text(pos2(x, r.top() + space::XL), Align2::LEFT_TOP, "Open link", fonts::ui(text::HEADLINE), t.on_surface);
|
||||
let body = p.layout("Paste the address of a video or stream. Pages from sites yt-dlp knows work too.".into(), fonts::ui(text::BODY), t.on_variant, w);
|
||||
p.galley(pos2(x, r.top() + space::XL + 40.0), body, t.on_variant);
|
||||
let fr = Rect::from_min_size(pos2(x, r.top() + 128.0), vec2(w, 48.0));
|
||||
let id = Id::new("url-field");
|
||||
let (resp, submitted) = text_field(ui, &t, id, fr, &mut app.url_text, "https://", g::LINK);
|
||||
if ui.data_mut(|d| d.remove_temp::<bool>(Id::new("url-focus"))).unwrap_or(false) {
|
||||
resp.request_focus();
|
||||
}
|
||||
if submitted {
|
||||
go = Some(false);
|
||||
}
|
||||
let by = r.bottom() - space::XL - 40.0;
|
||||
let open = Rect::from_min_size(pos2(r.right() - space::XL - 96.0, by), vec2(96.0, 40.0));
|
||||
let add = Rect::from_min_size(pos2(open.left() - space::S - 148.0, by), vec2(148.0, 40.0));
|
||||
let cancel = Rect::from_min_size(pos2(add.left() - space::S - 88.0, by), vec2(88.0, 40.0));
|
||||
let has = !app.url_text.trim().is_empty();
|
||||
if button(ui, &t, Id::new("url-cancel"), cancel, "", "Cancel", Kind::Text).clicked() {
|
||||
close = true;
|
||||
}
|
||||
ui.add_enabled_ui(has, |ui| {
|
||||
if button(ui, &t, Id::new("url-add"), add, "", "Add to playlist", Kind::Text).clicked() {
|
||||
go = Some(true);
|
||||
}
|
||||
if button(ui, &t, Id::new("url-open"), open, "", "Open", Kind::Filled).clicked() {
|
||||
go = Some(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(append) = go {
|
||||
let u = app.url_text.trim().to_string();
|
||||
if !u.is_empty() {
|
||||
acts.push(if append { Act::Append(u) } else { Act::Load(u) });
|
||||
app.url_text.clear();
|
||||
close = true;
|
||||
}
|
||||
}
|
||||
if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.dialog = Dialog::None;
|
||||
crate::motion::forget(("url", "grow"));
|
||||
crate::motion::forget(("url", "fade"));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings(ctx: &egui::Context, app: &mut App, ch: &mut Changed) {
|
||||
let t = app.theme.clone();
|
||||
let mut close = false;
|
||||
frame(ctx, "settings", size::DIALOG_L, 600.0, |ui, r| {
|
||||
let p = ui.painter().clone();
|
||||
// left: sections with a sliding pill
|
||||
let nav = Rect::from_min_size(r.min, vec2(196.0, r.height()));
|
||||
p.text(pos2(nav.left() + space::XL, nav.top() + space::XL), Align2::LEFT_TOP, "Settings", fonts::ui(text::HEADLINE), t.on_surface);
|
||||
let top = nav.top() + 80.0;
|
||||
let pill_y = spring("settings-pill", top + app.settings_page as f32 * 48.0, FAST);
|
||||
p.rect_filled(Rect::from_min_size(pos2(nav.left() + space::M, pill_y), vec2(nav.width() - 2.0 * space::M, 44.0)), cr(radius::FULL), t.secondary_container);
|
||||
for (i, (glyph, label)) in PAGES.iter().enumerate() {
|
||||
let rr = Rect::from_min_size(pos2(nav.left() + space::M, top + i as f32 * 48.0), vec2(nav.width() - 2.0 * space::M, 44.0));
|
||||
let resp = ui.interact(rr, Id::new(("settings-nav", i)), Sense::click());
|
||||
let f = feel(&resp, true);
|
||||
if f.tint > 0.001 {
|
||||
p.rect_filled(rr, cr(radius::FULL), alpha(t.on_surface, f.tint));
|
||||
}
|
||||
if f.focus {
|
||||
ring(&p, &t, rr, cr(radius::FULL));
|
||||
}
|
||||
let near = (1.0 - ((pill_y - rr.top()) / 48.0).abs()).clamp(0.0, 1.0);
|
||||
let ink = mix(t.on_variant, t.on_secondary_container, near);
|
||||
icon(&p, pos2(rr.left() + space::L + 10.0, rr.center().y), 20.0, glyph, ink);
|
||||
p.text(pos2(rr.left() + space::L + 20.0 + space::M, rr.center().y), Align2::LEFT_CENTER, *label, fonts::med(text::BODY), ink);
|
||||
if resp.clicked() {
|
||||
app.settings_page = i;
|
||||
}
|
||||
}
|
||||
if icon_button(ui, &t, Id::new("settings-close"), Rect::from_center_size(pos2(r.right() - space::L - 20.0, r.top() + space::L + 20.0), vec2(40.0, 40.0)), g::CLOSE, "Close", "Esc", Kind::Standard, false).clicked() {
|
||||
close = true;
|
||||
}
|
||||
let content = Rect::from_min_max(pos2(nav.right() + space::S, r.top() + 72.0), pos2(r.right() - space::S, r.bottom() - space::L));
|
||||
p.text(pos2(content.left() + space::L, r.top() + space::XL + 4.0), Align2::LEFT_TOP, PAGES[app.settings_page].1, fonts::semi(text::TITLE), t.on_surface);
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content));
|
||||
egui::ScrollArea::vertical().id_salt(("settings-page", app.settings_page)).auto_shrink([false, false]).show(&mut child, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
|
||||
let mut f = Form { ui, t: &t, x: content.left() + space::L, w: content.width() - 2.0 * space::L - space::S };
|
||||
match app.settings_page {
|
||||
0 => appearance(&mut f, app, ch),
|
||||
1 => playback(&mut f, app, ch),
|
||||
2 => languages(&mut f, app, ch),
|
||||
3 => mpv_page(&mut f, app, ch),
|
||||
4 => keys(&mut f),
|
||||
_ => about(&mut f, app),
|
||||
}
|
||||
f.space(space::L);
|
||||
});
|
||||
});
|
||||
if close {
|
||||
app.dialog = Dialog::None;
|
||||
}
|
||||
if !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.dialog = Dialog::None;
|
||||
}
|
||||
if app.dialog == Dialog::None {
|
||||
for k in ["grow", "fade"] {
|
||||
crate::motion::forget(("settings", k));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Form<'a> {
|
||||
ui: &'a mut Ui,
|
||||
t: &'a theme::Theme,
|
||||
x: f32,
|
||||
w: f32,
|
||||
}
|
||||
|
||||
impl Form<'_> {
|
||||
fn space(&mut self, h: f32) -> Rect {
|
||||
let (r, _) = self.ui.allocate_exact_size(vec2(self.w + 2.0 * space::L, h), Sense::hover());
|
||||
Rect::from_min_size(pos2(self.x, r.top()), vec2(self.w, h))
|
||||
}
|
||||
|
||||
fn heading(&mut self, what: &str) {
|
||||
let r = self.space(40.0);
|
||||
heading(self.ui.painter(), self.t, pos2(r.left(), r.top() + 16.0), what);
|
||||
}
|
||||
|
||||
fn note(&mut self, what: &str) {
|
||||
let g = self.ui.painter().layout(what.to_string(), fonts::ui(text::LABEL), self.t.on_variant, self.w);
|
||||
let r = self.space(g.size().y + space::XS);
|
||||
self.ui.painter().galley(r.min, g, self.t.on_variant);
|
||||
}
|
||||
|
||||
fn switch(&mut self, key: &str, label: &str, value: &mut bool) -> bool {
|
||||
let r = self.space(48.0);
|
||||
self.ui.painter().text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, label, fonts::ui(text::BODY), self.t.on_surface);
|
||||
let sw = Rect::from_min_size(pos2(r.right() - 52.0, r.center().y - 16.0), vec2(52.0, 32.0));
|
||||
let a = switch(self.ui, self.t, Id::new(("set-sw", key)), sw, value).changed();
|
||||
let row = self.ui.interact(Rect::from_min_max(r.min, pos2(sw.left() - space::S, r.max.y)), Id::new(("set-row", key)), Sense::click());
|
||||
if row.clicked() {
|
||||
*value = !*value;
|
||||
}
|
||||
a || row.clicked()
|
||||
}
|
||||
|
||||
fn segmented(&mut self, key: &str, label: &str, options: &[&str], chosen: &mut usize) -> bool {
|
||||
let r = self.space(28.0);
|
||||
self.ui.painter().text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, label, fonts::ui(text::BODY), self.t.on_surface);
|
||||
let r = self.space(40.0);
|
||||
let c = segmented(self.ui, self.t, Id::new(("set-seg", key)), r, options, chosen);
|
||||
self.space(space::M);
|
||||
c
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn slider(&mut self, key: &str, label: &str, value: &mut f64, min: f64, max: f64, step: f64, fmt: &dyn Fn(f64) -> String) -> bool {
|
||||
let r = self.space(24.0);
|
||||
controls::label_row(self.ui.painter(), self.t, r, label, &fmt(*value));
|
||||
let r = self.space(36.0);
|
||||
let c = slider(self.ui, self.t, Id::new(("set-sl", key)), r, value, min, max, step, None, fmt);
|
||||
self.space(space::S);
|
||||
c
|
||||
}
|
||||
|
||||
fn field(&mut self, key: &str, label: &str, value: &mut String, hint: &str) -> bool {
|
||||
let r = self.space(28.0);
|
||||
self.ui.painter().text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, label, fonts::ui(text::BODY), self.t.on_surface);
|
||||
let r = self.space(48.0);
|
||||
let (resp, _) = text_field(self.ui, self.t, Id::new(("set-field", key)), r, value, hint, "");
|
||||
self.space(space::S);
|
||||
resp.lost_focus() || resp.changed()
|
||||
}
|
||||
}
|
||||
|
||||
fn idx(list: &[&str], v: &str) -> usize {
|
||||
list.iter().position(|x| *x == v).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn appearance(f: &mut Form, app: &mut App, ch: &mut Changed) {
|
||||
let s = &mut app.settings;
|
||||
preview(f, s.wave);
|
||||
let mut from = match s.colour_from {
|
||||
ColourFrom::Desktop => 0,
|
||||
ColourFrom::Own => 1,
|
||||
ColourFrom::Video => 2,
|
||||
};
|
||||
if f.segmented("from", "Colours from", &["Desktop", "Own colour", "Video"], &mut from) {
|
||||
s.colour_from = [ColourFrom::Desktop, ColourFrom::Own, ColourFrom::Video][from];
|
||||
ch.theme = true;
|
||||
}
|
||||
if s.colour_from == ColourFrom::Desktop && !DESKTOP.with(|d| d.get()) {
|
||||
f.note("Your desktop doesn't share a colour, so Quince uses its own colour.");
|
||||
}
|
||||
if s.colour_from == ColourFrom::Video {
|
||||
f.note("Quince takes a colour from each video a moment after it starts, and uses its own colour until then.");
|
||||
}
|
||||
if s.colour_from != ColourFrom::Desktop || !DESKTOP.with(|d| d.get()) {
|
||||
let r = f.space(56.0);
|
||||
let mut x = r.left() + 20.0;
|
||||
for hexs in SWATCHES {
|
||||
let c = theme::hex(hexs).unwrap_or(Color32::GRAY);
|
||||
let at = pos2(x, r.center().y);
|
||||
let rr = Rect::from_center_size(at, vec2(40.0, 40.0));
|
||||
let resp = f.ui.interact(rr, Id::new(("swatch", hexs)), Sense::click());
|
||||
let fe = feel(&resp, true);
|
||||
let chosen = s.own_colour.eq_ignore_ascii_case(hexs);
|
||||
let k = spring((resp.id, "on"), f32::from(chosen), FAST);
|
||||
let p = f.ui.painter();
|
||||
let rad = 20.0 * (1.0 - 0.08 * fe.press);
|
||||
if k > 0.01 {
|
||||
let pts = shape::outline(Form_::Cookie9, at, rad, 0.0);
|
||||
let circle = shape::outline(Form_::Circle, at, rad, 0.0);
|
||||
let mixed: Vec<_> = circle.iter().zip(pts.iter()).map(|(a, b)| a.lerp(*b, k.clamp(0.0, 1.2))).collect();
|
||||
shape::fill(p, at, &mixed, c);
|
||||
} else {
|
||||
p.circle_filled(at, rad, c);
|
||||
}
|
||||
if fe.tint > 0.001 {
|
||||
p.circle_filled(at, rad, alpha(Color32::WHITE, fe.tint));
|
||||
}
|
||||
if k > 0.05 {
|
||||
let ink = if theme::lightness(c) > 0.6 { Color32::BLACK } else { Color32::WHITE };
|
||||
crate::widgets::icon(p, at, 20.0 * k.min(1.0), g::CHECK, ink);
|
||||
}
|
||||
if fe.focus {
|
||||
ring(p, f.t, rr, cr(20.0));
|
||||
}
|
||||
if resp.clicked() {
|
||||
s.own_colour = hexs.to_string();
|
||||
if s.colour_from == ColourFrom::Desktop {
|
||||
s.colour_from = ColourFrom::Own;
|
||||
}
|
||||
ch.theme = true;
|
||||
}
|
||||
x += 48.0;
|
||||
}
|
||||
let mut hex = s.own_colour.clone();
|
||||
let r2 = f.space(48.0);
|
||||
let (resp, _) = text_field(f.ui, f.t, Id::new("own-hex"), Rect::from_min_size(r2.min, vec2(180.0, 48.0)), &mut hex, "#rrggbb", g::PALETTE);
|
||||
if resp.changed() && theme::hex(&hex).is_some() {
|
||||
s.own_colour = hex;
|
||||
ch.theme = true;
|
||||
} else if resp.changed() {
|
||||
f.ui.data_mut(|d| d.insert_temp(Id::new("hex-draft"), hex));
|
||||
}
|
||||
f.space(space::M);
|
||||
}
|
||||
let mut i = idx(&config::SCHEMES, &s.scheme);
|
||||
if f.segmented("scheme", "Style", &["Tonal", "Vibrant", "Expressive", "Mono"], &mut i) {
|
||||
s.scheme = config::SCHEMES[i].into();
|
||||
ch.theme = true;
|
||||
}
|
||||
let mut i = idx(&config::APPEARANCES, &s.appearance);
|
||||
if f.segmented("appearance", "Appearance", &["Auto", "Light", "Dark", "AMOLED"], &mut i) {
|
||||
s.appearance = config::APPEARANCES[i].into();
|
||||
ch.theme = true;
|
||||
}
|
||||
let mut i = idx(&config::CONTRASTS, &s.contrast);
|
||||
if f.segmented("contrast", "Contrast", &["Standard", "Medium", "High"], &mut i) {
|
||||
s.contrast = config::CONTRASTS[i].into();
|
||||
ch.theme = true;
|
||||
}
|
||||
let cur = match s.motion() {
|
||||
crate::motion::Motion::Off => 0,
|
||||
crate::motion::Motion::Reduced => 1,
|
||||
crate::motion::Motion::Normal => 2,
|
||||
crate::motion::Motion::Expressive => 3,
|
||||
};
|
||||
let mut i = cur;
|
||||
if f.segmented("motion", "Motion", &["Off", "Reduced", "Normal", "Lively"], &mut i) {
|
||||
s.motion = config::MOTIONS[i].into();
|
||||
ch.theme = true;
|
||||
}
|
||||
if f.switch("wave", "Wavy seek bar while playing", &mut s.wave) {
|
||||
ch.any = true;
|
||||
}
|
||||
if ch.theme {
|
||||
ch.any = true;
|
||||
let now = f.ui.input(|i| i.time);
|
||||
f.ui.data_mut(|d| d.insert_temp(Id::new("preview-until"), now + 4.0));
|
||||
}
|
||||
}
|
||||
|
||||
use crate::shape::Form as Form_;
|
||||
|
||||
thread_local! {
|
||||
pub static DESKTOP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
|
||||
/// A small now-playing card that plays for a few seconds after each change, so colour and motion can be judged.
|
||||
fn preview(f: &mut Form, wave_on: bool) {
|
||||
let now = f.ui.input(|i| i.time);
|
||||
let until: f64 = f.ui.data(|d| d.get_temp(Id::new("preview-until"))).unwrap_or(0.0);
|
||||
let playing = now < until;
|
||||
if playing {
|
||||
f.ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(until - now));
|
||||
}
|
||||
let r = f.space(88.0);
|
||||
let t = f.t;
|
||||
let p = f.ui.painter().clone();
|
||||
p.rect_filled(r, cr(radius::L), t.high);
|
||||
let c = pos2(r.left() + space::L + 28.0, r.center().y);
|
||||
let k = spring("preview-k", f32::from(playing), DEFAULT);
|
||||
let m = crate::wave::with_state(f.ui.ctx(), Id::new("preview-shape"), |m: &mut Option<shape::Morpher>, _| {
|
||||
let m = m.get_or_insert_with(|| shape::Morpher::new(Form_::Circle));
|
||||
m.morph_to(if playing { Form_::Cookie9 } else { Form_::Circle });
|
||||
m.step();
|
||||
m.clone()
|
||||
});
|
||||
let pts = m.points(c, 28.0);
|
||||
shape::fill(&p, c, &pts, t.primary);
|
||||
play_pause_glyph(&p, c, 28.0, k, t.on_primary);
|
||||
let x = c.x + 28.0 + space::L;
|
||||
p.text(pos2(x, r.top() + space::L), Align2::LEFT_TOP, "Preview", fonts::med(text::BODY), t.on_surface);
|
||||
p.text(pos2(r.right() - space::L, r.top() + space::L), Align2::RIGHT_TOP, "1:24", fonts::ui(text::LABEL), t.on_variant);
|
||||
let bar = Rect::from_min_max(pos2(x, r.bottom() - space::L - 12.0), pos2(r.right() - space::L, r.bottom() - space::L));
|
||||
crate::wave::bar(f.ui, t, Id::new("preview-bar"), bar, 0.42, if playing && wave_on { 0.55 } else { 0.0 }, t.primary, t.secondary_container);
|
||||
f.space(space::S);
|
||||
}
|
||||
|
||||
fn playback(f: &mut Form, app: &mut App, ch: &mut Changed) {
|
||||
let s = &mut app.settings;
|
||||
f.heading("Playing");
|
||||
if f.switch("resume", "Carry on where I left off", &mut s.resume) {
|
||||
ch.mpv = true;
|
||||
}
|
||||
if f.switch("hwdec", "Hardware decoding", &mut s.hwdec) {
|
||||
ch.mpv = true;
|
||||
}
|
||||
f.switch("click", "Click the video to pause", &mut s.click_pauses);
|
||||
f.switch("thumbs", "Previews on the seek bar", &mut s.thumbnails);
|
||||
if !app.thumbs.available {
|
||||
f.note("Previews need ffmpeg, which wasn't found.");
|
||||
}
|
||||
f.heading("Controls");
|
||||
let mut h = s.hide_after as f64;
|
||||
if f.slider("hide", "Hide controls after", &mut h, 1.0, 8.0, 0.5, &|v| format!("{} s", crate::mpv::trim_num(v, 1))) {
|
||||
s.hide_after = h as f32;
|
||||
}
|
||||
f.slider("seek-small", "Arrow keys skip", &mut s.seek_small, 1.0, 30.0, 1.0, &|v| format!("{v:.0} s"));
|
||||
f.slider("seek-large", "Shift and arrow keys skip", &mut s.seek_large, 10.0, 300.0, 5.0, &|v| format!("{v:.0} s"));
|
||||
f.heading("Links");
|
||||
let mut i = config::QUALITIES.iter().position(|q| q.0 == s.ytdl_quality).unwrap_or(0);
|
||||
let labels: Vec<&str> = config::QUALITIES.iter().map(|q| q.1).collect();
|
||||
if f.segmented("quality", "Quality for online videos", &labels, &mut i) {
|
||||
s.ytdl_quality = config::QUALITIES[i].0.into();
|
||||
ch.mpv = true;
|
||||
}
|
||||
f.heading("Screenshots");
|
||||
if f.field("shots", "Save screenshots in", &mut s.screenshot_dir, "~/Pictures/Screenshots") {
|
||||
ch.mpv = true;
|
||||
}
|
||||
ch.any = true;
|
||||
}
|
||||
|
||||
fn languages(f: &mut Form, app: &mut App, ch: &mut Changed) {
|
||||
let s = &mut app.settings;
|
||||
f.note("Codes in order of preference, separated by commas, such as ja,en. Quince picks the first track that matches.");
|
||||
f.space(space::S);
|
||||
if f.field("alang", "Sound tracks", &mut s.alang, "en") {
|
||||
ch.mpv = true;
|
||||
}
|
||||
if f.field("slang", "Subtitles", &mut s.slang, "en") {
|
||||
ch.mpv = true;
|
||||
}
|
||||
ch.any = true;
|
||||
}
|
||||
|
||||
fn mpv_page(f: &mut Form, app: &mut App, ch: &mut Changed) {
|
||||
let s = &mut app.settings;
|
||||
f.note("Quince plays everything with mpv, so mpv's own settings, scripts and key bindings work here too.");
|
||||
f.space(space::S);
|
||||
if f.switch("conf", "Use mpv.conf, input.conf and scripts", &mut s.use_mpv_conf) {
|
||||
ch.any = true;
|
||||
}
|
||||
f.note("From ~/.config/mpv. Applies the next time Quince starts.");
|
||||
if f.switch("pass", "Send other keys to mpv", &mut s.pass_keys) {
|
||||
ch.any = true;
|
||||
}
|
||||
f.note("Keys Quince doesn't use go to mpv, so input.conf, the console (`) and statistics (i) work.");
|
||||
f.space(space::M);
|
||||
let r = f.space(40.0);
|
||||
let conf = dirs::config_dir().unwrap_or_default().join("mpv/mpv.conf");
|
||||
if button(f.ui, f.t, Id::new("open-conf"), Rect::from_min_size(r.min, vec2(160.0, 40.0)), g::OPEN_IN_NEW, "Edit mpv.conf", Kind::Tonal).clicked() {
|
||||
if !conf.exists() {
|
||||
let _ = std::fs::create_dir_all(conf.parent().unwrap());
|
||||
let _ = std::fs::write(&conf, "# mpv options, one per line, such as:\n# profile=gpu-hq\n");
|
||||
}
|
||||
let _ = std::process::Command::new("xdg-open").arg(&conf).spawn();
|
||||
}
|
||||
let log = dirs::cache_dir().unwrap_or_default().join("quince/mpv.log");
|
||||
if button(f.ui, f.t, Id::new("open-log"), Rect::from_min_size(pos2(r.left() + 168.0, r.top()), vec2(160.0, 40.0)), g::TEXT_FIELDS, "Show mpv's log", Kind::Text).clicked() {
|
||||
let _ = std::process::Command::new("xdg-open").arg(&log).spawn();
|
||||
}
|
||||
let version = app.player.as_ref().and_then(|p| p.get_str("mpv-version")).unwrap_or_default();
|
||||
if !version.is_empty() {
|
||||
f.space(space::M);
|
||||
f.note(&format!("Running {version}."));
|
||||
}
|
||||
}
|
||||
|
||||
pub const SHORTCUTS: [(&str, &str); 34] = [
|
||||
("Play or pause", "Space"),
|
||||
("Back or forward", "Left, Right"),
|
||||
("Skip further", "Shift+Left, Shift+Right"),
|
||||
("Skip one second", "Ctrl+Left, Ctrl+Right"),
|
||||
("Previous or next frame", ", ."),
|
||||
("Volume", "Up, Down"),
|
||||
("Mute", "M"),
|
||||
("Full screen", "F"),
|
||||
("Leave full screen, close", "Esc"),
|
||||
("Slower or faster", "[ ]"),
|
||||
("Normal speed", "Backspace"),
|
||||
("Previous or next chapter", "PgDn, PgUp"),
|
||||
("Previous or next in playlist", "P, N"),
|
||||
("Back to the start", "Home"),
|
||||
("Cycle subtitles", "J"),
|
||||
("Show subtitles", "V"),
|
||||
("Subtitles earlier or later", "Z, X"),
|
||||
("Cycle sound tracks", "A"),
|
||||
("Sound earlier or later", "Ctrl+-, Ctrl++"),
|
||||
("Loop between two points", "L"),
|
||||
("Repeat this video", "Shift+L"),
|
||||
("Screenshot", "S"),
|
||||
("Screenshot without subtitles", "Shift+S"),
|
||||
("Hardware decoding", "Ctrl+H"),
|
||||
("Open file", "Ctrl+O"),
|
||||
("Open link", "Ctrl+L"),
|
||||
("Playlist", "Ctrl+P"),
|
||||
("Adjust", "Ctrl+E"),
|
||||
("Settings", "Ctrl+,"),
|
||||
("Stop", "Ctrl+W"),
|
||||
("Quit", "Q"),
|
||||
("mpv console", "`"),
|
||||
("Statistics", "I"),
|
||||
("Menu", "Right click"),
|
||||
];
|
||||
|
||||
fn keys(f: &mut Form) {
|
||||
f.note("Other keys go to mpv when that's on, so your input.conf works too.");
|
||||
f.space(space::S);
|
||||
for (what, k) in SHORTCUTS {
|
||||
let r = f.space(40.0);
|
||||
f.ui.painter().text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, what, fonts::ui(text::BODY), f.t.on_surface);
|
||||
let mut x = r.right();
|
||||
for part in k.split(", ").collect::<Vec<_>>().into_iter().rev() {
|
||||
let w = keycap(f.ui.painter(), f.t, pos2(x, r.center().y), part);
|
||||
x -= w + space::S;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn about(f: &mut Form, app: &App) {
|
||||
let r = f.space(140.0);
|
||||
let c = pos2(r.left() + 56.0, r.center().y);
|
||||
let resp = f.ui.interact(Rect::from_center_size(c, vec2(96.0, 96.0)), Id::new("about-logo"), Sense::click());
|
||||
if resp.clicked() {
|
||||
crate::motion::kick("about-spin", 6.0);
|
||||
}
|
||||
let spin = spring("about-spin", 0.0, DEFAULT);
|
||||
crate::ui::chrome::logo(f.ui.painter(), c, 44.0, spin);
|
||||
let x = c.x + 72.0;
|
||||
let p = f.ui.painter();
|
||||
p.text(pos2(x, c.y - 24.0), Align2::LEFT_CENTER, "Quince", fonts::semi(text::HEADLINE), f.t.on_surface);
|
||||
p.text(pos2(x, c.y + 6.0), Align2::LEFT_CENTER, format!("Version {}", env!("CARGO_PKG_VERSION")), fonts::ui(text::BODY), f.t.on_variant);
|
||||
p.text(pos2(x, c.y + 28.0), Align2::LEFT_CENTER, "A video player built on mpv.", fonts::ui(text::BODY), f.t.on_variant);
|
||||
let version = app.player.as_ref().and_then(|p| p.get_str("mpv-version")).unwrap_or_else(|| "mpv isn't running".into());
|
||||
f.note(&format!("{version}. Rubik font under the SIL Open Font License; Material Symbols under the Apache License 2.0. Quince is under the MIT License."));
|
||||
let _ = (line, slider);
|
||||
}
|
||||
401
src/ui/sheets.rs
Normal file
401
src/ui/sheets.rs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
//! Side sheets that slide in from the right over the video: the playlist (play, remove, drag to reorder) and Adjust
|
||||
//! (picture, sound and subtitles).
|
||||
|
||||
use crate::app::{Act, Sheet, cmd, set};
|
||||
use crate::fonts;
|
||||
use crate::motion::spring;
|
||||
use crate::mpv::{State, display_name, trim_num};
|
||||
use crate::theme::alpha;
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{radius, size, space, text};
|
||||
use crate::ui::View;
|
||||
use crate::ui::controls::{heading, label_row, row, slider, tabs};
|
||||
use crate::ui::glyphs as g;
|
||||
use crate::ui::menus::ASPECTS;
|
||||
use crate::widgets::{Kind, button, chip, cr, floating_shadow, icon_button, line, switch};
|
||||
use eframe::egui::{self, Align2, Id, Order, Rect, Sense, Ui, pos2, vec2};
|
||||
|
||||
/// Draws the open sheet (or the one sliding away). Returns its rect.
|
||||
pub fn show(ctx: &egui::Context, v: &mut View, sheet: Sheet, tab: &mut usize, open_w: f32) -> Option<Rect> {
|
||||
let last_id = Id::new("last-sheet");
|
||||
let kind = if sheet == Sheet::None { ctx.data(|d| d.get_temp::<u8>(last_id)).map(|k| if k == 1 { Sheet::Playlist } else { Sheet::Adjust }) } else { Some(sheet) }?;
|
||||
ctx.data_mut(|d| d.insert_temp(last_id, if kind == Sheet::Playlist { 1u8 } else { 2u8 }));
|
||||
if open_w < 1.0 {
|
||||
return None;
|
||||
}
|
||||
let screen = ctx.content_rect();
|
||||
let w = size::SHEET.min(screen.width() - 2.0 * space::L);
|
||||
let x = screen.right() - open_w;
|
||||
let rect = Rect::from_min_size(pos2(x, screen.top() + space::L), vec2(w, screen.height() - 2.0 * space::L));
|
||||
let t = v.t;
|
||||
let mut acts = vec![];
|
||||
egui::Area::new(Id::new("sheet")).order(Order::Middle).fixed_pos(rect.min).constrain(false).show(ctx, |ui| {
|
||||
ui.set_min_size(rect.size());
|
||||
ui.set_max_size(rect.size());
|
||||
let p = ui.painter().clone();
|
||||
floating_shadow(&p, rect, cr(radius::XL), t.dark);
|
||||
p.rect_filled(rect, cr(radius::XL), t.container);
|
||||
// block clicks from reaching the video under it
|
||||
let _ = ui.interact(rect, Id::new("sheet-bg"), Sense::click());
|
||||
let head = Rect::from_min_size(rect.min, vec2(w, 64.0));
|
||||
let title = if kind == Sheet::Playlist { "Playlist" } else { "Adjust" };
|
||||
p.text(pos2(head.left() + space::XL, head.center().y), Align2::LEFT_CENTER, title, fonts::semi(text::TITLE), t.on_surface);
|
||||
if icon_button(ui, t, Id::new("sheet-close"), Rect::from_center_size(pos2(head.right() - space::M - 20.0, head.center().y), vec2(40.0, 40.0)), g::CLOSE, "Close", "Esc", Kind::Standard, false).clicked() {
|
||||
acts.push(Act::Sheet(kind));
|
||||
}
|
||||
let body = Rect::from_min_max(pos2(rect.left(), head.bottom()), rect.max);
|
||||
let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
inner.set_clip_rect(body.shrink(2.0));
|
||||
match kind {
|
||||
Sheet::Playlist => playlist(&mut inner, v.t, v.s, body, &mut acts),
|
||||
_ => adjust(&mut inner, v.t, v.s, body, tab, &mut acts),
|
||||
}
|
||||
});
|
||||
v.acts.extend(acts);
|
||||
Some(rect)
|
||||
}
|
||||
|
||||
fn playlist(ui: &mut Ui, t: &crate::theme::Theme, s: &State, body: Rect, acts: &mut Vec<Act>) {
|
||||
let p = ui.painter().clone();
|
||||
// tools
|
||||
let y = body.top();
|
||||
let add = Rect::from_min_size(pos2(body.left() + space::L, y), vec2(132.0, 40.0));
|
||||
if button(ui, t, Id::new("pl-add"), add, g::ADD, "Add files", Kind::Tonal).clicked() {
|
||||
acts.push(Act::AddFiles);
|
||||
}
|
||||
let mut x = body.right() - space::M - 20.0;
|
||||
let ic = |ui: &mut Ui, key: &str, x: f32, glyph: &str, name: &str, on: bool| {
|
||||
icon_button(ui, t, Id::new(("pl", key)), Rect::from_center_size(pos2(x, y + 20.0), vec2(40.0, 40.0)), glyph, name, "", Kind::Standard, on)
|
||||
};
|
||||
if ui.add_enabled_ui(!s.playlist.is_empty(), |ui| ic(ui, "clear", x, g::CLEAR_ALL, "Clear the playlist", false)).inner.clicked() {
|
||||
acts.push(cmd(&["playlist-clear"]));
|
||||
acts.push(cmd(&["playlist-remove", "current"]));
|
||||
}
|
||||
x -= 40.0;
|
||||
if ic(ui, "loop", x, g::REPEAT, if s.loop_playlist { "Repeat playlist: on" } else { "Repeat playlist: off" }, s.loop_playlist).clicked() {
|
||||
acts.push(set("loop-playlist", if s.loop_playlist { "no" } else { "inf" }));
|
||||
}
|
||||
x -= 40.0;
|
||||
if ui.add_enabled_ui(s.playlist.len() > 1, |ui| ic(ui, "shuffle", x, g::SHUFFLE, "Shuffle", false)).inner.clicked() {
|
||||
acts.push(cmd(&["playlist-shuffle"]));
|
||||
}
|
||||
let list = Rect::from_min_max(pos2(body.left(), y + 40.0 + space::M), pos2(body.right(), body.bottom() - space::S));
|
||||
if s.playlist.is_empty() {
|
||||
let c = list.center();
|
||||
p.text(pos2(c.x, c.y - 10.0), Align2::CENTER_CENTER, "The playlist is empty", fonts::med(text::BODY), t.on_surface);
|
||||
p.text(pos2(c.x, c.y + 12.0), Align2::CENTER_CENTER, "Add files to play them one after another.", fonts::ui(text::LABEL), t.on_variant);
|
||||
return;
|
||||
}
|
||||
let row_h = 56.0;
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(list));
|
||||
let drag_id = Id::new("pl-drag");
|
||||
let mut drag: Option<(usize, f32)> = child.data(|d| d.get_temp(drag_id));
|
||||
egui::ScrollArea::vertical().id_salt("pl-scroll").auto_shrink([false, false]).show(&mut child, |ui| {
|
||||
let n = s.playlist.len();
|
||||
let (all, _) = ui.allocate_exact_size(vec2(list.width(), n as f32 * row_h + space::S), Sense::hover());
|
||||
let top = all.top();
|
||||
let pointer_y = ui.ctx().pointer_interact_pos().map(|p| p.y);
|
||||
let target = drag.and_then(|(from, grab)| pointer_y.map(|py| (from, (((py - grab - top) / row_h).round() as i64).clamp(0, n as i64 - 1) as usize)));
|
||||
let mut released: Option<(usize, usize)> = None;
|
||||
for (i, e) in s.playlist.iter().enumerate() {
|
||||
// others make room for the dragged row
|
||||
let slot = match target {
|
||||
Some((from, to)) if i != from => {
|
||||
if from < to && i > from && i <= to {
|
||||
i - 1
|
||||
} else if from > to && i >= to && i < from {
|
||||
i + 1
|
||||
} else {
|
||||
i
|
||||
}
|
||||
}
|
||||
_ => i,
|
||||
};
|
||||
let key = (e.id, &e.filename);
|
||||
let ry = spring(("pl-y", key), slot as f32 * row_h, DEFAULT);
|
||||
let mut r = Rect::from_min_size(pos2(all.left() + space::S, top + ry), vec2(list.width() - 2.0 * space::S, row_h - 4.0));
|
||||
let dragging_me = drag.is_some_and(|(f, _)| f == i);
|
||||
if dragging_me && let (Some(py), Some((_, grab))) = (pointer_y, drag) {
|
||||
r = Rect::from_min_size(pos2(r.left(), py - grab), r.size());
|
||||
}
|
||||
if !ui.is_rect_visible(r) && !dragging_me {
|
||||
continue;
|
||||
}
|
||||
let id = Id::new(("pl-row", key));
|
||||
let detail = if e.filename.contains("://") { e.filename.split('/').nth(2).unwrap_or("").to_string() } else { std::path::Path::new(&e.filename).parent().map(|d| d.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default()).unwrap_or_default() };
|
||||
let glyph = if e.current { if s.pause { g::PAUSE } else { g::PLAY_ARROW } } else { "" };
|
||||
if dragging_me {
|
||||
floating_shadow(ui.painter(), r, cr(radius::FULL), t.dark);
|
||||
ui.painter().rect_filled(r, cr(radius::FULL), t.high);
|
||||
}
|
||||
let resp = row(ui, t, id, r, if glyph.is_empty() { g::DRAG_INDICATOR } else { glyph }, &e.name(), &detail, e.current);
|
||||
let resp = resp.interact(Sense::click_and_drag());
|
||||
if resp.drag_started()
|
||||
&& let Some(pp) = resp.interact_pointer_pos()
|
||||
{
|
||||
drag = Some((i, pp.y - r.top()));
|
||||
}
|
||||
if dragging_me && !ui.input(|inp| inp.pointer.any_down()) {
|
||||
released = target;
|
||||
drag = None;
|
||||
}
|
||||
if resp.double_clicked() || (resp.clicked() && !e.current) {
|
||||
acts.push(cmd(&["playlist-play-index", &i.to_string()]));
|
||||
}
|
||||
// remove, shown on hover
|
||||
let xr = Rect::from_center_size(pos2(r.right() - 24.0, r.center().y), vec2(32.0, 32.0));
|
||||
let show_x = spring((id, "x"), f32::from((resp.hovered() || ui.rect_contains_pointer(xr)) && drag.is_none()), EFFECT);
|
||||
if show_x > 0.01 {
|
||||
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(xr));
|
||||
c.multiply_opacity(show_x);
|
||||
if icon_button(&mut c, t, id.with("x"), xr, g::CLOSE, "Remove from playlist", "", Kind::Standard, false).clicked() {
|
||||
acts.push(cmd(&["playlist-remove", &i.to_string()]));
|
||||
}
|
||||
}
|
||||
let _ = display_name;
|
||||
}
|
||||
if let Some((from, to)) = released
|
||||
&& from != to
|
||||
{
|
||||
// mpv puts the entry before the given index
|
||||
let dest = if to > from { to + 1 } else { to };
|
||||
acts.push(cmd(&["playlist-move", &from.to_string(), &dest.to_string()]));
|
||||
}
|
||||
if drag.is_some() {
|
||||
crate::motion::keep_alive();
|
||||
}
|
||||
});
|
||||
child.data_mut(|d| match drag {
|
||||
Some(dr) => {
|
||||
d.insert_temp(drag_id, dr);
|
||||
}
|
||||
None => {
|
||||
d.remove_temp::<(usize, f32)>(drag_id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
struct Rows<'a> {
|
||||
ui: &'a mut Ui,
|
||||
t: &'a crate::theme::Theme,
|
||||
x: f32,
|
||||
w: f32,
|
||||
}
|
||||
|
||||
impl Rows<'_> {
|
||||
fn space(&mut self, h: f32) -> Rect {
|
||||
let (r, _) = self.ui.allocate_exact_size(vec2(self.w + 2.0 * space::XL, h), Sense::hover());
|
||||
Rect::from_min_size(pos2(self.x, r.top()), vec2(self.w, h))
|
||||
}
|
||||
|
||||
fn heading(&mut self, what: &str) {
|
||||
let r = self.space(36.0);
|
||||
heading(self.ui.painter(), self.t, pos2(r.left(), r.top() + 12.0), what);
|
||||
}
|
||||
|
||||
fn switch(&mut self, key: &str, label: &str, on: bool) -> Option<bool> {
|
||||
let r = self.space(48.0);
|
||||
self.ui.painter().text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, label, fonts::ui(text::BODY), self.t.on_surface);
|
||||
let mut v = on;
|
||||
let sw = Rect::from_min_size(pos2(r.right() - 52.0, r.center().y - 16.0), vec2(52.0, 32.0));
|
||||
let resp = switch(self.ui, self.t, Id::new(("sw", key)), sw, &mut v);
|
||||
let row = self.ui.interact(Rect::from_min_max(r.min, pos2(sw.left() - space::S, r.max.y)), Id::new(("sw-row", key)), Sense::click());
|
||||
if row.clicked() {
|
||||
v = !v;
|
||||
}
|
||||
(resp.changed() || row.clicked()).then_some(v)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn slider(&mut self, key: &str, label: &str, value: f64, min: f64, max: f64, step: f64, origin: Option<f64>, fmt: &dyn Fn(f64) -> String) -> Option<f64> {
|
||||
let r = self.space(24.0);
|
||||
label_row(self.ui.painter(), self.t, r, label, &fmt(value));
|
||||
let sr = self.space(36.0);
|
||||
let mut v = value;
|
||||
let changed = slider(self.ui, self.t, Id::new(("sl", key)), sr, &mut v, min, max, step, origin, fmt);
|
||||
self.space(space::S);
|
||||
changed.then_some(v)
|
||||
}
|
||||
|
||||
fn track_rows(&mut self, s: &State, kind: &str, prop: &str, current: &str, with_off: bool, acts: &mut Vec<Act>) {
|
||||
if with_off {
|
||||
let r = self.space(48.0);
|
||||
if row(self.ui, self.t, Id::new(("tr-off", prop)), r, g::BLOCK, "Off", "", current == "no" || current.is_empty()).clicked() {
|
||||
acts.push(set(prop, "no"));
|
||||
}
|
||||
}
|
||||
for tr in s.tracks_of(kind) {
|
||||
let r = self.space(if tr.detail().is_empty() { 48.0 } else { 56.0 });
|
||||
let on = current == tr.id.to_string();
|
||||
if row(self.ui, self.t, Id::new(("tr", prop, tr.id)), r, if on { g::CHECK_CIRCLE } else { g::RADIO_BUTTON_UNCHECKED }, &tr.label(), &tr.detail(), on).clicked() {
|
||||
acts.push(set(prop, tr.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn adjust(ui: &mut Ui, t: &crate::theme::Theme, s: &State, body: Rect, tab: &mut usize, acts: &mut Vec<Act>) {
|
||||
let tr = Rect::from_min_size(pos2(body.left() + space::L, body.top()), vec2(body.width() - 2.0 * space::L, 44.0));
|
||||
tabs(ui, t, Id::new("adjust-tabs"), tr, &["Picture", "Sound", "Subtitles"], tab);
|
||||
let rest = Rect::from_min_max(pos2(body.left(), tr.bottom() + space::S), pos2(body.right(), body.bottom() - space::S));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rest));
|
||||
egui::ScrollArea::vertical().id_salt(("adjust", *tab)).auto_shrink([false, false]).show(&mut child, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
|
||||
let x = rest.left() + space::XL;
|
||||
let w = rest.width() - 2.0 * space::XL;
|
||||
let mut r = Rows { ui, t, x, w };
|
||||
match *tab {
|
||||
0 => picture(&mut r, s, acts),
|
||||
1 => sound(&mut r, s, acts),
|
||||
_ => subs(&mut r, s, acts),
|
||||
}
|
||||
r.space(space::L);
|
||||
});
|
||||
}
|
||||
|
||||
fn pct(v: f64) -> String {
|
||||
if v.abs() < 0.5 { "0".into() } else { format!("{:+.0}", v) }
|
||||
}
|
||||
|
||||
fn picture(r: &mut Rows, s: &State, acts: &mut Vec<Act>) {
|
||||
if s.tracks_of("video").count() > 1 {
|
||||
r.heading("Video track");
|
||||
r.track_rows(s, "video", "vid", &s.vid, false, acts);
|
||||
}
|
||||
r.heading("Shape");
|
||||
// aspect chips, wrapping
|
||||
let mut x = r.x;
|
||||
let mut line_r = r.space(40.0);
|
||||
let cur = s.aspect_override.as_str();
|
||||
for (val, label) in ASPECTS {
|
||||
let wgal = r.ui.painter().layout_no_wrap(label.to_string(), fonts::med(text::BODY), r.t.on_variant).size().x + 2.0 * space::M + 18.0 + space::S;
|
||||
if x + wgal > r.x + r.w {
|
||||
x = r.x;
|
||||
line_r = r.space(40.0);
|
||||
}
|
||||
let mut on = if val == "-1" { cur == "-1" || cur == "no" || cur.is_empty() } else { cur == val || (cur.parse::<f64>().ok().zip(ratio(val)).is_some_and(|(a, b)| (a - b).abs() < 0.01)) };
|
||||
let was = on;
|
||||
chip(r.ui, r.t, Id::new(("aspect", val)), pos2(x, line_r.top()), label, &mut on);
|
||||
if on != was {
|
||||
acts.push(set("video-aspect-override", val));
|
||||
}
|
||||
x += wgal + space::S;
|
||||
}
|
||||
r.space(space::S);
|
||||
if let Some(v) = r.slider("zoom", "Zoom", s.zoom, -1.0, 2.0, 0.05, Some(0.0), &|z| format!("{:.0} %", 2f64.powf(z) * 100.0)) {
|
||||
acts.push(set("video-zoom", format!("{v:.2}")));
|
||||
}
|
||||
let rot = r.space(40.0);
|
||||
let mut chosen = (s.rotate.rem_euclid(360) / 90) as usize;
|
||||
let labels = ["0°", "90°", "180°", "270°"];
|
||||
r.ui.painter().text(pos2(rot.left(), rot.center().y), Align2::LEFT_CENTER, "Rotate", fonts::ui(text::BODY), r.t.on_surface);
|
||||
let seg = Rect::from_min_size(pos2(rot.right() - 216.0, rot.top()), vec2(216.0, 40.0));
|
||||
if crate::widgets::segmented(r.ui, r.t, Id::new("rotate"), seg, &labels, &mut chosen) {
|
||||
acts.push(set("video-rotate", chosen * 90));
|
||||
}
|
||||
r.space(space::S);
|
||||
if let Some(on) = r.switch("panscan", "Fill the window", s.panscan > 0.5) {
|
||||
acts.push(set("panscan", if on { "1" } else { "0" }));
|
||||
}
|
||||
if let Some(_on) = r.switch("mirror", "Mirror", s.vf.contains("hflip")) {
|
||||
acts.push(cmd(&["vf", "toggle", "hflip"]));
|
||||
}
|
||||
r.heading("Colour");
|
||||
for (key, label, val) in [("brightness", "Brightness", s.brightness), ("contrast", "Contrast", s.contrast), ("saturation", "Saturation", s.saturation), ("gamma", "Gamma", s.gamma), ("hue", "Hue", s.hue)] {
|
||||
if let Some(v) = r.slider(key, label, val, -100.0, 100.0, 1.0, Some(0.0), &pct) {
|
||||
acts.push(set(key, v.round()));
|
||||
}
|
||||
}
|
||||
r.heading("Decoding");
|
||||
if let Some(on) = r.switch("deint", "Deinterlace", s.deinterlace) {
|
||||
acts.push(set("deinterlace", if on { "yes" } else { "no" }));
|
||||
}
|
||||
if let Some(on) = r.switch("hwdec", "Hardware decoding", s.hwdec != "no") {
|
||||
acts.push(set("hwdec", if on { "auto-safe" } else { "no" }));
|
||||
}
|
||||
let info = r.space(24.0);
|
||||
let now = if s.hwdec_current.is_empty() || s.hwdec_current == "no" { "Decoding in software".to_string() } else { format!("Decoding with {}", s.hwdec_current) };
|
||||
r.ui.painter().text(pos2(info.left(), info.center().y), Align2::LEFT_CENTER, now, fonts::ui(text::LABEL), r.t.on_variant);
|
||||
r.space(space::M);
|
||||
let b = r.space(40.0);
|
||||
if button(r.ui, r.t, Id::new("reset-pic"), Rect::from_min_size(b.min, vec2(160.0, 40.0)), g::RESTART_ALT, "Reset picture", Kind::Outlined).clicked() {
|
||||
acts.push(Act::ResetVideo);
|
||||
}
|
||||
}
|
||||
|
||||
fn ratio(s: &str) -> Option<f64> {
|
||||
let (a, b) = s.split_once(':')?;
|
||||
Some(a.parse::<f64>().ok()? / b.parse::<f64>().ok()?)
|
||||
}
|
||||
|
||||
fn sound(r: &mut Rows, s: &State, acts: &mut Vec<Act>) {
|
||||
r.heading("Sound track");
|
||||
r.track_rows(s, "audio", "aid", &s.aid, true, acts);
|
||||
let b = r.space(48.0);
|
||||
if button(r.ui, r.t, Id::new("load-audio"), Rect::from_min_size(pos2(b.left(), b.top() + 4.0), vec2(172.0, 40.0)), g::ADD, "Load sound track", Kind::Text).clicked() {
|
||||
acts.push(Act::LoadAudio);
|
||||
}
|
||||
r.heading("Level and timing");
|
||||
if let Some(v) = r.slider("volume", "Volume", if s.mute { 0.0 } else { s.volume }, 0.0, 150.0, 1.0, None, &|v| format!("{} %", v.round())) {
|
||||
acts.push(Act::Volume(v));
|
||||
}
|
||||
if let Some(v) = r.slider("adelay", "Delay", s.audio_delay, -5.0, 5.0, 0.05, Some(0.0), &|v| format!("{:+.0} ms", v * 1000.0)) {
|
||||
acts.push(set("audio-delay", format!("{v:.3}")));
|
||||
}
|
||||
if let Some(on) = r.switch("pitch", "Keep the pitch at other speeds", s.audio_pitch_correction) {
|
||||
acts.push(set("audio-pitch-correction", if on { "yes" } else { "no" }));
|
||||
}
|
||||
if let Some(_on) = r.switch("norm", "Even out loud and quiet parts", s.af.contains("dynaudnorm")) {
|
||||
acts.push(cmd(&["af", "toggle", "@norm:lavfi=[dynaudnorm=f=250:g=31]"]));
|
||||
}
|
||||
if let Some(on) = r.switch("stereo", "Mix down to stereo", s.audio_channels == "stereo") {
|
||||
acts.push(set("audio-channels", if on { "stereo" } else { "auto-safe" }));
|
||||
}
|
||||
if !s.devices.is_empty() {
|
||||
r.heading("Output");
|
||||
for d in &s.devices {
|
||||
let label = if d.name == "auto" { "Automatic".to_string() } else if d.description.is_empty() { d.name.clone() } else { d.description.clone() };
|
||||
let rr = r.space(48.0);
|
||||
let on = s.audio_device == d.name;
|
||||
if row(r.ui, r.t, Id::new(("dev", &d.name)), rr, if on { g::CHECK_CIRCLE } else { g::RADIO_BUTTON_UNCHECKED }, &label, "", on).clicked() {
|
||||
acts.push(set("audio-device", &d.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
r.space(space::M);
|
||||
let b = r.space(40.0);
|
||||
if button(r.ui, r.t, Id::new("reset-snd"), Rect::from_min_size(b.min, vec2(152.0, 40.0)), g::RESTART_ALT, "Reset sound", Kind::Outlined).clicked() {
|
||||
acts.push(Act::ResetAudio);
|
||||
}
|
||||
}
|
||||
|
||||
fn subs(r: &mut Rows, s: &State, acts: &mut Vec<Act>) {
|
||||
r.heading("Subtitles");
|
||||
r.track_rows(s, "sub", "sid", &s.sid, true, acts);
|
||||
let b = r.space(48.0);
|
||||
if button(r.ui, r.t, Id::new("load-sub"), Rect::from_min_size(pos2(b.left(), b.top() + 4.0), vec2(160.0, 40.0)), g::ADD, "Load subtitles", Kind::Text).clicked() {
|
||||
acts.push(Act::LoadSub);
|
||||
}
|
||||
r.heading("Look and timing");
|
||||
if let Some(on) = r.switch("subvis", "Show subtitles", s.sub_visible) {
|
||||
acts.push(set("sub-visibility", if on { "yes" } else { "no" }));
|
||||
}
|
||||
if let Some(v) = r.slider("sdelay", "Delay", s.sub_delay, -10.0, 10.0, 0.05, Some(0.0), &|v| format!("{:+.0} ms", v * 1000.0)) {
|
||||
acts.push(set("sub-delay", format!("{v:.3}")));
|
||||
}
|
||||
if let Some(v) = r.slider("sscale", "Size", s.sub_scale, 0.5, 3.0, 0.05, Some(1.0), &|v| format!("{:.0} %", v * 100.0)) {
|
||||
acts.push(set("sub-scale", format!("{v:.2}")));
|
||||
}
|
||||
if let Some(v) = r.slider("spos", "Height on screen", s.sub_pos, 0.0, 150.0, 1.0, Some(100.0), &|v| format!("{:.0}", v)) {
|
||||
acts.push(set("sub-pos", v.round()));
|
||||
}
|
||||
if let Some(on) = r.switch("assov", "Override the file's subtitle styles", s.sub_ass_override == "force") {
|
||||
acts.push(set("sub-ass-override", if on { "force" } else { "scale" }));
|
||||
}
|
||||
r.space(space::M);
|
||||
let b = r.space(40.0);
|
||||
if button(r.ui, r.t, Id::new("reset-sub"), Rect::from_min_size(b.min, vec2(172.0, 40.0)), g::RESTART_ALT, "Reset subtitles", Kind::Outlined).clicked() {
|
||||
acts.push(Act::ResetSubs);
|
||||
}
|
||||
let _ = (trim_num(0.0, 0), line, alpha);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue