first commit
This commit is contained in:
commit
a408df2a76
218 changed files with 52376 additions and 0 deletions
696
src/engine/input.rs
Normal file
696
src/engine/input.rs
Normal file
|
|
@ -0,0 +1,696 @@
|
|||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use winit::event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent};
|
||||
use winit::keyboard::{Key as WinitKey, NamedKey};
|
||||
|
||||
use crate::engine::types::{Pos2, Rect, Vec2};
|
||||
|
||||
/// Strict Z-order rendering & hit-testing layers:
|
||||
/// `Base < Drawer < Popover < Modal < Titlebar`.
|
||||
/// Higher layers block pointer hover, clicks, and wheel scroll on lower layers!
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||
#[repr(usize)]
|
||||
pub enum ZLayer {
|
||||
#[default]
|
||||
Base = 0,
|
||||
Drawer = 1,
|
||||
Popover = 2,
|
||||
Modal = 3,
|
||||
Titlebar = 4,
|
||||
}
|
||||
|
||||
impl ZLayer {
|
||||
pub const COUNT: usize = 5;
|
||||
pub const ALL: [ZLayer; 5] = [
|
||||
ZLayer::Base,
|
||||
ZLayer::Drawer,
|
||||
ZLayer::Popover,
|
||||
ZLayer::Modal,
|
||||
ZLayer::Titlebar,
|
||||
];
|
||||
|
||||
#[inline]
|
||||
pub const fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// Fast deterministic widget identifier (FNV-1a 64-bit hash).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub struct WidgetId(pub u64);
|
||||
|
||||
impl WidgetId {
|
||||
#[inline]
|
||||
pub fn new(source: impl Hash) -> Self {
|
||||
let mut h = Fnv1aHasher::default();
|
||||
source.hash(&mut h);
|
||||
Self(h.finish())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_pair(a: impl Hash, b: impl Hash) -> Self {
|
||||
let mut h = Fnv1aHasher::default();
|
||||
a.hash(&mut h);
|
||||
0x9E37_79B9_7F4A_7C15u64.hash(&mut h);
|
||||
b.hash(&mut h);
|
||||
Self(h.finish())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn with(self, child: impl Hash) -> Self {
|
||||
let mut h = Fnv1aHasher(self.0);
|
||||
0x517C_C1B7_2722_0A95u64.hash(&mut h);
|
||||
child.hash(&mut h);
|
||||
Self(h.finish())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fnv1aHasher(u64);
|
||||
|
||||
impl Hasher for Fnv1aHasher {
|
||||
#[inline]
|
||||
fn finish(&self) -> u64 {
|
||||
if self.0 == 0 {
|
||||
0xCBF2_9CE4_8422_2325
|
||||
} else {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
let mut hash = if self.0 == 0 {
|
||||
0xCBF2_9CE4_8422_2325u64
|
||||
} else {
|
||||
self.0
|
||||
};
|
||||
for &b in bytes {
|
||||
hash ^= b as u64;
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01B3);
|
||||
}
|
||||
self.0 = hash;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clean egui-free keyboard key enum translated from `winit::keyboard::Key`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Key {
|
||||
Enter,
|
||||
Escape,
|
||||
Backspace,
|
||||
Delete,
|
||||
Tab,
|
||||
Space,
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
Home,
|
||||
End,
|
||||
PageUp,
|
||||
PageDown,
|
||||
MediaPlayPause,
|
||||
MediaNext,
|
||||
MediaPrev,
|
||||
MediaStop,
|
||||
F1,
|
||||
F2,
|
||||
F3,
|
||||
F4,
|
||||
F5,
|
||||
F6,
|
||||
F7,
|
||||
F8,
|
||||
F9,
|
||||
F10,
|
||||
F11,
|
||||
F12,
|
||||
Char(char),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct Modifiers {
|
||||
pub ctrl: bool,
|
||||
pub shift: bool,
|
||||
pub alt: bool,
|
||||
pub super_key: bool,
|
||||
}
|
||||
|
||||
impl Modifiers {
|
||||
/// Platform command modifier (`Ctrl` on Windows/Linux, `Cmd` on macOS).
|
||||
#[inline]
|
||||
pub const fn command(self) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
self.super_key
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
self.ctrl
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KeyPress {
|
||||
pub key: Key,
|
||||
pub modifiers: Modifiers,
|
||||
pub text: Option<String>,
|
||||
pub repeat: bool,
|
||||
}
|
||||
|
||||
/// Result of hit-testing a widget rect on the current `ZLayer`.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Interaction {
|
||||
pub rect: Rect,
|
||||
pub hovered: bool,
|
||||
pub pressed: bool,
|
||||
pub clicked: bool,
|
||||
pub double_clicked: bool,
|
||||
pub right_clicked: bool,
|
||||
pub dragged: bool,
|
||||
pub drag_started: bool,
|
||||
pub drag_stopped: bool,
|
||||
pub drag_delta: Vec2,
|
||||
}
|
||||
|
||||
impl Interaction {
|
||||
#[inline]
|
||||
pub fn any_click(&self) -> bool {
|
||||
self.clicked || self.double_clicked || self.right_clicked
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct LayerBlocker {
|
||||
layer: ZLayer,
|
||||
rect: Rect,
|
||||
}
|
||||
|
||||
/// Per-frame translated winit 0.30 input state with Z-layered hit-testing,
|
||||
/// drag tracking, double-click detection, keyboard/text events, and focus management.
|
||||
pub struct InputState {
|
||||
pub pointer_pos: Option<Pos2>,
|
||||
pub pointer_delta: Vec2,
|
||||
|
||||
pub left_down: bool,
|
||||
pub left_pressed: bool,
|
||||
pub left_released: bool,
|
||||
pub left_double_clicked: bool,
|
||||
|
||||
pub right_down: bool,
|
||||
pub right_pressed: bool,
|
||||
pub right_released: bool,
|
||||
|
||||
pub wheel_delta: Vec2,
|
||||
pub modifiers: Modifiers,
|
||||
pub key_events: Vec<KeyPress>,
|
||||
pub text_input: String,
|
||||
|
||||
pub focused_id: Option<WidgetId>,
|
||||
pub active_id: Option<WidgetId>,
|
||||
pub drag_origin: Option<Pos2>,
|
||||
pub is_dragging: bool,
|
||||
|
||||
pub window_focused: bool,
|
||||
pub scale_factor: f32,
|
||||
pub screen_size: Vec2,
|
||||
pub time: f64,
|
||||
pub dt: f32,
|
||||
|
||||
last_click_time: f64,
|
||||
last_click_pos: Pos2,
|
||||
prev_blockers: Vec<LayerBlocker>,
|
||||
curr_blockers: Vec<LayerBlocker>,
|
||||
}
|
||||
|
||||
impl Default for InputState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pointer_pos: None,
|
||||
pointer_delta: Vec2::ZERO,
|
||||
left_down: false,
|
||||
left_pressed: false,
|
||||
left_released: false,
|
||||
left_double_clicked: false,
|
||||
right_down: false,
|
||||
right_pressed: false,
|
||||
right_released: false,
|
||||
wheel_delta: Vec2::ZERO,
|
||||
modifiers: Modifiers::default(),
|
||||
key_events: Vec::with_capacity(8),
|
||||
text_input: String::new(),
|
||||
focused_id: None,
|
||||
active_id: None,
|
||||
drag_origin: None,
|
||||
is_dragging: false,
|
||||
window_focused: true,
|
||||
scale_factor: 1.0,
|
||||
screen_size: Vec2::new(1280.0, 800.0),
|
||||
time: 0.0,
|
||||
dt: 1.0 / 60.0,
|
||||
last_click_time: -10.0,
|
||||
last_click_pos: Pos2::new(-1000.0, -1000.0),
|
||||
prev_blockers: Vec::with_capacity(16),
|
||||
curr_blockers: Vec::with_capacity(16),
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate a `winit 0.30` `WindowEvent` into engine input state.
|
||||
/// Returns `true` if the UI should repaint.
|
||||
pub fn handle_winit_event(&mut self, event: &WindowEvent) -> bool {
|
||||
let sf = self.scale_factor.max(0.5);
|
||||
match event {
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
let next = Pos2::new(position.x as f32 / sf, position.y as f32 / sf);
|
||||
if let Some(prev) = self.pointer_pos {
|
||||
self.pointer_delta = self.pointer_delta + (next - prev);
|
||||
}
|
||||
self.pointer_pos = Some(next);
|
||||
if self.left_down {
|
||||
if let Some(origin) = self.drag_origin {
|
||||
if origin.distance(next) >= 3.0 {
|
||||
self.is_dragging = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
WindowEvent::CursorLeft { .. } => {
|
||||
self.pointer_pos = None;
|
||||
true
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
let is_down = *state == ElementState::Pressed;
|
||||
match button {
|
||||
MouseButton::Left => {
|
||||
if is_down {
|
||||
self.left_down = true;
|
||||
self.left_pressed = true;
|
||||
let pos = self.pointer_pos.unwrap_or(Pos2::ZERO);
|
||||
self.drag_origin = Some(pos);
|
||||
self.is_dragging = false;
|
||||
if (self.time - self.last_click_time) <= 0.35
|
||||
&& pos.distance(self.last_click_pos) <= 6.0
|
||||
{
|
||||
self.left_double_clicked = true;
|
||||
self.last_click_time = -10.0;
|
||||
} else {
|
||||
self.last_click_time = self.time;
|
||||
self.last_click_pos = pos;
|
||||
}
|
||||
} else {
|
||||
self.left_down = false;
|
||||
self.left_released = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
MouseButton::Right => {
|
||||
if is_down {
|
||||
self.right_down = true;
|
||||
self.right_pressed = true;
|
||||
} else {
|
||||
self.right_down = false;
|
||||
self.right_released = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
match delta {
|
||||
MouseScrollDelta::LineDelta(dx, dy) => {
|
||||
self.wheel_delta.x += *dx * 42.0;
|
||||
self.wheel_delta.y += *dy * 42.0;
|
||||
}
|
||||
MouseScrollDelta::PixelDelta(pos) => {
|
||||
self.wheel_delta.x += pos.x as f32 / sf;
|
||||
self.wheel_delta.y += pos.y as f32 / sf;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
WindowEvent::ModifiersChanged(mods) => {
|
||||
let s = mods.state();
|
||||
self.modifiers = Modifiers {
|
||||
ctrl: s.control_key(),
|
||||
shift: s.shift_key(),
|
||||
alt: s.alt_key(),
|
||||
super_key: s.super_key(),
|
||||
};
|
||||
false
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => self.handle_key_event(event),
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.window_focused = *focused;
|
||||
if !focused {
|
||||
self.left_down = false;
|
||||
self.right_down = false;
|
||||
self.active_id = None;
|
||||
self.is_dragging = false;
|
||||
self.modifiers = Modifiers::default();
|
||||
}
|
||||
true
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.scale_factor = *scale_factor as f32;
|
||||
true
|
||||
}
|
||||
WindowEvent::Resized(size) => {
|
||||
self.screen_size = Vec2::new(size.width as f32 / sf, size.height as f32 / sf);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_key_event(&mut self, event: &KeyEvent) -> bool {
|
||||
if event.state != ElementState::Pressed {
|
||||
return false;
|
||||
}
|
||||
let key_opt = translate_winit_key(&event.logical_key);
|
||||
let text_opt = event.text.as_ref().map(|s| s.to_string()).filter(|s| {
|
||||
!s.is_empty() && !self.modifiers.ctrl && !self.modifiers.alt && !self.modifiers.super_key
|
||||
});
|
||||
|
||||
if let Some(ref txt) = text_opt {
|
||||
for ch in txt.chars() {
|
||||
if !ch.is_control() {
|
||||
self.text_input.push(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(key) = key_opt {
|
||||
self.key_events.push(KeyPress {
|
||||
key,
|
||||
modifiers: self.modifiers,
|
||||
text: text_opt,
|
||||
repeat: event.repeat,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
text_opt.is_some()
|
||||
}
|
||||
|
||||
/// Call at the start of every UI frame.
|
||||
pub fn begin_frame(&mut self, screen_size: Vec2, scale_factor: f32, time: f64) {
|
||||
let prev_time = self.time;
|
||||
self.time = time;
|
||||
self.dt = if prev_time > 0.0 && time > prev_time {
|
||||
((time - prev_time) as f32).clamp(0.001, 0.1)
|
||||
} else {
|
||||
1.0 / 60.0
|
||||
};
|
||||
self.screen_size = screen_size;
|
||||
self.scale_factor = scale_factor.max(0.5);
|
||||
std::mem::swap(&mut self.prev_blockers, &mut self.curr_blockers);
|
||||
self.curr_blockers.clear();
|
||||
}
|
||||
|
||||
/// Call at the end of every UI frame to clear single-frame edge flags.
|
||||
pub fn end_frame(&mut self) {
|
||||
if self.left_released {
|
||||
self.active_id = None;
|
||||
self.drag_origin = None;
|
||||
self.is_dragging = false;
|
||||
}
|
||||
self.pointer_delta = Vec2::ZERO;
|
||||
self.left_pressed = false;
|
||||
self.left_released = false;
|
||||
self.left_double_clicked = false;
|
||||
self.right_pressed = false;
|
||||
self.right_released = false;
|
||||
self.wheel_delta = Vec2::ZERO;
|
||||
self.key_events.clear();
|
||||
self.text_input.clear();
|
||||
}
|
||||
|
||||
/// Register an opaque hit-blocking region on `layer` (e.g. Popover, Modal, Drawer, Titlebar).
|
||||
/// Prevents lower layers from receiving hover, click, or wheel events underneath `rect`.
|
||||
#[inline]
|
||||
pub fn register_blocker(&mut self, layer: ZLayer, rect: Rect) {
|
||||
if !rect.is_empty() {
|
||||
self.curr_blockers.push(LayerBlocker { layer, rect });
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if `pos` is covered by an opaque surface on any layer strictly above `layer`.
|
||||
pub fn is_blocked_at(&self, layer: ZLayer, pos: Pos2) -> bool {
|
||||
self.prev_blockers
|
||||
.iter()
|
||||
.chain(self.curr_blockers.iter())
|
||||
.any(|b| b.layer > layer && b.rect.contains(pos))
|
||||
}
|
||||
|
||||
/// Returns `true` if pointer is inside `rect` (intersected with optional `clip`) and not blocked by a higher layer.
|
||||
pub fn is_hovered_in(&self, layer: ZLayer, rect: Rect, clip: Option<Rect>) -> bool {
|
||||
let Some(pos) = self.pointer_pos else {
|
||||
return false;
|
||||
};
|
||||
let hit_rect = match clip {
|
||||
Some(c) if !c.is_empty() => rect.intersect(c),
|
||||
_ => rect,
|
||||
};
|
||||
if !hit_rect.contains(pos) {
|
||||
return false;
|
||||
}
|
||||
!self.is_blocked_at(layer, pos)
|
||||
}
|
||||
|
||||
/// Perform full Z-layered interaction testing for widget `id` at `rect`.
|
||||
pub fn interact(&mut self, id: WidgetId, layer: ZLayer, rect: Rect, clip: Option<Rect>) -> Interaction {
|
||||
let hovered = self.is_hovered_in(layer, rect, clip);
|
||||
let mut pressed = false;
|
||||
let mut clicked = false;
|
||||
let mut double_clicked = false;
|
||||
let mut right_clicked = false;
|
||||
let mut dragged = false;
|
||||
let mut drag_started = false;
|
||||
let mut drag_stopped = false;
|
||||
let mut drag_delta = Vec2::ZERO;
|
||||
|
||||
if hovered && self.left_pressed {
|
||||
self.active_id = Some(id);
|
||||
if self.left_double_clicked {
|
||||
double_clicked = true;
|
||||
}
|
||||
}
|
||||
|
||||
if hovered && self.right_pressed {
|
||||
right_clicked = true;
|
||||
}
|
||||
|
||||
if self.active_id == Some(id) {
|
||||
if self.left_down {
|
||||
pressed = true;
|
||||
if self.is_dragging {
|
||||
dragged = true;
|
||||
drag_delta = self.pointer_delta;
|
||||
if self.drag_origin.is_some() && self.pointer_delta != Vec2::ZERO {
|
||||
drag_started = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.left_released {
|
||||
if self.is_dragging {
|
||||
drag_stopped = true;
|
||||
} else if hovered {
|
||||
clicked = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Detect first frame of drag start
|
||||
if dragged && self.drag_origin.map_or(false, |o| {
|
||||
let p = self.pointer_pos.unwrap_or(o);
|
||||
o.distance(p) >= 3.0 && o.distance(p - self.pointer_delta) < 3.0
|
||||
}) {
|
||||
drag_started = true;
|
||||
}
|
||||
|
||||
Interaction {
|
||||
rect,
|
||||
hovered,
|
||||
pressed,
|
||||
clicked,
|
||||
double_clicked,
|
||||
right_clicked,
|
||||
dragged,
|
||||
drag_started,
|
||||
drag_stopped,
|
||||
drag_delta,
|
||||
}
|
||||
}
|
||||
|
||||
/// True if the user clicked (left or right mouse button) outside `rect` this frame.
|
||||
pub fn clicked_outside(&self, rect: Rect) -> bool {
|
||||
if !self.left_pressed && !self.right_pressed {
|
||||
return false;
|
||||
}
|
||||
match self.pointer_pos {
|
||||
Some(pos) => !rect.contains(pos),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// True if the user clicked outside ALL rects in `rects` (useful for parent menu + open submenu).
|
||||
pub fn clicked_outside_any(&self, rects: &[Rect]) -> bool {
|
||||
if !self.left_pressed && !self.right_pressed {
|
||||
return false;
|
||||
}
|
||||
match self.pointer_pos {
|
||||
Some(pos) => !rects.iter().any(|r| r.contains(pos)),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_pressed(&self, key: Key) -> bool {
|
||||
self.key_events.iter().any(|e| e.key == key)
|
||||
}
|
||||
|
||||
pub fn key_pressed_no_mods(&self, key: Key) -> bool {
|
||||
self.key_events
|
||||
.iter()
|
||||
.any(|e| e.key == key && !e.modifiers.ctrl && !e.modifiers.alt && !e.modifiers.super_key)
|
||||
}
|
||||
|
||||
pub fn shortcut(&self, command: bool, shift: bool, ch: char) -> bool {
|
||||
let lower = ch.to_ascii_lowercase();
|
||||
self.key_events.iter().any(|e| {
|
||||
e.modifiers.command() == command
|
||||
&& e.modifiers.shift == shift
|
||||
&& matches!(e.key, Key::Char(c) if c.to_ascii_lowercase() == lower)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_focus(&mut self, id: Option<WidgetId>) {
|
||||
self.focused_id = id;
|
||||
}
|
||||
|
||||
pub fn is_focused(&self, id: WidgetId) -> bool {
|
||||
self.focused_id == Some(id)
|
||||
}
|
||||
|
||||
pub fn has_text_focus(&self) -> bool {
|
||||
self.focused_id.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn translate_winit_key(key: &WinitKey) -> Option<Key> {
|
||||
match key {
|
||||
WinitKey::Named(named) => match named {
|
||||
NamedKey::Enter => Some(Key::Enter),
|
||||
NamedKey::Escape => Some(Key::Escape),
|
||||
NamedKey::Backspace => Some(Key::Backspace),
|
||||
NamedKey::Delete => Some(Key::Delete),
|
||||
NamedKey::Tab => Some(Key::Tab),
|
||||
NamedKey::Space => Some(Key::Space),
|
||||
NamedKey::ArrowLeft => Some(Key::ArrowLeft),
|
||||
NamedKey::ArrowRight => Some(Key::ArrowRight),
|
||||
NamedKey::ArrowUp => Some(Key::ArrowUp),
|
||||
NamedKey::ArrowDown => Some(Key::ArrowDown),
|
||||
NamedKey::Home => Some(Key::Home),
|
||||
NamedKey::End => Some(Key::End),
|
||||
NamedKey::PageUp => Some(Key::PageUp),
|
||||
NamedKey::PageDown => Some(Key::PageDown),
|
||||
NamedKey::MediaPlayPause => Some(Key::MediaPlayPause),
|
||||
NamedKey::MediaTrackNext => Some(Key::MediaNext),
|
||||
NamedKey::MediaTrackPrevious => Some(Key::MediaPrev),
|
||||
NamedKey::MediaStop => Some(Key::MediaStop),
|
||||
NamedKey::F1 => Some(Key::F1),
|
||||
NamedKey::F2 => Some(Key::F2),
|
||||
NamedKey::F3 => Some(Key::F3),
|
||||
NamedKey::F4 => Some(Key::F4),
|
||||
NamedKey::F5 => Some(Key::F5),
|
||||
NamedKey::F6 => Some(Key::F6),
|
||||
NamedKey::F7 => Some(Key::F7),
|
||||
NamedKey::F8 => Some(Key::F8),
|
||||
NamedKey::F9 => Some(Key::F9),
|
||||
NamedKey::F10 => Some(Key::F10),
|
||||
NamedKey::F11 => Some(Key::F11),
|
||||
NamedKey::F12 => Some(Key::F12),
|
||||
_ => None,
|
||||
},
|
||||
WinitKey::Character(s) => s.chars().next().map(Key::Char),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Smooth 60fps float & bool transition animator (matches `--ym-duration-transition: 0.3s`).
|
||||
#[derive(Default)]
|
||||
pub struct Animator {
|
||||
values: HashMap<WidgetId, f32>,
|
||||
active_this_frame: bool,
|
||||
}
|
||||
|
||||
impl Animator {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
values: HashMap::with_capacity(128),
|
||||
active_this_frame: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_frame(&mut self) {
|
||||
self.active_this_frame = false;
|
||||
}
|
||||
|
||||
pub fn needs_repaint(&self) -> bool {
|
||||
self.active_this_frame
|
||||
}
|
||||
|
||||
/// Smoothly animate a boolean toward `0.0` or `1.0` over `duration_secs`.
|
||||
pub fn animate_bool(&mut self, id: WidgetId, target: bool, duration_secs: f32, dt: f32) -> f32 {
|
||||
self.animate_f32(id, if target { 1.0 } else { 0.0 }, duration_secs, dt)
|
||||
}
|
||||
|
||||
/// Smoothly animate a float toward `target` over `duration_secs` (linear step with ease curve).
|
||||
pub fn animate_f32(&mut self, id: WidgetId, target: f32, duration_secs: f32, dt: f32) -> f32 {
|
||||
let entry = self.values.entry(id).or_insert(target);
|
||||
let diff = target - *entry;
|
||||
if diff.abs() <= 0.001 || duration_secs <= 0.001 {
|
||||
*entry = target;
|
||||
return target;
|
||||
}
|
||||
let max_step = (dt / duration_secs).max(0.001);
|
||||
if diff.abs() <= max_step {
|
||||
*entry = target;
|
||||
} else {
|
||||
*entry += diff.signum() * max_step;
|
||||
self.active_this_frame = true;
|
||||
}
|
||||
*entry
|
||||
}
|
||||
|
||||
/// Exponentially damped spring-like smoothing (great for scroll/hover scales).
|
||||
pub fn damp_f32(&mut self, id: WidgetId, target: f32, speed: f32, dt: f32) -> f32 {
|
||||
let entry = self.values.entry(id).or_insert(target);
|
||||
let diff = target - *entry;
|
||||
if diff.abs() <= 0.001 {
|
||||
*entry = target;
|
||||
return target;
|
||||
}
|
||||
let factor = 1.0 - (-speed * dt).exp();
|
||||
*entry += diff * factor;
|
||||
if (target - *entry).abs() > 0.001 {
|
||||
self.active_this_frame = true;
|
||||
} else {
|
||||
*entry = target;
|
||||
}
|
||||
*entry
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.values.clear();
|
||||
}
|
||||
}
|
||||
495
src/engine/layout.rs
Normal file
495
src/engine/layout.rs
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
pub use taffy::prelude::{
|
||||
AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent, NodeId,
|
||||
Position,
|
||||
};
|
||||
pub use taffy::style::Overflow;
|
||||
use taffy::style::{
|
||||
AvailableSpace, Dimension, GridPlacement, GridTemplateComponent, LengthPercentage,
|
||||
LengthPercentageAuto, Style, TrackSizingFunction,
|
||||
};
|
||||
use taffy::style_helpers::{evenly_sized_tracks, flex, fr, length, line, minmax, span, TaffyAuto};
|
||||
use taffy::TaffyTree;
|
||||
|
||||
use crate::engine::types::Rect;
|
||||
|
||||
/// Ergonomic CSS Flexbox & Grid style builder backed by `taffy 0.16`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LayoutStyle {
|
||||
pub inner: Style,
|
||||
}
|
||||
|
||||
impl Default for LayoutStyle {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
inner: Style::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutStyle {
|
||||
/// Horizontal Flexbox row container (`display: flex; flex-direction: row`).
|
||||
pub fn row() -> Self {
|
||||
Self {
|
||||
inner: Style {
|
||||
display: Display::Flex,
|
||||
flex_direction: FlexDirection::Row,
|
||||
..Style::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertical Flexbox column container (`display: flex; flex-direction: column`).
|
||||
pub fn col() -> Self {
|
||||
Self {
|
||||
inner: Style {
|
||||
display: Display::Flex,
|
||||
flex_direction: FlexDirection::Column,
|
||||
..Style::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// CSS Grid container with `cols` evenly-sized `1fr` columns (`grid-template-columns: repeat(cols, minmax(0, 1fr))`).
|
||||
pub fn grid(cols: u16) -> Self {
|
||||
Self {
|
||||
inner: Style {
|
||||
display: Display::Grid,
|
||||
grid_template_columns: evenly_sized_tracks(cols.max(1)),
|
||||
..Style::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// CSS Grid container with explicit column track sizing functions.
|
||||
pub fn grid_columns(tracks: Vec<TrackSizingFunction>) -> Self {
|
||||
let cols: Vec<GridTemplateComponent<String>> =
|
||||
tracks.into_iter().map(GridTemplateComponent::Single).collect();
|
||||
Self {
|
||||
inner: Style {
|
||||
display: Display::Grid,
|
||||
grid_template_columns: cols,
|
||||
..Style::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// CSS Grid container with `cols` equal columns and `rows` equal rows (e.g., FullscreenPlayer 3x3 overlay!).
|
||||
pub fn grid_xy(cols: u16, rows: u16) -> Self {
|
||||
Self {
|
||||
inner: Style {
|
||||
display: Display::Grid,
|
||||
grid_template_columns: evenly_sized_tracks(cols.max(1)),
|
||||
grid_template_rows: evenly_sized_tracks(rows.max(1)),
|
||||
..Style::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Standard block/leaf item.
|
||||
pub fn leaf() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn gap(mut self, g: f32) -> Self {
|
||||
self.inner.gap = taffy::geometry::Size {
|
||||
width: LengthPercentage::length(g),
|
||||
height: LengthPercentage::length(g),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn gap_xy(mut self, col_gap: f32, row_gap: f32) -> Self {
|
||||
self.inner.gap = taffy::geometry::Size {
|
||||
width: LengthPercentage::length(col_gap),
|
||||
height: LengthPercentage::length(row_gap),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pad(mut self, p: f32) -> Self {
|
||||
let lp = LengthPercentage::length(p);
|
||||
self.inner.padding = taffy::geometry::Rect {
|
||||
left: lp,
|
||||
right: lp,
|
||||
top: lp,
|
||||
bottom: lp,
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pad_xy(mut self, horizontal: f32, vertical: f32) -> Self {
|
||||
let h = LengthPercentage::length(horizontal);
|
||||
let v = LengthPercentage::length(vertical);
|
||||
self.inner.padding = taffy::geometry::Rect {
|
||||
left: h,
|
||||
right: h,
|
||||
top: v,
|
||||
bottom: v,
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pad_trbl(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
|
||||
self.inner.padding = taffy::geometry::Rect {
|
||||
top: LengthPercentage::length(top),
|
||||
right: LengthPercentage::length(right),
|
||||
bottom: LengthPercentage::length(bottom),
|
||||
left: LengthPercentage::length(left),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn margin(mut self, m: f32) -> Self {
|
||||
let lp = LengthPercentageAuto::length(m);
|
||||
self.inner.margin = taffy::geometry::Rect {
|
||||
left: lp,
|
||||
right: lp,
|
||||
top: lp,
|
||||
bottom: lp,
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn margin_xy(mut self, horizontal: f32, vertical: f32) -> Self {
|
||||
let h = LengthPercentageAuto::length(horizontal);
|
||||
let v = LengthPercentageAuto::length(vertical);
|
||||
self.inner.margin = taffy::geometry::Rect {
|
||||
left: h,
|
||||
right: h,
|
||||
top: v,
|
||||
bottom: v,
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn margin_trbl(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
|
||||
self.inner.margin = taffy::geometry::Rect {
|
||||
top: LengthPercentageAuto::length(top),
|
||||
right: LengthPercentageAuto::length(right),
|
||||
bottom: LengthPercentageAuto::length(bottom),
|
||||
left: LengthPercentageAuto::length(left),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn w(mut self, width: f32) -> Self {
|
||||
self.inner.size.width = Dimension::length(width);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn h(mut self, height: f32) -> Self {
|
||||
self.inner.size.height = Dimension::length(height);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn size(mut self, width: f32, height: f32) -> Self {
|
||||
self.inner.size = taffy::geometry::Size {
|
||||
width: Dimension::length(width),
|
||||
height: Dimension::length(height),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn w_pct(mut self, pct_0_to_1: f32) -> Self {
|
||||
self.inner.size.width = Dimension::percent(pct_0_to_1);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn h_pct(mut self, pct_0_to_1: f32) -> Self {
|
||||
self.inner.size.height = Dimension::percent(pct_0_to_1);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn w_full(self) -> Self {
|
||||
self.w_pct(1.0)
|
||||
}
|
||||
|
||||
pub fn h_full(self) -> Self {
|
||||
self.h_pct(1.0)
|
||||
}
|
||||
|
||||
pub fn full(self) -> Self {
|
||||
self.w_pct(1.0).h_pct(1.0)
|
||||
}
|
||||
|
||||
pub fn min_w(mut self, width: f32) -> Self {
|
||||
self.inner.min_size.width = LengthPercentageAuto::length(width);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn min_h(mut self, height: f32) -> Self {
|
||||
self.inner.min_size.height = LengthPercentageAuto::length(height);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn max_w(mut self, width: f32) -> Self {
|
||||
self.inner.max_size.width = LengthPercentageAuto::length(width);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn max_h(mut self, height: f32) -> Self {
|
||||
self.inner.max_size.height = LengthPercentageAuto::length(height);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn flex_grow(mut self, grow: f32) -> Self {
|
||||
self.inner.flex_grow = grow;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn flex_shrink(mut self, shrink: f32) -> Self {
|
||||
self.inner.flex_shrink = shrink;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn flex_1(mut self) -> Self {
|
||||
self.inner.flex_grow = 1.0;
|
||||
self.inner.flex_shrink = 1.0;
|
||||
self.inner.flex_basis = Dimension::length(0.0);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn wrap(mut self) -> Self {
|
||||
self.inner.flex_wrap = FlexWrap::Wrap;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn align_items(mut self, align: AlignItems) -> Self {
|
||||
self.inner.align_items = align;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn align_self(mut self, align: AlignSelf) -> Self {
|
||||
self.inner.align_self = Some(align);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn justify_content(mut self, justify: JustifyContent) -> Self {
|
||||
self.inner.justify_content = justify;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn center(mut self) -> Self {
|
||||
self.inner.align_items = AlignItems::CENTER;
|
||||
self.inner.justify_content = JustifyContent::CENTER;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn aspect_ratio(mut self, ratio: f32) -> Self {
|
||||
self.inner.aspect_ratio = Some(ratio);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn absolute(mut self) -> Self {
|
||||
self.inner.position = Position::Absolute;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn inset_trbl(
|
||||
mut self,
|
||||
top: Option<f32>,
|
||||
right: Option<f32>,
|
||||
bottom: Option<f32>,
|
||||
left: Option<f32>,
|
||||
) -> Self {
|
||||
self.inner.inset = taffy::geometry::Rect {
|
||||
top: top.map_or(LengthPercentageAuto::AUTO, LengthPercentageAuto::length),
|
||||
right: right.map_or(LengthPercentageAuto::AUTO, LengthPercentageAuto::length),
|
||||
bottom: bottom.map_or(LengthPercentageAuto::AUTO, LengthPercentageAuto::length),
|
||||
left: left.map_or(LengthPercentageAuto::AUTO, LengthPercentageAuto::length),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn grid_col_span(mut self, span_count: u16) -> Self {
|
||||
self.inner.grid_column = taffy::geometry::Line {
|
||||
start: GridPlacement::Auto,
|
||||
end: span(span_count),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn grid_row_span(mut self, span_count: u16) -> Self {
|
||||
self.inner.grid_row = taffy::geometry::Line {
|
||||
start: GridPlacement::Auto,
|
||||
end: span(span_count),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn grid_area(mut self, col_start: i16, col_span: u16, row_start: i16, row_span: u16) -> Self {
|
||||
self.inner.grid_column = taffy::geometry::Line {
|
||||
start: line(col_start),
|
||||
end: span(col_span),
|
||||
};
|
||||
self.inner.grid_row = taffy::geometry::Line {
|
||||
start: line(row_start),
|
||||
end: span(row_span),
|
||||
};
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Immediate-mode `taffy 0.16` layout solver that builds a Flexbox/Grid tree
|
||||
/// and computes exact screen-space `Rect`s for every node.
|
||||
pub struct LayoutTree {
|
||||
tree: TaffyTree<()>,
|
||||
rects: HashMap<NodeId, Rect>,
|
||||
}
|
||||
|
||||
impl Default for LayoutTree {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutTree {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tree: TaffyTree::new(),
|
||||
rects: HashMap::with_capacity(64),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.tree.clear();
|
||||
self.rects.clear();
|
||||
}
|
||||
|
||||
pub fn leaf(&mut self, style: LayoutStyle) -> NodeId {
|
||||
self.tree.new_leaf(style.inner).expect("taffy new_leaf")
|
||||
}
|
||||
|
||||
pub fn container(&mut self, style: LayoutStyle, children: &[NodeId]) -> NodeId {
|
||||
self.tree
|
||||
.new_with_children(style.inner, children)
|
||||
.expect("taffy new_with_children")
|
||||
}
|
||||
|
||||
/// Solve layout for `root` inside screen-space `bounds`, caching every descendant's absolute `Rect`.
|
||||
pub fn compute(&mut self, root: NodeId, bounds: Rect) {
|
||||
self.rects.clear();
|
||||
let avail = taffy::geometry::Size {
|
||||
width: AvailableSpace::Definite(bounds.w.max(0.0)),
|
||||
height: AvailableSpace::Definite(bounds.h.max(0.0)),
|
||||
};
|
||||
let _ = self.tree.compute_layout(root, avail);
|
||||
self.collect_rects(root, bounds.x, bounds.y);
|
||||
}
|
||||
|
||||
fn collect_rects(&mut self, node: NodeId, parent_x: f32, parent_y: f32) {
|
||||
let Ok(layout) = self.tree.layout(node) else {
|
||||
return;
|
||||
};
|
||||
let x = parent_x + layout.location.x;
|
||||
let y = parent_y + layout.location.y;
|
||||
self.rects.insert(
|
||||
node,
|
||||
Rect::from_xywh(x, y, layout.size.width, layout.size.height),
|
||||
);
|
||||
if let Ok(children) = self.tree.children(node) {
|
||||
for child in children {
|
||||
self.collect_rects(child, x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve the solved screen-space logical `Rect` for `node`.
|
||||
#[inline]
|
||||
pub fn rect(&self, node: NodeId) -> Rect {
|
||||
self.rects.get(&node).copied().unwrap_or(Rect::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
/// Quick Flexbox horizontal split inside `bounds`.
|
||||
/// Pass positive widths for fixed px items, or negative (`-1.0`, `-2.0`) for `flex_grow(|w|)`.
|
||||
pub fn hstack(bounds: Rect, gap: f32, widths: &[f32]) -> Vec<Rect> {
|
||||
let mut lt = LayoutTree::new();
|
||||
let mut nodes = Vec::with_capacity(widths.len());
|
||||
for &w in widths {
|
||||
let s = if w < 0.0 {
|
||||
LayoutStyle::leaf().flex_grow(-w).flex_shrink(1.0).h_full()
|
||||
} else {
|
||||
LayoutStyle::leaf().w(w).flex_shrink(0.0).h_full()
|
||||
};
|
||||
nodes.push(lt.leaf(s));
|
||||
}
|
||||
let root = lt.container(
|
||||
LayoutStyle::row().size(bounds.w, bounds.h).gap(gap),
|
||||
&nodes,
|
||||
);
|
||||
lt.compute(root, bounds);
|
||||
nodes.into_iter().map(|n| lt.rect(n)).collect()
|
||||
}
|
||||
|
||||
/// Quick Flexbox vertical split inside `bounds`.
|
||||
/// Pass positive heights for fixed px items, or negative (`-1.0`, `-2.0`) for `flex_grow(|h|)`.
|
||||
pub fn vstack(bounds: Rect, gap: f32, heights: &[f32]) -> Vec<Rect> {
|
||||
let mut lt = LayoutTree::new();
|
||||
let mut nodes = Vec::with_capacity(heights.len());
|
||||
for &h in heights {
|
||||
let s = if h < 0.0 {
|
||||
LayoutStyle::leaf().flex_grow(-h).flex_shrink(1.0).w_full()
|
||||
} else {
|
||||
LayoutStyle::leaf().h(h).flex_shrink(0.0).w_full()
|
||||
};
|
||||
nodes.push(lt.leaf(s));
|
||||
}
|
||||
let root = lt.container(
|
||||
LayoutStyle::col().size(bounds.w, bounds.h).gap(gap),
|
||||
&nodes,
|
||||
);
|
||||
lt.compute(root, bounds);
|
||||
nodes.into_iter().map(|n| lt.rect(n)).collect()
|
||||
}
|
||||
|
||||
/// Compute a responsive CSS Grid using `taffy 0.16` for cards (Albums, Playlists, Artists, Mixes).
|
||||
/// Returns `(column_count, column_width, total_height, item_rects)`.
|
||||
pub fn responsive_grid(
|
||||
origin_x: f32,
|
||||
origin_y: f32,
|
||||
avail_width: f32,
|
||||
min_col_width: f32,
|
||||
gap_x: f32,
|
||||
gap_y: f32,
|
||||
count: usize,
|
||||
item_height_fn: impl Fn(f32) -> f32,
|
||||
) -> (usize, f32, f32, Vec<Rect>) {
|
||||
if count == 0 || avail_width <= 1.0 {
|
||||
return (1, avail_width.max(0.0), 0.0, Vec::new());
|
||||
}
|
||||
let cols = (((avail_width + gap_x) / (min_col_width + gap_x)).floor() as usize).max(1);
|
||||
let col_w = ((avail_width - gap_x * (cols.saturating_sub(1)) as f32) / cols as f32).max(1.0);
|
||||
let item_h = item_height_fn(col_w);
|
||||
let rows = (count + cols - 1) / cols;
|
||||
let total_h = rows as f32 * item_h + rows.saturating_sub(1) as f32 * gap_y;
|
||||
|
||||
let mut lt = LayoutTree::new();
|
||||
let mut nodes = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
nodes.push(lt.leaf(LayoutStyle::leaf().h(item_h)));
|
||||
}
|
||||
let root = lt.container(
|
||||
LayoutStyle::grid(cols as u16)
|
||||
.w(avail_width)
|
||||
.gap_xy(gap_x, gap_y),
|
||||
&nodes,
|
||||
);
|
||||
lt.compute(root, Rect::from_xywh(origin_x, origin_y, avail_width, total_h));
|
||||
let rects = nodes.into_iter().map(|n| lt.rect(n)).collect();
|
||||
(cols, col_w, total_h, rects)
|
||||
}
|
||||
|
||||
/// Helper to create a `TrackSizingFunction` for custom CSS Grids (`minmax(min_px, 1fr)`).
|
||||
#[inline]
|
||||
pub fn grid_track_minmax_fr(min_px: f32, fr_val: f32) -> TrackSizingFunction {
|
||||
minmax(length(min_px), fr(fr_val))
|
||||
}
|
||||
|
||||
/// Helper to create a `TrackSizingFunction` for equal `1fr` columns.
|
||||
#[inline]
|
||||
pub fn grid_track_fr(fr_val: f32) -> TrackSizingFunction {
|
||||
flex(fr_val)
|
||||
}
|
||||
482
src/engine/mod.rs
Normal file
482
src/engine/mod.rs
Normal file
|
|
@ -0,0 +1,482 @@
|
|||
pub mod input;
|
||||
pub mod layout;
|
||||
pub mod scroll;
|
||||
pub mod text;
|
||||
pub mod textures;
|
||||
pub mod theme;
|
||||
pub mod types;
|
||||
pub mod widgets;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::icons::{Icon, IconCache};
|
||||
|
||||
pub use input::{Animator, InputState, Interaction, Key, KeyPress, Modifiers, WidgetId, ZLayer};
|
||||
pub use layout::{
|
||||
grid_track_fr, grid_track_minmax_fr, hstack, responsive_grid, vstack, AlignContent, AlignItems,
|
||||
AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent, LayoutStyle, LayoutTree, NodeId,
|
||||
Overflow, Position,
|
||||
};
|
||||
pub use scroll::{visible_row_range, ScrollState, ScrollStore};
|
||||
pub use text::{
|
||||
copy_to_clipboard, paste_from_clipboard, FontRole, RichSpan, TextAlign, TextEngine,
|
||||
TextInputEvent, TextInputState, TextStyle,
|
||||
};
|
||||
pub use textures::{premultiply_rgba_srgb, TextureRegistry};
|
||||
pub use theme::{
|
||||
YmPalette, CARD_RADIUS, CONTENT_RADIUS, LAYOUT_GAP, NAVBAR_COLLAPSED_WIDTH, NAVBAR_FULL_WIDTH,
|
||||
PLAYER_BAR_HEIGHT, TITLEBAR_BTN_WIDTH, TITLEBAR_HEIGHT, TRACK_ROW_HEIGHT,
|
||||
};
|
||||
pub use types::{
|
||||
css_rgba, pos2, vec2, BlurRegion, Color, CornerRadii, CursorKind, DisplayList, Pos2, Rect,
|
||||
TextureFormat, TextureId, TextureUpload, UiInstance, Vec2, BLUR_TEXTURE_ID,
|
||||
FIRST_USER_TEXTURE_ID, GLYPH_ATLAS_TEXTURE_ID, NONE_TEXTURE_ID, VIBE_TEXTURE_ID,
|
||||
};
|
||||
|
||||
/// Output produced by `UiContext::end_frame()` and consumed directly by `UiVulkanRenderer` / `HeadlessVulkanRenderer`.
|
||||
pub struct FrameOutput {
|
||||
pub display_list: DisplayList,
|
||||
pub texture_uploads: Vec<TextureUpload>,
|
||||
pub cursor: CursorKind,
|
||||
pub needs_repaint: bool,
|
||||
pub repaint_after: Option<std::time::Duration>,
|
||||
}
|
||||
|
||||
/// Unified pure-Rust UI engine context combining:
|
||||
/// - Z-layered `DisplayList`s (`Base < Drawer < Popover < Modal < Titlebar`)
|
||||
/// - `winit 0.30` input state + Z-layered hit-testing + smooth 60fps `Animator`
|
||||
/// - `cosmic-text 0.19` + `swash` R8 glyph atlas `TextEngine` & stateful `TextInputState`s
|
||||
/// - `ScrollStore` for smooth vertical/horizontal scroll views
|
||||
/// - `TextureRegistry` & `IconCache`
|
||||
pub struct UiContext {
|
||||
pub input: InputState,
|
||||
pub text: TextEngine,
|
||||
pub animator: Animator,
|
||||
pub scrolls: ScrollStore,
|
||||
pub textures: TextureRegistry,
|
||||
pub icons: IconCache,
|
||||
pub(crate) layers: [DisplayList; ZLayer::COUNT],
|
||||
pub(crate) current_layer: ZLayer,
|
||||
pub(crate) text_inputs: HashMap<WidgetId, TextInputState>,
|
||||
cursor: CursorKind,
|
||||
repaint_requested: bool,
|
||||
repaint_after: Option<std::time::Duration>,
|
||||
pending_tooltip: Option<(Rect, String)>,
|
||||
}
|
||||
|
||||
impl Default for UiContext {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl UiContext {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
input: InputState::new(),
|
||||
text: TextEngine::new(),
|
||||
animator: Animator::new(),
|
||||
scrolls: ScrollStore::new(),
|
||||
textures: TextureRegistry::new(),
|
||||
icons: IconCache::new(),
|
||||
layers: [
|
||||
DisplayList::new(),
|
||||
DisplayList::new(),
|
||||
DisplayList::new(),
|
||||
DisplayList::new(),
|
||||
DisplayList::new(),
|
||||
],
|
||||
current_layer: ZLayer::Base,
|
||||
text_inputs: HashMap::with_capacity(16),
|
||||
cursor: CursorKind::Default,
|
||||
repaint_requested: false,
|
||||
repaint_after: None,
|
||||
pending_tooltip: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Begin a new logical UI frame. Call before rendering views/chrome.
|
||||
pub fn begin_frame(&mut self, screen_size: Vec2, scale_factor: f32, time: f64) {
|
||||
for dl in &mut self.layers {
|
||||
dl.clear();
|
||||
}
|
||||
self.current_layer = ZLayer::Base;
|
||||
self.cursor = CursorKind::Default;
|
||||
self.repaint_requested = false;
|
||||
self.repaint_after = None;
|
||||
self.pending_tooltip = None;
|
||||
self.input.begin_frame(screen_size, scale_factor, time);
|
||||
self.animator.begin_frame();
|
||||
self.text.set_scale_factor(scale_factor);
|
||||
}
|
||||
|
||||
/// Composite all Z-layers in strict order (`Base < Drawer < Popover < Modal < Titlebar`),
|
||||
/// render any hover tooltip, drain GPU texture uploads, and reset per-frame input edges.
|
||||
pub fn end_frame(&mut self, pal: &YmPalette) -> FrameOutput {
|
||||
// Render deferred hover tooltip on top of Popover layer
|
||||
if let Some((anchor, label)) = self.pending_tooltip.take() {
|
||||
let prev = self.set_layer(ZLayer::Titlebar);
|
||||
let pad_x = 10.0;
|
||||
let text_sz = self.measure_text(&label, TextStyle::medium(12.0, Color::WHITE), None);
|
||||
let tip_w = text_sz.x + pad_x * 2.0;
|
||||
let tip_h = 26.0;
|
||||
let screen = self.input.screen_size;
|
||||
let mut tx = (anchor.center_x() - tip_w * 0.5).clamp(8.0, (screen.x - tip_w - 8.0).max(8.0));
|
||||
let mut ty = anchor.top() - tip_h - 6.0;
|
||||
if ty < 36.0 {
|
||||
ty = anchor.bottom() + 6.0;
|
||||
}
|
||||
if ty + tip_h > screen.y - 8.0 {
|
||||
ty = (screen.y - tip_h - 8.0).max(8.0);
|
||||
}
|
||||
tx = tx.round();
|
||||
ty = ty.round();
|
||||
let tip_r = Rect::from_xywh(tx, ty, tip_w, tip_h);
|
||||
self.dl()
|
||||
.push_shadow(tip_r, 8.0, 10.0, 0.0, Vec2::new(0.0, 2.0), css_rgba(0, 0, 0, 110));
|
||||
self.dl().push_rect(tip_r, 8.0, pal.bg_tooltip);
|
||||
self.draw_text_ellipsis(
|
||||
&label,
|
||||
TextStyle::medium(12.0, Color::WHITE),
|
||||
tip_r,
|
||||
TextAlign::Center,
|
||||
);
|
||||
self.set_layer(prev);
|
||||
}
|
||||
|
||||
let mut combined = DisplayList::new();
|
||||
for layer in ZLayer::ALL {
|
||||
combined.extend(&self.layers[layer.index()]);
|
||||
}
|
||||
|
||||
let texture_uploads = self.textures.drain_uploads();
|
||||
let immediate_repaint =
|
||||
self.repaint_requested || self.animator.needs_repaint() || !texture_uploads.is_empty();
|
||||
let repaint_after = if immediate_repaint {
|
||||
Some(std::time::Duration::from_millis(16))
|
||||
} else {
|
||||
self.repaint_after
|
||||
};
|
||||
let needs_repaint = immediate_repaint || repaint_after.is_some();
|
||||
let cursor = self.cursor;
|
||||
self.input.end_frame();
|
||||
|
||||
FrameOutput {
|
||||
display_list: combined,
|
||||
texture_uploads,
|
||||
cursor,
|
||||
needs_repaint,
|
||||
repaint_after,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_layer(&self) -> ZLayer {
|
||||
self.current_layer
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_layer(&mut self, layer: ZLayer) -> ZLayer {
|
||||
let prev = self.current_layer;
|
||||
self.current_layer = layer;
|
||||
prev
|
||||
}
|
||||
|
||||
/// Execute closure `f` drawing & hit-testing on `layer`, then restore previous layer.
|
||||
pub fn with_layer<R>(&mut self, layer: ZLayer, f: impl FnOnce(&mut Self) -> R) -> R {
|
||||
let prev = self.set_layer(layer);
|
||||
let res = f(self);
|
||||
self.set_layer(prev);
|
||||
res
|
||||
}
|
||||
|
||||
/// Mutable reference to the currently active Z-layer's `DisplayList`.
|
||||
#[inline]
|
||||
pub fn dl(&mut self) -> &mut DisplayList {
|
||||
&mut self.layers[self.current_layer.index()]
|
||||
}
|
||||
|
||||
/// Mutable reference to a specific Z-layer's `DisplayList`.
|
||||
#[inline]
|
||||
pub fn dl_for(&mut self, layer: ZLayer) -> &mut DisplayList {
|
||||
&mut self.layers[layer.index()]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn push_clip(&mut self, rect: Rect, radius: f32) {
|
||||
self.dl().push_clip(rect, radius);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn push_clip_raw(&mut self, rect: Rect, radius: f32) {
|
||||
self.dl().push_clip_raw(rect, radius);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn pop_clip(&mut self) {
|
||||
self.dl().pop_clip();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn screen_rect(&self) -> Rect {
|
||||
Rect::from_xywh(0.0, 0.0, self.input.screen_size.x, self.input.screen_size.y)
|
||||
}
|
||||
|
||||
/// Effective visible culling rect for the current Z-layer:
|
||||
/// intersects the active clip rect (if any) with `screen_rect()`.
|
||||
/// Returns `Rect::ZERO` when an active clip intersection is completely empty (clipped off-screen).
|
||||
#[inline]
|
||||
pub fn current_clip_rect(&self) -> Rect {
|
||||
let screen = self.screen_rect();
|
||||
let (clip_r, _) = self.layers[self.current_layer.index()].current_clip();
|
||||
if clip_r == Rect::ZERO {
|
||||
screen
|
||||
} else if clip_r.is_empty() {
|
||||
Rect::ZERO
|
||||
} else {
|
||||
screen.intersect(clip_r)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if `rect` intersects the active clip/screen viewport (optionally expanded by `margin` px).
|
||||
#[inline]
|
||||
pub fn is_visible_in_clip(&self, rect: Rect, margin: f32) -> bool {
|
||||
if rect.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let clip = self.current_clip_rect();
|
||||
if clip.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let bounds = if margin > 0.0 {
|
||||
clip.expand(margin)
|
||||
} else {
|
||||
clip
|
||||
};
|
||||
rect.intersects(bounds)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn register_blocker(&mut self, rect: Rect) {
|
||||
self.input.register_blocker(self.current_layer, rect);
|
||||
}
|
||||
|
||||
/// Z-layer & clip-aware widget interaction test.
|
||||
pub fn interact(&mut self, id: WidgetId, rect: Rect) -> Interaction {
|
||||
let (clip_r, _) = self.layers[self.current_layer.index()].current_clip();
|
||||
let clip = if clip_r.is_empty() { None } else { Some(clip_r) };
|
||||
self.input.interact(id, self.current_layer, rect, clip)
|
||||
}
|
||||
|
||||
/// Z-layer & clip-aware hover check.
|
||||
pub fn is_hovered(&self, rect: Rect) -> bool {
|
||||
let (clip_r, _) = self.layers[self.current_layer.index()].current_clip();
|
||||
let clip = if clip_r.is_empty() { None } else { Some(clip_r) };
|
||||
self.input.is_hovered_in(self.current_layer, rect, clip)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor(&mut self, cursor: CursorKind) {
|
||||
self.cursor = cursor;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn request_repaint(&mut self) {
|
||||
self.repaint_requested = true;
|
||||
}
|
||||
|
||||
/// Request a low-frequency scheduled repaint (e.g. 250ms caret blink or 40ms playing dot)
|
||||
/// without forcing 60 FPS continuous GPU rendering.
|
||||
#[inline]
|
||||
pub fn request_repaint_after(&mut self, delay: std::time::Duration) {
|
||||
self.repaint_after = Some(match self.repaint_after {
|
||||
Some(prev) => prev.min(delay),
|
||||
None => delay,
|
||||
});
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn show_tooltip(&mut self, anchor: Rect, text: impl Into<String>) {
|
||||
self.pending_tooltip = Some((anchor, text.into()));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn animate_bool(&mut self, id: WidgetId, target: bool, duration_secs: f32) -> f32 {
|
||||
self.animator
|
||||
.animate_bool(id, target, duration_secs, self.input.dt)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn animate_f32(&mut self, id: WidgetId, target: f32, duration_secs: f32) -> f32 {
|
||||
self.animator
|
||||
.animate_f32(id, target, duration_secs, self.input.dt)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn damp_f32(&mut self, id: WidgetId, target: f32, speed: f32) -> f32 {
|
||||
self.animator.damp_f32(id, target, speed, self.input.dt)
|
||||
}
|
||||
|
||||
/// Draw a crisp tinted official SVG icon into `rect`.
|
||||
pub fn draw_icon(&mut self, icon: Icon, rect: Rect, tint: Color) {
|
||||
let tex_id = self.icons.get(&mut self.textures, icon);
|
||||
self.layers[self.current_layer.index()].push_image(rect, tex_id, 0.0, tint);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn measure_text(&mut self, text: &str, style: TextStyle, max_width: Option<f32>) -> Vec2 {
|
||||
self.text.measure(text, style, max_width)
|
||||
}
|
||||
|
||||
pub fn draw_text(
|
||||
&mut self,
|
||||
text: &str,
|
||||
style: TextStyle,
|
||||
pos: Pos2,
|
||||
max_width: Option<f32>,
|
||||
align: TextAlign,
|
||||
) -> Vec2 {
|
||||
let dl = &mut self.layers[self.current_layer.index()];
|
||||
self.text
|
||||
.draw_text(dl, &mut self.textures, text, style, pos, max_width, align)
|
||||
}
|
||||
|
||||
pub fn draw_text_ellipsis(
|
||||
&mut self,
|
||||
text: &str,
|
||||
style: TextStyle,
|
||||
rect: Rect,
|
||||
align: TextAlign,
|
||||
) -> Vec2 {
|
||||
let dl = &mut self.layers[self.current_layer.index()];
|
||||
self.text
|
||||
.draw_text_ellipsis(dl, &mut self.textures, text, style, rect, align)
|
||||
}
|
||||
|
||||
pub fn draw_text_wrapped(
|
||||
&mut self,
|
||||
text: &str,
|
||||
style: TextStyle,
|
||||
rect: Rect,
|
||||
max_lines: Option<usize>,
|
||||
align: TextAlign,
|
||||
) -> Vec2 {
|
||||
let dl = &mut self.layers[self.current_layer.index()];
|
||||
self.text
|
||||
.draw_text_wrapped(dl, &mut self.textures, text, style, rect, max_lines, align)
|
||||
}
|
||||
|
||||
pub fn draw_rich_text(
|
||||
&mut self,
|
||||
spans: &[RichSpan<'_>],
|
||||
rect: Rect,
|
||||
max_lines: Option<usize>,
|
||||
align: TextAlign,
|
||||
) -> Vec<(usize, Rect)> {
|
||||
let dl = &mut self.layers[self.current_layer.index()];
|
||||
self.text
|
||||
.draw_rich_text(dl, &mut self.textures, spans, rect, max_lines, align)
|
||||
}
|
||||
|
||||
/// Draw single-line text with smooth per-glyph transparent alpha fade across
|
||||
/// `[left, left + left_fade_px]` and `[right - right_fade_px, right]` of `clip_rect`
|
||||
/// (zero opaque fade boxes over translucent glass; `<= 0.01` keeps that edge at 100% alpha).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn draw_text_marquee_fade(
|
||||
&mut self,
|
||||
text: &str,
|
||||
style: TextStyle,
|
||||
origin_x: f32,
|
||||
center_y: f32,
|
||||
clip_rect: Rect,
|
||||
left_fade_px: f32,
|
||||
right_fade_px: f32,
|
||||
) -> Vec2 {
|
||||
let dl = &mut self.layers[self.current_layer.index()];
|
||||
self.text.draw_text_marquee_fade(
|
||||
dl,
|
||||
&mut self.textures,
|
||||
text,
|
||||
style,
|
||||
origin_x,
|
||||
center_y,
|
||||
clip_rect,
|
||||
left_fade_px,
|
||||
right_fade_px,
|
||||
)
|
||||
}
|
||||
|
||||
/// Begin a vertical scroll view inside `viewport` (pushes clip & applies wheel scroll).
|
||||
/// Returns the current vertical scroll offset (`>= 0.0`).
|
||||
pub fn begin_scroll_v(&mut self, id: WidgetId, viewport: Rect, clip_radius: f32) -> f32 {
|
||||
let layer = self.current_layer;
|
||||
let animating = self
|
||||
.scrolls
|
||||
.get_or_create(id)
|
||||
.update(&self.input, layer, viewport, true, false);
|
||||
if animating {
|
||||
self.request_repaint();
|
||||
}
|
||||
let offset_y = self.scrolls.get_or_create(id).offset.y;
|
||||
self.push_clip(viewport, clip_radius);
|
||||
offset_y
|
||||
}
|
||||
|
||||
/// End a vertical scroll view (pops clip & draws interactive floating scrollbar).
|
||||
pub fn end_scroll_v(
|
||||
&mut self,
|
||||
id: WidgetId,
|
||||
pal: &YmPalette,
|
||||
actual_content_height: f32,
|
||||
show_scrollbar: bool,
|
||||
) {
|
||||
self.pop_clip();
|
||||
let layer = self.current_layer;
|
||||
let dl = &mut self.layers[layer.index()];
|
||||
let dragging = self.scrolls.get_or_create(id).finish_vertical(
|
||||
dl,
|
||||
&mut self.input,
|
||||
layer,
|
||||
pal,
|
||||
actual_content_height,
|
||||
show_scrollbar,
|
||||
);
|
||||
if dragging {
|
||||
self.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Begin a horizontal scroll view inside `viewport` (e.g. Search AI prompts carousel, filter chips).
|
||||
/// Returns the current horizontal scroll offset (`>= 0.0`).
|
||||
pub fn begin_scroll_h(&mut self, id: WidgetId, viewport: Rect, clip_radius: f32) -> f32 {
|
||||
let layer = self.current_layer;
|
||||
let animating = self
|
||||
.scrolls
|
||||
.get_or_create(id)
|
||||
.update(&self.input, layer, viewport, false, true);
|
||||
if animating {
|
||||
self.request_repaint();
|
||||
}
|
||||
let offset_x = self.scrolls.get_or_create(id).offset.x;
|
||||
self.push_clip(viewport, clip_radius);
|
||||
offset_x
|
||||
}
|
||||
|
||||
/// End a horizontal scroll view (pops clip & updates content width).
|
||||
pub fn end_scroll_h(
|
||||
&mut self,
|
||||
id: WidgetId,
|
||||
pal: &YmPalette,
|
||||
actual_content_width: f32,
|
||||
show_scrollbar: bool,
|
||||
) {
|
||||
self.pop_clip();
|
||||
let dl = &mut self.layers[self.current_layer.index()];
|
||||
self.scrolls.get_or_create(id).finish_horizontal(
|
||||
dl,
|
||||
pal,
|
||||
actual_content_width,
|
||||
show_scrollbar,
|
||||
);
|
||||
}
|
||||
}
|
||||
381
src/engine/scroll.rs
Normal file
381
src/engine/scroll.rs
Normal file
|
|
@ -0,0 +1,381 @@
|
|||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
|
||||
use crate::engine::input::{InputState, WidgetId, ZLayer};
|
||||
use crate::engine::theme::YmPalette;
|
||||
use crate::engine::types::{css_rgba, DisplayList, Rect, Vec2};
|
||||
|
||||
/// Persistent vertical & horizontal scroll state with smooth clamping,
|
||||
/// wheel scrolling, scrollbar thumb drag, and programmatic `scroll_to` (for Search AI arrows!).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScrollState {
|
||||
pub offset: Vec2,
|
||||
pub target: Vec2,
|
||||
pub content_size: Vec2,
|
||||
pub viewport: Rect,
|
||||
dragging_v: bool,
|
||||
dragging_h: bool,
|
||||
drag_start_offset: f32,
|
||||
drag_start_pointer: f32,
|
||||
scrollbar_alpha: f32,
|
||||
last_scroll_time: f64,
|
||||
}
|
||||
|
||||
impl Default for ScrollState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScrollState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
offset: Vec2::ZERO,
|
||||
target: Vec2::ZERO,
|
||||
content_size: Vec2::ZERO,
|
||||
viewport: Rect::ZERO,
|
||||
dragging_v: false,
|
||||
dragging_h: false,
|
||||
drag_start_offset: 0.0,
|
||||
drag_start_pointer: 0.0,
|
||||
scrollbar_alpha: 0.0,
|
||||
last_scroll_time: -10.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max_offset(&self) -> Vec2 {
|
||||
Vec2::new(
|
||||
(self.content_size.x - self.viewport.w).max(0.0),
|
||||
(self.content_size.y - self.viewport.h).max(0.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// Smoothly scroll vertically to `y` (clamped to valid range).
|
||||
pub fn scroll_to_y(&mut self, y: f32) {
|
||||
let max_y = self.max_offset().y;
|
||||
self.target.y = y.clamp(0.0, max_y);
|
||||
}
|
||||
|
||||
/// Smoothly scroll horizontally to `x` (clamped to valid range).
|
||||
/// Used by Search AI prompt carousel `<` / `>` arrows!
|
||||
pub fn scroll_to_x(&mut self, x: f32) {
|
||||
let max_x = self.max_offset().x;
|
||||
self.target.x = x.clamp(0.0, max_x);
|
||||
}
|
||||
|
||||
/// Alias for programmatic horizontal/vertical scroll (`scroll_to`).
|
||||
pub fn scroll_to(&mut self, offset: Vec2) {
|
||||
let max = self.max_offset();
|
||||
self.target = Vec2::new(offset.x.clamp(0.0, max.x), offset.y.clamp(0.0, max.y));
|
||||
}
|
||||
|
||||
/// Relative smooth horizontal scroll (e.g., `± viewport.w * 0.5` for Search AI `<` `>` arrows!).
|
||||
pub fn scroll_by_x(&mut self, dx: f32) {
|
||||
self.scroll_to_x(self.target.x + dx);
|
||||
}
|
||||
|
||||
/// Relative smooth vertical scroll.
|
||||
pub fn scroll_by_y(&mut self, dy: f32) {
|
||||
self.scroll_to_y(self.target.y + dy);
|
||||
}
|
||||
|
||||
/// Instant vertical jump (e.g., reset scroll to top on page navigation).
|
||||
pub fn jump_to_y(&mut self, y: f32) {
|
||||
let max_y = self.max_offset().y;
|
||||
let clamped = y.clamp(0.0, max_y);
|
||||
self.offset.y = clamped;
|
||||
self.target.y = clamped;
|
||||
}
|
||||
|
||||
/// Instant horizontal jump.
|
||||
pub fn jump_to_x(&mut self, x: f32) {
|
||||
let max_x = self.max_offset().x;
|
||||
let clamped = x.clamp(0.0, max_x);
|
||||
self.offset.x = clamped;
|
||||
self.target.x = clamped;
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.offset = Vec2::ZERO;
|
||||
self.target = Vec2::ZERO;
|
||||
}
|
||||
|
||||
/// True when horizontal carousel can scroll backward (`<` arrow enabled).
|
||||
#[inline]
|
||||
pub fn can_scroll_left(&self) -> bool {
|
||||
self.target.x > 1.0
|
||||
}
|
||||
|
||||
/// True when horizontal carousel can scroll forward (`>` arrow enabled, 10px tolerance per Yandex spec).
|
||||
#[inline]
|
||||
pub fn can_scroll_right(&self) -> bool {
|
||||
self.content_size.x - self.target.x > self.viewport.w + 10.0
|
||||
}
|
||||
|
||||
/// Advance smooth interpolation & handle wheel input if hovered on `layer`.
|
||||
/// Returns `true` if animation is still in flight (caller should request repaint).
|
||||
pub fn update(
|
||||
&mut self,
|
||||
input: &InputState,
|
||||
layer: ZLayer,
|
||||
viewport: Rect,
|
||||
vertical: bool,
|
||||
horizontal: bool,
|
||||
) -> bool {
|
||||
self.viewport = viewport;
|
||||
let mut animating = false;
|
||||
|
||||
let hovered = input.is_hovered_in(layer, viewport, None);
|
||||
if hovered && (input.wheel_delta.x.abs() > 0.01 || input.wheel_delta.y.abs() > 0.01) {
|
||||
if vertical && input.wheel_delta.y.abs() > 0.01 && (!horizontal || !input.modifiers.shift) {
|
||||
self.target.y -= input.wheel_delta.y;
|
||||
self.last_scroll_time = input.time;
|
||||
}
|
||||
if horizontal {
|
||||
let dx = if input.wheel_delta.x.abs() > 0.01 {
|
||||
-input.wheel_delta.x
|
||||
} else if !vertical || input.modifiers.shift {
|
||||
-input.wheel_delta.y
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if dx.abs() > 0.01 {
|
||||
self.target.x += dx;
|
||||
self.last_scroll_time = input.time;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp targets against known content size
|
||||
let max = self.max_offset();
|
||||
self.target.x = self.target.x.clamp(0.0, max.x);
|
||||
self.target.y = self.target.y.clamp(0.0, max.y);
|
||||
|
||||
// Smooth exponential approach to target (snappy 60fps glide)
|
||||
let factor = 1.0 - (-18.0 * input.dt).exp();
|
||||
let dx = self.target.x - self.offset.x;
|
||||
let dy = self.target.y - self.offset.y;
|
||||
if dx.abs() > 0.25 {
|
||||
self.offset.x += dx * factor;
|
||||
animating = true;
|
||||
} else {
|
||||
self.offset.x = self.target.x;
|
||||
}
|
||||
if dy.abs() > 0.25 {
|
||||
self.offset.y += dy * factor;
|
||||
animating = true;
|
||||
} else {
|
||||
self.offset.y = self.target.y;
|
||||
}
|
||||
|
||||
// Clamp current offset as well in case content shrank
|
||||
self.offset.x = self.offset.x.clamp(0.0, max.x);
|
||||
self.offset.y = self.offset.y.clamp(0.0, max.y);
|
||||
|
||||
// Fade floating scrollbar smoothly
|
||||
let bar_active = self.dragging_v
|
||||
|| self.dragging_h
|
||||
|| (input.time - self.last_scroll_time) < 1.1
|
||||
|| (hovered && input.pointer_pos.map_or(false, |p| p.x >= viewport.right() - 16.0));
|
||||
let alpha_target = if bar_active { 1.0 } else { 0.0 };
|
||||
let alpha_diff = alpha_target - self.scrollbar_alpha;
|
||||
if alpha_diff.abs() > 0.01 {
|
||||
self.scrollbar_alpha += alpha_diff * (1.0 - (-10.0 * input.dt).exp());
|
||||
animating = true;
|
||||
} else {
|
||||
self.scrollbar_alpha = alpha_target;
|
||||
}
|
||||
|
||||
animating
|
||||
}
|
||||
|
||||
/// Update measured content height and render floating vertical scrollbar with drag support.
|
||||
/// Returns `true` if scrollbar is actively dragging or animating.
|
||||
pub fn finish_vertical(
|
||||
&mut self,
|
||||
dl: &mut DisplayList,
|
||||
input: &mut InputState,
|
||||
layer: ZLayer,
|
||||
pal: &YmPalette,
|
||||
actual_content_height: f32,
|
||||
show_scrollbar: bool,
|
||||
) -> bool {
|
||||
self.content_size.y = actual_content_height.max(0.0);
|
||||
let max_y = self.max_offset().y;
|
||||
if self.target.y > max_y {
|
||||
self.target.y = max_y;
|
||||
self.offset.y = self.offset.y.min(max_y);
|
||||
}
|
||||
if max_y <= 1.0 || !show_scrollbar {
|
||||
self.dragging_v = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
let vp = self.viewport;
|
||||
let track_pad = 4.0;
|
||||
let track_h = (vp.h - track_pad * 2.0).max(20.0);
|
||||
let visible_ratio = (vp.h / self.content_size.y).clamp(0.05, 1.0);
|
||||
let thumb_h = (track_h * visible_ratio).clamp(36.0, track_h);
|
||||
let scroll_ratio = (self.offset.y / max_y).clamp(0.0, 1.0);
|
||||
let thumb_y = vp.y + track_pad + (track_h - thumb_h) * scroll_ratio;
|
||||
|
||||
let bar_w = if self.dragging_v { 7.0 } else { 5.0 };
|
||||
let thumb_rect = Rect::from_xywh(vp.right() - bar_w - 3.0, thumb_y, bar_w, thumb_h);
|
||||
let hit_rect = Rect::from_xywh(vp.right() - 14.0, thumb_y - 4.0, 14.0, thumb_h + 8.0);
|
||||
|
||||
let hovered = input.is_hovered_in(layer, hit_rect, None);
|
||||
if hovered && input.left_pressed {
|
||||
self.dragging_v = true;
|
||||
self.drag_start_offset = self.offset.y;
|
||||
self.drag_start_pointer = input.pointer_pos.map_or(0.0, |p| p.y);
|
||||
self.last_scroll_time = input.time;
|
||||
}
|
||||
if self.dragging_v {
|
||||
if input.left_down {
|
||||
if let Some(p) = input.pointer_pos {
|
||||
let dy = p.y - self.drag_start_pointer;
|
||||
let travel = (track_h - thumb_h).max(1.0);
|
||||
let next = (self.drag_start_offset + (dy / travel) * max_y).clamp(0.0, max_y);
|
||||
self.offset.y = next;
|
||||
self.target.y = next;
|
||||
self.last_scroll_time = input.time;
|
||||
}
|
||||
} else {
|
||||
self.dragging_v = false;
|
||||
}
|
||||
}
|
||||
|
||||
let alpha = if self.dragging_v {
|
||||
0.55
|
||||
} else if hovered {
|
||||
0.40
|
||||
} else {
|
||||
0.25 * self.scrollbar_alpha
|
||||
};
|
||||
if alpha > 0.01 {
|
||||
let a = (alpha * 255.0).round() as u8;
|
||||
let col = if pal.is_dark {
|
||||
css_rgba(255, 255, 255, a)
|
||||
} else {
|
||||
css_rgba(0, 0, 0, a)
|
||||
};
|
||||
dl.push_rect(thumb_rect, bar_w * 0.5, col);
|
||||
}
|
||||
|
||||
self.dragging_v
|
||||
}
|
||||
|
||||
/// Update measured content width and optionally render horizontal scrollbar.
|
||||
pub fn finish_horizontal(
|
||||
&mut self,
|
||||
dl: &mut DisplayList,
|
||||
pal: &YmPalette,
|
||||
actual_content_width: f32,
|
||||
show_scrollbar: bool,
|
||||
) {
|
||||
self.content_size.x = actual_content_width.max(0.0);
|
||||
let max_x = self.max_offset().x;
|
||||
if self.target.x > max_x {
|
||||
self.target.x = max_x;
|
||||
self.offset.x = self.offset.x.min(max_x);
|
||||
}
|
||||
if max_x <= 1.0 || !show_scrollbar || self.scrollbar_alpha <= 0.02 {
|
||||
return;
|
||||
}
|
||||
|
||||
let vp = self.viewport;
|
||||
let track_pad = 4.0;
|
||||
let track_w = (vp.w - track_pad * 2.0).max(20.0);
|
||||
let visible_ratio = (vp.w / self.content_size.x).clamp(0.05, 1.0);
|
||||
let thumb_w = (track_w * visible_ratio).clamp(36.0, track_w);
|
||||
let scroll_ratio = (self.offset.x / max_x).clamp(0.0, 1.0);
|
||||
let thumb_x = vp.x + track_pad + (track_w - thumb_w) * scroll_ratio;
|
||||
|
||||
let bar_h = 4.0;
|
||||
let thumb_rect = Rect::from_xywh(thumb_x, vp.bottom() - bar_h - 2.0, thumb_w, bar_h);
|
||||
let a = (0.25 * self.scrollbar_alpha * 255.0).round() as u8;
|
||||
let col = if pal.is_dark {
|
||||
css_rgba(255, 255, 255, a)
|
||||
} else {
|
||||
css_rgba(0, 0, 0, a)
|
||||
};
|
||||
dl.push_rect(thumb_rect, bar_h * 0.5, col);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collection of `ScrollState`s indexed by `WidgetId`, owned by `UiContext`.
|
||||
#[derive(Default)]
|
||||
pub struct ScrollStore {
|
||||
states: HashMap<WidgetId, ScrollState>,
|
||||
}
|
||||
|
||||
impl ScrollStore {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
states: HashMap::with_capacity(32),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, id: WidgetId) -> Option<&ScrollState> {
|
||||
self.states.get(&id)
|
||||
}
|
||||
|
||||
pub fn get_or_create(&mut self, id: WidgetId) -> &mut ScrollState {
|
||||
self.states.entry(id).or_default()
|
||||
}
|
||||
|
||||
pub fn scroll_to_x(&mut self, id: WidgetId, x: f32) {
|
||||
self.get_or_create(id).scroll_to_x(x);
|
||||
}
|
||||
|
||||
pub fn scroll_to_y(&mut self, id: WidgetId, y: f32) {
|
||||
self.get_or_create(id).scroll_to_y(y);
|
||||
}
|
||||
|
||||
pub fn scroll_by_x(&mut self, id: WidgetId, dx: f32) {
|
||||
self.get_or_create(id).scroll_by_x(dx);
|
||||
}
|
||||
|
||||
pub fn jump_to_y(&mut self, id: WidgetId, y: f32) {
|
||||
self.get_or_create(id).jump_to_y(y);
|
||||
}
|
||||
|
||||
pub fn reset(&mut self, id: WidgetId) {
|
||||
if let Some(s) = self.states.get_mut(&id) {
|
||||
s.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// O(1) virtualized visible row range helper for large track lists (10,000+ liked tracks).
|
||||
/// - `viewport`: clipped scroll viewport rect
|
||||
/// - `list_top_y`: screen-space Y where row 0 starts (already shifted by `-scroll_y`!)
|
||||
/// - `row_height`: fixed row height (e.g. `TRACK_ROW_HEIGHT = 56.0`)
|
||||
/// - `total_rows`: total number of items
|
||||
/// - `overscan`: extra rows above/below viewport for smooth scrolling (e.g. `2`)
|
||||
pub fn visible_row_range(
|
||||
viewport: Rect,
|
||||
list_top_y: f32,
|
||||
row_height: f32,
|
||||
total_rows: usize,
|
||||
overscan: usize,
|
||||
) -> Range<usize> {
|
||||
if total_rows == 0 || row_height <= 0.0 || viewport.is_empty() {
|
||||
return 0..0;
|
||||
}
|
||||
let rel_top = viewport.top() - list_top_y;
|
||||
let rel_bottom = viewport.bottom() - list_top_y;
|
||||
if rel_bottom <= 0.0 {
|
||||
return 0..0;
|
||||
}
|
||||
let first = if rel_top > 0.0 {
|
||||
(rel_top / row_height).floor() as usize
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let last = (rel_bottom / row_height).ceil() as usize;
|
||||
let start = first.saturating_sub(overscan).min(total_rows);
|
||||
let end = last.saturating_add(overscan).min(total_rows);
|
||||
start..end
|
||||
}
|
||||
1178
src/engine/text.rs
Normal file
1178
src/engine/text.rs
Normal file
File diff suppressed because it is too large
Load diff
166
src/engine/textures.rs
Normal file
166
src/engine/textures.rs
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use crate::engine::types::{
|
||||
TextureFormat, TextureId, TextureUpload, FIRST_USER_TEXTURE_ID,
|
||||
};
|
||||
|
||||
/// Linear sRGB premultiply matching Chromium's CSS compositing on our UNORM Vulkan swapchain.
|
||||
pub fn premultiply_rgba_srgb(raw: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(raw.len());
|
||||
for px in raw.chunks_exact(4) {
|
||||
let a = px[3] as u16;
|
||||
if a == 255 {
|
||||
out.extend_from_slice(px);
|
||||
} else if a == 0 {
|
||||
out.extend_from_slice(&[0, 0, 0, 0]);
|
||||
} else {
|
||||
out.push(((px[0] as u16 * a + 127) / 255) as u8);
|
||||
out.push(((px[1] as u16 * a + 127) / 255) as u8);
|
||||
out.push(((px[2] as u16 * a + 127) / 255) as u8);
|
||||
out.push(px[3]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// CPU-side GPU texture ID registry & deferred upload queue drained each frame by `UiVulkanRenderer`.
|
||||
pub struct TextureRegistry {
|
||||
next_id: u32,
|
||||
pending: Vec<TextureUpload>,
|
||||
sizes: HashMap<TextureId, (u32, u32)>,
|
||||
}
|
||||
|
||||
impl Default for TextureRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TextureRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
next_id: FIRST_USER_TEXTURE_ID,
|
||||
pending: Vec::with_capacity(64),
|
||||
sizes: HashMap::with_capacity(128),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocate_id(&mut self) -> TextureId {
|
||||
let id = TextureId(self.next_id);
|
||||
self.next_id = self.next_id.wrapping_add(1).max(FIRST_USER_TEXTURE_ID);
|
||||
id
|
||||
}
|
||||
|
||||
/// Create a new GPU texture from straight (unpremultiplied) RGBA8 bytes.
|
||||
/// Premultiplies linearly in sRGB space so bilinear filtering has zero dark edge fringes.
|
||||
pub fn create_rgba_unpremul(&mut self, width: u32, height: u32, rgba: &[u8]) -> TextureId {
|
||||
let id = self.allocate_id();
|
||||
let premul = premultiply_rgba_srgb(rgba);
|
||||
self.upload_rgba_premul_with_id(id, width, height, premul);
|
||||
id
|
||||
}
|
||||
|
||||
/// Create a new GPU texture from already-premultiplied RGBA8 bytes (e.g. `resvg` pixmap).
|
||||
pub fn create_rgba_premul(&mut self, width: u32, height: u32, rgba: Vec<u8>) -> TextureId {
|
||||
let id = self.allocate_id();
|
||||
self.upload_rgba_premul_with_id(id, width, height, rgba);
|
||||
id
|
||||
}
|
||||
|
||||
/// Upload or replace a specific `TextureId` with premultiplied RGBA8 pixels.
|
||||
pub fn upload_rgba_premul_with_id(
|
||||
&mut self,
|
||||
id: TextureId,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: Vec<u8>,
|
||||
) {
|
||||
self.sizes.insert(id, (width, height));
|
||||
self.pending.push(TextureUpload::CreateOrReplace {
|
||||
id,
|
||||
width: width.max(1),
|
||||
height: height.max(1),
|
||||
format: TextureFormat::Rgba8Premul,
|
||||
pixels,
|
||||
});
|
||||
}
|
||||
|
||||
/// Upload or replace an R8 single-channel texture (used by `GLYPH_ATLAS_TEXTURE_ID`).
|
||||
pub fn upload_r8_with_id(&mut self, id: TextureId, width: u32, height: u32, pixels: Vec<u8>) {
|
||||
self.sizes.insert(id, (width, height));
|
||||
self.pending.push(TextureUpload::CreateOrReplace {
|
||||
id,
|
||||
width: width.max(1),
|
||||
height: height.max(1),
|
||||
format: TextureFormat::R8,
|
||||
pixels,
|
||||
});
|
||||
}
|
||||
|
||||
/// Partial sub-rectangle upload for an existing R8 texture (fast glyph atlas updates).
|
||||
pub fn update_r8_region(
|
||||
&mut self,
|
||||
id: TextureId,
|
||||
x: u32,
|
||||
y: u32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: Vec<u8>,
|
||||
) {
|
||||
if width == 0 || height == 0 {
|
||||
return;
|
||||
}
|
||||
self.pending.push(TextureUpload::UpdateRegion {
|
||||
id,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
format: TextureFormat::R8,
|
||||
pixels,
|
||||
});
|
||||
}
|
||||
|
||||
/// Partial sub-rectangle upload for an existing premultiplied RGBA8 texture.
|
||||
pub fn update_rgba_region(
|
||||
&mut self,
|
||||
id: TextureId,
|
||||
x: u32,
|
||||
y: u32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: Vec<u8>,
|
||||
) {
|
||||
if width == 0 || height == 0 {
|
||||
return;
|
||||
}
|
||||
self.pending.push(TextureUpload::UpdateRegion {
|
||||
id,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
format: TextureFormat::Rgba8Premul,
|
||||
pixels,
|
||||
});
|
||||
}
|
||||
|
||||
/// Queue GPU destruction for an evicted texture.
|
||||
pub fn free(&mut self, id: TextureId) {
|
||||
self.sizes.remove(&id);
|
||||
self.pending.push(TextureUpload::Free { id });
|
||||
}
|
||||
|
||||
pub fn size_of(&self, id: TextureId) -> Option<(u32, u32)> {
|
||||
self.sizes.get(&id).copied()
|
||||
}
|
||||
|
||||
pub fn has_pending(&self) -> bool {
|
||||
!self.pending.is_empty()
|
||||
}
|
||||
|
||||
/// Drain all queued GPU texture uploads/frees for submission to `UiVulkanRenderer`.
|
||||
pub fn drain_uploads(&mut self) -> Vec<TextureUpload> {
|
||||
std::mem::take(&mut self.pending)
|
||||
}
|
||||
}
|
||||
258
src/engine/theme.rs
Normal file
258
src/engine/theme.rs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
use crate::config::ThemeMode;
|
||||
use crate::engine::types::{css_rgba, Color};
|
||||
|
||||
// Exact Yandex Music Desktop v5.129.0 layout geometry (verified verbatim via decompiled CSS & live 1280x800 CDP DOM)
|
||||
pub const TITLEBAR_HEIGHT: f32 = 32.0; // exact 32px
|
||||
pub const TITLEBAR_BTN_WIDTH: f32 = 46.0; // exact 46x32
|
||||
pub const NAVBAR_FULL_WIDTH: f32 = 224.0; // exact 224px (8+204+12)
|
||||
pub const NAVBAR_COLLAPSED_WIDTH: f32 = 72.0; // exact 72px
|
||||
pub const PLAYER_BAR_HEIGHT: f32 = 80.0; // exact 80px (y=708..788, bottom margin 12px)
|
||||
pub const LAYOUT_GAP: f32 = 12.0; // exact 12px
|
||||
pub const CONTENT_RADIUS: f32 = 16.0; // exact 16px (--ym-radius-size-xl)
|
||||
pub const CARD_RADIUS: f32 = 12.0; // exact 12px (--ym-radius-size-l)
|
||||
pub const TRACK_ROW_HEIGHT: f32 = 56.0; // exact 56px
|
||||
|
||||
/// Complete Yandex Music 5.129.0 color palette extracted verbatim from `.ym-dark-theme`
|
||||
/// and `.ym-light-theme` in `beautified/css/1d39aa9337a03444.css`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct YmPalette {
|
||||
pub is_dark: bool,
|
||||
|
||||
// Backgrounds (Section 1.1.A)
|
||||
pub bg_basic: Color, // --ym-background-color-primary-enabled-basic: #000 / #f5f5f5
|
||||
pub bg_content: Color, // --ym-background-color-primary-enabled-content: #121212 / #fff
|
||||
pub bg_player: Color, // --ym-background-color-primary-enabled-player: #141414 / #999
|
||||
pub bg_popover: Color, // --ym-background-color-primary-enabled-popover: #1a1a1a / #f5f5f5
|
||||
pub bg_menu: Color, // --ym-background-color-primary-enabled-menu: rgba(26,26,26,.7) / hsla(0,0%,96%,.7)
|
||||
pub bg_overlay: Color, // --ym-background-color-primary-enabled-overlay: rgba(0,0,0,.5) / rgba(0,0,0,.8)
|
||||
pub bg_header: Color, // --ym-background-color-primary-enabled-header: rgba(0,0,0,.5) / hsla(0,0%,100%,.24)
|
||||
pub bg_tooltip: Color, // --ym-background-color-primary-enabled-tooltip: #0449c8
|
||||
pub profile_bg: Color, // UserProfile_dialog: #121212 / #fff
|
||||
|
||||
// Borders / Outlines
|
||||
pub border_subtle: Color, // --ym-outline-color-primary-disabled: hsla(0,0%,100%,.04) / rgba(0,0,0,.1)
|
||||
pub border_control: Color, // --ym-controls-color-primary-outline-enabled: #333 / #e6e6e6
|
||||
pub input_border: Color, // --ym-controls-color-secondary-outline-enabled_stroke: #4d4d4d / rgba(0,0,0,.3)
|
||||
pub input_border_hover: Color, // --ym-controls-color-secondary-outline-hovered_stroke: #808080 / #737373
|
||||
|
||||
// Typography
|
||||
pub text_bright: Color, // --ym-logo-color-primary-enabled: #fff / #000
|
||||
pub text_primary: Color, // --ym-controls-color-primary-text-enabled_variant: #e6e6e6 / #1a1a1a
|
||||
pub text_secondary: Color, // --ym-controls-color-primary-text-enabled: hsla(0,0%,100%,.5) / #666
|
||||
pub text_disabled: Color, // --ym-controls-color-primary-text-disabled / secondary disabled
|
||||
pub text_on_outline: Color, // --ym-controls-color-primary-on_outline-enabled: #fff / #1a1a1a
|
||||
|
||||
// Brand Yellow & Logo
|
||||
pub yellow: Color, // --ym-controls-color-primary-default-enabled: #ff0 / #fe0
|
||||
pub yellow_hover: Color, // --ym-controls-color-primary-default-hovered: #dada0b / #f5e400
|
||||
pub yellow_pressed: Color, // --ym-controls-color-primary-default-pressed: #ffff80 / #fff780
|
||||
pub on_yellow: Color, // --ym-controls-color-primary-on_default-enabled: #000 / #000
|
||||
pub logo_text: Color, // --ym-logo-color-primary-text: #ff0 / #000
|
||||
pub logo_variant: Color, // --ym-logo-color-primary-variant: #ff0 / #fe0
|
||||
pub outline_selected: Color, // --ym-controls-color-primary-outline-selected_stroke: #ff0 / #0449c8
|
||||
|
||||
// Surfaces & Chips
|
||||
pub chip_bg: Color, // --ym-controls-color-primary-outline-enabled: #333 / #e6e6e6
|
||||
pub chip_hover: Color, // --ym-controls-color-primary-outline-hovered: #4d4d4d / #ccc
|
||||
pub input_bg: Color, // Search input / pill: #252525 Dark / rgba(0,0,0,.07) Light
|
||||
pub surface_secondary: Color, // --ym-controls-color-secondary-default-enabled: hsla(0,0%,100%,.08) / rgba(0,0,0,.07)
|
||||
pub surface_hover: Color, // --ym-controls-color-secondary-default-hovered: hsla(0,0%,100%,.12) / rgba(0,0,0,.1)
|
||||
pub surface_pressed: Color, // --ym-controls-color-secondary-default-pressed: hsla(0,0%,100%,.24) / rgba(0,0,0,.12)
|
||||
pub surface_list_active: Color, // --ym-surface-color-primary-enabled-list: hsla(0,0%,100%,.08) / rgba(0,0,0,.08)
|
||||
pub surface_entity: Color, // --ym-surface-color-primary-enabled-entity: rgba(0,0,0,.64) / rgba(77,77,77,.5)
|
||||
|
||||
// Sliders
|
||||
pub slider_track: Color, // --ym-slider-color-primary-disabled: hsla(0,0%,100%,.08) / rgba(0,0,0,.08)
|
||||
pub slider_buffered: Color, // --ym-slider-color-primary-progress: hsla(0,0%,100%,.16) / rgba(0,0,0,.16)
|
||||
pub slider_fill: Color, // --ym-slider-color-primary-enabled: #e6e6e6 (both themes on player bar)
|
||||
pub slider_fill_on_content: Color, // #e6e6e6 Dark / #1a1a1a Light (for settings sliders on bg_content)
|
||||
|
||||
// Accents, Status & Shadows
|
||||
pub accent_coral: Color, // --ym-controls-color-accent-default-enabled: #d5594d
|
||||
pub accent_coral_hover: Color, // --ym-controls-color-accent-default-hovered: #da6c62
|
||||
pub success: Color, // --ym-message-color-successful-text-enabled: #37c84f
|
||||
pub error: Color, // --ym-message-color-error-text-enabled: #fb2904
|
||||
pub close_red: Color, // Windows caption close hover: #f23f42
|
||||
pub shadow_menu: Color, // --ym-shadow-menu: rgba(0,0,0,.48) / rgba(0,0,0,.16)
|
||||
pub shadow_modal: Color, // --ym-shadow-modal-xl: rgba(0,0,0,.48)
|
||||
|
||||
// My Vibe text & icon tokens
|
||||
pub vibe_text_top: Color,
|
||||
pub vibe_text_bottom: Color,
|
||||
pub vibe_icon: Color,
|
||||
}
|
||||
|
||||
impl YmPalette {
|
||||
pub fn from_mode(mode: ThemeMode) -> Self {
|
||||
if mode.is_dark_resolved() {
|
||||
Self::dark()
|
||||
} else {
|
||||
Self::light()
|
||||
}
|
||||
}
|
||||
|
||||
/// Verbatim `.ym-dark-theme` tokens from Yandex Music 5.129.0 (`1d39aa9337a03444.css`).
|
||||
pub fn dark() -> Self {
|
||||
Self {
|
||||
is_dark: true,
|
||||
|
||||
bg_basic: Color::rgb(0x00, 0x00, 0x00),
|
||||
bg_content: Color::rgb(0x12, 0x12, 0x12),
|
||||
bg_player: Color::rgb(0x14, 0x14, 0x14),
|
||||
bg_popover: Color::rgb(0x1A, 0x1A, 0x1A),
|
||||
bg_menu: css_rgba(0x1A, 0x1A, 0x1A, 179),
|
||||
bg_overlay: css_rgba(0, 0, 0, 128),
|
||||
bg_header: css_rgba(0, 0, 0, 128),
|
||||
bg_tooltip: Color::rgb(0x04, 0x49, 0xC8),
|
||||
profile_bg: Color::rgb(0x12, 0x12, 0x12),
|
||||
|
||||
border_subtle: css_rgba(255, 255, 255, 10),
|
||||
border_control: Color::rgb(0x33, 0x33, 0x33),
|
||||
input_border: Color::rgb(0x4D, 0x4D, 0x4D),
|
||||
input_border_hover: Color::rgb(0x80, 0x80, 0x80),
|
||||
|
||||
text_bright: Color::rgb(0xFF, 0xFF, 0xFF),
|
||||
text_primary: Color::rgb(0xE6, 0xE6, 0xE6),
|
||||
text_secondary: css_rgba(255, 255, 255, 128),
|
||||
text_disabled: Color::rgb(0x4D, 0x4D, 0x4D),
|
||||
text_on_outline: Color::rgb(0xFF, 0xFF, 0xFF),
|
||||
|
||||
yellow: Color::rgb(0xFF, 0xFF, 0x00),
|
||||
yellow_hover: Color::rgb(0xDA, 0xDA, 0x0B),
|
||||
yellow_pressed: Color::rgb(0xFF, 0xFF, 0x80),
|
||||
on_yellow: Color::rgb(0x00, 0x00, 0x00),
|
||||
logo_text: Color::rgb(0xFF, 0xFF, 0x00),
|
||||
logo_variant: Color::rgb(0xFF, 0xFF, 0x00),
|
||||
outline_selected: Color::rgb(0xFF, 0xFF, 0x00),
|
||||
|
||||
chip_bg: Color::rgb(0x33, 0x33, 0x33),
|
||||
chip_hover: Color::rgb(0x4D, 0x4D, 0x4D),
|
||||
input_bg: Color::rgb(0x25, 0x25, 0x25),
|
||||
surface_secondary: css_rgba(255, 255, 255, 20),
|
||||
surface_hover: css_rgba(255, 255, 255, 31),
|
||||
surface_pressed: css_rgba(255, 255, 255, 61),
|
||||
surface_list_active: css_rgba(255, 255, 255, 20),
|
||||
surface_entity: css_rgba(0, 0, 0, 163),
|
||||
|
||||
slider_track: css_rgba(255, 255, 255, 20),
|
||||
slider_buffered: css_rgba(255, 255, 255, 41),
|
||||
slider_fill: Color::rgb(0xE6, 0xE6, 0xE6),
|
||||
slider_fill_on_content: Color::rgb(0xE6, 0xE6, 0xE6),
|
||||
|
||||
accent_coral: Color::rgb(0xD5, 0x59, 0x4D),
|
||||
accent_coral_hover: Color::rgb(0xDA, 0x6C, 0x62),
|
||||
success: Color::rgb(0x37, 0xC8, 0x4F),
|
||||
error: Color::rgb(0xFB, 0x29, 0x04),
|
||||
close_red: Color::rgb(0xF2, 0x3F, 0x42),
|
||||
shadow_menu: css_rgba(0, 0, 0, 122),
|
||||
shadow_modal: css_rgba(0, 0, 0, 122),
|
||||
|
||||
vibe_text_top: css_rgba(255, 255, 255, 235),
|
||||
vibe_text_bottom: css_rgba(255, 255, 255, 184),
|
||||
vibe_icon: css_rgba(255, 255, 255, 184),
|
||||
}
|
||||
}
|
||||
|
||||
/// Verbatim `.ym-light-theme` tokens from Yandex Music 5.129.0 (`1d39aa9337a03444.css`).
|
||||
pub fn light() -> Self {
|
||||
Self {
|
||||
is_dark: false,
|
||||
|
||||
bg_basic: Color::rgb(0xF5, 0xF5, 0xF5),
|
||||
bg_content: Color::rgb(0xFF, 0xFF, 0xFF),
|
||||
bg_player: Color::rgb(0x99, 0x99, 0x99),
|
||||
bg_popover: Color::rgb(0xF5, 0xF5, 0xF5),
|
||||
bg_menu: css_rgba(0xF5, 0xF5, 0xF5, 179),
|
||||
bg_overlay: css_rgba(0, 0, 0, 204),
|
||||
bg_header: css_rgba(255, 255, 255, 61),
|
||||
bg_tooltip: Color::rgb(0x04, 0x49, 0xC8),
|
||||
profile_bg: Color::rgb(0xFF, 0xFF, 0xFF),
|
||||
|
||||
border_subtle: css_rgba(0, 0, 0, 26),
|
||||
border_control: Color::rgb(0xE6, 0xE6, 0xE6),
|
||||
input_border: css_rgba(0, 0, 0, 77),
|
||||
input_border_hover: Color::rgb(0x73, 0x73, 0x73),
|
||||
|
||||
text_bright: Color::rgb(0x00, 0x00, 0x00),
|
||||
text_primary: Color::rgb(0x1A, 0x1A, 0x1A),
|
||||
text_secondary: Color::rgb(0x66, 0x66, 0x66),
|
||||
text_disabled: Color::rgb(0xB3, 0xB3, 0xB3),
|
||||
text_on_outline: Color::rgb(0x1A, 0x1A, 0x1A),
|
||||
|
||||
yellow: Color::rgb(0xFF, 0xEE, 0x00),
|
||||
yellow_hover: Color::rgb(0xF5, 0xE4, 0x00),
|
||||
yellow_pressed: Color::rgb(0xFF, 0xF7, 0x80),
|
||||
on_yellow: Color::rgb(0x00, 0x00, 0x00),
|
||||
logo_text: Color::rgb(0x00, 0x00, 0x00),
|
||||
logo_variant: Color::rgb(0xFF, 0xEE, 0x00),
|
||||
outline_selected: Color::rgb(0x04, 0x49, 0xC8),
|
||||
|
||||
chip_bg: Color::rgb(0xE6, 0xE6, 0xE6),
|
||||
chip_hover: Color::rgb(0xCC, 0xCC, 0xCC),
|
||||
input_bg: css_rgba(0, 0, 0, 18),
|
||||
surface_secondary: css_rgba(0, 0, 0, 18),
|
||||
surface_hover: css_rgba(0, 0, 0, 26),
|
||||
surface_pressed: css_rgba(0, 0, 0, 31),
|
||||
surface_list_active: css_rgba(0, 0, 0, 20),
|
||||
surface_entity: css_rgba(77, 77, 77, 128),
|
||||
|
||||
slider_track: css_rgba(0, 0, 0, 20),
|
||||
slider_buffered: css_rgba(0, 0, 0, 41),
|
||||
slider_fill: Color::rgb(0xE6, 0xE6, 0xE6),
|
||||
slider_fill_on_content: Color::rgb(0x1A, 0x1A, 0x1A),
|
||||
|
||||
accent_coral: Color::rgb(0xD5, 0x59, 0x4D),
|
||||
accent_coral_hover: Color::rgb(0xDA, 0x6C, 0x62),
|
||||
success: Color::rgb(0x37, 0xC8, 0x4F),
|
||||
error: Color::rgb(0xFB, 0x29, 0x04),
|
||||
close_red: Color::rgb(0xF2, 0x3F, 0x42),
|
||||
shadow_menu: css_rgba(0, 0, 0, 41),
|
||||
shadow_modal: css_rgba(0, 0, 0, 122),
|
||||
|
||||
vibe_text_top: css_rgba(0, 0, 0, 235),
|
||||
vibe_text_bottom: css_rgba(35, 35, 35, 230),
|
||||
vibe_icon: css_rgba(0, 0, 0, 230),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_color_f32(&self) -> [f32; 4] {
|
||||
[
|
||||
self.bg_basic.r as f32 / 255.0,
|
||||
self.bg_basic.g as f32 / 255.0,
|
||||
self.bg_basic.b as f32 / 255.0,
|
||||
1.0,
|
||||
]
|
||||
}
|
||||
|
||||
/// Official 5.129.0 PlayerBar background (`4872` mod `92644`):
|
||||
/// converts track `averageColor` to `hsl(h, s%, 20%)` in BOTH dark & light themes;
|
||||
/// falls back to `bg_player` (`#141414` dark / `#999999` light) when idle.
|
||||
pub fn player_bar_bg(&self, track_color: Option<Color>) -> Color {
|
||||
match track_color {
|
||||
Some(c) => {
|
||||
let (h, s, _l) = c.to_hsl();
|
||||
Color::from_hsl(h, s, 0.20)
|
||||
}
|
||||
None => self.bg_player,
|
||||
}
|
||||
}
|
||||
|
||||
/// Official 5.129.0 Playlist/Album header gradient adjustment (`6305` mod `53158`):
|
||||
/// Dark theme: `floor(0.8 * channel)` (20% darker);
|
||||
/// Light theme: `min(255, floor(channel + (255 - channel) * 0.3))` (30% lighter toward white).
|
||||
pub fn header_gradient_color(&self, avg_color: Color) -> Color {
|
||||
if self.is_dark {
|
||||
Color::rgb(
|
||||
(avg_color.r as f32 * 0.8).floor() as u8,
|
||||
(avg_color.g as f32 * 0.8).floor() as u8,
|
||||
(avg_color.b as f32 * 0.8).floor() as u8,
|
||||
)
|
||||
} else {
|
||||
Color::rgb(
|
||||
((avg_color.r as f32 + (255.0 - avg_color.r as f32) * 0.3).floor() as u16).min(255) as u8,
|
||||
((avg_color.g as f32 + (255.0 - avg_color.g as f32) * 0.3).floor() as u16).min(255) as u8,
|
||||
((avg_color.b as f32 + (255.0 - avg_color.b as f32) * 0.3).floor() as u16).min(255) as u8,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
1148
src/engine/types.rs
Normal file
1148
src/engine/types.rs
Normal file
File diff suppressed because it is too large
Load diff
1772
src/engine/widgets.rs
Normal file
1772
src/engine/widgets.rs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue