diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index b48549113..7de084c6d 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -455,7 +455,7 @@ impl Component for FontPicker<'_> { /// The width of the longest family names in common use, so the field keeps its size whichever family is picked. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { let current = cx.value().map_or("", String::as_str); - let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.layout(&TextRun::new(text)).size()).fold(Vec2::ZERO, Vec2::max); + let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max); let name = cx.words::().list.clone(); Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name)), widest.y) } diff --git a/crates/timeline/src/ui/mod.rs b/crates/timeline/src/ui/mod.rs index dcd73e45f..1162ed909 100644 --- a/crates/timeline/src/ui/mod.rs +++ b/crates/timeline/src/ui/mod.rs @@ -52,7 +52,7 @@ pub use render_queue::{ RenderItemId, RenderQueueEvent, RenderQueueItem, RenderQueueList, RenderQueueListOutput, RenderQueueWords, RenderStatus, format_eta, }; pub use ruler::{RenderBarState, RenderSpan, SplitMarks, TimeTick, TimelineRuler, TimelineRulerResponse, ruler_ladder, ruler_ticks}; -pub use stack::{TrackRow, TrackStack}; +pub use stack::{HeaderColumns, TrackRow, TrackStack}; pub use timecode::{ TimecodeCodec, TimecodeField, TimecodeFieldOutput, TimecodePanel, TimecodePanelOutput, TimecodePanelSettings, TimecodeRow, TimecodeRowKind, TimecodeSource, TimecodeText, TimecodeWords, diff --git a/crates/timeline/src/ui/panel.rs b/crates/timeline/src/ui/panel.rs index d3b8fe5ff..c9b1f656b 100644 --- a/crates/timeline/src/ui/panel.rs +++ b/crates/timeline/src/ui/panel.rs @@ -6,7 +6,7 @@ use super::clips::{ClipContent, ClipLane, TimelineTool}; use super::markers::{MarkerEdit, MarkerSpan, MarkerStrip}; use super::ruler::TimelineRuler; use super::stack::{ - LANE, LOCK, MUTE, MovePointer, MoveTarget, NAME, NAME_DEFAULT, OUTPUT, RowGeom, SOLO, SYNC_LOCK, Side, TARGET, TrackEvent, TrackRow, TrackStack, + HeaderColumns, LANE, LOCK, MUTE, MovePointer, MoveTarget, NAME, OUTPUT, RowGeom, SOLO, SYNC_LOCK, Side, TARGET, TrackEvent, TrackRow, TrackStack, Tracks, resolve_move, set_event, }; use super::view::{Overlay, TimelineView, TimelineWords, time_axis}; @@ -16,13 +16,14 @@ use crate::clock::FollowMode; use crate::markers::MarkerColor; use crate::model::{ClipId, ClipInfo, TimelineModel, TrackId, TrackInfo, TrackKind}; use crate::time::{Tick, TimeRange}; +use crate::timecode::TimeFormat; use craft_behavior::{ - Axis, ColumnKey, ColumnWidth, CursorIcon, CursorPriority, EditEvent, EditEvents, GestureId, IconId, MarqueeSelect, Metrics, Mixed, + Axis, ColumnKey, ColumnWidth, CursorIcon, CursorPriority, EditEvent, EditEvents, GestureId, IconId, MarqueeSelect, Metrics, Mixed, Proposal, SelectionChange, }; use craft_ui::buttons::{IconButton, ToggleButton}; use craft_ui::contract::{ - Bind, BodyCx, BodyLayout, CollectionEvent, CollectionResponse, ColumnEvent, Common, Component, Container, ContainerProps, Cx, EditResponse, + Bind, BodyCx, BodyLayout, CollectionEvent, CollectionResponse, ColumnEvent, Common, Component, Container, ContainerProps, Cx, EditResponse, Gap, NoValue, Outcome, Pattern, Props, Remember as _, Role, Show as _, ShowCollection as _, ShowContainer as _, ShownRow, SizeLimits, Sizing, SweepApply, SweepStep, }; @@ -177,8 +178,10 @@ pub struct TimelineToolbar { /// Layout, top to bottom: the large [`TimecodeField`] and the toolbar over the headers beside the [`MarkerStrip`] and the /// [`TimelineRuler`]; then the caption tracks, the video tracks (V1 nearest the divider), the divider, the audio tracks /// and the Mix row when the model has a master volume; the bar of the [`TimelineView`] at the bottom. The headers are the -/// header columns of each [`TrackStack`], `header_width` wide at the name column and resizable -/// ([`TimelineEdit::HeaderWidth`]); the lanes paint their clips' content through [`content`](Self::content). +/// [`HeaderColumns`] of every [`TrackStack`]: the colour strip, the name column and the switches some track has. The name +/// column is as wide as the widest track name until the user drags it ([`TimelineEdit::HeaderWidth`], kept as +/// `header_width`), and the headers are never narrower than the timecode and the toolbar over them. The lanes paint +/// their clips' content through [`content`](Self::content). /// /// Input: the wheel, the pinch and the keys of [`TimelineView`]; the colour strip of a header opens the label menu; the /// Menu key and Shift+F10 report [`TimelineEdit::ContextMenu`] for the selection's last clip, else the first targeted @@ -282,7 +285,7 @@ struct PlacedRow { /// What the panes share in a pass. struct Panes<'p, 'a> { words: &'p TimelineWords, - name: Option, + header: &'p HeaderColumns, selection: &'p [ClipId], targets: Option<&'p SnapTargets>, tool: TimelineTool, @@ -299,7 +302,7 @@ impl Panes<'_, '_> { Side::Upper => "Video", Side::Lower => "Audio", }; - let mut stack = TrackStack::new(label, self.name, self.words).tracks(pane); + let mut stack = TrackStack::new(label, self.header, self.words).tracks(pane); match side { Side::Upper => stack = stack.anchored_at_end(), // The caption tracks take the height their rows need, so the video and audio panes keep the rest. @@ -330,7 +333,7 @@ impl Panes<'_, '_> { struct Mapping<'p> { pane: &'p [TrackInfo<'p>], words: &'p TimelineWords, - name: Option, + header: &'p HeaderColumns, palette: &'p LabelPalette, } @@ -396,7 +399,7 @@ impl Mapping<'_> { } CollectionEvent::Column(ColumnEvent::Resized { key, width, .. }) if *key == NAME => { edits.push(TimelineEdit::HeaderWidth(set_event( - self.name.unwrap_or(NAME_DEFAULT), + ColumnWidth::Fixed(self.header.name), ColumnWidth::Fixed(*width), self.words.header_width.as_str(), ))); @@ -524,9 +527,13 @@ impl Timeline<'_, M> { (Side::Upper, of_kind(|kind| kind == TrackKind::Video)), (Side::Lower, of_kind(|kind| !matches!(kind, TrackKind::Caption | TrackKind::Video))), ]; + // The head block over the headers sets their least width; the headers are worked out before the view shows, + // since its inset and every pane's columns take them. + let least = Stack::new().measure_in(ui, Proposal::Ideal, |ui, _| head_block(ui, &words, playhead, format, snap, linked_selection)).x; + let header = HeaderColumns::measure(ui, &tracks, header_width, least); let shared = Panes { words: &words, - name: header_width, + header: &header, selection: &selection, targets: targets.as_ref(), tool, @@ -541,22 +548,17 @@ impl Timeline<'_, M> { let overlay = Overlay::default(); let area = TimelineView::new(label, Bind::given(view), format, duration) - .headers(true) + .header_extent(header.extent()) .follow(follow, playing, playhead) .edit_points(&points) .overlay(&overlay); - let area = match header_width { - Some(width) => area.header_width(width), - None => area, - }; let body = |ui: &mut Ui, cx: &mut BodyCx<'_>| { - TopStrip::new().show(ui, |ui, _| { + TopStrip::new(header.extent()).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { - let field = TimecodeField::new(words.panel.clone(), Bind::given(playhead), format).large().show(ui); - timecode_edit = field.edit.events; - toolbar = toolbar_row(ui, &words, snap, linked_selection); + (timecode_edit, toolbar) = head_block(ui, &words, playhead, format, snap, linked_selection); }); - Stack::new().show(ui, |ui, _| { + // The marker strip and the ruler fill the cell over the time area. + Stack::new().fill_width().show(ui, |ui, _| { let strip = MarkerStrip::new(words.overview.clone(), markers); let strip = match shared.targets { Some(targets) => strip.snap(targets), @@ -585,7 +587,7 @@ impl Timeline<'_, M> { let pane: Vec> = indices.iter().map(|&i| tracks[i].clone()).collect(); let out = shared.show(ui, side, &pane, indices); pane_rects.push(out.response.rect); - let mapping = Mapping { pane: &pane, words: &words, name: header_width, palette: &palette }; + let mapping = Mapping { pane: &pane, words: &words, header: &header, palette: &palette }; mapping.collect(&out, &mut edits, &mut memory, &mut reports); mapping.label_menu(ui, &out.response, &mut memory, &mut edits); }; @@ -787,6 +789,20 @@ fn retarget(event: &mut EditEvent, target: MoveTarget) { } /// The toolbar under the timecode: Snap, Linked Selection, Add Marker and the display settings. +/// The block over the headers, a stack's body: the large timecode, then the toolbar. The panel measures it for the +/// headers' least width and shows it in the top strip's head cell. +fn head_block( + ui: &mut Ui, + words: &TimelineWords, + playhead: Tick, + format: TimeFormat, + snap: bool, + linked_selection: bool, +) -> (EditEvents, Option) { + let field = TimecodeField::new(words.panel.clone(), Bind::given(playhead), format).large().show(ui); + (field.edit.events, toolbar_row(ui, words, snap, linked_selection)) +} + fn toolbar_row(ui: &mut Ui, words: &TimelineWords, snap: bool, linked_selection: bool) -> Option { let shown = Row::new().show(ui, |ui, _| { let snap = ToggleButton::new(words.snap.clone(), Bind::given(snap)).icon(IconSpec::svg(IconId::new("snap"))).icon_only().show(ui); @@ -809,7 +825,8 @@ fn mix_row(ui: &mut Ui, words: &TimelineWords, value: &str) { }); } -/// The top strip: the head block over the headers, then the marker strip and the ruler over the time area. +/// The top strip: the head block over the headers, then the marker strip and the ruler over the time area. Its head +/// column is the headers' extent and its columns touch, so the ruler starts where the lanes do. #[derive(Component)] #[component(container)] struct TopStrip { @@ -820,9 +837,13 @@ struct TopStrip { } impl TopStrip { - fn new() -> Self { - const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::fill(1.0)]; - TopStrip { common: Common::new(), props: ContainerProps::new().sizing(Sizing::FillWidth).layout(BodyLayout::grid(COLUMNS)) } + /// A strip whose head column is `headers` wide. + fn new(headers: f32) -> Self { + let columns = vec![ColumnWidth::Fixed(headers), ColumnWidth::fill(1.0)]; + TopStrip { + common: Common::new(), + props: ContainerProps::new().sizing(Sizing::FillWidth).layout(BodyLayout::grid(columns)).body_gap(Gap::None), + } } } diff --git a/crates/timeline/src/ui/panel/stories.rs b/crates/timeline/src/ui/panel/stories.rs index 31fff851e..c04ed7955 100644 --- a/crates/timeline/src/ui/panel/stories.rs +++ b/crates/timeline/src/ui/panel/stories.rs @@ -8,7 +8,7 @@ use crate::model::{ClipId, ClipInfo, TimelineModel, TrackId, TrackInfo, TrackKin use crate::rates::FrameRate; use crate::time::{Tick, TimeRange, TimeView}; use crate::timecode::TimeFormat; -use craft_behavior::{ColumnWidth, Selection, SelectionModel as _}; +use craft_behavior::{ColumnWidth, Proposal, Selection, SelectionModel as _}; use craft_ui::contract::{Show as _, ShowContainer as _}; use craft_ui::display::Text; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; @@ -233,7 +233,9 @@ fn timeline_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// The strip over the headers and the time area: the head block in the first column, the ruler row in the second. #[story(TopStrip, covers = [Default], drive = Drive::Never)] fn top_strip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - let out = TopStrip::new().show(ui, |ui, _| { + // The head column is as wide as its text, as the panel's is as wide as the headers. + let head = Text::new("Head").measure_in(ui, Proposal::Ideal).x; + let out = TopStrip::new(head).show(ui, |ui, _| { Text::new("Head").show(ui); Text::new("Ruler").show(ui); }); diff --git a/crates/timeline/src/ui/stack.rs b/crates/timeline/src/ui/stack.rs index c99dcf6ba..7e9c7cf2b 100644 --- a/crates/timeline/src/ui/stack.rs +++ b/crates/timeline/src/ui/stack.rs @@ -1,10 +1,11 @@ //! `TrackStack` and `TrackRow`: the tracks of one pane of a timeline on the collection contract (20.6). //! -//! A stack is one collection keyed by [`TrackId`]. Its columns are the colour strip, the track name (the header width the -//! app keeps, frozen and resizable), one sweepable toggle column per switch of the [`TrackInfo`] and the lane. A row paints -//! its header in the cells and registers the lane's clips as parts of the lane cell through [`ClipLane`], so a track of -//! any number of clips costs one pipeline run. Switches reach the app as the collection's `Toggle` events, the width of -//! the header as its `Column` events; everything else a row reports is its [`TrackEvent`]. +//! A stack is one collection keyed by [`TrackId`]. Its columns are the colour strip, the track name (frozen and +//! resizable), one sweepable toggle column per switch some track of the timeline has and the lane, as one +//! [`HeaderColumns`] gives them to every pane. A row paints its header in the cells and registers the lane's clips as +//! parts of the lane cell through [`ClipLane`], so a track of any number of clips costs one pipeline run. Switches +//! reach the app as the collection's `Toggle` events, the width of the header as its `Column` events; everything else a +//! row reports is its [`TrackEvent`]. use super::clips::{ClipLane, ClipLaneEvents, ClipLook}; use super::view::{TimelineWords, time_axis}; @@ -14,19 +15,20 @@ use crate::model::{ClipId, TrackId, TrackInfo, TrackKind}; use crate::time::Tick; use craft_behavior::{ ColumnKey, ColumnWidth, CursorIcon, DisplayOrder, EditEvent, EditEvents, HitLevel, HitPriority, IconId, ItemSource, MarqueeSelect, Metrics, - Mixed, PartKey, PressPhase, Selection, SelectionChange, Sense, SizeHint, SpanLayout, + Mixed, PartKey, PressPhase, Proposal, Selection, SelectionChange, Sense, SizeHint, SpanLayout, }; use craft_theme::Opacity; use craft_ui::contract::{ Access, Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnKind, ColumnSpec, Common, Component, ContainerProps, Cx, Edit as _, ItemKeys, ItemOutput, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _, Props, Remember as _, Role, Scroll, ScrollAnchor, SelectMode, - Sizing, Styled as _, ToggleColumn, WordSetCx as _, + Show as _, Sizing, Styled as _, ToggleColumn, WordSetCx as _, }; +use craft_ui::display::Text; use craft_ui::primitives::{IconSpec, PaintShape, RectSide, RuleKind}; use craft_ui::runtime::commands::FireSource; -use craft_ui::runtime::env::Label; +use craft_ui::runtime::env::{Env, Label}; use craft_ui::style::{ComponentStyle, DataColor, IconLook, Stateful, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole, UiTokens}; -use egui::{CornerRadius, Pos2, Rect, Response, Vec2}; +use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2}; use std::sync::Arc; /// The colour strip: a click on it opens the label menu. @@ -83,12 +85,10 @@ pub struct TrackSizes { /// A track grows to at most this many heights of a large thumbnail. const MOST_IN_THUMBS: f32 = 4.0; -/// The name column's width until the user drags it. -pub(crate) const NAME_DEFAULT: ColumnWidth = ColumnWidth::Controls(6.0); -/// A switch column is one control wide. -const SWITCH_WIDTH: ColumnWidth = ColumnWidth::Controls(1.0); -/// The colour strip is a quarter of a control wide. -const STRIP_WIDTH: ColumnWidth = ColumnWidth::Controls(0.25); +/// The colour strip is this share of a switch column wide. +const STRIP_SHARE: f32 = 0.25; +/// The role the track name paints in, and is measured in for the name column. +const NAME_ROLE: TypeRole = TypeRole::Label; impl TrackSizes { /// The sizes the tokens give. @@ -120,18 +120,85 @@ impl TrackSizes { let (short, tall) = (self.caption, self.video); if now < (short + tall) / 2.0 { tall } else { short } } +} - /// The width of the headers (colour strip, name and the switches) for a name column `name` wide: where the lane - /// begins. The view reads it before its body has laid the stacks out, so it sums the same column widths the stacks - /// declare. - pub fn header_extent(&self, name: Option) -> f32 { - let fixed = |width: ColumnWidth| match width.in_unit(self.unit) { +/// The track headers of a timeline in one pass: the switch columns some track has and the name column's width. Every +/// pane's [`TrackStack`] declares these columns, and the panel's head cell and the view's inset take +/// [`extent`](Self::extent), so the lanes, the ruler and the time area start at one x however the panes split the +/// tracks. The view reads the extent before its body runs, so it is worked out from the model before the view shows. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct HeaderColumns { + /// The switch columns some track of the timeline has, in header order. A track without one leaves its cell empty. + pub switches: Vec, + /// The name column's width, in points. + pub name: f32, + /// A switch column's width: one control height. + pub switch: f32, +} + +impl HeaderColumns { + /// The headers of `tracks` under `ui`. The name column is `dragged` wide once the user dragged it, else as wide as + /// the widest track name with its pads and indent. It widens until the headers are `least` wide: the block over + /// them (the timecode and the toolbar) sets their least width, as Premiere's does. + pub fn measure(ui: &Ui, tracks: &[TrackInfo<'_>], dragged: Option, least: f32) -> HeaderColumns { + let env = Env::of(ui); + let (switch, pad) = (env.tokens.size.control.md, name_pad(&env.tokens)); + let switches = + SWITCHES.iter().map(|(key, _, _)| key.clone()).filter(|key| tracks.iter().any(|track| switch_of(track, key).is_some())).collect(); + let dragged = dragged.and_then(|width| match width.in_unit(switch) { ColumnWidth::Fixed(width) => Some(width), _ => None, - }; - let name = name.and_then(fixed).or_else(|| fixed(NAME_DEFAULT)).unwrap_or(0.0); - let switches = SWITCHES.len() as f32 * fixed(SWITCH_WIDTH).unwrap_or(0.0); - fixed(STRIP_WIDTH).unwrap_or(0.0) + name + switches + }); + let name = dragged.unwrap_or_else(|| { + tracks + .iter() + .map(|track| { + let text = Text::new(track.name.to_owned()).role(NAME_ROLE).measure_in(ui, Proposal::Ideal).x; + text + 2.0 * name_inset(pad, track) + }) + .fold(0.0, f32::max) + }); + let mut header = HeaderColumns { switches, name, switch }; + header.name += (least - header.extent()).max(0.0); + header + } + + /// The colour strip's width. + pub fn strip(&self) -> f32 { + self.switch * STRIP_SHARE + } + + /// The width of the headers: the colour strip, the name and the switches. The lanes begin here. + pub fn extent(&self) -> f32 { + self.strip() + self.name + self.switches.len() as f32 * self.switch + } +} + +/// The pad between the colour strip and the name, and the indent of one level of depth. +fn name_pad(tokens: &UiTokens) -> f32 { + tokens.space.pad.regular +} + +/// The inset of `track`'s name from each side of the name cell: one pad and its depth's indent. +fn name_inset(pad: f32, track: &TrackInfo<'_>) -> f32 { + pad * (1.0 + f32::from(track.depth)) +} + +/// Whether `track`'s switch in `column` is on; `None` when the track has no such switch. +fn switch_of(track: &TrackInfo<'_>, column: &ColumnKey) -> Option { + if *column == LOCK { + track.locked + } else if *column == TARGET { + track.targeted + } else if *column == SYNC_LOCK { + track.sync_lock + } else if *column == OUTPUT { + track.enabled + } else if *column == MUTE { + track.muted + } else { + track.solo } } @@ -165,39 +232,11 @@ impl DisplayOrder for Tracks<'_> { impl ItemSource for Tracks<'_> { fn toggled(&self, at: usize, column: &ColumnKey) -> bool { - let track = &self.tracks[at]; - let on = if *column == LOCK { - track.locked - } else if *column == TARGET { - track.targeted - } else if *column == SYNC_LOCK { - track.sync_lock - } else if *column == OUTPUT { - track.enabled - } else if *column == MUTE { - track.muted - } else { - track.solo - }; - on.unwrap_or(false) + switch_of(&self.tracks[at], column).unwrap_or(false) } fn toggle_enabled(&self, at: usize, column: &ColumnKey) -> bool { - let track = &self.tracks[at]; - let switch = if *column == LOCK { - track.locked - } else if *column == TARGET { - track.targeted - } else if *column == SYNC_LOCK { - track.sync_lock - } else if *column == OUTPUT { - track.enabled - } else if *column == MUTE { - track.muted - } else { - track.solo - }; - switch.is_some() + switch_of(&self.tracks[at], column).is_some() } } @@ -270,8 +309,8 @@ pub struct TrackStack { } impl TrackStack { - /// A stack named `label` whose name column is `name` wide (the default until the user drags it). - pub fn new(label: impl Into