mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
Merge remote-tracking branch 'upstream/next' into frame-t3-fix
# Conflicts: # crates/color-ui/src/ui/panel.rs
This commit is contained in:
@@ -60,7 +60,9 @@ impl ActionsSettings {
|
||||
|
||||
/// The Actions panel's persisted section: Button Mode and the collapsed sets.
|
||||
/// Selection and expansion are not persisted.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ActionsSettings {
|
||||
@@ -72,7 +74,7 @@ pub struct ActionsSettings {
|
||||
|
||||
/// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at
|
||||
/// a time) and the list's key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub enum ActionSelection {
|
||||
/// The set header of this name.
|
||||
@@ -89,7 +91,7 @@ pub enum ActionSelection {
|
||||
/// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder)
|
||||
/// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the
|
||||
/// app clears `selected` (the panel cannot tell which rows the delete removed).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct ActionsPanelState {
|
||||
/// The persisted section.
|
||||
|
||||
@@ -62,7 +62,19 @@ craft_ui::words! {
|
||||
|
||||
/// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default;
|
||||
/// the theme never changes it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
Default,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
serde::Serialize,
|
||||
serde::Deserialize,
|
||||
craft_ui::contract::MemoProps,
|
||||
craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelMode {
|
||||
@@ -129,7 +141,19 @@ impl ColorPanelMode {
|
||||
}
|
||||
|
||||
/// The ramp under the sliders. Shift-click on the ramp cycles them in this order.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
Default,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
serde::Serialize,
|
||||
serde::Deserialize,
|
||||
craft_ui::contract::MemoProps,
|
||||
craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelRamp {
|
||||
@@ -179,7 +203,9 @@ impl ColorPanelRamp {
|
||||
}
|
||||
|
||||
/// The Color panel's settings, kept across runs (settings section `color_panel`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPanelState {
|
||||
|
||||
@@ -398,7 +398,7 @@ struct Scene {
|
||||
/// the selected anchors or the picked handle (⌥ alone); Delete and Backspace report
|
||||
/// [`delete`](BezierOutput::delete) under the tools that delete anchors (Direct, Convert, Curvature, Add Anchor,
|
||||
/// Delete Anchor), Insert [`insert`](BezierOutput::insert) halfway along the segment leaving the picked anchor;
|
||||
/// Escape deselects.
|
||||
/// Escape leaves the selection and goes to the window.
|
||||
/// - The anchor tools ([`BezierTool::AddAnchor`], [`BezierTool::DeleteAnchor`], [`BezierTool::AutoAddDelete`]) and
|
||||
/// [`BezierTool::Curvature`] take only a press that hits what they edit, and draw the [`HitMark`] of what a press
|
||||
/// would take under the pointer. [`segment_mark`](Self::segment_mark), [`anchors`](Self::anchors) and
|
||||
@@ -1121,9 +1121,6 @@ impl<'a> BezierOverlay<'a> {
|
||||
self.report.delete = Some(AnchorDelete::new(path, self.selection.anchors.clone(), true));
|
||||
}
|
||||
}
|
||||
if keyed && cx.gesture().is_none() && cx.intents().take(Intent::Cancel) && *self.selection != PathSelection::default() {
|
||||
self.report.select = Some(PathSelection::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// The path ⌘A selects: the selection's, else the picked part's, else the only one.
|
||||
|
||||
@@ -57,7 +57,7 @@ impl BezierTool {
|
||||
matches!(self, BezierTool::AddAnchor | BezierTool::DeleteAnchor | BezierTool::AutoAddDelete)
|
||||
}
|
||||
|
||||
/// Whether the tool has the arrow, ⌘A and Esc keys: Direct, Convert and Curvature. Add and Delete have Delete
|
||||
/// Whether the tool has the arrow and ⌘A keys: Direct, Convert and Curvature. Add and Delete have Delete
|
||||
/// only, Auto Add/Delete none.
|
||||
pub(super) fn keyed(self) -> bool {
|
||||
matches!(self, BezierTool::Direct | BezierTool::Convert | BezierTool::Curvature)
|
||||
|
||||
@@ -421,7 +421,7 @@ fn hit_test_matches_the_overlays_press_priority() {
|
||||
|
||||
// ---- the anchor tools and the Curvature tool ----
|
||||
|
||||
// Arrows, select all and Escape belong to Direct, Convert and Curvature; Add, Delete and Auto Add/Delete have none.
|
||||
// Arrows and select all belong to Direct, Convert and Curvature; Add, Delete and Auto Add/Delete have none.
|
||||
|
||||
#[trial]
|
||||
fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_no_part() {
|
||||
@@ -1202,6 +1202,23 @@ fn arrow_keys_nudge_the_selected_anchors_and_shift_nudges_farther() {
|
||||
assert_eq!(h.state.borrow().changes.len(), 2, "one edit per press");
|
||||
}
|
||||
|
||||
// Escape on a focused anchor leaves the anchor selection and the targeted path under Direct, Convert and Curvature; it
|
||||
// goes on to the window. A key still reaches the overlay afterwards.
|
||||
#[trial]
|
||||
fn escape_on_a_focused_anchor_keeps_the_selection() {
|
||||
for tool in [BezierTool::Direct, BezierTool::Convert, BezierTool::Curvature] {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)])));
|
||||
h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle();
|
||||
let before = h.state.borrow().selection.clone();
|
||||
assert!(before != PathSelection::default(), "{tool:?}: an anchor is selected");
|
||||
h.fixture.key(egui::Key::Escape, egui::Modifiers::NONE).settle();
|
||||
assert_eq!(h.state.borrow().selection, before, "{tool:?}: Escape keeps the selection");
|
||||
h.fixture.key(egui::Key::ArrowRight, egui::Modifiers::NONE).settle();
|
||||
assert!(h.last_change().is_some(), "{tool:?}: the overlay still has the keys");
|
||||
}
|
||||
}
|
||||
|
||||
// A press belongs to the tool it began under: switching the host's tool in the middle of a drag leaves the drag its
|
||||
// own, and it commits as that tool's edit.
|
||||
#[trial]
|
||||
|
||||
@@ -207,7 +207,7 @@ impl HistogramData {
|
||||
}
|
||||
|
||||
/// A range of whole levels (bin positions) a plot has selected, both ends included.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct LevelRange {
|
||||
/// The first level.
|
||||
|
||||
@@ -4,7 +4,19 @@ use crate::ui::histogram::LevelRange;
|
||||
use crate::ui::scopes::clipping::{ClippingDiagnostic, ClippingMode, ClippingWarnings};
|
||||
|
||||
/// The panel's view (its menu's Compact, Expanded and All Channels View).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
Default,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
serde::Serialize,
|
||||
serde::Deserialize,
|
||||
craft_ui::contract::MemoProps,
|
||||
craft_ui::contract::PlainData,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ScopeView {
|
||||
@@ -20,7 +32,7 @@ pub enum ScopeView {
|
||||
/// The scope panel's persisted section: the app keeps it with its preferences (PhotoCraft's
|
||||
/// `histogramPanel` and `filter.cameraRaw.scope`). Unknown fields are ignored, missing ones take
|
||||
/// their defaults.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ScopeSettings {
|
||||
@@ -93,7 +105,7 @@ impl ScopeSettings {
|
||||
|
||||
/// What the panel keeps for the app between passes: the persisted settings and the selected
|
||||
/// level range (not persisted).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct ScopePanelState {
|
||||
/// The persisted section.
|
||||
|
||||
@@ -31,9 +31,10 @@ pub(in crate::ui::panel) struct DisplayRow<Id> {
|
||||
/// What the display order derives from: the tree's tracked revision, the filter and the groups a reveal opens. A
|
||||
/// change of any of them builds the rows again; nothing else does.
|
||||
#[derive(MemoProps)]
|
||||
pub(in crate::ui::panel) struct RowsKey<'a, Id: MemoProps> {
|
||||
pub(in crate::ui::panel) struct RowsKey<'a, Id> {
|
||||
pub(in crate::ui::panel) tree: Revision,
|
||||
pub(in crate::ui::panel) filter: &'a LayerFilter,
|
||||
#[memo_props(hash = "tree ids are plain model ids (LayerTree::Id: PlainData); Hash covers them")]
|
||||
pub(in crate::ui::panel) opened: &'a [Id],
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::hash::Hash;
|
||||
use craft_behavior::IconId;
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::LabelColor;
|
||||
use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove};
|
||||
use craft_ui::contract::{Entry, PlainData, ReorderMove};
|
||||
use craft_ui::list::ThumbTarget;
|
||||
|
||||
use super::filter::{EffectKind, LayerFilter, SmartSource};
|
||||
@@ -22,6 +22,9 @@ use super::panel::MenuTarget;
|
||||
/// the panel derives from the tree.
|
||||
///
|
||||
/// ```ignore
|
||||
/// #[derive(Clone, PartialEq, Eq, Hash, Debug, PlainData)]
|
||||
/// struct LayerId(u64);
|
||||
///
|
||||
/// #[derive(PlainData)]
|
||||
/// struct PhotoLayers { layers: LayerIndex, open: HashSet<LayerId> }
|
||||
/// impl LayerTree for PhotoLayers {
|
||||
@@ -36,9 +39,10 @@ use super::panel::MenuTarget;
|
||||
/// [`children`](Self::children) and [`is_open`](Self::is_open) are walked to build the display order, and only when the
|
||||
/// tracked revision, the filter or a reveal's opens changed.
|
||||
pub trait LayerTree: PlainData {
|
||||
/// The app's layer id: the key of a row, of its thumbnails and of every event. It feeds the memo key of the
|
||||
/// display order when a reveal opens groups.
|
||||
type Id: Clone + Eq + Hash + Debug + Send + Sync + MemoProps + 'static;
|
||||
/// The app's layer id: the key of a row, of its thumbnails and of every event. It is plain model data
|
||||
/// (`#[derive(PlainData)]`), so the panel keys it by its `Hash`, including in the memo key of the display order
|
||||
/// when a reveal opens groups.
|
||||
type Id: Clone + Eq + Hash + Debug + Send + Sync + PlainData + 'static;
|
||||
|
||||
/// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the
|
||||
/// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text.
|
||||
|
||||
@@ -97,10 +97,10 @@ pub use theme::{
|
||||
pub use token_group::{GroupValues, TokenGroup};
|
||||
pub use tokens::{
|
||||
AccentColors, BarSizes, CaptionColors, ColorToken, ColorTokens, ControlSizes, DataColors, DialogSizes, DockColumnSizes, Edge, EdgeColors,
|
||||
ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LineColors, Motion, MotionTokens,
|
||||
OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StateColors, Status,
|
||||
StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle, TypeTokens, WellShape,
|
||||
WindowSizes,
|
||||
ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LetterCase, LineColors, Motion,
|
||||
MotionTokens, OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens,
|
||||
StateColors, Status, StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle,
|
||||
TypeTokens, WellShape, WindowSizes,
|
||||
};
|
||||
pub use values::ColorSource;
|
||||
pub use variant::{CustomVariant, Emphasis, RadiusStep, Variant, VariantLook};
|
||||
|
||||
@@ -30,6 +30,8 @@ pub struct TypeStyle {
|
||||
pub enum TypeRole {
|
||||
/// Small print, badges.
|
||||
Caption,
|
||||
/// A heading over a group of fields or cards: the caption's size and font, set in capitals.
|
||||
SectionCaption,
|
||||
/// Control labels.
|
||||
Label,
|
||||
/// Body text.
|
||||
@@ -48,6 +50,26 @@ pub enum TypeRole {
|
||||
Display,
|
||||
}
|
||||
|
||||
/// How a type role sets its letters.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum LetterCase {
|
||||
/// As written.
|
||||
#[default]
|
||||
AsWritten,
|
||||
/// In capitals; the stored text stays as written.
|
||||
Upper,
|
||||
}
|
||||
|
||||
impl TypeRole {
|
||||
/// How the role sets its letters.
|
||||
pub fn letter_case(self) -> LetterCase {
|
||||
match self {
|
||||
TypeRole::SectionCaption => LetterCase::Upper,
|
||||
_ => LetterCase::AsWritten,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every type role.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct TypeTokens {
|
||||
@@ -75,7 +97,7 @@ impl TypeTokens {
|
||||
/// The style of `role`.
|
||||
pub fn get(&self, role: TypeRole) -> TypeStyle {
|
||||
match role {
|
||||
TypeRole::Caption => self.caption,
|
||||
TypeRole::Caption | TypeRole::SectionCaption => self.caption,
|
||||
TypeRole::Label => self.label,
|
||||
TypeRole::Body => self.body,
|
||||
TypeRole::BodyStrong => self.body_strong,
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::runtime::overlay::CloseReason;
|
||||
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::overlay::{Align, Side};
|
||||
use craft_behavior::{EditEvent, IconId, Metrics, Mixed, Sense};
|
||||
use craft_behavior::{EditEvent, GesturePhase, IconId, Metrics, Mixed, Sense};
|
||||
use egui::{Pos2, Rect, Response, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -245,8 +245,7 @@ impl<'a> TaskBar<'a> {
|
||||
let rect = shown.output.response.rect;
|
||||
let pick = menu.pick;
|
||||
if shows && kind == TaskBarKind::Task {
|
||||
let moved = shown.output.moved.filter(|moved| moved.min != rect.min);
|
||||
let next = settled(held, rect, area, moved, pick);
|
||||
let next = settled(held, rect, area, shown.output.moved, pick);
|
||||
if next != held {
|
||||
let word = match pick {
|
||||
Some(MenuPick::Reset) => &words.task_bar_reset,
|
||||
@@ -303,8 +302,8 @@ fn layer_overlay(held: &TaskBarPlace, hang: Option<Rect>, area: Rect, side: Side
|
||||
}
|
||||
}
|
||||
|
||||
/// The place after a pass that showed the bar at `shown`. A move (`moved`, a rect other than `shown`) keeps the bar
|
||||
/// where it was dropped; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A
|
||||
/// The place after a pass that showed the bar at `shown`. A move that ended (`moved`, where it was dropped) keeps the
|
||||
/// bar there; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A
|
||||
/// non-finite place is cleared. With no move and no pick, the place stays unchanged; the overlay host keeps the layer
|
||||
/// inside the area.
|
||||
fn settled(held: TaskBarPlace, shown: Rect, area: Rect, moved: Option<Rect>, pick: Option<MenuPick>) -> TaskBarPlace {
|
||||
@@ -333,7 +332,7 @@ pub struct TaskBarLayerStyle {
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
/// What the task bar's layer reports: its response, the last move of this pass and why it closed.
|
||||
/// What the task bar's layer reports: its response, the move that ended in this pass and why it closed.
|
||||
#[derive(Debug)]
|
||||
struct TaskBarLayerOutput {
|
||||
response: Response,
|
||||
@@ -361,6 +360,8 @@ struct TaskBarLayer {
|
||||
props: ContainerProps,
|
||||
/// Open while the bar shows; the caller shows the bar again each pass it wants it.
|
||||
open: Bind<'static, bool>,
|
||||
/// Where a move by the grip ended in this pass. The layer host shows the bar under the pointer while the move
|
||||
/// runs, so the place is written once, on the drop.
|
||||
moved: Option<Rect>,
|
||||
/// Why the layer closed, once it has.
|
||||
closed: Option<CloseReason>,
|
||||
@@ -411,7 +412,7 @@ impl Container for TaskBarLayer {
|
||||
}
|
||||
|
||||
fn placement_changed(&mut self, change: &PlacementChange) {
|
||||
if change.kind == PlacementKind::Move {
|
||||
if change.kind == PlacementKind::Move && change.phase == GesturePhase::Commit {
|
||||
self.moved = Some(change.rect);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use craft_ui::buttons::Button;
|
||||
use craft_ui::canvas_controls::{TaskBar, TaskBarDismiss, TaskBarPlace};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::testing::canvas_story::on_canvas;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
@@ -272,3 +273,39 @@ fn the_grip_sits_on_the_members_line() {
|
||||
let dropped = seen(&scene);
|
||||
assert!((dropped.rect.min - (bar.min + by)).length() < 2.0 * SLACK, "a drag on the grip moves the bar: {:?}", dropped.rect);
|
||||
}
|
||||
|
||||
/// A drag of the grip moves the bar under the pointer in the frame of each step, in one pass, and writes its place
|
||||
/// once, on the drop: one edit for the whole move.
|
||||
#[trial]
|
||||
fn a_dragged_task_bar_stands_under_the_pointer_in_each_frame_and_writes_its_place_on_the_drop() {
|
||||
let scene = Rc::new(RefCell::new(Scene {
|
||||
anchor: frame(DocVec::ZERO),
|
||||
place: TaskBarPlace::default(),
|
||||
bounds: Rect::NOTHING,
|
||||
area: Rect::NOTHING,
|
||||
rect: Rect::NOTHING,
|
||||
}));
|
||||
let mut fixture = fixture(&scene);
|
||||
fixture.settle();
|
||||
let start = seen(&scene).rect;
|
||||
let from = fixture.by_label("Move bar").expect("the grip is named").center();
|
||||
fixture.frame(vec![moved(from)]);
|
||||
fixture.frame(vec![press(from)]);
|
||||
let step = Vec2::new(-30.0, 15.0);
|
||||
for n in 1..=4 {
|
||||
let to = start.min + step * n as f32;
|
||||
fixture.frame(vec![moved(from + step * n as f32)]);
|
||||
let now = seen(&scene);
|
||||
assert!((now.rect.min - to).length() < SLACK, "step {n}: the bar stands under the pointer in its frame: {:?}, wanted {to:?}", now.rect);
|
||||
assert_eq!(fixture.passes(), 1, "step {n}: the frame runs one pass");
|
||||
assert_eq!(now.place, TaskBarPlace::default(), "step {n}: the place is not written while the drag runs");
|
||||
}
|
||||
let dropped_at = start.min + step * 4.0;
|
||||
fixture.frame(vec![release(from + step * 4.0)]);
|
||||
let dropped = seen(&scene);
|
||||
assert!((dropped.rect.min - dropped_at).length() < SLACK, "the bar stays where it was dropped: {:?}", dropped.rect);
|
||||
let at = dropped.place.at.map(|at| dropped.area.min + Vec2::from(at));
|
||||
assert!(at.is_some_and(|at| (at - dropped_at).length() < SLACK), "the drop writes the place: {:?}", dropped.place);
|
||||
fixture.settle();
|
||||
assert!((seen(&scene).rect.min - dropped_at).length() < SLACK, "the written place keeps the bar there: {:?}", seen(&scene).rect);
|
||||
}
|
||||
|
||||
@@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> {
|
||||
/// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent
|
||||
/// flow showed it this run: its own measuring run shows its content in a flow of its own.
|
||||
in_column: bool,
|
||||
/// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it
|
||||
/// this run: a rule above its header is not drawn, so two rules never follow each other.
|
||||
after_rule: bool,
|
||||
/// A bottom-anchored region is following the end of its content.
|
||||
follows_end: bool,
|
||||
}
|
||||
@@ -242,6 +245,7 @@ impl<'b> BodyHooks<'b> {
|
||||
held: false,
|
||||
across: false,
|
||||
in_column: true,
|
||||
after_rule: false,
|
||||
follows_end: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::open::open_now;
|
||||
use super::placement::{Placement, measure_layer, overlay_of, shown_placement};
|
||||
use super::regions::{
|
||||
LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_body, footer_in_end, footer_rule_under,
|
||||
gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
|
||||
gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_bracket, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
|
||||
};
|
||||
use super::reorder::REORDER_BAND;
|
||||
use super::scroll::{
|
||||
@@ -68,7 +68,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
}
|
||||
|
||||
fn host(&mut self, comp: &C, at: crate::contract::run::HostCx<'_>) -> Box<dyn crate::contract::run::Host> {
|
||||
let mounted = crate::contract::mount::host(comp.props(Internal::new()), &at, self.open, at.label);
|
||||
let props = comp.props(Internal::new());
|
||||
let moving = overlay_of(props).filter(|overlay| overlay.movable).and_then(|_| self.mode.running_move(at.ui.ctx(), at.id));
|
||||
let mounted = crate::contract::mount::host(props, &at, self.open, at.label, moving);
|
||||
if mounted.exiting {
|
||||
self.exiting = true;
|
||||
self.open = true;
|
||||
@@ -157,7 +159,8 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
self.region_gap = gap_of(&env.tokens, Gap::Tight);
|
||||
self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap));
|
||||
self.header_gap = header_gap_of(props, &env.tokens);
|
||||
self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx));
|
||||
self.after_rule = layout::flow_start(&ctx, env) == Some(true);
|
||||
self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx), self.after_rule);
|
||||
self.least_width = least_of(&env.tokens, props.least_width);
|
||||
let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx);
|
||||
if !matches!(props.mount, Mount::Inline | Mount::Pane(_))
|
||||
@@ -185,7 +188,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
Mount::Layer(_) | Mount::Viewport { .. } => {
|
||||
let placement = overlay_of(props).map_or_else(Placement::default, |overlay| {
|
||||
let screen = crate::contract::overlay::screen_for(&ctx, env, overlay);
|
||||
shown_placement(&ctx, id, save.as_ref(), overlay, screen, env.tokens.space.inset.screen)
|
||||
shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen)
|
||||
});
|
||||
// A layer the user sized takes that size, at its saved position or where its anchor places it.
|
||||
placement.size.is_some()
|
||||
@@ -1305,12 +1308,12 @@ impl BodyHooks<'_> {
|
||||
&& env.values.get::<label::LabelScheme>() == label::LabelScheme::Inspector;
|
||||
let (room, content_column, scroll, beside, label_width) =
|
||||
(plan.room, plan.content_column, plan.scroll, plan.regions.beside, plan.label_extra.x);
|
||||
let first_body = plan.first.1;
|
||||
let (first_body, layout_id) = (plan.first.1, plan.layout_id);
|
||||
// The slot of a footer the body places takes the size the measuring run's footer took.
|
||||
let footer_slot = footer_in_body(props)
|
||||
.then(|| FooterSlotOf { owner: id, size: if real { self.measured_footer } else { self.footer_size.unwrap_or(Vec2::ZERO) } });
|
||||
plan.body_env = Some(plan.line_env.derive_local(|scoped| {
|
||||
self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside });
|
||||
self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside, layout: layout_id });
|
||||
scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held);
|
||||
scoped.cell_fills = cell_fills;
|
||||
if footer_slot.is_some() {
|
||||
@@ -1569,6 +1572,12 @@ impl BodyHooks<'_> {
|
||||
/// size counts the label column.
|
||||
fn after_body(&mut self, ui: &mut Ui, env: &Env, plan: &mut BodyPlan<'_>) {
|
||||
let (props, ctx, real) = (plan.props, &plan.ctx, plan.real);
|
||||
if let Some(bracket) = props.bracket {
|
||||
let took = layout::take_bracket(ctx, plan.layout_id);
|
||||
if let (true, crate::contract::Bracket::Linked, Some(took)) = (real, bracket, took) {
|
||||
paint_bracket(ui, env, &took, plan.rtl);
|
||||
}
|
||||
}
|
||||
// A measuring run decided the label before the control reported its minimum width: it decides again
|
||||
// from the minimum this run recorded, so the extent it measures is the one the real run lays out.
|
||||
if let (false, Some(input)) = (real, plan.label_input.as_mut()) {
|
||||
@@ -1580,6 +1589,12 @@ impl BodyHooks<'_> {
|
||||
plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl);
|
||||
}
|
||||
if let Some(size) = &mut self.body_size {
|
||||
// A labelled row of a bracketed row reports where its control lies: the bracket runs from it.
|
||||
if let (Some(row), Some(_)) = (env.bracket, props.label.as_ref()) {
|
||||
let body = plan.body_rect;
|
||||
let left = if plan.rtl { body.max.x - size.x } else { body.min.x };
|
||||
layout::report_bracket_control(ctx, row, Rect::from_min_size(egui::pos2(left, body.min.y), *size), plan.rtl);
|
||||
}
|
||||
let label_extra = plan.label_extra;
|
||||
// A body beside its label in a content-sized column of rows reports how far it reaches past the label
|
||||
// column, so that column's container measures its rows at the widest label.
|
||||
@@ -1801,7 +1816,8 @@ impl BodyHooks<'_> {
|
||||
self.region_gap = gap_of(&at.env.tokens, Gap::Tight);
|
||||
self.end_gap = gap_of(&at.env.tokens, props.end.map_or(Gap::Tight, |end| end.gap));
|
||||
self.header_gap = header_gap_of(&props, &at.env.tokens);
|
||||
self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx()));
|
||||
self.after_rule = layout::flow_start(at.ui.ctx(), at.env) == Some(true);
|
||||
self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx()), self.after_rule);
|
||||
self.least_width = least_of(&at.env.tokens, props.least_width);
|
||||
self.room = match at.width {
|
||||
Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)),
|
||||
|
||||
@@ -19,6 +19,8 @@ pub(super) struct BodyScope {
|
||||
pub(super) label_width: f32,
|
||||
/// The width the regions beside the body take on its line (`Regions::beside`).
|
||||
pub(super) beside: f32,
|
||||
/// The id the body's layout runs under (`BodyPlan::layout_id`).
|
||||
pub(super) layout: Id,
|
||||
}
|
||||
|
||||
/// The surface a container paints under its regions: its props' surface, else its style's in its current state.
|
||||
@@ -96,10 +98,23 @@ impl BodyHooks<'_> {
|
||||
|
||||
/// What the body inherits on top of the line's env: arena, transform, the room it is offered and its scroll axes.
|
||||
pub(super) fn scope_body(&self, scoped: &mut Scoped, props: &ContainerProps, id: Id, body: BodyScope) {
|
||||
let BodyScope { room, real, content_column, scroll, label_width, beside } = body;
|
||||
let BodyScope { room, real, content_column, scroll, label_width, beside, layout } = body;
|
||||
if props.arena {
|
||||
scoped.arena = Some(ArenaId::new(id));
|
||||
}
|
||||
// The body's flow starts after a rule when the container draws one under its header, or when the container
|
||||
// draws nothing of its own (no header, surface or mount) and itself started after a rule.
|
||||
scoped.after_rule = props.header.is_some_and(|header| header.rule && !header.inline)
|
||||
|| (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule);
|
||||
scoped.flow_body = None;
|
||||
scoped.column_row =
|
||||
self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start });
|
||||
// A bracketed row's rows report to it up to the first labelled container, whose body is its own control.
|
||||
if props.bracket.is_some() {
|
||||
scoped.bracket = Some(layout);
|
||||
} else if props.label.is_some() {
|
||||
scoped.bracket = None;
|
||||
}
|
||||
scoped.transform = props.transform;
|
||||
scoped.content_column = content_column;
|
||||
scoped.given_column = !content_column && matches!(props.layout, crate::layout::BodyLayout::Stack);
|
||||
|
||||
@@ -28,8 +28,7 @@ impl Placement {
|
||||
|
||||
/// The placement the caller of `overlay` gives, when it places the layer.
|
||||
fn given(overlay: &crate::contract::Overlay) -> Option<Placement> {
|
||||
let kept = |rect: Rect| overlay.bounds.map_or(rect, |bounds| super::window::keep_inside(rect, bounds));
|
||||
overlay.placed.map(|rect| Placement::at(kept(rect))).or_else(|| overlay.placed_at.map(Placement::at_pos))
|
||||
overlay.placed.map(|rect| Placement::at(super::window::kept_in(rect, overlay.bounds))).or_else(|| overlay.placed_at.map(Placement::at_pos))
|
||||
}
|
||||
|
||||
/// The rect it names, taking the position and size it lacks from `rect`.
|
||||
@@ -46,7 +45,9 @@ pub(crate) fn placement_id(id: Id) -> Id {
|
||||
/// is `placed` has the caller's rect instead: the slot reads it and writes nothing, since the caller owns the
|
||||
/// placement and learns of the user's changes from `PlacementChange` reports. A layer hung from its anchor keeps only
|
||||
/// its size, whether or not the user can move it: each opening places it from its anchor at that size, and a caller
|
||||
/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of.
|
||||
/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. While the
|
||||
/// user drags the move band, the layer host shows the layer at the drag's rect whatever the slot holds
|
||||
/// ([`shown_placement`]), so a caller places it from the drag's `Commit` alone.
|
||||
pub(super) struct PlacementSlot<'s> {
|
||||
stage: &'s mut MemoryStage,
|
||||
id: Id,
|
||||
@@ -96,7 +97,28 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement {
|
||||
/// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less `screen_inset` on
|
||||
/// each side, centred or at the overlay's float position. A saved size and position win over the default. A size with
|
||||
/// no position places an anchored layer from its anchor at that size.
|
||||
///
|
||||
/// While a drag of the layer's move band runs, `moving` is the rect it puts the layer at in this pass
|
||||
/// (`WindowMode::running_move`): the layer shows there, within its bounds, at the size the placement gives. The
|
||||
/// caller's place, the stored one or the anchor applies again once the drag ends.
|
||||
pub(crate) fn shown_placement(
|
||||
ctx: &Context,
|
||||
id: Id,
|
||||
save: Option<&SaveKey>,
|
||||
overlay: &crate::contract::Overlay,
|
||||
moving: Option<Rect>,
|
||||
screen: Rect,
|
||||
screen_inset: f32,
|
||||
) -> Placement {
|
||||
let mut placement = resting_placement(ctx, id, save, overlay, screen, screen_inset);
|
||||
if let Some(moving) = moving {
|
||||
placement.pos = Some(super::window::kept_in(moving, overlay.bounds).min.into());
|
||||
}
|
||||
placement
|
||||
}
|
||||
|
||||
/// The placement a layer is shown at while no drag moves it ([`shown_placement`]).
|
||||
fn resting_placement(
|
||||
ctx: &Context,
|
||||
id: Id,
|
||||
save: Option<&SaveKey>,
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::runtime::egui::{alloc, child, style};
|
||||
use crate::runtime::env::{Env, RowLine};
|
||||
use crate::runtime::memory::sub;
|
||||
use crate::runtime::overlay::CloseReason;
|
||||
use crate::style::{RuleKind, UiTokens, rule_look};
|
||||
use crate::style::{RuleKind, RuleLook, RuleWidth, UiTokens, rule_look};
|
||||
use egui::{Align, Id, Layout, Pos2, Rect, Ui, UiBuilder, Vec2};
|
||||
|
||||
/// The slots of a container's own header parts at the edges of the header's line (`Container::header_parts`).
|
||||
@@ -84,12 +84,13 @@ pub(super) struct RuleBands {
|
||||
}
|
||||
|
||||
impl RuleBands {
|
||||
/// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`.
|
||||
pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32) -> Self {
|
||||
/// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. A rule above separates the
|
||||
/// container from what precedes it in flow: right after a rule (`after_rule`) there is none.
|
||||
pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32, after_rule: bool) -> Self {
|
||||
let width = rule_look(tokens, RuleKind::Divider).width.points(pixels_per_point);
|
||||
let on = |rule: bool| if rule { width } else { 0.0 };
|
||||
RuleBands {
|
||||
above: on(props.header.is_some_and(|header| header.rule_above)),
|
||||
above: on(!after_rule && props.header.is_some_and(|header| header.rule_above)),
|
||||
under: on(props.header.is_some_and(|header| header.rule && !header.inline)),
|
||||
footer: on(props.footer.is_some_and(|footer| footer.rule)),
|
||||
end: on(props.end.is_some_and(|end| end.rule)),
|
||||
@@ -217,6 +218,30 @@ pub(super) fn paint_rules(ui: &mut Ui, env: &Env, regions: &Regions) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bracket of a linked `Row` (`Bracket::Linked`) from what its rows reported in `took`: a tick from the end of the
|
||||
/// first and the last row's controls, `space.gap.tight` past them, to the middle child's centre line, and a stroke
|
||||
/// along that line from each tick to the middle child's edge. `text.muted`, `stroke.thin` wide.
|
||||
pub(super) fn paint_bracket(ui: &mut Ui, env: &Env, took: &crate::layout::BracketTook, rtl: bool) {
|
||||
let (Some(first), Some(last), Some(end), Some(middle)) = (took.first, took.last, took.end, took.middle) else { return };
|
||||
if last <= first {
|
||||
return;
|
||||
}
|
||||
let tokens = &env.tokens;
|
||||
let tight = tokens.tokens().space.gap.tight;
|
||||
let look = RuleLook { color: crate::style::rgba_color(tokens.color.text.muted), width: RuleWidth::Points(tokens.stroke.thin) };
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let (start, line) = if rtl { (-end - tight, middle.center().x) } else { (end + tight, middle.center().x) };
|
||||
let painter = ui.painter();
|
||||
for (from, to) in [
|
||||
(Pos2::new(start, first), Pos2::new(line, first)),
|
||||
(Pos2::new(start, last), Pos2::new(line, last)),
|
||||
(Pos2::new(line, first), Pos2::new(line, middle.top().max(first))),
|
||||
(Pos2::new(line, middle.bottom().min(last)), Pos2::new(line, last)),
|
||||
] {
|
||||
painter.extend(Rule::shapes(&look, from, to, ppp));
|
||||
}
|
||||
}
|
||||
|
||||
impl BodyHooks<'_> {
|
||||
/// The footer's rect and how far its left edge lies past the container's, under the control column of a
|
||||
/// label-scoped container; along an axis the room leaves unbounded, the footer follows the body and the end region.
|
||||
@@ -610,7 +635,11 @@ fn own_labels<R>(ui: &mut Ui, id: Id, (room, seed): (f32, Option<Columns>), foun
|
||||
group.offer(room);
|
||||
body(ui)
|
||||
});
|
||||
(found.extent, found.unsettled) = (scoped.extent, scoped.unsettled);
|
||||
found.extent = scoped.extent;
|
||||
// A later sweep of the same run may take a row's measure from the earlier sweep without reading the column again
|
||||
// (a stack's sweep at the width its first sweep found): that measure is still the one taken at the narrower
|
||||
// column, so the rows run again whenever any sweep found one.
|
||||
found.unsettled = scoped.unsettled.or(found.unsettled.take());
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ pub(super) struct MeasureKey {
|
||||
/// Whether the body shows, and how much of it an animated collapse shows.
|
||||
shows: (bool, f32),
|
||||
env: EnvFacts,
|
||||
/// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), and with a rule
|
||||
/// just before it (a rule above its header is not drawn).
|
||||
flow: (bool, bool),
|
||||
}
|
||||
|
||||
/// The props a body was measured under, compared on the fields its measure reads.
|
||||
@@ -92,6 +95,7 @@ impl<'b> BodyHooks<'b> {
|
||||
width,
|
||||
shows: (self.open, self.presence.t),
|
||||
env: EnvFacts::of(env),
|
||||
flow: (self.in_column, self.after_rule),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,9 @@ pub(super) struct WindowMode {
|
||||
kind: Option<WindowModeKind>,
|
||||
restore: Placement,
|
||||
began: Option<Rect>,
|
||||
/// The rect the layer had when a press went down on its move band or a grip, until the press ends: a drag that
|
||||
/// starts from the press runs from it.
|
||||
pressed: Option<Rect>,
|
||||
moving: Option<WindowMove>,
|
||||
sizing: Option<WindowSize>,
|
||||
/// The index in `GRIPS` of the grip a drag holds, from its `DragStart` to its release: `move_parts` keeps it
|
||||
@@ -136,6 +139,23 @@ impl WindowMode {
|
||||
pub(super) fn held(&self) -> Option<usize> {
|
||||
self.held
|
||||
}
|
||||
|
||||
/// The rect a drag of the move band of the layer `id` puts the layer at in this pass, before the bounds keep it:
|
||||
/// the rect the layer had when the press went down, moved by the pointer's travel since. `window_drag` reports the
|
||||
/// same rect for the step. `None` while no move by the band runs. The layer host shows the layer there
|
||||
/// (`shown_placement`) before the container's pass runs, so the layer stands under the pointer in the frame of
|
||||
/// each step, whoever owns its placement.
|
||||
pub(super) fn running_move(&self, ctx: &Context, id: Id) -> Option<Rect> {
|
||||
if self.pressed.is_none() && self.began.is_none() {
|
||||
return None;
|
||||
}
|
||||
let (began, start, pos) = match crate::primitives::sensing::part_press(ctx, id, MOVE_BAND.into()).press.phase {
|
||||
PressPhase::DragStart { start, pos, .. } => (self.pressed?, start, pos),
|
||||
PressPhase::Drag { start, pos, .. } | PressPhase::Release { start, pos, .. } => (self.began?, start, pos),
|
||||
_ => return None,
|
||||
};
|
||||
Some(began.translate(pos - start.origin))
|
||||
}
|
||||
}
|
||||
|
||||
/// A move of a viewport mount's OS window that the app runs (`Overlay::moved_by_app`), from its Begin to its Commit
|
||||
@@ -200,6 +220,11 @@ pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect {
|
||||
rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y)))
|
||||
}
|
||||
|
||||
/// `rect` kept inside `bounds`, when the layer has bounds.
|
||||
pub(super) fn kept_in(rect: Rect, bounds: Option<Rect>) -> Rect {
|
||||
bounds.map_or(rect, |bounds| keep_inside(rect, bounds))
|
||||
}
|
||||
|
||||
/// What every change of a layer's rect keeps to: the least and most size, and the rect it stays inside.
|
||||
struct Limits {
|
||||
min: Vec2,
|
||||
@@ -214,8 +239,7 @@ impl Limits {
|
||||
|
||||
/// `rect` moved by `delta`, kept inside the bounds.
|
||||
fn moved(&self, rect: Rect, delta: Vec2) -> Rect {
|
||||
let rect = rect.translate(delta);
|
||||
self.bounds.map_or(rect, |bounds| keep_inside(rect, bounds))
|
||||
kept_in(rect.translate(delta), self.bounds)
|
||||
}
|
||||
|
||||
/// `rect` with the edges `dx` and `dy` (-1: low edge, 1: high edge, 0: none) moved by `delta`, within the size
|
||||
@@ -377,14 +401,7 @@ impl BodyHooks<'_> {
|
||||
if mode.kind == Some(kind) {
|
||||
mode = WindowMode::default();
|
||||
} else {
|
||||
mode = WindowMode {
|
||||
kind: Some(kind),
|
||||
restore: current.clone(),
|
||||
began: Some(current.rect_over(rect)),
|
||||
moving: None,
|
||||
sizing: None,
|
||||
held: None,
|
||||
};
|
||||
mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), ..WindowMode::default() };
|
||||
self.reports.push(step(current.rect_over(rect), GesturePhase::Begin));
|
||||
}
|
||||
}
|
||||
@@ -436,7 +453,8 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
|
||||
/// A drag of the move band or a grip of a layer (not an OS window): the layer follows the pointer within the
|
||||
/// limits, and each step is reported. Escape, which cancels the press, restores the placement from before.
|
||||
/// limits, and each step is reported. The drag runs from the rect the layer had when the press went down. Escape,
|
||||
/// which cancels the press, restores the placement from before.
|
||||
pub(super) fn window_drag<C: Container>(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
let Some(overlay) = overlay_of(props) else { return };
|
||||
// A band that moves the window below starts the OS move of the window the layer is shown in.
|
||||
@@ -455,9 +473,11 @@ impl BodyHooks<'_> {
|
||||
let mut pressed = vec![(None, phase((MOVE_BAND, None)))];
|
||||
pressed.extend((0..GRIPS.len()).map(|index| (Some(index), phase((GRIP, Some(index as u64))))));
|
||||
let Some((grip, phase)) = pressed.into_iter().find_map(|(grip, phase)| match phase? {
|
||||
phase @ (PressPhase::DragStart { .. } | PressPhase::Drag { .. } | PressPhase::Release { .. } | PressPhase::Cancel { .. }) => {
|
||||
Some((grip, phase))
|
||||
}
|
||||
phase @ (PressPhase::Down { .. }
|
||||
| PressPhase::DragStart { .. }
|
||||
| PressPhase::Drag { .. }
|
||||
| PressPhase::Release { .. }
|
||||
| PressPhase::Cancel { .. }) => Some((grip, phase)),
|
||||
_ => None,
|
||||
}) else {
|
||||
return;
|
||||
@@ -465,8 +485,14 @@ impl BodyHooks<'_> {
|
||||
let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay);
|
||||
let current = slot.read();
|
||||
let (origin, pos, gesture) = match phase {
|
||||
PressPhase::Down { .. } => {
|
||||
self.mode.pressed = Some(current.rect_over(rect));
|
||||
return;
|
||||
}
|
||||
PressPhase::DragStart { start, pos, .. } => {
|
||||
self.mode.began = Some(current.rect_over(rect));
|
||||
// The layer host shows this pass at the step's rect already (`running_move`): the drag runs from where
|
||||
// the layer stood at the press.
|
||||
self.mode.began = Some(self.mode.pressed.unwrap_or_else(|| current.rect_over(rect)));
|
||||
self.mode.restore = current.clone();
|
||||
self.mode.held = grip;
|
||||
(start.origin, Some(pos), GesturePhase::Begin)
|
||||
@@ -476,6 +502,9 @@ impl BodyHooks<'_> {
|
||||
PressPhase::Cancel { start, .. } => (start.origin, None, GesturePhase::Cancel),
|
||||
_ => return,
|
||||
};
|
||||
if matches!(gesture, GesturePhase::Commit | GesturePhase::Cancel) {
|
||||
self.mode.pressed = None;
|
||||
}
|
||||
let Some(began) = self.mode.began else { return };
|
||||
let (dx, dy, _) = grip.map_or((0, 0, CursorIcon::Grab), |index| GRIPS[index]);
|
||||
let kind = if grip.is_some() { PlacementKind::Size(edge_of(dx, dy)) } else { PlacementKind::Move };
|
||||
|
||||
@@ -12,7 +12,8 @@ pub use events::{
|
||||
CollectionEvent, ColumnEvent, ColumnRequest, ContextMenuRequest, HeaderMenuRequest, ListDrag, OpenChange, Rename, ReorderMove, ToggleEdit,
|
||||
};
|
||||
pub use props::{
|
||||
ActivateOn, CollectionProps, DragPayload, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed, RowState, SelectMode, SpaceAction,
|
||||
ActivateOn, CollectionProps, DragPayload, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed, RowState, SelectMode,
|
||||
SpaceAction,
|
||||
};
|
||||
pub(crate) use response::Gestures;
|
||||
pub(crate) use response::ItemsOut;
|
||||
|
||||
@@ -119,6 +119,21 @@ pub enum LeadOnOpen {
|
||||
First,
|
||||
}
|
||||
|
||||
/// What the pointer moving over the rows changes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum HoverLead {
|
||||
/// Nothing: only a press moves the lead.
|
||||
#[default]
|
||||
Off,
|
||||
/// The lead moves to the row under the pointer; the selection stays until a pick (click, Enter, or a key move):
|
||||
/// option lists, where the selection is the chosen value.
|
||||
Lead,
|
||||
/// The lead moves and picks the row, as the arrow keys do: menus and the undo list, where the hover range is
|
||||
/// the point.
|
||||
LeadAndSelection,
|
||||
}
|
||||
|
||||
/// How tall a collection's rows are. Read-only display tables (a metadata table) take text rows; lists the user picks
|
||||
/// from or navigates keep control-high rows, a pointer target as tall as a control. A row with a thumbnail or a
|
||||
/// detail line is as tall as those need either way.
|
||||
@@ -173,9 +188,8 @@ pub struct CollectionProps {
|
||||
pub allow_empty: bool,
|
||||
/// Where the lead starts.
|
||||
pub lead_on_open: LeadOnOpen,
|
||||
/// The lead, and the selection with it as for the arrow keys, moves to the row under the pointer when the pointer
|
||||
/// moves: menus, popup lists and the undo list.
|
||||
pub lead_follows_hover: bool,
|
||||
/// What the pointer moving over the rows changes: the lead, and for some lists the selection too.
|
||||
pub hover_lead: HoverLead,
|
||||
/// The arrow keys select the row they move the lead to. Off: they move the lead only, and Space, Enter or a click
|
||||
/// selects it (a swatch table, a tab strip, a preset browser); Enter then activates it as well.
|
||||
pub arrows_select: bool,
|
||||
@@ -299,7 +313,7 @@ impl CollectionProps {
|
||||
striped: false,
|
||||
allow_empty: false,
|
||||
lead_on_open: LeadOnOpen::Selected,
|
||||
lead_follows_hover: false,
|
||||
hover_lead: HoverLead::Off,
|
||||
arrows_select: true,
|
||||
focus_on_press: true,
|
||||
rows_stamp: None,
|
||||
@@ -434,10 +448,10 @@ impl CollectionProps {
|
||||
self
|
||||
}
|
||||
|
||||
/// The lead follows the pointer over the rows.
|
||||
/// What the pointer moving over the rows changes.
|
||||
#[must_use]
|
||||
pub const fn lead_follows_hover(mut self, on: bool) -> Self {
|
||||
self.lead_follows_hover = on;
|
||||
pub const fn hover_lead(mut self, hover: HoverLead) -> Self {
|
||||
self.hover_lead = hover;
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -727,6 +727,19 @@ impl EnvValue for InMenu {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and
|
||||
/// height to their chain): a tick from each of the first and the last row's controls to the middle child's centre
|
||||
/// line, joined along that line. The middle child sits halfway between the two controls. The value is the link's
|
||||
/// state.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Bracket {
|
||||
/// The rows are linked: the bracket is drawn.
|
||||
Linked,
|
||||
/// The rows are not linked: the middle child keeps its place, with no bracket.
|
||||
Unlinked,
|
||||
}
|
||||
|
||||
/// What a container or collection adds to `Common`. A builder added here is added to the forwarder list in
|
||||
/// `crates/ui-macros/src/props.rs` too.
|
||||
///
|
||||
@@ -820,6 +833,9 @@ pub struct ContainerProps {
|
||||
pub label_column: bool,
|
||||
/// How the labelled rows under the container show their labels; `None` keeps the scheme of the scope.
|
||||
pub labels: Option<LabelScheme>,
|
||||
/// The bracket an unwrapped `Row` placed from its start draws from its first child's labelled rows to the child
|
||||
/// after them; any other body draws none.
|
||||
pub bracket: Option<Bracket>,
|
||||
/// The component whose memory holds the container's shown memory and its layer's bookkeeping, when it is another:
|
||||
/// the body of a popup an `overlay` hook shows belongs to the component that shows it.
|
||||
pub(crate) owner: Option<egui::Id>,
|
||||
@@ -860,6 +876,7 @@ impl ContainerProps {
|
||||
&& self.outer_edit == other.outer_edit
|
||||
&& self.collection_body == other.collection_body
|
||||
&& self.labels == other.labels
|
||||
&& self.bracket == other.bracket
|
||||
}
|
||||
|
||||
/// Props with every field at its default.
|
||||
@@ -901,6 +918,7 @@ impl ContainerProps {
|
||||
collection_body: false,
|
||||
label_column: false,
|
||||
labels: None,
|
||||
bracket: None,
|
||||
owner: None,
|
||||
}
|
||||
}
|
||||
@@ -1122,6 +1140,12 @@ impl ContainerProps {
|
||||
self
|
||||
}
|
||||
|
||||
/// The bracket of a `Row` from its first child's labelled rows to the child after them ([`bracket`](Self::bracket)).
|
||||
pub const fn bracket(mut self, bracket: Bracket) -> Self {
|
||||
self.bracket = Some(bracket);
|
||||
self
|
||||
}
|
||||
|
||||
/// The labelled rows under the container show their labels in `scheme`: its regions, its body and every container
|
||||
/// inside, until one sets a scheme of its own.
|
||||
pub const fn labels(mut self, scheme: LabelScheme) -> Self {
|
||||
|
||||
@@ -8,7 +8,7 @@ use super::{Held, ITEM_NODE, ItemsHooks, LastLayout, Lead, Placement, Renaming,
|
||||
use super::{request, rows};
|
||||
use crate::contract::ValueOf;
|
||||
use crate::contract::collection::{
|
||||
CollectionEvent, ColumnLayout, ContextMenuRequest, DropAt, Gestures, ItemsOut, OpenChange, PendingDrop, Rename, RowState, ShownRow,
|
||||
CollectionEvent, ColumnLayout, ContextMenuRequest, DropAt, Gestures, HoverLead, ItemsOut, OpenChange, PendingDrop, Rename, RowState, ShownRow,
|
||||
};
|
||||
use crate::contract::cx::{BodyCx, CxCore, Pointer as _};
|
||||
use crate::contract::run::{Measuring, ShapeHooks, ShowAt};
|
||||
@@ -277,8 +277,8 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
|
||||
let seen = Placement { offset: ScrollPos { x: self.offset_x_at_read, y: self.offset_at_read }, ..at };
|
||||
self.edge_step(cx);
|
||||
self.press_step(comp, cx, &props, &layout, seen);
|
||||
if props.lead_follows_hover {
|
||||
self.hover_lead(comp, cx, &layout, seen);
|
||||
if props.hover_lead != HoverLead::Off {
|
||||
self.hover_lead(comp, cx, &layout, seen, props.hover_lead);
|
||||
}
|
||||
if props.select_under_drag {
|
||||
self.drag_select(comp, cx, &layout, seen);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The lead and the selection: picks, ranges, and where the lead starts and follows.
|
||||
|
||||
use super::{ItemsHooks, Placement};
|
||||
use crate::contract::collection::{CollectionEvent, LeadOnOpen, LeadSource, ListDrag, SelectMode};
|
||||
use crate::contract::collection::{CollectionEvent, HoverLead, LeadOnOpen, LeadSource, ListDrag, SelectMode};
|
||||
use crate::contract::{Collection, Cx};
|
||||
use craft_behavior::{Flow, ItemLayout, PointerEvent, SelectionChange, SelectionModel};
|
||||
use egui::{Pos2, Rect, Vec2};
|
||||
@@ -135,10 +135,10 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
layout.hit(local, offset).filter(|&row| self.source.enabled(row) && !self.source.is_section(row) && layout.shown(row))
|
||||
}
|
||||
|
||||
/// The lead follows a moving pointer over the rows, and the selection follows the lead the way it does for the
|
||||
/// arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead
|
||||
/// The lead follows a moving pointer over the rows; with `HoverLead::LeadAndSelection` the selection follows the
|
||||
/// lead the way it does for the arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead
|
||||
/// with no movement to measure, and a modifier change under a resting pointer leaves the lead where the keys put it.
|
||||
pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) {
|
||||
pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement, hover: HoverLead) {
|
||||
let moved =
|
||||
crate::runtime::pointer::with_pass_raw(&cx.core.ctx, |pass| pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. })));
|
||||
if !moved {
|
||||
@@ -147,7 +147,9 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
let Some(row) = Self::hovered_pos(cx).and_then(|pos| self.row_under(layout, at, pos)) else { return };
|
||||
if self.lead.key.as_ref() != Some(&self.source.key(row)) {
|
||||
self.move_lead(row, LeadSource::Pointer);
|
||||
self.pick(comp, row, false, false);
|
||||
if hover == HoverLead::LeadAndSelection {
|
||||
self.pick(comp, row, false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,8 @@ impl LeafPlaced {
|
||||
pub(crate) fn leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option<Trailing<'_>>) -> LeafPlaced {
|
||||
let scope = sub(at.id, "field");
|
||||
let enabled = at.under.enabled;
|
||||
// Read before the child measures: nothing it does there may count as a child placed in flow.
|
||||
let in_column = in_column(ui);
|
||||
let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x;
|
||||
let input = LabelIn {
|
||||
scope,
|
||||
@@ -131,7 +133,7 @@ pub(crate) fn leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &
|
||||
size: at.under.size,
|
||||
control_min,
|
||||
leaf: true,
|
||||
in_column: in_column(ui),
|
||||
in_column,
|
||||
claims: C::LABELLED_AFTER,
|
||||
status: false,
|
||||
trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size),
|
||||
@@ -227,9 +229,15 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
|
||||
placed
|
||||
}
|
||||
|
||||
/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line.
|
||||
/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. The first child of an
|
||||
/// unwrapped row that is itself a row of a vertical flow (`Scoped::column_row`) starts where that flow's rows start,
|
||||
/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls.
|
||||
pub(crate) fn in_column(flow: &Ui) -> bool {
|
||||
!flow.layout().is_horizontal()
|
||||
if !flow.layout().is_horizontal() {
|
||||
return true;
|
||||
}
|
||||
let env = Env::of(flow);
|
||||
env.column_row && crate::layout::at_flow_start(flow.ctx(), &env)
|
||||
}
|
||||
|
||||
/// A control with its label after it that the label step moved into the control column (its `control` starts past
|
||||
|
||||
@@ -177,6 +177,7 @@ impl Lazy {
|
||||
if memo {
|
||||
place_view(ui, rect);
|
||||
} else {
|
||||
crate::layout::close_flow_start_in(ui);
|
||||
alloc::advance_past(ui, rect);
|
||||
}
|
||||
if view.is_some() || memo {
|
||||
@@ -269,6 +270,7 @@ fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 {
|
||||
/// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`.
|
||||
fn place_view(ui: &mut Ui, rect: Rect) -> Rect {
|
||||
if take_cell(ui, rect.size()).is_none() {
|
||||
crate::layout::close_flow_start_in(ui);
|
||||
alloc::advance_past(ui, rect);
|
||||
}
|
||||
rect
|
||||
|
||||
@@ -60,16 +60,17 @@ pub use body::{STRIP_BACK, STRIP_FORWARD};
|
||||
pub use collection::{
|
||||
ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove,
|
||||
ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest,
|
||||
ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, RowState,
|
||||
SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit,
|
||||
HoverLead, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed,
|
||||
RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit,
|
||||
};
|
||||
#[doc(hidden)]
|
||||
pub use container::InBar;
|
||||
#[doc(hidden)]
|
||||
pub use container::InMenu;
|
||||
pub use container::{
|
||||
BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth,
|
||||
Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth,
|
||||
BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion,
|
||||
LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope,
|
||||
WrapWidth,
|
||||
};
|
||||
pub use craft_tracked::{PlainData, Revision, Tracked};
|
||||
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
|
||||
|
||||
@@ -26,7 +26,8 @@ pub(super) struct Mounted {
|
||||
}
|
||||
|
||||
/// The host for `props.mount`. A layer-like mount of a closed container shows nothing once its exit fade ended.
|
||||
pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label) -> Mounted {
|
||||
/// `moving` is the rect a running drag of the container's move band puts its layer at in this pass.
|
||||
pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label, moving: Option<Rect>) -> Mounted {
|
||||
let ctx = at.ui.ctx();
|
||||
let layer = |overlay: &Overlay| {
|
||||
let presence = if at.ui.is_sizing_pass() {
|
||||
@@ -46,7 +47,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &
|
||||
Mount::Pane(pane) => Mounted { host: Box::new(PaneHost(*pane)), exiting: false },
|
||||
Mount::Window { .. } => Mounted { host: Box::new(WindowContentHost), exiting: false },
|
||||
Mount::Layer(overlay) => match layer(overlay) {
|
||||
(Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size)), exiting },
|
||||
(Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size, moving)), exiting },
|
||||
(None, _) => closed(),
|
||||
},
|
||||
Mount::FullWindow => full_window(props.focus),
|
||||
@@ -57,7 +58,9 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &
|
||||
full_window(fallback.focus)
|
||||
} else if !viewports {
|
||||
match layer(fallback) {
|
||||
(Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size)), exiting },
|
||||
(Some(fade), exiting) => {
|
||||
Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size, moving)), exiting }
|
||||
}
|
||||
(None, _) => closed(),
|
||||
}
|
||||
} else if open {
|
||||
@@ -196,12 +199,14 @@ struct LayerHost {
|
||||
fade: f32,
|
||||
/// The size the container measured for this pass.
|
||||
size: Vec2,
|
||||
/// The rect a running drag of the move band puts the layer at in this pass, in screen space.
|
||||
moving: Option<Rect>,
|
||||
dismissed: Option<CloseReason>,
|
||||
}
|
||||
|
||||
impl LayerHost {
|
||||
fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2) -> Self {
|
||||
LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, dismissed: None }
|
||||
fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2, moving: Option<Rect>) -> Self {
|
||||
LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, moving, dismissed: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,7 +232,7 @@ impl Host for LayerHost {
|
||||
overlay = mapped;
|
||||
}
|
||||
let screen = overlay::screen_for(&ctx, env, &overlay);
|
||||
let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, screen, env.tokens.space.inset.screen);
|
||||
let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, env.tokens.space.inset.screen);
|
||||
// An anchored resizable layer has no position to seed: its default size is held as its minimum until the
|
||||
// user resizes it.
|
||||
if overlay.fit == overlay::OverlayFit::Resizable
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(crate) use host::{Layer, forget_layer, host, host_window};
|
||||
pub(crate) use opener::{LayerFloor, anchor_floor};
|
||||
pub use opener::{Opener, Trigger};
|
||||
pub use place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare};
|
||||
pub use placement::PopupRegion;
|
||||
pub use placement::{PopupRegion, layer_room};
|
||||
pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for};
|
||||
pub(crate) use popups::dwell;
|
||||
pub use popups::{HOLD, Overlays, PopupHandle};
|
||||
|
||||
@@ -73,6 +73,27 @@ pub(super) fn dismissal(
|
||||
None
|
||||
}
|
||||
|
||||
/// The dismissal of a layer shown in the popup window `popup`, decided in its opener's pass, beside what the popup's
|
||||
/// own pass decides: a layer that closes on outside presses closes on one in the opener outside it and its anchor
|
||||
/// (absorbed or not, as its rule says), and on one in any other window of the app; a popup also closes once the app
|
||||
/// has no focus. An absorbing layer can't keep a press in another OS window from reaching that window.
|
||||
pub(super) fn popup_dismissal(
|
||||
ctx: &Context,
|
||||
layer: &Layer<'_>,
|
||||
rect: Rect,
|
||||
anchor: Rect,
|
||||
popup: egui::ViewportId,
|
||||
appears: bool,
|
||||
) -> Option<CloseReason> {
|
||||
let here = match layer.overlay.dismiss.outside {
|
||||
Outside::Keep => return None,
|
||||
Outside::Absorb => overlay::absorbed_press(ctx).is_some(),
|
||||
Outside::Close => press_outside(ctx, layer, rect, anchor),
|
||||
};
|
||||
let away = layer.overlay.rank == Rank::Popup && crate::runtime::windows::app_away(ctx);
|
||||
(here || away || crate::runtime::windows::pressed_elsewhere(ctx, popup, appears)).then_some(CloseReason::Outside)
|
||||
}
|
||||
|
||||
/// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it.
|
||||
fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool {
|
||||
let Some(press) = pointer::primary_press(ctx) else {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The overlay host: shows a layer on an egui layer, remembers it while shown and closes its family.
|
||||
|
||||
use super::dismissal::dismissal;
|
||||
use super::dismissal::{dismissal, popup_dismissal};
|
||||
use super::opener::{Opening, Trigger};
|
||||
use super::place::{OverlayFit, Place};
|
||||
use super::placement::{anchor_rect, opened_overlay, placement};
|
||||
@@ -13,6 +13,7 @@ use crate::runtime::layout_memory;
|
||||
use crate::runtime::memory::{MemoryStage, sub};
|
||||
use crate::runtime::motion::{self, Driver};
|
||||
use crate::runtime::overlay::{self, Backdrop, CloseReason, OpenEntry, Rank};
|
||||
use crate::runtime::windows::{self, PopupOpen, PopupRoom, WindowSpec};
|
||||
use craft_behavior::{MotionKind, Playback};
|
||||
use egui::{Context, Id, Pos2, Rect, Ui, Vec2};
|
||||
|
||||
@@ -90,6 +91,7 @@ pub(crate) fn forget_layer(ctx: &Context, id: Id, owner: Id) {
|
||||
if taken.is_some_and(|memory| !memory.family_closed) {
|
||||
overlay::close_descendants(ctx, id);
|
||||
}
|
||||
windows::close_popup(ctx, id);
|
||||
}
|
||||
|
||||
/// Asks the layers opened from inside `layer` to close once the layer closes or starts to fade out, in the pass that
|
||||
@@ -106,8 +108,14 @@ fn area_id(id: Id) -> Id {
|
||||
sub(id, "area")
|
||||
}
|
||||
|
||||
/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal.
|
||||
/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. A layer opened in a palette
|
||||
/// window shows in a popup window of its own ([`host_in_popup`]); a full-window layer covers its own window.
|
||||
pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut Ui)) -> LayerOut {
|
||||
if !layer.overlay.is_full_window()
|
||||
&& let Some(popup) = windows::popup_room(ctx)
|
||||
{
|
||||
return host_in_popup(ctx, layer, popup, body);
|
||||
}
|
||||
// A layer that appears starts with nothing it remembered while shown before, also when it opens again during its
|
||||
// exit fade or its host never saw it hide: the focus that was inside it does not close it as `focus_left`.
|
||||
let appears = overlay::appears(ctx, layer.id, layer.exiting);
|
||||
@@ -260,6 +268,150 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
|
||||
LayerOut { dismissed }
|
||||
}
|
||||
|
||||
/// A layer opened in a palette window, shown in a popup window of its own (`WindowSpec::popup`): placed in the
|
||||
/// opener's points within the work area around it, the window at that place in desktop points.
|
||||
///
|
||||
/// The layer's bookkeeping is split between the two windows. The popup's pass shows the layer at the window's origin
|
||||
/// and records it in the popup's stack, with its focus scope and the dismissal its own input decides (Escape, Enter,
|
||||
/// activations, focus, timeout). The opener's pass records an entry that stands for the window (`OpenEntry::popup`),
|
||||
/// so its family, its anchor and the presses in the opener are judged where they happen; a press in any other window
|
||||
/// of the app, and for a popup the app losing focus, close it too ([`popup_dismissal`]).
|
||||
///
|
||||
/// A layer whose size its container measured is placed before the window opens. A layer without one (a tooltip) is
|
||||
/// laid out in the popup's pass first, in the room its unplaced form has, and placed by the size it took there.
|
||||
/// A popup that takes keys (a menu, a flyout) takes the OS focus; a tooltip takes none and lets the pointer through.
|
||||
fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut dyn FnMut(&mut Ui)) -> LayerOut {
|
||||
let appears = overlay::appears(ctx, layer.id, layer.exiting);
|
||||
let mut memory = if appears { LayerMemory::default() } else { recall(layer, ctx) };
|
||||
let opened = opened_overlay(ctx, layer.overlay, memory.opening);
|
||||
if let Some((_, opening)) = &opened {
|
||||
memory.opening.get_or_insert(*opening);
|
||||
}
|
||||
// The popup window lies outside any region of the opener: the work area is its room.
|
||||
let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer };
|
||||
let overlay = layer.overlay;
|
||||
let bounds = popup.room;
|
||||
let anchor = anchor_rect(ctx, layer, bounds, &mut memory);
|
||||
let min_width = overlay.least_width(anchor.width());
|
||||
let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y));
|
||||
let unplaced = placement(ctx, layer, measured, bounds, anchor);
|
||||
let parent = overlay::drawing_parent(ctx);
|
||||
let tier = overlay::layer_tier(ctx, overlay.rank);
|
||||
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
|
||||
if overlay.rank.is_modal() && appears {
|
||||
overlay::close_popups_outside(ctx, &[layer.id]);
|
||||
}
|
||||
// The body reports in its parent's space: the popup's points are the opener's screen less the layer's place.
|
||||
let to_parent = overlay::parent_space(ctx, layer.id);
|
||||
let tooltip = overlay.rank == Rank::Tooltip;
|
||||
let spec = WindowSpec::popup().takes_focus(!tooltip && (scope.is_some() || overlay.rank.takes_keys())).passes_pointer(tooltip);
|
||||
let known = measured.map(|size| Rect::from_min_size(unplaced.at, size));
|
||||
let open = PopupOpen { id: layer.id, spec: &spec, rect: known.map(|rect| rect.translate(popup.origin.to_vec2())) };
|
||||
let mut shown = None;
|
||||
windows::show_popup(ctx, &open, |ui| {
|
||||
let at = unplaced.at.to_vec2();
|
||||
overlay::note_parent_space(ui.ctx(), layer.id, egui::emath::TSTransform::from_translation(-at) * to_parent);
|
||||
shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body));
|
||||
});
|
||||
let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None));
|
||||
let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) };
|
||||
let rect = Rect::from_min_size(placed.at, size);
|
||||
if known.is_none() {
|
||||
windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2()));
|
||||
}
|
||||
let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, rect, areas::layer_of(tier, area_id(layer.id)));
|
||||
entry.parent = parent;
|
||||
entry.anchor = matches!(overlay.place, Place::Anchored { .. }).then_some(anchor);
|
||||
entry.side = placed.side;
|
||||
entry.exiting = layer.exiting;
|
||||
entry.scoped = scope.is_some();
|
||||
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
|
||||
entry.window = true;
|
||||
entry.popup = true;
|
||||
overlay::record(ctx, entry);
|
||||
let viewport = crate::runtime::egui::viewports::viewport_id(layer.id);
|
||||
let dismissed = if layer.exiting { None } else { dismissed.or_else(|| popup_dismissal(ctx, layer, rect, anchor, viewport, appears)) };
|
||||
close_family(ctx, layer, layer.exiting || dismissed.is_some(), &mut memory);
|
||||
remember(layer, ctx, memory);
|
||||
LayerOut { dismissed }
|
||||
}
|
||||
|
||||
/// The popup window's pass of [`host_in_popup`]: the layer at the window's origin, offered the room `placed` leaves,
|
||||
/// its entry in the popup's stack and the dismissal the popup's own input decides. Returns the size the layer took
|
||||
/// and that dismissal.
|
||||
fn show_in_popup(
|
||||
ui: &mut Ui,
|
||||
layer: &Layer<'_>,
|
||||
placed: &super::placement::Placed,
|
||||
min_width: f32,
|
||||
scope: Option<FocusPolicy>,
|
||||
memory: &mut LayerMemory,
|
||||
body: &mut dyn FnMut(&mut Ui),
|
||||
) -> (Vec2, Option<CloseReason>) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let overlay = layer.overlay;
|
||||
let window = ctx.content_rect();
|
||||
let area = area_id(layer.id);
|
||||
let tier = overlay::layer_tier(&ctx, overlay.rank);
|
||||
let cover = match overlay.rank {
|
||||
Rank::Modal { backdrop } => {
|
||||
let scrim = match backdrop {
|
||||
Backdrop::Scrim => crate::style::scrim_color(&layer.env.tokens).gamma_multiply(layer.fade),
|
||||
Backdrop::None => egui::Color32::TRANSPARENT,
|
||||
};
|
||||
let cover_id = sub(layer.id, "cover");
|
||||
let through = crate::runtime::sampler::through(&ctx, crate::runtime::egui::pass::current_viewport(&ctx), layer.id);
|
||||
areas::show_cover_layer(&ctx, areas::CoverLayer { id: cover_id, tier, screen: window, scrim, through, absorbs: !layer.exiting });
|
||||
Some(areas::layer_of(tier, cover_id))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts.
|
||||
let opener = layer.env.capture().env();
|
||||
let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root));
|
||||
let mut spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None };
|
||||
// The layer's root node, made before its `Area` shows, as in `host`.
|
||||
if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) {
|
||||
spec.root = areas::content_rect(&ctx, &spec).map(|rect| access::report_layer(&ctx, layer.id, rect, layer.exiting));
|
||||
}
|
||||
overlay::begin_layer(&ctx, layer.id, tier, layer.exiting, placed.side);
|
||||
let shown = areas::show_layer(&ctx, &spec, |ui| {
|
||||
areas::fade(ui, layer.fade * overlay.opacity);
|
||||
let installed = Env::install_for(ui, env.clone());
|
||||
let real = !ui.is_sizing_pass();
|
||||
if spec.root.is_some() && layer.exiting {
|
||||
access::hide_exiting_content(&ctx, ui.unique_id());
|
||||
}
|
||||
// The focused stop the scope returns to is in the opener's window; the opener's window takes the OS focus
|
||||
// back when the popup closes (`windows::close_popup`).
|
||||
if real {
|
||||
let entering = !std::mem::replace(&mut memory.scope_entered, true);
|
||||
focus::push_scope_from(&ctx, layer.id, overlay.focus, None, None, layer.exiting, Some(entering));
|
||||
}
|
||||
areas::bound(ui, placed.room, min_width.min(placed.room.x));
|
||||
if overlay.fit == OverlayFit::Resizable {
|
||||
ui.set_min_size(overlay.size_limits.min.min(placed.room));
|
||||
}
|
||||
access::scope::outside(&ctx, || layout_memory::boundary(&ctx, true, || body(ui)));
|
||||
if real && overlay.rank.is_modal() {
|
||||
access::report_modal(&ctx, layer.id);
|
||||
}
|
||||
if real {
|
||||
focus::pop_scope(&ctx);
|
||||
}
|
||||
Env::restore(&ctx, installed);
|
||||
});
|
||||
overlay::end_layer(&ctx);
|
||||
let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, shown.rect, shown.layer);
|
||||
entry.side = placed.side;
|
||||
entry.exiting = layer.exiting;
|
||||
entry.cover = cover;
|
||||
entry.scoped = scope.is_some();
|
||||
overlay::record(&ctx, entry);
|
||||
let dismissed = if layer.exiting { None } else { dismissal(&ctx, layer, shown.rect, Rect::NOTHING, scope, memory) };
|
||||
(shown.rect.size(), dismissed)
|
||||
}
|
||||
|
||||
/// The motion slot of a layer's nudge, under the layer's id.
|
||||
// PLAN: the decision names a `NUDGE_SPEC`; `MotionSpec::new` (`runtime/motion.rs:39`) is a private `const fn` of a file outside this set, so
|
||||
// the nudge runs on `spec::OPEN_FADE` (a fade, which reduced motion still runs) over the open token's duration.
|
||||
|
||||
@@ -82,10 +82,16 @@ pub(crate) fn region_for(env: &Env, overlay: &Overlay) -> Option<Rect> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen rect a layer of `overlay` opened in `env` keeps inside: the safe rect, or the part of it a contained
|
||||
/// layer's region leaves.
|
||||
/// The room a layer opened in the running viewport may take, in its points: the work area around a palette window,
|
||||
/// whose layers show in popup windows of their own (`windows::popup_room`), else the window's safe rect.
|
||||
pub fn layer_room(ctx: &Context) -> Rect {
|
||||
crate::runtime::windows::popup_room(ctx).map_or_else(|| areas::safe_rect(ctx), |popup| popup.room)
|
||||
}
|
||||
|
||||
/// The screen rect a layer of `overlay` opened in `env` keeps inside: the layer room ([`layer_room`]), or the part
|
||||
/// of it a contained layer's region leaves.
|
||||
pub(crate) fn screen_for(ctx: &Context, env: &Env, overlay: &Overlay) -> Rect {
|
||||
let safe = areas::safe_rect(ctx);
|
||||
let safe = layer_room(ctx);
|
||||
region_for(env, overlay).map_or(safe, |region| region.intersect(safe))
|
||||
}
|
||||
|
||||
|
||||
@@ -76,10 +76,10 @@ impl<'a> OverlayUi<'a> {
|
||||
}
|
||||
|
||||
/// Keeps the popups this component shows from here on, and every popup opened from them, below the component:
|
||||
/// inside the safe rect less the part above the component's bottom edge. A menu bar's menus and their submenus
|
||||
/// inside the layer room less the part above the component's bottom edge. A menu bar's menus and their submenus
|
||||
/// never cover the bar.
|
||||
pub fn contain_popups_below(&mut self) {
|
||||
let safe = areas::safe_rect(self.ctx);
|
||||
let safe = super::layer_room(self.ctx);
|
||||
let top = (self.to_screen * self.anchor).bottom().clamp(safe.top(), safe.bottom());
|
||||
let region = Rect::from_min_max(egui::pos2(safe.left(), top), safe.max);
|
||||
self.env = self.env.derive(|scoped| {
|
||||
|
||||
@@ -1609,8 +1609,11 @@ fn extent_step(
|
||||
let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id);
|
||||
let env = begun.env();
|
||||
// A body root with parts steps its press machine before its measuring run, so the body reads this pass's part
|
||||
// presses in both runs (`BodyCx::part_press`). Step 8 finds the outcome. A member of another arena senses at step 8.
|
||||
if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && (t.arena() || facts.text() || env.arena.is_none()) {
|
||||
// presses in both runs (`BodyCx::part_press`) and its host reads them before it places the body. Step 8 finds the
|
||||
// outcome. A member of another arena senses at step 8. A root its host shows on a layer of its own (not in flow)
|
||||
// senses in its own arena: its steps 6 to 16 run in the layer's env, which is outside its opener's arena.
|
||||
let own_arena = t.arena() || facts.text() || env.arena.is_none() || !t.in_flow();
|
||||
if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && own_arena {
|
||||
sensing::sense_early(ctx, id, resolved.enabled);
|
||||
}
|
||||
let scx = steps::style_cx(ctx, &begun.env, &begun.step1);
|
||||
|
||||
@@ -546,6 +546,7 @@ pub(crate) fn show_container_taking<C: Container, R>(
|
||||
body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
) -> Inner<C::Output, R> {
|
||||
let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None);
|
||||
crate::layout::close_flow_start_in(ui);
|
||||
crate::runtime::egui::alloc::advance_past(ui, rect);
|
||||
shown
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_>
|
||||
placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect)));
|
||||
}
|
||||
let whole = flow.to_physical(Rect::from_min_size(room.min, taken));
|
||||
super::close_flow_start_in(ui);
|
||||
alloc::advance_past(ui, whole);
|
||||
whole
|
||||
}
|
||||
|
||||
@@ -211,6 +211,79 @@ fn report_first_line(ctx: &egui::Context, target: Id, at: Option<f32>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The bodies whose flow has placed nothing yet in the sweep or run under way, by body id, each with whether a rule
|
||||
/// precedes the body's start (`Scoped::after_rule`).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FlowStarts(IdMap<bool>);
|
||||
|
||||
/// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed
|
||||
/// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`);
|
||||
/// `None` once a child took room there, and outside a body.
|
||||
pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option<bool> {
|
||||
let body = env.flow_body?;
|
||||
pass_state::with::<FlowStarts, _>(ctx, |starts| starts.0.get(&body).copied())
|
||||
}
|
||||
|
||||
/// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`).
|
||||
pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool {
|
||||
flow_start(ctx, env).is_some()
|
||||
}
|
||||
|
||||
/// A child took room in the flow of the body that places the children under `env`: its flow start closes.
|
||||
pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) {
|
||||
if let Some(body) = env.flow_body {
|
||||
pass_state::with::<FlowStarts, _>(ctx, |starts| starts.0.remove(&body));
|
||||
}
|
||||
}
|
||||
|
||||
/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`.
|
||||
pub(crate) fn close_flow_start_in(ui: &Ui) {
|
||||
close_flow_start(ui.ctx(), &Env::of(ui));
|
||||
}
|
||||
|
||||
/// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or
|
||||
/// run under way, and the rect of the row's last child in flow, by the row's layout id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Brackets(IdMap<BracketTook>);
|
||||
|
||||
/// The controls of a bracket's rows and the child after them.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct BracketTook {
|
||||
/// The centre line of the first row's control.
|
||||
pub(crate) first: Option<f32>,
|
||||
/// The centre line of the last row's control.
|
||||
pub(crate) last: Option<f32>,
|
||||
/// How far the rows' controls reach toward the row's end edge, at most: right, or left under right-to-left.
|
||||
pub(crate) end: Option<f32>,
|
||||
/// The rect of the row's last child placed in flow: the control in the bracket's middle.
|
||||
pub(crate) middle: Option<Rect>,
|
||||
}
|
||||
|
||||
impl BracketTook {
|
||||
/// The centre line between the first and the last row's controls, once two rows reported.
|
||||
pub(crate) fn centre(&self) -> Option<f32> {
|
||||
self.first.zip(self.last).filter(|(first, last)| last > first).map(|(first, last)| (first + last) / 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports the `control` rect of a labelled row to the bracketed row `row`, its end edge `rtl`-aware.
|
||||
pub(crate) fn report_bracket_control(ctx: &egui::Context, row: Id, control: Rect, rtl: bool) {
|
||||
pass_state::with::<Brackets, _>(ctx, |brackets| {
|
||||
if let Some(took) = brackets.0.get_mut(&row) {
|
||||
let centre = control.center().y;
|
||||
took.first.get_or_insert(centre);
|
||||
took.last = Some(centre);
|
||||
let end = if rtl { -control.min.x } else { control.max.x };
|
||||
took.end = Some(took.end.map_or(end, |was: f32| was.max(end)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// What the rows of the bracketed row `row` reported in the run that just ended; `None` outside a bracketed row.
|
||||
pub(crate) fn take_bracket(ctx: &egui::Context, row: Id) -> Option<BracketTook> {
|
||||
pass_state::with::<Brackets, _>(ctx, |brackets| brackets.0.remove(&row))
|
||||
}
|
||||
|
||||
/// How a child that fills the main axis of the body it sits in sizes along it.
|
||||
enum MainFill {
|
||||
/// The body is being measured: the child takes no room along the axis and is counted.
|
||||
@@ -1115,9 +1188,16 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect {
|
||||
let env = Env::of(ui);
|
||||
let (line, target) = (env.row_line, env.first_line);
|
||||
let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child };
|
||||
let above = line.and_then(|line| line.centre).zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0));
|
||||
// A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its
|
||||
// rows reported before it.
|
||||
let bracket = line.filter(|line| env.bracket == Some(line.body)).and_then(|line| {
|
||||
let took = pass_state::with::<Brackets, _>(ui.ctx(), |brackets| brackets.0.get(&line.body).copied())?;
|
||||
Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top())))
|
||||
});
|
||||
let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre));
|
||||
let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0));
|
||||
let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y)));
|
||||
let (rect, in_cell) = take_in(ui, env.grid, slot);
|
||||
let (rect, in_cell) = take_in(ui, &env, slot);
|
||||
let placed = if child.fill && in_cell {
|
||||
rect
|
||||
} else {
|
||||
@@ -1130,6 +1210,9 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect {
|
||||
};
|
||||
Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below))
|
||||
};
|
||||
if let Some((row, _)) = bracket {
|
||||
pass_state::with::<Brackets, _>(ui.ctx(), |brackets| brackets.0.get_mut(&row).map(|took| took.middle = Some(placed)));
|
||||
}
|
||||
if measure::active(ui.ctx()) {
|
||||
if let Some(line) = line {
|
||||
pass_state::with::<RowLines, _>(ui.ctx(), |rows| {
|
||||
@@ -1148,7 +1231,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect {
|
||||
/// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the
|
||||
/// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell.
|
||||
pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) {
|
||||
take_in(ui, Env::of(ui).grid, size)
|
||||
take_in(ui, &Env::of(ui), size)
|
||||
}
|
||||
|
||||
/// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it.
|
||||
@@ -1158,13 +1241,15 @@ pub fn empty_cell(ui: &mut Ui) {
|
||||
let env = Env::of(ui);
|
||||
let grid = env.grid.filter(|body| pass_state::with::<Cursors, _>(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_)))));
|
||||
if grid.is_some() {
|
||||
take_in(ui, grid, Vec2::ZERO);
|
||||
take_in(ui, &env, Vec2::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
/// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself.
|
||||
fn take_in(ui: &mut Ui, grid: Option<Id>, size: Vec2) -> (Rect, bool) {
|
||||
match cell_in(ui, grid, size) {
|
||||
/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start
|
||||
/// closes.
|
||||
fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) {
|
||||
close_flow_start(ui.ctx(), env);
|
||||
match cell_in(ui, env.grid, size) {
|
||||
Some(cell) => (cell, true),
|
||||
None => (alloc::space(ui, size), false),
|
||||
}
|
||||
@@ -1173,7 +1258,12 @@ fn take_in(ui: &mut Ui, grid: Option<Id>, size: Vec2) -> (Rect, bool) {
|
||||
/// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns
|
||||
/// it; `None`, taking nothing, outside such a body.
|
||||
pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option<Rect> {
|
||||
cell_in(ui, Env::of(ui).grid, size)
|
||||
let env = Env::of(ui);
|
||||
let cell = cell_in(ui, env.grid, size);
|
||||
if cell.is_some() {
|
||||
close_flow_start(ui.ctx(), &env);
|
||||
}
|
||||
cell
|
||||
}
|
||||
|
||||
fn cell_in(ui: &mut Ui, grid: Option<Id>, size: Vec2) -> Option<Rect> {
|
||||
@@ -1324,6 +1414,7 @@ fn run_grid<R>(
|
||||
scoped.derive_local(|scoped| {
|
||||
scoped.grid = Some(id);
|
||||
scoped.grid_top = cells == CellAlign::Top;
|
||||
scoped.flow_body = Some(id);
|
||||
}),
|
||||
);
|
||||
let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body);
|
||||
@@ -1598,8 +1689,14 @@ pub(crate) fn run_body_measured<R>(
|
||||
// Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh.
|
||||
let target = env.first_line.filter(|_| sizing);
|
||||
let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id);
|
||||
// Each sweep and the real run start the body's flow, and a bracketed row's reports, afresh.
|
||||
let (after_rule, bracket) = (env.after_rule, env.bracket == Some(id));
|
||||
let body = |ui: &mut Ui| {
|
||||
open_sweep(&ctx, target, row);
|
||||
pass_state::with::<FlowStarts, _>(&ctx, |starts| starts.0.insert(id, after_rule));
|
||||
if bracket {
|
||||
pass_state::with::<Brackets, _>(&ctx, |brackets| brackets.0.insert(id, BracketTook::default()));
|
||||
}
|
||||
body(ui)
|
||||
};
|
||||
// Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack.
|
||||
@@ -1627,7 +1724,10 @@ struct RowIn {
|
||||
/// A `Stack` body: each leaf shows at most the stack's room, never below its least.
|
||||
fn run_stack<R>(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> R) -> R {
|
||||
let ctx = ui.ctx().clone();
|
||||
let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit));
|
||||
let env = env.derive_local(|scoped| {
|
||||
scoped.shrink = Some(Shrink::Fit);
|
||||
scoped.flow_body = Some(at.id);
|
||||
});
|
||||
let installed = Env::install_for(ui, env.clone());
|
||||
// A held child of a column whose own room is unbounded keeps the width it measured at.
|
||||
let inner = if env.content_column && flow_room(ui).x.is_finite() {
|
||||
@@ -1652,6 +1752,7 @@ fn run_spread_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m
|
||||
scoped.grid_top = false;
|
||||
scoped.row_line = Some(line);
|
||||
scoped.first_line = None;
|
||||
scoped.flow_body = Some(id);
|
||||
}),
|
||||
);
|
||||
let inner = run_spread(ui, id, gap.x, rtl, &mut body);
|
||||
@@ -1675,6 +1776,7 @@ fn run_start_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu
|
||||
scoped.row_room = Some(room.width());
|
||||
scoped.row_line = Some(line);
|
||||
scoped.first_line = None;
|
||||
scoped.flow_body = Some(id);
|
||||
}),
|
||||
);
|
||||
let inner = run_shrinking(ui, id, &mut body);
|
||||
@@ -1724,6 +1826,7 @@ fn run_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
|
||||
env.derive_local(|scoped| {
|
||||
scoped.row_room = Some(room.width());
|
||||
scoped.row_line = line;
|
||||
scoped.flow_body = Some(id);
|
||||
if line.is_some() {
|
||||
scoped.first_line = None;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ pub use body::place_in_flow;
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) use body::run_body;
|
||||
pub(crate) use body::{
|
||||
InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, in_grid_content_column,
|
||||
leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured,
|
||||
shares_y, shrink_cap, take_cell, take_in_flow, view_room,
|
||||
BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region,
|
||||
flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control,
|
||||
report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow,
|
||||
view_room,
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::runtime::egui::memory;
|
||||
use crate::runtime::egui::text_layout;
|
||||
pub use crate::style::Span;
|
||||
use crate::style::text_measure::{paragraph_job, span_format};
|
||||
use crate::style::{StyleColor, TypeRole, UiTokens};
|
||||
use crate::style::{LetterCase, StyleColor, TypeRole, UiTokens};
|
||||
use craft_i18n::Direction;
|
||||
use egui::epaint::text::FontCacheRevision;
|
||||
use egui::text::{LayoutJob, TextWrapping};
|
||||
@@ -118,6 +118,11 @@ impl<'a> TextRun<'a> {
|
||||
/// Sets the type role.
|
||||
pub fn role(mut self, role: TypeRole) -> Self {
|
||||
self.role = role;
|
||||
if role.letter_case() == LetterCase::Upper {
|
||||
for span in &mut self.spans {
|
||||
span.text = Cow::Owned(span.text.to_uppercase());
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,12 @@ pub(crate) struct Spec<'a> {
|
||||
pub resizable: bool,
|
||||
/// Whether the window has a taskbar or Dock entry.
|
||||
pub taskbar: bool,
|
||||
/// Whether the window opens hidden; [`show`] reveals it.
|
||||
/// Whether the window opens hidden; [`set_visible`] reveals it.
|
||||
pub hidden: bool,
|
||||
/// Whether the window takes OS focus when it opens.
|
||||
pub active: bool,
|
||||
/// Whether pointer input passes through the window.
|
||||
pub passes_pointer: bool,
|
||||
/// The app id the OS window carries (dock icon, Wayland compositor rules); empty carries none.
|
||||
pub app_id: &'a str,
|
||||
}
|
||||
@@ -48,6 +52,12 @@ pub(crate) fn show_immediate<T>(ctx: &Context, id: ViewportId, spec: &Spec<'_>,
|
||||
if spec.hidden {
|
||||
builder = builder.with_visible(false);
|
||||
}
|
||||
if !spec.active {
|
||||
builder = builder.with_active(false);
|
||||
}
|
||||
if spec.passes_pointer {
|
||||
builder = builder.with_mouse_passthrough(true);
|
||||
}
|
||||
if !spec.app_id.is_empty() {
|
||||
builder = builder.with_app_id(spec.app_id);
|
||||
}
|
||||
@@ -74,9 +84,9 @@ pub(crate) fn show_immediate<T>(ctx: &Context, id: ViewportId, spec: &Spec<'_>,
|
||||
ctx.show_viewport_immediate(id, builder, |ui, _| body(ui))
|
||||
}
|
||||
|
||||
/// Makes the hidden viewport `id` visible.
|
||||
pub(crate) fn show(ctx: &Context, id: ViewportId) {
|
||||
ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(true));
|
||||
/// Shows or hides the window of viewport `id`.
|
||||
pub(crate) fn set_visible(ctx: &Context, id: ViewportId, visible: bool) {
|
||||
ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(visible));
|
||||
}
|
||||
|
||||
/// The viewport id of the container `id`.
|
||||
@@ -168,6 +178,16 @@ pub(crate) fn raise(ctx: &Context, viewport: ViewportId) {
|
||||
ctx.request_repaint_of(viewport);
|
||||
}
|
||||
|
||||
/// Brings `viewport`'s window in front of the app's other windows without giving it focus, by standing it above every
|
||||
/// window and then back at `level`, its own level. egui-winit ignores `Focus` for a window that has focus, and the
|
||||
/// window holding a modal usually has it; on Windows the level change also puts the window in front of the ordinary
|
||||
/// windows that were made ordinary before it. A Wayland compositor gives clients no stacking control.
|
||||
pub(crate) fn raise_above(ctx: &Context, viewport: ViewportId, level: WindowLevel) {
|
||||
command(ctx, viewport, ViewportCommand::WindowLevel(WindowLevel::AlwaysOnTop));
|
||||
command(ctx, viewport, ViewportCommand::WindowLevel(level));
|
||||
ctx.request_repaint_of(viewport);
|
||||
}
|
||||
|
||||
/// Cancels an OS close request of the running viewport so the owner can decide.
|
||||
pub(crate) fn cancel_close(ctx: &Context) {
|
||||
ctx.send_viewport_cmd(ViewportCommand::CancelClose);
|
||||
|
||||
@@ -138,6 +138,18 @@ pub struct Scoped {
|
||||
/// Where the first child the scope places in flow reports its first line: a container's header or body
|
||||
/// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself.
|
||||
pub(crate) first_line: Option<Id>,
|
||||
/// The body whose flow places the scope's direct children: the flow start a child reads (`layout::flow_start`)
|
||||
/// and the one a child placed in flow closes.
|
||||
pub(crate) flow_body: Option<Id>,
|
||||
/// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws
|
||||
/// nothing of its own and itself follows one. The body's layout opens its flow start with it.
|
||||
pub(crate) after_rule: bool,
|
||||
/// The body is an unwrapped `Row` placed from its start whose container is a row of a vertical flow: its first
|
||||
/// child in flow starts where the rows of that flow start (`label::in_column`).
|
||||
pub(crate) column_row: bool,
|
||||
/// The layout of the bracketed `Row` body (`ContainerProps::bracket`) whose labelled rows report their controls to
|
||||
/// it: set for the row's body and kept through the containers inside it up to a labelled one.
|
||||
pub(crate) bracket: Option<Id>,
|
||||
/// The container whose footer stands in its body (`FooterPlace::Body`) and the size that footer measured: a
|
||||
/// `FooterSlot` shown under it takes that size and is where the footer is drawn.
|
||||
pub(crate) footer_slot: Option<FooterSlotOf>,
|
||||
@@ -358,6 +370,7 @@ impl Scoped {
|
||||
/// layer is no line of a bar it was opened from. A layer's content measures and runs in this.
|
||||
pub(crate) fn start_layer(&mut self) {
|
||||
self.start_room();
|
||||
self.bracket = None;
|
||||
self.measure = None;
|
||||
self.arena = None;
|
||||
self.roving = None;
|
||||
@@ -387,6 +400,8 @@ impl Scoped {
|
||||
self.row_room = None;
|
||||
self.row_line = None;
|
||||
self.first_line = None;
|
||||
self.flow_body = None;
|
||||
self.column_row = false;
|
||||
self.fill_body = None;
|
||||
self.fill_share = None;
|
||||
self.shrink = None;
|
||||
@@ -568,6 +583,10 @@ impl Env {
|
||||
row_room: None,
|
||||
row_line: None,
|
||||
first_line: None,
|
||||
flow_body: None,
|
||||
after_rule: false,
|
||||
column_row: false,
|
||||
bracket: None,
|
||||
footer_slot: None,
|
||||
fill_body: None,
|
||||
fill_share: None,
|
||||
@@ -657,6 +676,7 @@ impl Env {
|
||||
pub(crate) fn new_room(&self) -> Env {
|
||||
self.derive_local(|scoped| {
|
||||
scoped.start_room();
|
||||
scoped.bracket = None;
|
||||
scoped.lazy = None;
|
||||
scoped.measure = None;
|
||||
// A pane opened from a bar is not the bar's line.
|
||||
|
||||
@@ -197,6 +197,13 @@ pub struct Stamped<T> {
|
||||
value: T,
|
||||
}
|
||||
|
||||
impl<T> Stamped<T> {
|
||||
/// The record as its viewport's latest pass left it.
|
||||
pub(crate) fn value(&self) -> &T {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Default> PerViewport<T> {
|
||||
fn record(&mut self, viewport: ViewportId) -> &mut T {
|
||||
let at = match self.records.iter().position(|(id, _)| *id == viewport) {
|
||||
@@ -257,6 +264,11 @@ impl<T: Stored> PerViewport<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on the record of `viewport` when it has one; creates none.
|
||||
pub(crate) fn with_existing<R>(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut T) -> R) -> Option<R> {
|
||||
T::records(ctx, |records| records.records.iter_mut().find(|(id, _)| *id == viewport).map(|(_, record)| f(record)))
|
||||
}
|
||||
|
||||
/// Runs `f` on the record of every viewport that has one.
|
||||
pub(crate) fn each(ctx: &Context, mut f: impl FnMut(&mut T)) {
|
||||
T::records(ctx, |records| records.records.iter_mut().for_each(|(_, record)| f(record)));
|
||||
|
||||
@@ -1239,6 +1239,11 @@ pub(crate) mod guard {
|
||||
("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"),
|
||||
("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"),
|
||||
("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"),
|
||||
(
|
||||
"layout::body::FlowStarts",
|
||||
"flow starts: opened by each sweep of the body and closed by its first child in flow; a child reads its body's at its own start, and its measure key holds what it read",
|
||||
),
|
||||
("layout::body::Brackets", "bracket reports: opened by each sweep of the bracketed row and taken after its body"),
|
||||
("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"),
|
||||
("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"),
|
||||
("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"),
|
||||
|
||||
@@ -76,7 +76,7 @@ impl Rank {
|
||||
|
||||
/// Whether a layer of this rank takes keys without a focus scope. Modal chrome takes none: Cancel and Enter stay
|
||||
/// with the modal under it.
|
||||
const fn takes_keys(self) -> bool {
|
||||
pub(crate) const fn takes_keys(self) -> bool {
|
||||
matches!(self, Rank::Popup | Rank::Modal { .. })
|
||||
}
|
||||
|
||||
@@ -153,6 +153,10 @@ pub struct OpenEntry {
|
||||
/// The entry is an OS window of the integration: it takes its place in the stack's order and facts, and no egui
|
||||
/// layer is shown for it.
|
||||
pub(crate) window: bool,
|
||||
/// The entry stands in its opener's stack for a layer shown in a popup window of its own (with `window`): the
|
||||
/// family, the anchor and the presses in the opener's window are judged here, and the popup's own stack holds the
|
||||
/// layer, so the entry blocks nothing here.
|
||||
pub(crate) popup: bool,
|
||||
/// The screen rect the layer is contained in: its scrim, placement, clip and input blocking stop at it.
|
||||
pub(crate) region: Option<Rect>,
|
||||
/// The layer's place on its dialog stack (`stack_place`): the modal families of one stack stack in its order.
|
||||
@@ -202,6 +206,7 @@ impl OpenEntry {
|
||||
scoped: false,
|
||||
absorbs: false,
|
||||
window: false,
|
||||
popup: false,
|
||||
region: None,
|
||||
place: None,
|
||||
dialog: None,
|
||||
@@ -211,7 +216,7 @@ impl OpenEntry {
|
||||
/// Whether the layer is a modal over its whole window: a modal contained in a region blocks only inside it, and the
|
||||
/// window's keys, commands and hits stay with the rest.
|
||||
pub(crate) fn blocks_window(&self) -> bool {
|
||||
self.rank.is_modal() && self.region.is_none()
|
||||
self.rank.is_modal() && self.region.is_none() && !self.popup
|
||||
}
|
||||
|
||||
/// Whether the layer takes keys: the layers `top` can name. A layer with a focus scope takes keys whatever its rank.
|
||||
@@ -560,11 +565,38 @@ pub fn opening(ctx: &Context, id: Id) -> bool {
|
||||
/// not outlive it. The closes are carried: with no motion the layer's body hides in the same frame, so the owner of
|
||||
/// a popup in it runs again only when the layer reopens, and takes the close then.
|
||||
pub(crate) fn close_descendants(ctx: &Context, id: Id) {
|
||||
for descendant in family(ctx, id).into_iter().filter(|member| *member != id) {
|
||||
let mut members: Vec<Id> = family(ctx, id).into_vec();
|
||||
// A member shown in a popup window keeps the layers opened from inside it in that window's stack.
|
||||
let mut at = 0;
|
||||
while at < members.len() {
|
||||
let member = members[at];
|
||||
for inner in family_in(ctx, crate::runtime::egui::viewports::viewport_id(member), member) {
|
||||
if !members.contains(&inner) {
|
||||
members.push(inner);
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
for descendant in members.into_iter().filter(|member| *member != id) {
|
||||
push_close(ctx, descendant, CloseReason::Requested, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// `id` and everything opened from inside it, as `viewport`'s latest pass showed them (a popup window's: its pass of
|
||||
/// this frame, or its last one once it is no longer shown); none for a viewport that has no stack.
|
||||
fn family_in(ctx: &Context, viewport: ViewportId, id: Id) -> Vec<Id> {
|
||||
let Some(last) = PerViewport::<Stamped<Pass>>::with_existing(ctx, viewport, |pass| pass.value().current.clone()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out: Vec<Id> = last.iter().filter(|entry| entry.id == id).map(|entry| entry.id).collect();
|
||||
for entry in &last {
|
||||
if entry.parent.is_some_and(|parent| out.contains(&parent)) && !out.contains(&entry.id) {
|
||||
out.push(entry.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Records that a primary press landed outside the layer `id`, its anchor and its family in this pass.
|
||||
pub(crate) fn note_pressed_outside(ctx: &Context, id: Id) {
|
||||
with_pass(ctx, |pass| pass.pressed_outside.push(id));
|
||||
@@ -853,7 +885,7 @@ pub(crate) fn end_pass(ctx: &Context) {
|
||||
}
|
||||
|
||||
fn modal_in_other_viewports(ctx: &Context, running: ViewportId) -> bool {
|
||||
pass::live_viewports(ctx).into_iter().filter(|viewport| *viewport != running).any(|viewport| with_persist(ctx, viewport, |persist| persist.modal))
|
||||
modal_viewport(ctx, running).is_some()
|
||||
}
|
||||
|
||||
/// Whether a modal layer is open in a viewport other than `viewport`: the global open-modal fact the input hook
|
||||
@@ -929,9 +961,19 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option<Id>) {
|
||||
(root.is_some() || modal_in_other_viewports(ctx, viewport), root)
|
||||
}
|
||||
|
||||
/// The live viewports with a modal layer open as of their last finished pass.
|
||||
fn modal_viewports(ctx: &Context) -> impl Iterator<Item = ViewportId> + '_ {
|
||||
pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal))
|
||||
}
|
||||
|
||||
/// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises.
|
||||
pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option<ViewportId> {
|
||||
pass::live_viewports(ctx).into_iter().filter(|other| *other != viewport).find(|other| with_persist(ctx, *other, |persist| persist.modal))
|
||||
modal_viewports(ctx).find(|other| *other != viewport)
|
||||
}
|
||||
|
||||
/// A viewport that has a modal layer open: the window that blocks the app's other windows.
|
||||
pub(crate) fn app_modal_viewport(ctx: &Context) -> Option<ViewportId> {
|
||||
modal_viewports(ctx).next()
|
||||
}
|
||||
|
||||
/// Whether a layer of key class `class` that is not fading out was shown last frame and the screen point `at` lies in
|
||||
|
||||
@@ -96,6 +96,8 @@ pass_state! {
|
||||
held_widths: crate::layout::body::HeldWidths,
|
||||
first_lines: crate::layout::body::FirstLines,
|
||||
row_lines: crate::layout::body::RowLines,
|
||||
flow_starts: crate::layout::body::FlowStarts,
|
||||
brackets: crate::layout::body::Brackets,
|
||||
cursors: crate::layout::body::Cursors,
|
||||
footer_slots: crate::contract::footer_slot::Slots,
|
||||
column_groups: crate::layout::column_group::Open,
|
||||
|
||||
@@ -48,9 +48,9 @@ pub use shell::shell_of;
|
||||
use shell::{refresh, window_info};
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) use shell::{set_chrome, set_os};
|
||||
use spec::chrome_of;
|
||||
use spec::{AppState, chrome_of};
|
||||
pub use spec::{WindowLevel, WindowSpec};
|
||||
pub(crate) use viewport::{ViewportOpen, show_viewport, take_close_request, unplaced};
|
||||
pub(crate) use viewport::{PopupOpen, ViewportOpen, close_popup, place_popup, show_popup, show_viewport, take_close_request, unplaced};
|
||||
|
||||
/// Seconds between writes of a changed placement store.
|
||||
const FLUSH_SECONDS: f64 = 1.0;
|
||||
@@ -86,11 +86,17 @@ pub(crate) struct Shared {
|
||||
desktop: Option<Desktop>,
|
||||
/// Whether the root window had focus in the last root pass.
|
||||
root_focused: bool,
|
||||
/// Whether no window of the app had focus when the last frame's windows had all reported.
|
||||
away: bool,
|
||||
/// The app's state when the last frame's windows had all reported, which its palettes follow.
|
||||
app: AppState,
|
||||
/// Whether a palette window stood lowered under an app-modal layer in this frame.
|
||||
lowered: bool,
|
||||
/// Where the raise of the modal's window above the palettes it lowered stands.
|
||||
raise: Raise,
|
||||
/// The app's windows from the one focused longest ago to the one focused last: the stacking order of
|
||||
/// overlapping windows.
|
||||
stacking: Vec<ViewportId>,
|
||||
/// The windows that got a primary press, each with the root frame of the press, in this root frame and the last.
|
||||
presses: Vec<(ViewportId, u64)>,
|
||||
}
|
||||
|
||||
/// One viewport's window record.
|
||||
@@ -105,8 +111,10 @@ pub(crate) struct Record {
|
||||
chrome: Option<WindowChrome>,
|
||||
/// The caption buttons the app draws in this window.
|
||||
captions: Option<Captions>,
|
||||
/// The level the window was opened with or last set to; a palette's egui level follows the app's activity.
|
||||
/// The level the window was opened with or last set to; a palette's egui level follows the app's state.
|
||||
level: Option<WindowLevel>,
|
||||
/// Whether the window is hidden because the app's state hides it (a palette while the main window is minimized).
|
||||
hidden: bool,
|
||||
/// H4: whether the primary button is down as the viewport's events left the input hook.
|
||||
primary_down: bool,
|
||||
/// Whether the user can resize the window; unknown for a window not opened by `show_viewport`.
|
||||
@@ -146,6 +154,22 @@ pub(crate) struct Record {
|
||||
seen: Option<Rect>,
|
||||
/// The smallest inner size its caller asks for, as the window's builder carries it.
|
||||
min_size: Option<Vec2>,
|
||||
/// For a popup window ([`show_popup`]): the window its layer was opened from, while the layer shows.
|
||||
opener: Option<ViewportId>,
|
||||
}
|
||||
|
||||
/// The raise of the window holding an app-modal layer above the palettes the modal lowered. The raise goes out in the
|
||||
/// frame after a palette was built lowered: a raise in the same frame may reach the OS before the palette's new level
|
||||
/// does, and the palette, made an ordinary window after it, would stand in front again.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum Raise {
|
||||
/// No palette has stood lowered under the open modal yet, or no modal is open.
|
||||
#[default]
|
||||
Waiting,
|
||||
/// A palette stood lowered in the last frame: the modal's window is raised in this one.
|
||||
Due,
|
||||
/// The modal's window was raised.
|
||||
Done,
|
||||
}
|
||||
|
||||
/// Passes between searches for an OS window that was not found.
|
||||
@@ -294,6 +318,15 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool {
|
||||
if handed_off && tracked == Some(viewport) {
|
||||
shared(ctx, |shared| shared.tracked_move = None);
|
||||
}
|
||||
let pressed =
|
||||
input.events.iter().any(|event| matches!(event, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. }));
|
||||
if pressed {
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
shared(ctx, |shared| {
|
||||
shared.presses.retain(|(_, at)| at + 1 >= frame);
|
||||
shared.presses.push((viewport, frame));
|
||||
});
|
||||
}
|
||||
released
|
||||
}
|
||||
|
||||
@@ -350,6 +383,73 @@ fn opens_over(ctx: &Context, opener: ViewportId) -> bool {
|
||||
!covers
|
||||
}
|
||||
|
||||
/// Where the layers opened in a palette window show: in popup windows of their own, placed in desktop points.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct PopupRoom {
|
||||
/// The palette window's inner top-left corner in desktop points: the origin of its viewport's points.
|
||||
pub origin: Pos2,
|
||||
/// The room its layers may take, in its viewport's points: the work area of the monitor the window is on, or where
|
||||
/// no monitor is listed, the area the app's windows other than popups span.
|
||||
pub room: Rect,
|
||||
}
|
||||
|
||||
/// The room of the layers opened in the running viewport when it is a palette window (a dock window or a popup
|
||||
/// window, both at [`WindowLevel::Palette`]) that opens OS windows ([`opens_over`]) where the platform places them:
|
||||
/// every such layer shows in a popup window of its own. `None` in every other window, whose layers stay in it.
|
||||
pub(crate) fn popup_room(ctx: &Context) -> Option<PopupRoom> {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
if !base_shell(ctx).window_positions() || !opens_over(ctx, viewport) {
|
||||
return None;
|
||||
}
|
||||
let facts = PerViewport::<Record>::with_existing(ctx, viewport, |record| record.facts.filter(|_| record.level == Some(WindowLevel::Palette)))??;
|
||||
let origin = facts.inner?.min;
|
||||
let scale = host::scale_of(ctx, &facts).unwrap_or(1.0).max(f32::EPSILON);
|
||||
let work = host::monitor_of(ctx, &facts).map(|monitor| {
|
||||
let (pos, size) = monitor.work_px.unwrap_or((monitor.pos_px, monitor.size_px));
|
||||
let min = Pos2::new(pos[0] as f32, pos[1] as f32) / scale;
|
||||
Rect::from_min_size(min, Vec2::new(size[0] as f32, size[1] as f32) / scale)
|
||||
});
|
||||
// The popup windows themselves don't count: a popup's room never depends on where a popup stands.
|
||||
let spanned = || {
|
||||
let popup = |viewport: ViewportId| PerViewport::<Record>::with_existing(ctx, viewport, |record| record.opener.is_some()).unwrap_or(false);
|
||||
viewports::reported(ctx)
|
||||
.iter()
|
||||
.filter(|(viewport, _)| !popup(*viewport))
|
||||
.filter_map(|(_, facts)| facts.inner)
|
||||
.fold(Rect::NOTHING, Rect::union)
|
||||
};
|
||||
let room = work.unwrap_or_else(spanned).translate(-origin.to_vec2());
|
||||
Some(PopupRoom { origin, room })
|
||||
}
|
||||
|
||||
/// Whether a primary press landed, in this root frame (or in the last one, unless the popup window `popup` just
|
||||
/// `appeared`), in a window of the app other than the running viewport (the popup's opener, whose own presses its
|
||||
/// layer stack judges) and the popup window and the popup windows opened from it.
|
||||
pub(crate) fn pressed_elsewhere(ctx: &Context, popup: ViewportId, appeared: bool) -> bool {
|
||||
let opener = pass::current_viewport(ctx);
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let presses = shared(ctx, |shared| shared.presses.clone());
|
||||
presses.into_iter().filter(|(_, at)| *at == frame || (!appeared && at + 1 == frame)).any(|(viewport, _)| {
|
||||
if viewport == opener {
|
||||
return false;
|
||||
}
|
||||
// A press in a popup window opened from the popup, at any depth, is inside its family.
|
||||
let mut at = Some(viewport);
|
||||
while let Some(window) = at {
|
||||
if window == popup {
|
||||
return false;
|
||||
}
|
||||
at = PerViewport::<Record>::with_existing(ctx, window, |record| record.opener).flatten();
|
||||
}
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether no window of the app has focus, as the last frame's windows reported.
|
||||
pub(crate) fn app_away(ctx: &Context) -> bool {
|
||||
shared(ctx, |shared| shared.app.away)
|
||||
}
|
||||
|
||||
/// Refuses the close request of the running viewport while an app-modal layer blocks it, and raises the modal's
|
||||
/// window. True when it refused.
|
||||
fn refuse_close_under_modal(ctx: &Context) -> bool {
|
||||
@@ -465,12 +565,14 @@ fn flush_store(ctx: &Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the app's activity and the stacking order of its windows current from the windows' focus. A palette's
|
||||
/// window level follows the activity: the mounts build their viewports with the level of the moment, and a change
|
||||
/// Keeps the app's state and the stacking order of its windows current from the windows' facts. A palette's window
|
||||
/// level and visibility follow the state: the mounts build their viewports with the state of the moment, and a change
|
||||
/// asks for the next frame. Runs at the end of the root pass, inside which every child window's pass of the frame
|
||||
/// has run, so each window's focus is the one its own pass reported after its input batch. The root input's list of
|
||||
/// windows holds each child as of its previous pass, so it is not read for focus. The app is inactive when no
|
||||
/// window reports focus: the batch that took focus from one window gave it to no other.
|
||||
///
|
||||
/// Once a palette has stood lowered under an app-modal layer, the modal's window is raised above it, once per modal.
|
||||
fn follow_activity(ctx: &Context) {
|
||||
let windows = viewports::reported(ctx);
|
||||
let focused: Vec<ViewportId> = windows
|
||||
@@ -478,13 +580,27 @@ fn follow_activity(ctx: &Context) {
|
||||
.map(|(viewport, _)| *viewport)
|
||||
.filter(|viewport| PerViewport::<Record>::with(ctx, *viewport, |record| record.facts.is_some_and(|facts| facts.focused)))
|
||||
.collect();
|
||||
let changed = shared(ctx, |shared| {
|
||||
let modal = overlay::app_modal_viewport(ctx);
|
||||
let minimized = viewports::current(ctx).minimized;
|
||||
let (repaint, raise) = shared(ctx, |shared| {
|
||||
shared.stacking.retain(|viewport| windows.iter().any(|(open, _)| open == viewport) && !focused.contains(viewport));
|
||||
shared.stacking.extend(&focused);
|
||||
let away = focused.is_empty();
|
||||
std::mem::replace(&mut shared.away, away) != away
|
||||
let app = AppState { away: focused.is_empty(), modal, minimized };
|
||||
let lowered = std::mem::take(&mut shared.lowered);
|
||||
let (step, raise) = match shared.raise {
|
||||
_ if app.modal != shared.app.modal => (Raise::Waiting, None),
|
||||
Raise::Waiting if lowered => (Raise::Due, None),
|
||||
Raise::Due => (Raise::Done, app.modal),
|
||||
step => (step, None),
|
||||
};
|
||||
shared.raise = step;
|
||||
let changed = std::mem::replace(&mut shared.app, app) != app;
|
||||
(changed || step == Raise::Due, raise)
|
||||
});
|
||||
if changed {
|
||||
if let Some(modal) = raise {
|
||||
act(ctx, modal, WindowAction::Raise);
|
||||
}
|
||||
if repaint {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,7 +421,7 @@ pub(super) fn monitors(ctx: &Context) -> Vec<Monitor> {
|
||||
|
||||
/// The monitor the top-left corner of a window with `facts` lies on. A corner is on a monitor when its pixel position
|
||||
/// at that monitor's scale is inside the monitor.
|
||||
fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option<Monitor> {
|
||||
pub(super) fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option<Monitor> {
|
||||
let corner = facts.outer.or(facts.inner)?.min;
|
||||
monitors(ctx).into_iter().find(|monitor| monitor.rect_px().contains(corner * monitor.scale))
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::host::scale_of;
|
||||
#[cfg(doc)]
|
||||
use super::logic;
|
||||
use super::shell::{base_shell, os_of, window_info};
|
||||
use super::spec::WindowLevel;
|
||||
use super::spec::{Standing, WindowLevel};
|
||||
use super::{HandOff, Record, SEARCH_EVERY, shared};
|
||||
use crate::runtime::egui::{pass, viewports};
|
||||
use crate::runtime::frame::{PerViewport, Stored};
|
||||
@@ -40,6 +40,9 @@ pub enum WindowAction {
|
||||
SetMaximized(bool),
|
||||
/// Raises the window and gives it OS focus.
|
||||
Focus,
|
||||
/// Brings the window in front of the app's other windows without giving it focus, as the window holding an
|
||||
/// app-modal layer comes in front of the palettes the modal lowered.
|
||||
Raise,
|
||||
/// The OS starts moving the window with the pointer.
|
||||
StartMove,
|
||||
/// The OS starts resizing the window from `edge`.
|
||||
@@ -100,7 +103,8 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool {
|
||||
| WindowAction::Restore
|
||||
| WindowAction::SetMinInnerSize(_)
|
||||
| WindowAction::SetLevel(_)
|
||||
| WindowAction::SetTitle(_) => commands,
|
||||
| WindowAction::SetTitle(_)
|
||||
| WindowAction::Raise => commands,
|
||||
WindowAction::SetOpacity(_) => false,
|
||||
};
|
||||
if !allowed {
|
||||
@@ -109,6 +113,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool {
|
||||
match action {
|
||||
WindowAction::Close => viewports::close(ctx, viewport),
|
||||
WindowAction::Focus => viewports::raise(ctx, viewport),
|
||||
WindowAction::Raise => viewports::raise_above(ctx, viewport, standing(ctx, viewport, level_of(ctx, viewport)).level),
|
||||
WindowAction::Minimize => viewports::command(ctx, viewport, egui::ViewportCommand::Minimized(true)),
|
||||
WindowAction::ToggleMaximize => viewports::command(ctx, viewport, egui::ViewportCommand::Maximized(window.state != WindowState::Maximized)),
|
||||
WindowAction::ToggleFullscreen => {
|
||||
@@ -147,8 +152,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool {
|
||||
if opened {
|
||||
ctx.request_repaint_of(viewport);
|
||||
} else {
|
||||
let active = !shared(ctx, |shared| shared.away);
|
||||
viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(level.for_egui(active, os_of(ctx))));
|
||||
viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(standing(ctx, viewport, level).level));
|
||||
}
|
||||
}
|
||||
WindowAction::SetTitle(title) => {
|
||||
@@ -172,6 +176,16 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The level `viewport`'s window was opened with or last set to.
|
||||
fn level_of(ctx: &Context, viewport: ViewportId) -> WindowLevel {
|
||||
PerViewport::<Record>::with(ctx, viewport, |record| record.level.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// How `viewport`'s window at `level` stands in the app's current state.
|
||||
fn standing(ctx: &Context, viewport: ViewportId, level: WindowLevel) -> Standing {
|
||||
level.standing(viewport, shared(ctx, |shared| shared.app), os_of(ctx))
|
||||
}
|
||||
|
||||
/// Applies `opacity` to the OS window. A faded window is told again in every pass, because the window system's own
|
||||
/// style changes can drop the layered style; an opaque one only when it was faded. Returns whether the platform applied
|
||||
/// it now.
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::shared;
|
||||
use super::shell::{base_shell, os_of};
|
||||
use craft_host::target::{Os, WindowChrome, WindowKind};
|
||||
use craft_window::policy::{CaptionFamily, Captions, Frame, MacInset, tool_frame};
|
||||
use egui::Context;
|
||||
use egui::{Context, ViewportId};
|
||||
|
||||
/// Where a window stands in the stack of windows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -13,26 +13,53 @@ pub enum WindowLevel {
|
||||
/// An ordinary window.
|
||||
#[default]
|
||||
Normal,
|
||||
/// A palette: above the app's other windows while the app is active, and an ordinary window (behind other
|
||||
/// apps' windows on Windows) once none of the app's windows has focus, so it stays shown without covering
|
||||
/// other apps.
|
||||
/// A palette: above the app's other windows while the app is active, an ordinary window while an app-modal layer
|
||||
/// in another window blocks it, and an ordinary window (behind other apps' windows on Windows) once none of the
|
||||
/// app's windows has focus, so it stays shown without covering other apps or the modal. Hidden while the main
|
||||
/// window is minimized, except on macOS, where the app stays active and its palettes stay.
|
||||
Palette,
|
||||
/// Above every other window.
|
||||
AlwaysOnTop,
|
||||
}
|
||||
|
||||
/// The app's state that its palettes follow, as its windows reported it in the last frame.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct AppState {
|
||||
/// No window of the app has focus.
|
||||
pub away: bool,
|
||||
/// The window that holds an app-modal layer, which blocks the app's other windows.
|
||||
pub modal: Option<ViewportId>,
|
||||
/// The main window is minimized.
|
||||
pub minimized: bool,
|
||||
}
|
||||
|
||||
/// How a window stands among the windows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Standing {
|
||||
/// The level egui is given.
|
||||
pub level: egui::WindowLevel,
|
||||
/// Whether the window is shown.
|
||||
pub shown: bool,
|
||||
/// Whether the window stands as an ordinary window because an app-modal layer in another window blocks it.
|
||||
pub lowered: bool,
|
||||
}
|
||||
|
||||
impl WindowLevel {
|
||||
/// The level egui is given while the app is `active` or not, on `os`. An inactive app's palette goes behind
|
||||
/// other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the
|
||||
/// activated app's included, so the palette goes to the bottom.
|
||||
pub(super) fn for_egui(self, active: bool, os: Os) -> egui::WindowLevel {
|
||||
match self {
|
||||
/// How `viewport`'s window at this level stands while the app is in `app`, on `os`. An inactive app's palette goes
|
||||
/// behind other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the
|
||||
/// activated app's included, so the palette goes to the bottom. A palette blocked by a modal stands as an ordinary
|
||||
/// window, so the modal's window can be raised above it.
|
||||
pub(super) fn standing(self, viewport: ViewportId, app: AppState, os: Os) -> Standing {
|
||||
let palette = self == WindowLevel::Palette;
|
||||
let lowered = palette && !app.away && app.modal.is_some_and(|modal| modal != viewport);
|
||||
let level = match self {
|
||||
WindowLevel::Normal => egui::WindowLevel::Normal,
|
||||
WindowLevel::AlwaysOnTop => egui::WindowLevel::AlwaysOnTop,
|
||||
WindowLevel::Palette if active => egui::WindowLevel::AlwaysOnTop,
|
||||
WindowLevel::Palette if os == Os::Windows => egui::WindowLevel::AlwaysOnBottom,
|
||||
WindowLevel::Palette => egui::WindowLevel::Normal,
|
||||
}
|
||||
WindowLevel::Palette if app.away && os == Os::Windows => egui::WindowLevel::AlwaysOnBottom,
|
||||
WindowLevel::Palette if app.away || lowered => egui::WindowLevel::Normal,
|
||||
WindowLevel::Palette => egui::WindowLevel::AlwaysOnTop,
|
||||
};
|
||||
Standing { level, shown: !(palette && app.minimized && os != Os::Mac), lowered }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +85,10 @@ pub struct WindowSpec {
|
||||
pub taskbar: bool,
|
||||
/// Whether the window opens hidden and appears once its first pass has been laid out and painted.
|
||||
pub shown_after_first_paint: bool,
|
||||
/// Whether the window takes OS focus when it opens.
|
||||
pub takes_focus: bool,
|
||||
/// Whether pointer input passes through the window to the window below it.
|
||||
pub passes_pointer: bool,
|
||||
}
|
||||
|
||||
impl WindowSpec {
|
||||
@@ -67,6 +98,13 @@ impl WindowSpec {
|
||||
WindowSpec { kind: WindowKind::Tool, level: WindowLevel::Palette, taskbar: false, ..Self::dialog() }
|
||||
}
|
||||
|
||||
/// A popup window: a layer opened from a palette window (a flyout, menu or tooltip) in an OS window of its own. It
|
||||
/// has no frame, no taskbar entry and a palette level, and appears once its first pass ran, at the size and place
|
||||
/// its layer took in that pass.
|
||||
pub fn popup() -> Self {
|
||||
WindowSpec { chrome: Some(WindowChrome::Integrated), shown_after_first_paint: true, ..Self::tool() }
|
||||
}
|
||||
|
||||
/// A document window with the installed decision's frame.
|
||||
pub fn document() -> Self {
|
||||
WindowSpec { kind: WindowKind::Document, ..Self::dialog() }
|
||||
@@ -81,6 +119,8 @@ impl WindowSpec {
|
||||
level: WindowLevel::Normal,
|
||||
taskbar: true,
|
||||
shown_after_first_paint: false,
|
||||
takes_focus: true,
|
||||
passes_pointer: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +170,20 @@ impl WindowSpec {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the window takes OS focus when it opens.
|
||||
#[must_use]
|
||||
pub fn takes_focus(mut self, takes_focus: bool) -> Self {
|
||||
self.takes_focus = takes_focus;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether pointer input passes through the window to the window below it (a tooltip's).
|
||||
#[must_use]
|
||||
pub fn passes_pointer(mut self, passes_pointer: bool) -> Self {
|
||||
self.passes_pointer = passes_pointer;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the window opens hidden and appears after its first paint, so a window that shows a capture or
|
||||
/// other content that must be ready does not flash an empty frame.
|
||||
#[must_use]
|
||||
|
||||
@@ -54,10 +54,10 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
|
||||
keep_placed(ctx, viewport, pos, size.filter(|_| open.follows_size));
|
||||
}
|
||||
let spec = open.spec;
|
||||
let active = !shared(ctx, |shared| shared.away);
|
||||
let state = shared(ctx, |shared| shared.app);
|
||||
let os = os_of(ctx);
|
||||
let (chrome, captions) = frame_of_spec(ctx, spec);
|
||||
let level = PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
let standing = PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
record.kind = Some(spec.kind);
|
||||
record.chrome = Some(chrome);
|
||||
record.captions = captions.clone();
|
||||
@@ -73,8 +73,11 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
|
||||
record.searched = None;
|
||||
}
|
||||
}
|
||||
record.level.get_or_insert(spec.level).for_egui(active, os)
|
||||
record.level.get_or_insert(spec.level).standing(viewport, state, os)
|
||||
});
|
||||
if standing.lowered {
|
||||
shared(ctx, |shared| shared.lowered = true);
|
||||
}
|
||||
let app = app_id(ctx);
|
||||
let opens = viewports::Spec {
|
||||
title: open.title,
|
||||
@@ -88,10 +91,12 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
|
||||
// egui sends a limit only when it has one: an open window always carries its maximum, unbounded when the
|
||||
// caller has none, so a lifted maximum reaches the OS.
|
||||
max_size: open.limits.1.or(opened.then_some(Vec2::INFINITY)),
|
||||
level,
|
||||
level: standing.level,
|
||||
resizable: open.resizable,
|
||||
taskbar: spec.taskbar,
|
||||
hidden: PerViewport::<Record>::with(ctx, viewport, |record| record.awaiting_first_paint),
|
||||
active: spec.takes_focus,
|
||||
passes_pointer: spec.passes_pointer,
|
||||
app_id: &app,
|
||||
};
|
||||
viewports::show_immediate(ctx, viewport, &opens, |ui| {
|
||||
@@ -115,8 +120,77 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
|
||||
record_placement(&ctx, viewport, key, &at_known(&ctx, viewport, viewports::current(&ctx)));
|
||||
}
|
||||
});
|
||||
if PerViewport::<Record>::with(ctx, viewport, |record| std::mem::take(&mut record.awaiting_first_paint)) {
|
||||
viewports::show(ctx, viewport);
|
||||
// A window opened hidden appears once its first pass ran; a window the app's state hides goes and comes back with
|
||||
// it. The builder's visibility only opens the window: egui sends no change of it once the window is open.
|
||||
let hidden = !standing.shown;
|
||||
let (reveal, changed) = PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
let first = std::mem::take(&mut record.awaiting_first_paint);
|
||||
let changed = std::mem::replace(&mut record.hidden, hidden) != hidden;
|
||||
(first || changed, changed)
|
||||
});
|
||||
if hidden && changed {
|
||||
viewports::set_visible(ctx, viewport, false);
|
||||
} else if !hidden && reveal {
|
||||
viewports::set_visible(ctx, viewport, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a layer shown in a popup window asks for ([`show_popup`]).
|
||||
pub(crate) struct PopupOpen<'a> {
|
||||
/// The layer's id; the popup's viewport derives from it.
|
||||
pub id: Id,
|
||||
/// How the window opens: a [`WindowSpec::popup`].
|
||||
pub spec: &'a WindowSpec,
|
||||
/// The window's place in desktop points (outer top-left corner and inner size) when the layer's size is known
|
||||
/// before its pass; otherwise the caller places it after the pass ([`place_popup`]).
|
||||
pub rect: Option<Rect>,
|
||||
}
|
||||
|
||||
/// Opens the popup window of a layer opened in the running viewport (its opener) and runs `body` in its pass. The
|
||||
/// window is a viewport mount without a container: it opens at `open.rect` and follows it, and the opener gets the OS
|
||||
/// focus back when it closes ([`close_popup`]).
|
||||
pub(crate) fn show_popup(ctx: &Context, open: &PopupOpen<'_>, body: impl FnMut(&mut Ui)) {
|
||||
let opener = crate::runtime::egui::pass::current_viewport(ctx);
|
||||
PerViewport::<Record>::with(ctx, viewports::viewport_id(open.id), |record| record.opener = Some(opener));
|
||||
let mount = ViewportOpen {
|
||||
id: open.id,
|
||||
title: "",
|
||||
size: open.rect.map(|rect| rect.size()),
|
||||
follows_size: true,
|
||||
save: None,
|
||||
spec: open.spec,
|
||||
limits: (None, None),
|
||||
position: open.rect.map(|rect| rect.min),
|
||||
resizable: false,
|
||||
moved_by_app: false,
|
||||
};
|
||||
show_viewport(ctx, &mount, body);
|
||||
}
|
||||
|
||||
/// Sends the popup window of layer `id` to `rect` (desktop points) where it is not there already: a layer whose size
|
||||
/// its pass measured is placed once that pass ran.
|
||||
pub(crate) fn place_popup(ctx: &Context, id: Id, rect: Rect) {
|
||||
let viewport = viewports::viewport_id(id);
|
||||
let known = PerViewport::<Record>::with(ctx, viewport, |record| record.known);
|
||||
if known.is_none_or(|known| differs(ctx, viewport, rect.min - known.min)) {
|
||||
act(ctx, viewport, WindowAction::SetOuterPosition(rect.min));
|
||||
}
|
||||
if known.is_none_or(|known| differs(ctx, viewport, rect.size() - known.size())) {
|
||||
act(ctx, viewport, WindowAction::SetInnerSize(rect.size()));
|
||||
}
|
||||
PerViewport::<Record>::with(ctx, viewport, |record| record.known = Some(rect));
|
||||
}
|
||||
|
||||
/// The layer `id` is hidden: when it showed in a popup window that still has the OS focus, the window it was opened
|
||||
/// from takes the focus back. Once per close; a layer that never showed in a popup does nothing.
|
||||
pub(crate) fn close_popup(ctx: &Context, id: Id) {
|
||||
let viewport = viewports::viewport_id(id);
|
||||
let closed = PerViewport::<Record>::with_existing(ctx, viewport, |record| {
|
||||
let focused = record.facts.is_some_and(|facts| facts.focus_reported);
|
||||
record.opener.take().filter(|_| focused)
|
||||
});
|
||||
if let Some(opener) = closed.flatten() {
|
||||
act(ctx, opener, WindowAction::Focus);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,9 +225,17 @@ pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool {
|
||||
&& PerViewport::<Record>::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none())
|
||||
}
|
||||
|
||||
/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a
|
||||
/// placement records the position in pixels.
|
||||
const ROUNDING: f32 = 0.5;
|
||||
/// How far a caller's place may differ from the known place before it is a change, in physical pixels of the window's
|
||||
/// display: the OS rounds to pixels, and a placement records the position in pixels.
|
||||
const ROUNDING_PX: f32 = 0.5;
|
||||
|
||||
/// Whether `delta`, in points, moves the window `viewport` by more than rounding on its display: a whole pixel on
|
||||
/// a 2x display is half a point.
|
||||
fn differs(ctx: &Context, viewport: ViewportId, delta: Vec2) -> bool {
|
||||
let facts = PerViewport::<Record>::with(ctx, viewport, |record| record.facts);
|
||||
let scale = facts.and_then(|facts| super::host::scale_of(ctx, &facts)).unwrap_or(1.0);
|
||||
delta.x.abs() * scale > ROUNDING_PX || delta.y.abs() * scale > ROUNDING_PX
|
||||
}
|
||||
|
||||
/// The place of a window with `facts`: its outer top-left corner and its inner size.
|
||||
fn place_of(facts: &viewports::Facts) -> Option<Rect> {
|
||||
@@ -182,11 +264,10 @@ fn keep_placed(ctx: &Context, viewport: ViewportId, pos: Option<Pos2>, size: Opt
|
||||
(record.known, state || record.moved_pointer.is_some())
|
||||
});
|
||||
let Some(known) = known.filter(|_| !held) else { return };
|
||||
let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING;
|
||||
if let Some(pos) = pos.filter(|pos| differs(*pos - known.min)) {
|
||||
if let Some(pos) = pos.filter(|pos| differs(ctx, viewport, *pos - known.min)) {
|
||||
act(ctx, viewport, WindowAction::SetOuterPosition(pos));
|
||||
}
|
||||
if let Some(size) = size.filter(|size| differs(*size - known.size())) {
|
||||
if let Some(size) = size.filter(|size| differs(ctx, viewport, *size - known.size())) {
|
||||
act(ctx, viewport, WindowAction::SetInnerSize(size));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ pub use cache::{Accepted, accepted_variant};
|
||||
pub use craft_behavior::{ControlMetrics, Insets, Metrics};
|
||||
#[doc(hidden)]
|
||||
pub use craft_theme::GroupValues;
|
||||
pub use craft_theme::LetterCase;
|
||||
pub use craft_theme::{FlagMask, Flags, Mix, Resolve, State, StateMix, Stateful, States, TokenGroup, Tokens, TypeRole, Variant};
|
||||
pub use craft_ui_macros::{ComponentStyle, TokenGroup};
|
||||
pub(crate) use cx::control_metrics;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS
|
||||
//! resize (H4), the raise of a modal's window, the mount of a full-window container (in a window of its own, or in a
|
||||
//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows,
|
||||
//! injected keys across a focus loss, non-finite injected points, a repeated injected press, the window that has the
|
||||
//! keys, and `act`.
|
||||
//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a
|
||||
//! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus
|
||||
//! loss, non-finite injected points, a repeated injected press, the window that has the keys, and `act`.
|
||||
|
||||
use craft_behavior::{Cursor, CursorIcon, PointerButton};
|
||||
use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
|
||||
@@ -302,6 +302,81 @@ fn a_palette_drops_its_level_while_the_app_is_inactive() {
|
||||
assert_eq!(frame(true, false), on_top, "the frame after the main window took focus again");
|
||||
}
|
||||
|
||||
/// A palette stands as an ordinary window while an app-modal layer in the main window blocks it, so the modal is never
|
||||
/// behind a palette: the frame after the modal opens builds the palette's window at the ordinary level, a later frame
|
||||
/// raises the main window above it once, by its level (egui ignores `Focus` for a window that has focus), and the
|
||||
/// palette stands above the app's windows again once the modal closes.
|
||||
#[trial]
|
||||
fn a_palette_stands_behind_the_window_that_holds_a_modal() {
|
||||
let windows = Windows::new();
|
||||
windows.root_info(ViewportInfo { focused: Some(true), ..ViewportInfo::default() });
|
||||
let frame = |modal: bool| {
|
||||
let out = windows.frame(vec![], vec![], |ui| {
|
||||
windows.child_info(ViewportInfo { focused: Some(false), ..ViewportInfo::default() });
|
||||
Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {});
|
||||
if modal {
|
||||
let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal()));
|
||||
Modal { common: Common::new(), props }.id_salt("save prompt").show(ui, |_, _| {});
|
||||
}
|
||||
});
|
||||
let raise: Vec<ViewportCommand> = out
|
||||
.commands
|
||||
.iter()
|
||||
.filter(|(id, command)| *id == ViewportId::ROOT && matches!(command, ViewportCommand::WindowLevel(_) | ViewportCommand::Focus))
|
||||
.map(|(_, command)| command.clone())
|
||||
.collect();
|
||||
(builder_titled(&out, "tool").1.window_level, raise)
|
||||
};
|
||||
let (on_top, normal) = (Some(egui::WindowLevel::AlwaysOnTop), Some(egui::WindowLevel::Normal));
|
||||
assert_eq!(frame(false), (on_top, vec![]), "no modal: the palette stands above the main window");
|
||||
let frames: Vec<_> = (0..4).map(|_| frame(true)).collect();
|
||||
assert_eq!(frames.last().map(|(level, _)| *level), Some(normal), "the modal open: the palette is an ordinary window");
|
||||
let raises: Vec<usize> = frames.iter().enumerate().filter(|(_, (_, raise))| !raise.is_empty()).map(|(at, _)| at).collect();
|
||||
let lowered = frames.iter().position(|(level, _)| *level == normal);
|
||||
assert_eq!(raises.len(), 1, "the main window is raised once: {frames:?}");
|
||||
assert!(lowered.is_some_and(|lowered| raises[0] > lowered), "the raise follows the frame that lowered the palette: {frames:?}");
|
||||
let level = |level| ViewportCommand::WindowLevel(level);
|
||||
assert_eq!(
|
||||
frames[raises[0]].1,
|
||||
vec![level(egui::WindowLevel::AlwaysOnTop), level(egui::WindowLevel::Normal)],
|
||||
"the raise stands the main window above every window and back, without focus"
|
||||
);
|
||||
frame(false);
|
||||
assert_eq!(frame(false), (on_top, vec![]), "the modal closed: the palette stands above again");
|
||||
}
|
||||
|
||||
/// A palette's window is hidden while the main window is minimized and shown again at its place when the main window
|
||||
/// is restored, on Windows and Linux; a document window stays. On macOS a minimized main window leaves the app active,
|
||||
/// and its palettes stay.
|
||||
#[trial]
|
||||
fn palettes_hide_while_the_main_window_is_minimized() {
|
||||
for os in [Os::Windows, Os::Linux, Os::Mac] {
|
||||
let windows = Windows::with(InstallSpec::new(ShellInfo::default().os(os).caps(Caps::native(os)), Arc::new(FakeSystem::new())));
|
||||
let frame = |minimized: bool| {
|
||||
windows.root_info(ViewportInfo { minimized: Some(minimized), ..ViewportInfo::default() });
|
||||
windows.frame(vec![], vec![], |ui| {
|
||||
Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {});
|
||||
Palette::new("doc", Some(WindowSpec::document())).show(ui, |_, _| {});
|
||||
})
|
||||
};
|
||||
let first = frame(false);
|
||||
let (tool, doc) = (builder_titled(&first, "tool").0, builder_titled(&first, "doc").0);
|
||||
frame(false);
|
||||
let commands = |minimized: bool| -> Vec<(ViewportId, ViewportCommand)> { (0..3).flat_map(|_| frame(minimized).commands).collect() };
|
||||
let sent = |commands: &[(ViewportId, ViewportCommand)], to: ViewportId| -> Vec<ViewportCommand> {
|
||||
commands.iter().filter(|(id, _)| *id == to).map(|(_, command)| command.clone()).collect()
|
||||
};
|
||||
let (minimized, restored) = (commands(true), commands(false));
|
||||
let hides = os != Os::Mac;
|
||||
let visible = |on: bool| if hides { vec![ViewportCommand::Visible(on)] } else { vec![] };
|
||||
let (tool_minimized, doc_minimized) = (sent(&minimized, tool), sent(&minimized, doc));
|
||||
let (tool_restored, doc_restored) = (sent(&restored, tool), sent(&restored, doc));
|
||||
assert_eq!(tool_minimized, visible(false), "{os:?}: the main window minimized: the palette is hidden, and nothing else is sent");
|
||||
assert_eq!(tool_restored, visible(true), "{os:?}: the main window restored: the palette is shown where it was");
|
||||
assert_eq!((doc_minimized, doc_restored), (vec![], vec![]), "{os:?}: a document window is left as it is");
|
||||
}
|
||||
}
|
||||
|
||||
/// A full-window container mounted in its own window opens a resizable OS window titled as the container where
|
||||
/// viewports are available, and covers the main window's content where they are not.
|
||||
#[trial]
|
||||
|
||||
@@ -175,7 +175,7 @@ const COLLECTION: &[Forwarded] = &[
|
||||
("striped", "bool", "Odd rows are tinted: the item reads `ItemCx::row.striped`."),
|
||||
("allow_empty", "bool", "A press on the empty space below the rows empties the selection."),
|
||||
("lead_on_open", "$ui::contract::LeadOnOpen", "Where the lead lands when rows first show."),
|
||||
("lead_follows_hover", "bool", "The lead, and the selection with it, moves to the row under the pointer when the pointer moves."),
|
||||
("hover_lead", "$ui::contract::HoverLead", "What the pointer moving over the rows changes: nothing, the lead, or the lead and the selection."),
|
||||
("arrows_select", "bool", "The arrow keys select the row they move the lead to; off, they move the lead only."),
|
||||
("arrows_wrap", "bool", "The arrow keys wrap from the last item to the first and back."),
|
||||
("type_ahead", "bool", "Typed letters move the lead to the next item whose text starts with them; off, they stay shortcut candidates."),
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron};
|
||||
use super::drop::{DragUnit, start_group_drag};
|
||||
use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native};
|
||||
use super::{DockDropTarget, DockDropped, DockSizes, DockWords, GroupDrag, PanelDrag, PanelKey, native};
|
||||
use crate::contract::BodyCx;
|
||||
use crate::contract::SizeLimits;
|
||||
use crate::contract::overlay::{PlacementChange, PlacementKind, Popup, ResizeEdges};
|
||||
@@ -53,14 +53,21 @@ pub struct FloatingGroupStyle {
|
||||
|
||||
/// The column a dock's floating window holds. The window's title row is the column's bar: it shows the column's
|
||||
/// double arrow at the end on `edge`, and a collapsed column shows against that edge of the window's rect.
|
||||
///
|
||||
/// A column whose content fixes its height ([`held`](Self::held)) shows at that height whatever the rect's, and the
|
||||
/// rect keeps its own height for when the content no longer fixes it: a column collapsed to icons, and one whose
|
||||
/// every group is minimized.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct WindowColumn {
|
||||
/// The edge of the float area, in reading order, that the window keeps to: the dock model's `Floating::edge`,
|
||||
/// else the one nearer the window.
|
||||
pub edge: DockEdge,
|
||||
/// The size of the collapsed column under the title row; `None` while the column is expanded.
|
||||
pub collapsed: Option<Vec2>,
|
||||
/// The height of the column under the title row when its content fixes it: a collapsed column's icons, or the
|
||||
/// tab strips of a column whose every group is minimized. `None` while the rect gives the height.
|
||||
pub held: Option<f32>,
|
||||
/// The width of the collapsed column; `None` while the column is expanded, and the rect gives the width.
|
||||
pub collapsed: Option<f32>,
|
||||
/// The least and most width the sides of a collapsed column's window resize it to
|
||||
/// ([`DockSizes::iconic_bounds`](super::DockSizes::iconic_bounds)); unbounded while the column is expanded.
|
||||
pub widths: (f32, f32),
|
||||
@@ -74,20 +81,27 @@ pub struct WindowColumn {
|
||||
impl WindowColumn {
|
||||
/// An expanded column that keeps to `edge`.
|
||||
pub fn expanded(edge: DockEdge) -> Self {
|
||||
WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse }
|
||||
WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse }
|
||||
}
|
||||
|
||||
/// A column collapsed to icons, `size` under the title row, that keeps to `edge`. The window's sides resize its
|
||||
/// width within `widths`, as a docked collapsed column's inner edge does; its height stays `size`'s.
|
||||
pub fn collapsed(edge: DockEdge, size: Vec2, widths: (f32, f32)) -> Self {
|
||||
WindowColumn { edge, collapsed: Some(size), widths, fitted: None, arrow: ColumnArrow::Collapse }
|
||||
WindowColumn { edge, held: Some(size.y), collapsed: Some(size.x), widths, fitted: None, arrow: ColumnArrow::Collapse }
|
||||
}
|
||||
|
||||
/// An expanded column whose every group is minimized, their strips `height` under the title row, that keeps to
|
||||
/// `edge`. The window shows at its rect's place and width and that height; its sides resize the width, and the
|
||||
/// rect keeps its height, which the window takes back once a group is restored.
|
||||
pub fn minimized(edge: DockEdge, height: f32) -> Self {
|
||||
WindowColumn { edge, held: Some(height), collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse }
|
||||
}
|
||||
|
||||
/// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at
|
||||
/// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's
|
||||
/// steps, and a move keeps the rect's size.
|
||||
pub fn fitted(edge: DockEdge, size: Vec2) -> Self {
|
||||
WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse }
|
||||
WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse }
|
||||
}
|
||||
|
||||
/// The column with the double arrow `arrow` ([`ColumnArrow::of`]).
|
||||
@@ -96,20 +110,25 @@ impl WindowColumn {
|
||||
self
|
||||
}
|
||||
|
||||
/// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under the window's
|
||||
/// chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect` and against the edge the window keeps
|
||||
/// to. `None` while the column is expanded.
|
||||
/// Where a window that keeps `rect` shows while its content fixes its height ([`Self::held`]): the column under
|
||||
/// the window's chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect`, as wide as a collapsed
|
||||
/// column or else as `rect`, and against the edge the window keeps to. `None` while the rect gives the height.
|
||||
pub fn shown(self, rect: Rect, chrome: f32, rtl: bool) -> Option<Rect> {
|
||||
let size = self.collapsed? + Vec2::new(0.0, chrome);
|
||||
let size = Vec2::new(self.collapsed.unwrap_or(rect.width()), self.held? + chrome);
|
||||
let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x };
|
||||
Some(Rect::from_min_size(Pos2::new(left, rect.top()), size))
|
||||
}
|
||||
|
||||
/// The rect a window that keeps `rect` keeps when it shows at `shown`: while collapsed, `rect` moved with the
|
||||
/// collapsed column ([`Self::shown`]) so that the column's side on the edge the window keeps to stays on that side
|
||||
/// of `rect`, whatever width the column shows at; `rect` keeps its expanded size. While expanded, `shown`.
|
||||
/// The rect a window that keeps `rect` keeps when it shows at `shown`, so that it keeps its height while its
|
||||
/// content fixes the shown one ([`Self::shown`]). While collapsed, `rect` moved with the collapsed column so that
|
||||
/// the column's side on the edge the window keeps to stays on that side of `rect`, whatever width the column shows
|
||||
/// at; `rect` keeps its expanded size. While every group is minimized, `shown`'s place and width with `rect`'s
|
||||
/// height. Otherwise `shown`.
|
||||
pub fn kept(self, shown: Rect, rect: Rect, chrome: f32, rtl: bool) -> Rect {
|
||||
let Some(at) = self.shown(rect, chrome, rtl) else { return shown };
|
||||
if self.collapsed.is_none() {
|
||||
return Rect::from_min_size(shown.min, Vec2::new(shown.width(), rect.height()));
|
||||
}
|
||||
let dx = if at_left(self.edge, rtl) { shown.left() - at.left() } else { shown.right() - at.right() };
|
||||
rect.translate(Vec2::new(dx, shown.top() - at.top()))
|
||||
}
|
||||
@@ -126,7 +145,8 @@ impl WindowColumn {
|
||||
/// at the same place against that edge ([`Self::around_strip`]); an expanded window keeps `rect`, and the edge
|
||||
/// nearer it (`None`).
|
||||
pub fn dropped(self, rect: Rect, bounds: Rect, rtl: bool) -> (Rect, Option<DockEdge>) {
|
||||
let Some(size) = self.collapsed else { return (rect, None) };
|
||||
let (Some(width), Some(height)) = (self.collapsed, self.held) else { return (rect, None) };
|
||||
let size = Vec2::new(width, height);
|
||||
let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x };
|
||||
let (rect, edge) = Self::around_strip(Rect::from_min_size(Pos2::new(left, rect.top()), size), rect.size(), bounds, rtl);
|
||||
(rect, Some(edge))
|
||||
@@ -199,7 +219,8 @@ impl Outcome for FloatingGroupOutput {
|
||||
/// in [`FloatingGroupOutput::collapsed_width`]) while its height stays the icons', and the rect keeps its size. A
|
||||
/// column its content sizes ([`WindowColumn::fitted`]) shows at that size at the rect's place; its resizes are
|
||||
/// reported as the user makes them, and in an OS window the app runs them, so the window takes only the size the
|
||||
/// host gives it.
|
||||
/// host gives it. A column whose every group is minimized ([`WindowColumn::minimized`]) shows at the rect's place
|
||||
/// and width and its strips' height; its sides resize the width, and the rect keeps its height.
|
||||
/// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag
|
||||
/// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release.
|
||||
/// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where
|
||||
@@ -256,6 +277,9 @@ pub struct FloatingGroup<'a> {
|
||||
placed: Option<PlacementChange>,
|
||||
/// The width a resize gave the collapsed column this pass.
|
||||
collapsed_width: Option<f32>,
|
||||
/// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the
|
||||
/// running window's.
|
||||
scale: Option<f32>,
|
||||
/// Starts the window-unit drag; set by `window_of`.
|
||||
start_drag: Option<StartDrag<'a>>,
|
||||
/// Takes the drops released on the group, on the group's own layer.
|
||||
@@ -302,6 +326,7 @@ impl<'a> FloatingGroup<'a> {
|
||||
rtl: false,
|
||||
placed: None,
|
||||
collapsed_width: None,
|
||||
scale: None,
|
||||
start_drag: None,
|
||||
take_drop: None,
|
||||
moving: false,
|
||||
@@ -338,6 +363,14 @@ impl<'a> FloatingGroup<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the
|
||||
/// running window's: its chrome is sized at that scale.
|
||||
#[must_use]
|
||||
pub fn scale(mut self, pixels_per_point: f32) -> Self {
|
||||
self.scale = Some(pixels_per_point);
|
||||
self
|
||||
}
|
||||
|
||||
/// The action parts at the end of the title row, in reading order.
|
||||
#[must_use]
|
||||
pub fn actions(mut self, actions: impl IntoIterator<Item = HeaderAction>) -> Self {
|
||||
@@ -348,11 +381,11 @@ impl<'a> FloatingGroup<'a> {
|
||||
/// Shows the group; `body` fills the area under the title row unless the group is minimized.
|
||||
pub fn show_group<R>(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<FloatingGroupOutput, R> {
|
||||
let env = Env::of(ui);
|
||||
let header = title_row(&env.tokens);
|
||||
// A window in the app window keeps the band over its title row that a layer the user moves keeps for its top
|
||||
// grip; an OS window's grips lie over its title row.
|
||||
let band = if self.native.is_none() { crate::contract::grip_band(&env.tokens) } else { 0.0 };
|
||||
(self.header, self.chrome, self.rtl) = (header, header + band, env.direction.is_rtl());
|
||||
// grip; an OS window's grips lie over its title row. The rule under the title row takes a band of its own.
|
||||
let sizes = DockSizes::style(&StyleCx::of_env(ui.ctx(), &env));
|
||||
let sizes = self.scale.map_or(sizes, |scale| sizes.at_scale(scale));
|
||||
(self.header, self.chrome, self.rtl) = (sizes.title_row, sizes.window_chrome(self.native.is_none()), env.direction.is_rtl());
|
||||
let mount = self.mount();
|
||||
self.props = self.props.mount(mount);
|
||||
let minimized = self.minimized;
|
||||
@@ -367,10 +400,15 @@ impl<'a> FloatingGroup<'a> {
|
||||
fn mount(&self) -> Mount {
|
||||
// The frame's limits are the body's with the chrome on top.
|
||||
let frame = self.limits.around(Vec2::new(0.0, self.chrome));
|
||||
let collapsed = self.collapsed_rect().zip(self.column.map(|column| column.widths));
|
||||
// A collapsed column's width stays within its own bounds, a minimized one's within the panels' limits.
|
||||
let widths = self.column.map(|column| match column.collapsed {
|
||||
Some(_) => column.widths,
|
||||
None => (frame.min.x, frame.max.map_or(f32::INFINITY, |max| max.x)),
|
||||
});
|
||||
let held = self.held_rect().zip(widths);
|
||||
let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized).opacity(self.opacity).body_scroll(false);
|
||||
overlay = if let Some((shown, (least, most))) = collapsed {
|
||||
// The sides resize a collapsed column's width; its height is its icons'.
|
||||
overlay = if let Some((shown, (least, most))) = held {
|
||||
// The sides resize the column's width; its content fixes its height.
|
||||
let height = shown.height();
|
||||
let edges = if self.minimized { ResizeEdges::NONE } else { ResizeEdges::LEFT.union(ResizeEdges::RIGHT) };
|
||||
overlay.placed(shown).resize_edges(edges).size_limits(SizeLimits::new(Vec2::new(least, height), Vec2::new(most.max(least), height)))
|
||||
@@ -399,9 +437,9 @@ impl<'a> FloatingGroup<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the group shows while its column is collapsed: the collapsed column under the chrome, at the top of the
|
||||
/// rect and against its edge the window keeps to. `None` while the column is expanded.
|
||||
fn collapsed_rect(&self) -> Option<Rect> {
|
||||
/// Where the group shows while its column's content fixes its height ([`WindowColumn::shown`]). `None` while the
|
||||
/// rect gives the height.
|
||||
fn held_rect(&self) -> Option<Rect> {
|
||||
self.column?.shown(self.rect, self.chrome, self.rtl)
|
||||
}
|
||||
|
||||
@@ -524,14 +562,15 @@ impl Container for FloatingGroup<'_> {
|
||||
fn placement_changed(&mut self, change: &PlacementChange) {
|
||||
let mut change = *change;
|
||||
let fitted = self.column.is_some_and(|column| column.fitted.is_some());
|
||||
if let Some(column) = self.column.filter(|column| column.collapsed.is_some()) {
|
||||
// A resize of the collapsed window sets the column's width; the rect keeps its expanded size.
|
||||
if let Some(column) = self.column.filter(|column| column.held.is_some()) {
|
||||
// A resize of the collapsed window sets the column's width; the rect keeps its expanded size. A minimized
|
||||
// window's rect takes the width and keeps its height.
|
||||
let resized = match change.kind {
|
||||
PlacementKind::Size(_) => true,
|
||||
PlacementKind::Keyboard => self.collapsed_rect().is_some_and(|shown| change.rect.width() != shown.width()),
|
||||
PlacementKind::Keyboard => self.held_rect().is_some_and(|shown| change.rect.width() != shown.width()),
|
||||
_ => false,
|
||||
};
|
||||
if resized {
|
||||
if resized && column.collapsed.is_some() {
|
||||
self.collapsed_width = Some(change.rect.width());
|
||||
}
|
||||
change.rect = column.kept(change.rect, self.rect, self.chrome, self.rtl);
|
||||
|
||||
@@ -205,7 +205,9 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> {
|
||||
/// Whether Auto-Collapse Iconic Panels is on.
|
||||
#[prop]
|
||||
auto_collapse: bool,
|
||||
/// The rect the dock may grow within, which bounds how wide its inner edge can make the column.
|
||||
/// The rect the dock may grow within, which bounds how wide its inner edge can make the column, and the rect its
|
||||
/// flyouts open in. Unset, the flyouts take the room layers opened there have (`overlay::layer_room`): around a
|
||||
/// palette window, the work area.
|
||||
#[prop]
|
||||
within: Rect,
|
||||
open: Bind<'a, Option<P>>,
|
||||
@@ -617,7 +619,7 @@ impl<P: Value + Hash + Debug + 'static> Component for IconicColumn<'_, P> {
|
||||
let (opens, auto_collapse, column) = (self.opens, self.auto_collapse, cx.rect);
|
||||
// The screen side the flyouts open on, mirrored in a right-to-left layout.
|
||||
let right = (opens == Side::End) != cx.flow.is_rtl();
|
||||
let within = if self.within.is_positive() { self.within } else { cx.core.ctx.content_rect() };
|
||||
let within = if self.within.is_positive() { self.within } else { crate::contract::overlay::layer_room(&cx.core.ctx) };
|
||||
// The column side of the bounds stops at the column, so a saved width wider than the room keeps that side.
|
||||
let bounds = if right { within.with_min_x(within.min.x.max(column.right())) } else { within.with_max_x(within.max.x.min(column.left())) };
|
||||
if !bounds.is_positive() {
|
||||
|
||||
@@ -46,6 +46,12 @@ pub fn opens_os_windows(ctx: &Context, config: &DockConfig) -> bool {
|
||||
config.native_windows && host.opens_windows() && host.positions_reported()
|
||||
}
|
||||
|
||||
/// The display scale the OS window `viewport` lays out at: its monitor's scale with the app's zoom, as the window
|
||||
/// reported it (`WindowHost::facts`). `None` before it reported one.
|
||||
pub fn pixels_per_point(ctx: &Context, viewport: ViewportId) -> Option<f32> {
|
||||
WindowHost::of(ctx).facts(viewport)?.scale.map(|scale| scale * ctx.zoom_factor())
|
||||
}
|
||||
|
||||
/// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool
|
||||
/// window (a palette level, no taskbar entry).
|
||||
pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds};
|
||||
use crate::contract::DropMark;
|
||||
use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored};
|
||||
use crate::style::StyleCx;
|
||||
use crate::style::{RuleKind, RuleWidth, StyleCx};
|
||||
use craft_behavior::DockSide;
|
||||
use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones};
|
||||
use egui::{Context, Id, Pos2, Rect, Vec2};
|
||||
@@ -53,6 +53,12 @@ pub struct DockSizes {
|
||||
pub bar: f32,
|
||||
/// The height of a floating window's title row, which is the bar of the column the window holds.
|
||||
pub title_row: f32,
|
||||
/// The divider rule a floating window draws under its title row, which the container lays out in a band of its
|
||||
/// own: the rule's width in whole physical pixels on the window's display ([`Self::pixels_per_point`]).
|
||||
pub title_rule: RuleWidth,
|
||||
/// The display scale the sizes that depend on it are for: the running window's, or with [`Self::at_scale`] an OS
|
||||
/// window's own.
|
||||
pub pixels_per_point: f32,
|
||||
/// The band a floating window in the app window keeps clear over its title row for its top grip
|
||||
/// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's
|
||||
/// height less its chrome ([`Self::window_chrome`]).
|
||||
@@ -107,6 +113,8 @@ impl DockSizes {
|
||||
strip: size.panel_header,
|
||||
bar: size.control.sm,
|
||||
title_row: super::floating::title_row(cx.tokens),
|
||||
title_rule: cx.rule(RuleKind::Divider).width,
|
||||
pixels_per_point: cx.frame_ctx().pixels_per_point(),
|
||||
top_band: crate::contract::grip_band(cx.tokens),
|
||||
least: size.panel_header,
|
||||
reach: size.hit.target,
|
||||
@@ -119,10 +127,23 @@ impl DockSizes {
|
||||
}
|
||||
}
|
||||
|
||||
/// The height above a floating window's body: its title row and, for a window in the app window (`in_app`), the
|
||||
/// band over it.
|
||||
/// The height above a floating window's body: its title row, the rule under it and, for a window in the app
|
||||
/// window (`in_app`), the band over it.
|
||||
pub fn window_chrome(&self, in_app: bool) -> f32 {
|
||||
self.title_row + if in_app { self.top_band } else { 0.0 }
|
||||
self.title_row + self.title_rule.points(self.pixels_per_point) + if in_app { self.top_band } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The sizes for a window on a display of `pixels_per_point`: an OS window lays out at its own monitor's scale.
|
||||
#[must_use]
|
||||
pub fn at_scale(mut self, pixels_per_point: f32) -> Self {
|
||||
self.pixels_per_point = pixels_per_point;
|
||||
self
|
||||
}
|
||||
|
||||
/// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None`
|
||||
/// while a group is open.
|
||||
pub fn minimized_height<P>(&self, column: &Column<P>) -> Option<f32> {
|
||||
column.groups.iter().all(|group| group.minimized).then_some(self.strip * column.groups.len() as f32)
|
||||
}
|
||||
|
||||
/// The width bounds of an expanded column from the limits of its panels.
|
||||
|
||||
@@ -187,7 +187,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
|
||||
struct AreaMemory<P> {
|
||||
/// The open flyout when the host binds none.
|
||||
open: Option<P>,
|
||||
/// The running move or resize of a floating window.
|
||||
/// The running resize or keyboard move of a floating window.
|
||||
moving: Option<Moving<P>>,
|
||||
/// The least window id above every id the workspaces this area showed held: an undo that brings back an older
|
||||
/// workspace keeps its new windows above it ([`Workspace::raise_window_floor`]).
|
||||
@@ -1270,6 +1270,10 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
/// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records
|
||||
/// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]).
|
||||
///
|
||||
/// A window whose every group is minimized shows its title row and their strips at its rect's place and width
|
||||
/// ([`WindowColumn::minimized`]): its sides resize its width, and its placement keeps its expanded height, so a
|
||||
/// restore shows it at that height again.
|
||||
///
|
||||
/// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that
|
||||
/// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or
|
||||
/// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps
|
||||
@@ -1297,6 +1301,14 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let dock = scene.dock.with(("floating", window.id));
|
||||
let group_id = dock.with("window");
|
||||
let opening = native::opening(&ctx, scene.config, window, &specs, group_id);
|
||||
// An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the
|
||||
// main window's.
|
||||
let scale = opening
|
||||
.spec
|
||||
.as_ref()
|
||||
.and_then(|_| WindowHost::of(&ctx).viewport_of(group_id))
|
||||
.and_then(|viewport| native::pixels_per_point(&ctx, viewport));
|
||||
let window_sizes = scale.map_or(scene.sizes, |scale| scene.sizes.at_scale(scale));
|
||||
let movable = rights.iter().all(|rights| rights.movable);
|
||||
// The title row is the column's bar: its double arrow and Close; the menu opens from a context request on
|
||||
// its band.
|
||||
@@ -1330,6 +1342,8 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
WindowColumn::collapsed(edge, size, scene.sizes.iconic_bounds(&window.column, &spec_of))
|
||||
} else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) {
|
||||
WindowColumn::fitted(edge, Vec2::new(width, content))
|
||||
} else if let Some(strips) = scene.sizes.minimized_height(&window.column) {
|
||||
WindowColumn::minimized(edge, strips)
|
||||
} else {
|
||||
WindowColumn::expanded(edge)
|
||||
}
|
||||
@@ -1343,6 +1357,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
.takes_drops(target, &dropped)
|
||||
.command_scope(DockCommands::SCOPE)
|
||||
.id(group_id);
|
||||
if let Some(scale) = scale {
|
||||
group = group.scale(scale);
|
||||
}
|
||||
group = match opening.spec.clone() {
|
||||
Some(window_spec) => group.native(window_spec),
|
||||
None => group.bounds(scene.bounds),
|
||||
@@ -1363,7 +1380,10 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
while let Some((command, _)) = body.take_command::<DockCommands>() {
|
||||
commands.push(command);
|
||||
}
|
||||
let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within: scene.bounds, open: open.clone() };
|
||||
// An OS window's flyouts and other layers take the room around the window (`overlay::layer_room`); an
|
||||
// in-app window's stay in the float area.
|
||||
let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds };
|
||||
let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone() };
|
||||
self.column(ui, body, &window.column, at);
|
||||
});
|
||||
self.dock = area_dock;
|
||||
@@ -1373,8 +1393,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
cross_window::accept_cross_window(&ctx);
|
||||
self.report.actions.push(dropped.action);
|
||||
}
|
||||
// The height above the window's body: the title row, and in the app window the band over it.
|
||||
let chrome = scene.sizes.window_chrome(opening.spec.is_none());
|
||||
// The height above the window's body at its scale: the title row, the rule under it, and in the app window
|
||||
// the band over it.
|
||||
let chrome = window_sizes.window_chrome(opening.spec.is_none());
|
||||
// A resize of a window whose column has steps: the steps it sets, and the window's rect at them.
|
||||
let resized = output
|
||||
.placed
|
||||
@@ -1406,8 +1427,11 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl));
|
||||
self.report.actions.extend(reported);
|
||||
}
|
||||
} else if let Some(mut change) = output.placed {
|
||||
// A collapsed window keeps the edge its move began with until the move ends where its strip was dropped.
|
||||
} else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit)
|
||||
{
|
||||
// The layer host shows a window its title row moves under the pointer, so the move reaches the workspace
|
||||
// once, when it ends: one edit. A collapsed window keeps its edge until then, and the move ends where its
|
||||
// strip was dropped.
|
||||
let mut keeps = shape.collapsed.map(|_| edge);
|
||||
if change.phase == GesturePhase::Commit && output.collapsed_width.is_none() {
|
||||
(change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl);
|
||||
@@ -1470,8 +1494,9 @@ fn split_changes<P>(from: &Node<P>, to: &Node<P>) -> Vec<(Vec<bool>, SplitSize)>
|
||||
|
||||
/// The workspace edit of a floating window's move or resize, the step `phase` of a gesture that `action`
|
||||
/// (`Action::MoveFloating`) places the window by: the gesture runs from the window's `Begin` to its `Commit`, so one
|
||||
/// drag is one undo step. `moving` holds the gesture and the workspace it began on; `rights` are the panels'
|
||||
/// permissions with the lock applied, which refuse the move of a locked workspace.
|
||||
/// drag is one undo step. A move by the title row arrives only as its `Commit`, which sets the place. `moving` holds
|
||||
/// the gesture and the workspace it began on; `rights` are the panels' permissions with the lock applied, which refuse
|
||||
/// the move of a locked workspace.
|
||||
fn window_edit<P: Clone + Eq + Hash>(
|
||||
ctx: &Context,
|
||||
current: &Arc<Workspace<P>>,
|
||||
|
||||
@@ -96,38 +96,45 @@ impl DockPanels<usize> for Demo {
|
||||
}
|
||||
|
||||
/// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the
|
||||
/// end, with one floating group and one floating window collapsed to icons.
|
||||
fn workspace() -> Arc<Workspace<usize>> {
|
||||
/// end, with one floating group, `minimized` or not, and one floating window collapsed to icons.
|
||||
fn workspace(minimized: bool) -> Arc<Workspace<usize>> {
|
||||
let tools = Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1);
|
||||
let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS], 0), Group::new(vec![PROPERTIES], 0)]).with_width(SIDE);
|
||||
let mut icons = Column::new(vec![Group::new(vec![SWATCHES], 0)]).with_width(SIDE);
|
||||
icons.iconic = true;
|
||||
let centre = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![icons]));
|
||||
let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![tools, side]), centre);
|
||||
let window = Floating::single(1, vec![HISTORY], 0, WINDOW);
|
||||
let mut window = Floating::single(1, vec![HISTORY], 0, WINDOW);
|
||||
window.column.groups[0].minimized = minimized;
|
||||
let mut collapsed = Floating::single(2, vec![NAVIGATOR], 0, COLLAPSED_WINDOW);
|
||||
collapsed.column.iconic = true;
|
||||
Arc::new(Workspace::new(Layout::new(Some(root), vec![window, collapsed])))
|
||||
}
|
||||
|
||||
fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput {
|
||||
fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo, minimized: bool) -> StoryOutput {
|
||||
/// One spec model for every story, so its revision stays put across frames.
|
||||
static SPECS: LazyLock<Tracked<DemoSpecs>> = LazyLock::new(|| Tracked::new(DemoSpecs));
|
||||
let (workspace, workspace_at) = data.value_at("workspace", workspace());
|
||||
let (workspace, workspace_at) = data.value_at("workspace", workspace(minimized));
|
||||
DockArea::new("Dock", workspace_at.bind(&mut *workspace), &*SPECS, demo, DockConfig::default()).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)]
|
||||
fn docked_columns_a_floating_group_and_a_flyout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
dock(ui, data, &mut Demo { canvas_view: false, host_rows: false })
|
||||
dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, false)
|
||||
}
|
||||
|
||||
#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)]
|
||||
fn a_canvas_group_the_host_draws(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
dock(ui, data, &mut Demo { canvas_view: true, host_rows: false })
|
||||
dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }, false)
|
||||
}
|
||||
|
||||
#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)]
|
||||
fn host_rows_above_the_dock_rows_in_a_panel_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
dock(ui, data, &mut Demo { canvas_view: false, host_rows: true })
|
||||
dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }, false)
|
||||
}
|
||||
|
||||
/// The floating group minimized: its window shows the title row and the tab strip at its width.
|
||||
#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)]
|
||||
fn a_minimized_floating_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, true)
|
||||
}
|
||||
|
||||
@@ -388,7 +388,7 @@ const MIN_SIDE: f64 = 1.0;
|
||||
|
||||
impl ExportOptions {
|
||||
/// The options as the controls can hold them for a document of size `source`: a format the list has (the first
|
||||
/// when not), a resample method of `methods` (the first when not; any method when `methods` is empty), a quality
|
||||
/// when not), a resample method of `methods` (Automatic when listed, else the first; any method when `methods` is empty), a quality
|
||||
/// of 1 to 100, and a size the document can take. A linked pixel width keeps its width and
|
||||
/// takes the height from this document (the last export's proportions would stretch another shape); unlinked
|
||||
/// pixels stay as asked when in range; anything out of range becomes 100 percent.
|
||||
@@ -399,10 +399,8 @@ impl ExportOptions {
|
||||
{
|
||||
self.format = first.id.to_owned();
|
||||
}
|
||||
if let Some(first) = Resample::ALL.iter().find(|method| methods.contains(method))
|
||||
&& !methods.contains(&self.resample)
|
||||
{
|
||||
self.resample = *first;
|
||||
if !methods.is_empty() && !methods.contains(&self.resample) {
|
||||
self.resample = if methods.contains(&default_resample()) { default_resample() } else { methods[0] };
|
||||
}
|
||||
self.quality = self.quality.clamp(*QUALITY.start(), *QUALITY.end());
|
||||
let in_range = |side: u32| (MIN_SIDE..=MAX_DOCUMENT_SIDE).contains(&f64::from(side));
|
||||
|
||||
@@ -140,8 +140,8 @@ pub struct ExportAsDialog<'a> {
|
||||
/// The formats the list offers.
|
||||
#[prop(into)]
|
||||
formats: Vec<ExportFormat>,
|
||||
/// The resample methods the list offers, in the order of [`Resample::ALL`]; all of them when empty. A method the
|
||||
/// list lacks, remembered or from a preset, opens as the first listed one.
|
||||
/// The resample methods the list offers, in the order given; all of them when empty. A method the list lacks,
|
||||
/// remembered or from a preset, opens as Automatic when listed, else as the first listed one.
|
||||
#[prop]
|
||||
methods: Vec<Resample>,
|
||||
/// The dialog's title in place of "Export As" ("Export As: Layer 1").
|
||||
@@ -451,7 +451,7 @@ impl HostedExportAs {
|
||||
self
|
||||
}
|
||||
|
||||
/// The resample methods the list offers, in the order of [`Resample::ALL`]; all of them when empty
|
||||
/// The resample methods the list offers, in the order given; all of them when empty
|
||||
/// ([`ExportAsDialog::methods`]).
|
||||
#[must_use]
|
||||
pub fn methods(mut self, methods: Vec<Resample>) -> Self {
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::display::{Shade, Text};
|
||||
use crate::list::{List, ListRow, ThumbAspect};
|
||||
use crate::patterns::presets::PresetId;
|
||||
use crate::primitives::{ContentPainterCx, StrokeWidth};
|
||||
use crate::runtime::env::{Env, Label, UnitKind};
|
||||
use crate::runtime::env::{Label, UnitKind};
|
||||
use crate::style::TypeRole;
|
||||
use crate::tabs::{Tab, TabKind, TabStrip};
|
||||
use crate::tile_grid::{Tile, TileGrid};
|
||||
@@ -171,7 +171,7 @@ pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, rea
|
||||
} else {
|
||||
let count = read.units.number(cards.len() as f64, 0..=0);
|
||||
let heading = Label::from(words.presets_heading.fill(&[("n", &count)]));
|
||||
Text::new(Env::of(ui).view().resolve(&heading).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
Text::new(heading).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui);
|
||||
let shown = TileGrid::<usize>::new(words.cards.clone())
|
||||
.card_columns(CARD_COLUMNS)
|
||||
.card()
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::presets::{
|
||||
BackgroundContents, ColorMode, DocumentOptions, MAX_NAME, MAX_SAVED, Orientation, PIXEL_ASPECTS, RESOLUTION_UNITS, SIZE_UNITS, SQUARE_PIXELS,
|
||||
};
|
||||
use super::{NewDocumentWords, Read, Session, background_rgb, depth_label, mode_label};
|
||||
use crate::buttons::Button;
|
||||
use crate::buttons::{Button, IconButton};
|
||||
use crate::choice::{Checkbox, Segmented, Swatch};
|
||||
use crate::contract::{Bind, Entry, FieldLayout, Gap, MemoProps, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked};
|
||||
use crate::display::{Shade, Text};
|
||||
@@ -123,16 +123,29 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
|
||||
PIXEL_ASPECTS.iter().map(|(id, _)| Entry::new((*id).to_owned(), pixel_aspect_label(words, id).clone())).collect();
|
||||
pixel_aspects.extend(setup.custom_pixel_aspects.iter().map(|(id, name)| Entry::new(id.clone(), name.clone())));
|
||||
|
||||
Text::new(Env::of(ui).view().resolve(&words.preset_details).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
Text::new(words.preset_details.clone()).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui);
|
||||
FieldGroup::new(words.preset_details.clone()).gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Field::new(words.name.clone()).layout(FieldLayout::Above).id_salt("name").show(ui, |ui, _| {
|
||||
let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())).limit(MAX_NAME).select_on_focus().show(ui);
|
||||
if let Some(name) = shown.value().cloned() {
|
||||
values.name = name;
|
||||
}
|
||||
if std::mem::take(&mut session.focus_name) {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(shown.response.id));
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone()))
|
||||
.limit(MAX_NAME)
|
||||
.select_on_focus()
|
||||
.sizing(Sizing::FillWidth)
|
||||
.show(ui);
|
||||
if let Some(name) = shown.value().cloned() {
|
||||
values.name = name;
|
||||
}
|
||||
if std::mem::take(&mut session.focus_name) {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(shown.response.id));
|
||||
}
|
||||
let title = words.save_preset_title.clone();
|
||||
let save = IconButton::new(IconId::new("square_plus")).label(title.clone()).tooltip(title).id_salt("save-preset").show(ui);
|
||||
if clicked(&save) {
|
||||
session.naming = Some(proposed_name(read));
|
||||
session.name_tried = false;
|
||||
session.focus_preset_name = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let dimension = |ui: &mut Ui, session: &mut Session, side: Side| {
|
||||
@@ -229,22 +242,6 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
|
||||
}
|
||||
});
|
||||
});
|
||||
Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| {
|
||||
let current = values.profile.clone().filter(|profile| others.contains(&profile));
|
||||
let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui);
|
||||
if let Some(profile) = shown.value().cloned() {
|
||||
values.profile = profile;
|
||||
}
|
||||
});
|
||||
Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| {
|
||||
let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect));
|
||||
let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() };
|
||||
let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui);
|
||||
if let Some(id) = shown.value().cloned() {
|
||||
values.pixel_aspect = id;
|
||||
}
|
||||
});
|
||||
|
||||
Field::new(words.background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let kind = BackgroundKind::of(values.background);
|
||||
@@ -265,15 +262,23 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti
|
||||
}
|
||||
});
|
||||
});
|
||||
Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| {
|
||||
let current = values.profile.clone().filter(|profile| others.contains(&profile));
|
||||
let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui);
|
||||
if let Some(profile) = shown.value().cloned() {
|
||||
values.profile = profile;
|
||||
}
|
||||
});
|
||||
Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| {
|
||||
let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect));
|
||||
let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() };
|
||||
let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui);
|
||||
if let Some(id) = shown.value().cloned() {
|
||||
values.pixel_aspect = id;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let save = Button::new(words.save_preset_title.clone()).painted(words.save_preset.clone()).id_salt("save-preset").show(ui);
|
||||
if clicked(&save) {
|
||||
session.naming = Some(proposed_name(read));
|
||||
session.name_tried = false;
|
||||
session.focus_preset_name = true;
|
||||
}
|
||||
|
||||
let fitted = values.clone().fitted();
|
||||
if fitted != *values {
|
||||
*values = fitted;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use super::FormDialog;
|
||||
use super::size_model::{LinkedSize, MAX_DOCUMENT_SIDE};
|
||||
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
|
||||
use crate::contract::{Bind, Bracket, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use crate::dialog::{DialogResult, FieldRefusal, HeldAnswer};
|
||||
use crate::display::Text;
|
||||
use crate::form::{Field, FieldGroup};
|
||||
@@ -138,11 +138,11 @@ impl Resample {
|
||||
}
|
||||
}
|
||||
|
||||
/// The list entries of the methods in `allowed`, in the order of [`Resample::ALL`]; all of them when `allowed` names
|
||||
/// none.
|
||||
/// The list entries of the methods in `allowed`, in the order given; all of them in the order of
|
||||
/// [`Resample::ALL`] when `allowed` names none.
|
||||
pub fn entries(words: &SizingWords, allowed: &[Resample]) -> Vec<Entry<Resample>> {
|
||||
let listed = |method: &Resample| allowed.is_empty() || allowed.contains(method);
|
||||
Resample::ALL.iter().copied().filter(listed).map(|method| Entry::new(method, method.label(words))).collect()
|
||||
let methods = if allowed.is_empty() { &Resample::ALL[..] } else { allowed };
|
||||
methods.iter().map(|&method| Entry::new(method, method.label(words))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,10 +412,11 @@ impl Kit {
|
||||
}
|
||||
}
|
||||
|
||||
/// The width and height rows, with the chain beside them when the model draws one.
|
||||
/// The width and height rows, with the chain bracketed to them when the model draws one.
|
||||
pub(super) fn sides(&self, ui: &mut Ui, size: &mut LinkedSize) {
|
||||
let chain = size.has_chain();
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let row = if chain { Row::new().bracket(if size.is_linked() { Bracket::Linked } else { Bracket::Unlinked }) } else { Row::new() };
|
||||
row.show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
self.row(ui, size, Dimension::Width);
|
||||
self.row(ui, size, Dimension::Height);
|
||||
@@ -465,6 +466,7 @@ impl Kit {
|
||||
.range(range.clone())
|
||||
.unit_label(unit_name.clone())
|
||||
.number_enabled(editable)
|
||||
.sizing(Sizing::Content)
|
||||
.id_salt("field")
|
||||
.show(ui);
|
||||
if let Some(number) = shown.edit.value().copied().flatten() {
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{Kit, LinkedSize, Resample, SizeForm, SizingOutput, set_size_json, sh
|
||||
use crate::choice::Checkbox;
|
||||
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use crate::form::Field;
|
||||
use crate::layout_components::Row;
|
||||
use crate::pickers::Select;
|
||||
use crate::runtime::env::{ColumnSize, Label, UnitKind};
|
||||
use crate::runtime::{keys, overlay};
|
||||
@@ -155,7 +155,7 @@ pub struct ImageSize<'a> {
|
||||
/// Binds the open state to `open`.
|
||||
#[prop(name = "opened")]
|
||||
open: Option<Bind<'a, bool>>,
|
||||
/// The methods the list offers, in the order of [`Resample::ALL`]; all of them when empty.
|
||||
/// The methods the list offers, in the order given; all of them when empty.
|
||||
#[prop]
|
||||
methods: Vec<Resample>,
|
||||
/// The bytes one pixel of the flat image takes, for the file size readout: the mode's colour channels at the
|
||||
@@ -220,18 +220,19 @@ impl<'a> ImageSize<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui);
|
||||
if let Some(on) = on.value().copied() {
|
||||
state.size.resampling(on);
|
||||
}
|
||||
if state.size.is_resampling() {
|
||||
Field::new(words.resample_method.clone()).id_salt("method").show(ui, |ui, _| {
|
||||
let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).show(ui);
|
||||
// Resample and its method share a row that starts in the control column.
|
||||
Row::new().id_salt("resample-row").show(ui, |ui, _| {
|
||||
let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui);
|
||||
if let Some(on) = on.value().copied() {
|
||||
state.size.resampling(on);
|
||||
}
|
||||
if state.size.is_resampling() {
|
||||
let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).id_salt("method").show(ui);
|
||||
if let Some(method) = picked.value().copied() {
|
||||
state.method = method;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
let styles = Checkbox::new(Bind::given(state.scale_styles))
|
||||
.label(words.scale_styles.clone())
|
||||
.id_salt("scale-styles")
|
||||
|
||||
@@ -65,6 +65,10 @@ struct Bed {
|
||||
}
|
||||
|
||||
fn bed(layout: Layout<usize>) -> Bed {
|
||||
bed_with(layout, DockConfig::default())
|
||||
}
|
||||
|
||||
fn bed_with(layout: Layout<usize>, config: DockConfig) -> Bed {
|
||||
let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout))));
|
||||
let actions: Rc<RefCell<Vec<Action<usize>>>> = Rc::default();
|
||||
let second = Rc::new(Cell::new(false));
|
||||
@@ -77,7 +81,7 @@ fn bed(layout: Layout<usize>) -> Bed {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut workspace = held.borrow().clone();
|
||||
let mut panels = Panels;
|
||||
let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui);
|
||||
let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, config.clone()).show(ui);
|
||||
*held.borrow_mut() = workspace;
|
||||
seen_actions.borrow_mut().extend(out.actions);
|
||||
if let Some(space) = out.float_space {
|
||||
@@ -138,15 +142,13 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() {
|
||||
assert!(window.panels().any(|panel| *panel == SECOND), "the tab joined the window: {:?}", bed.actions.borrow());
|
||||
}
|
||||
|
||||
/// A window's move is the area's own edit, written each pass, and keeps its drag; a host that replaces the workspace
|
||||
/// ends the drag, and the release drops nothing.
|
||||
/// A host that replaces the workspace while a window's move runs ends the drag, and the release drops nothing.
|
||||
#[trial]
|
||||
fn a_replaced_workspace_ends_the_drag_that_the_areas_own_edits_keep() {
|
||||
fn a_replaced_workspace_ends_a_window_drag() {
|
||||
let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))));
|
||||
let by = Vec2::new(-40.0, 30.0);
|
||||
press_and_move(&mut bed.fixture, window_title(), by);
|
||||
let moved_to = bed.workspace.borrow().layout().floating[0].rect;
|
||||
assert!(dragging(&bed) && moved_to != WINDOW_AT, "the window moves under its drag: {moved_to:?}");
|
||||
assert!(dragging(&bed), "the window's drag runs");
|
||||
Arc::make_mut(&mut bed.workspace.borrow_mut()).replace(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0)))));
|
||||
bed.fixture.frame(vec![moved(window_title() + by * 1.25)]);
|
||||
assert!(!dragging(&bed), "the replacement ended the drag");
|
||||
@@ -175,7 +177,7 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let given = held.borrow().clone();
|
||||
let mut panels = Requesting;
|
||||
let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default()).show(ui);
|
||||
let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default().title_bar_docks(false)).show(ui);
|
||||
Arc::make_mut(&mut held.borrow_mut()).apply_all(out.actions, false, |_| Permissions::ALL).expect("the area's actions apply");
|
||||
seen.borrow_mut().extend(out.requested);
|
||||
});
|
||||
@@ -185,11 +187,40 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() {
|
||||
let own = |action: &Action<usize>| *action == Action::activate(DOCKED) || *action == Action::activate(WINDOW);
|
||||
assert!(!asked.is_empty() && asked.iter().all(own), "each body's request came back: {asked:?}");
|
||||
assert_eq!(workspace.borrow().layout().floating[0].rect, WINDOW_AT, "nothing moved yet");
|
||||
press_and_move(&mut fixture, window_title(), Vec2::new(-40.0, 30.0));
|
||||
let by = Vec2::new(-40.0, 30.0);
|
||||
press_and_move(&mut fixture, window_title(), by);
|
||||
fixture.frame(vec![release(window_title() + by)]);
|
||||
fixture.settle();
|
||||
let moved_to = workspace.borrow().layout().floating[0].rect;
|
||||
assert!(moved_to != WINDOW_AT, "the host's copy took the window's move: {moved_to:?}");
|
||||
}
|
||||
|
||||
/// A drag of a floating window's title row shows the window under the pointer in the frame of each step, in one pass;
|
||||
/// the workspace takes the move once, on the drop.
|
||||
#[trial]
|
||||
fn a_dragged_floating_window_stands_under_the_pointer_in_each_frame_and_moves_on_the_drop() {
|
||||
let mut bed = bed(with_window(None));
|
||||
let from = window_title();
|
||||
let step = Vec2::new(-10.0, 8.0);
|
||||
bed.fixture.frame(vec![moved(from)]);
|
||||
bed.fixture.frame(vec![press(from)]);
|
||||
for n in 1..=4 {
|
||||
let to = WINDOW_AT.translate(step * n as f32);
|
||||
bed.fixture.frame(vec![moved(from + step * n as f32)]);
|
||||
let shown = layer_rects(bed.fixture.ctx());
|
||||
assert!(
|
||||
shown.iter().any(|rect| (rect.min - to.min).length() < SLACK && (rect.size() - to.size()).length() < SLACK),
|
||||
"step {n}: the window stands under the pointer in its frame: {shown:?}, wanted {to:?}"
|
||||
);
|
||||
assert_eq!(bed.fixture.passes(), 1, "step {n}: the frame runs one pass");
|
||||
assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "step {n}: the workspace is not written while the move runs");
|
||||
}
|
||||
bed.fixture.frame(vec![release(from + step * 4.0)]);
|
||||
bed.fixture.settle();
|
||||
let rect = bed.workspace.borrow().layout().floating.first().map(|window| window.rect);
|
||||
assert!(rect.is_some_and(|rect| (rect.min - (WINDOW_AT.min + step * 4.0)).length() < SLACK), "the drop moves the window: {rect:?}");
|
||||
}
|
||||
|
||||
/// A dock area's first pass leaves a drag running in another area alone.
|
||||
#[trial]
|
||||
fn an_areas_first_pass_keeps_a_running_drag() {
|
||||
@@ -247,11 +278,14 @@ fn a_floating_windows_group_starts_under_the_chrome_the_area_sizes_windows_by()
|
||||
);
|
||||
}
|
||||
|
||||
/// The window's rect while a press at `from` drags by `by`, before the release, which would dock a window moved over
|
||||
/// the docked group.
|
||||
/// The window's rect after a press at `from` drags by `by` and releases, in an area whose title-row drags only move a
|
||||
/// window, so the release docks nothing.
|
||||
fn dragged_from(from: Pos2, by: Vec2) -> Rect {
|
||||
let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))));
|
||||
let config = DockConfig::default().title_bar_docks(false);
|
||||
let mut bed = bed_with(with_window(Some(Node::tabs(vec![DOCKED], 0))), config);
|
||||
press_and_move(&mut bed.fixture, from, by);
|
||||
bed.fixture.frame(vec![release(from + by)]);
|
||||
bed.fixture.settle();
|
||||
bed.workspace.borrow().layout().floating[0].rect
|
||||
}
|
||||
|
||||
@@ -520,6 +554,52 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col
|
||||
assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "the expanded rect is unchanged");
|
||||
}
|
||||
|
||||
/// A floating window whose every group is minimized shows its title row and tab strip at its place and width. Its free
|
||||
/// side resizes its width and not its height, and its rect keeps the expanded height, which the window shows at again
|
||||
/// once the group is restored.
|
||||
#[trial]
|
||||
fn a_window_whose_groups_are_all_minimized_shows_its_strip_and_comes_back_at_its_height() {
|
||||
let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))));
|
||||
let window_layer = |bed: &Bed| {
|
||||
let layers = layer_rects(bed.fixture.ctx()).into_iter().filter(|rect| rect.contains(window_title()));
|
||||
layers.min_by(|a, b| a.area().total_cmp(&b.area())).expect("the window's layer holds its title row")
|
||||
};
|
||||
let strip = |bed: &Bed| {
|
||||
let lists = bed.fixture.by_role(Role::TAB_LIST).into_iter().filter(|list| WINDOW_AT.expand(SLACK).contains_rect(list.rect));
|
||||
lists.map(|list| list.rect).next().expect("the window shows its tab strip")
|
||||
};
|
||||
Arc::make_mut(&mut bed.workspace.borrow_mut())
|
||||
.apply(Action::set_minimized(WINDOW, true), false, |_| Permissions::ALL)
|
||||
.expect("the group minimizes");
|
||||
bed.fixture.settle();
|
||||
let shown = window_layer(&bed);
|
||||
assert!((shown.bottom() - strip(&bed).bottom()).abs() <= SLACK, "the window ends at its strip: {shown:?}, {:?}", strip(&bed));
|
||||
assert!((shown.min - WINDOW_AT.min).length() <= SLACK && (shown.width() - WINDOW_AT.width()).abs() <= SLACK, "at its place and width: {shown:?}");
|
||||
|
||||
// The window keeps to the end edge; its start side is free, and a press just inside it holds the side's grip.
|
||||
let side = Pos2::new(shown.left() + 2.0, shown.center().y);
|
||||
let by = Vec2::new(-40.0, 10.0);
|
||||
press_and_move(&mut bed.fixture, side, by);
|
||||
bed.fixture.frame(vec![release(side + by)]);
|
||||
bed.fixture.settle();
|
||||
let resized = window_layer(&bed);
|
||||
let rect = bed.workspace.borrow().layout().floating[0].rect;
|
||||
assert!((resized.width() - (shown.width() - by.x)).abs() <= SLACK, "the side resizes the width: {shown:?}, then {resized:?}");
|
||||
assert!((resized.height() - shown.height()).abs() <= SLACK, "the height stays the strip's: {resized:?}");
|
||||
assert!(
|
||||
(rect.width() - resized.width()).abs() <= SLACK && rect.height() == WINDOW_AT.height(),
|
||||
"the rect takes the width and keeps its height: {rect:?}"
|
||||
);
|
||||
|
||||
Arc::make_mut(&mut bed.workspace.borrow_mut())
|
||||
.apply(Action::set_minimized(WINDOW, false), false, |_| Permissions::ALL)
|
||||
.expect("the group restores");
|
||||
bed.fixture.settle();
|
||||
let restored = window_layer(&bed);
|
||||
assert!((restored.height() - WINDOW_AT.height()).abs() <= SLACK, "restored, the window shows at its height: {restored:?}");
|
||||
assert!((restored.width() - resized.width()).abs() <= SLACK, "at the width the side gave it: {restored:?}");
|
||||
}
|
||||
|
||||
/// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to.
|
||||
#[trial]
|
||||
fn a_floating_collapsed_columns_flyout_opens_towards_the_room() {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace};
|
||||
use craft_behavior::placement::Placement;
|
||||
use craft_host::target::{Backend, Caps, Os, ShellInfo};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::contract::{Bind, BodyCx, DropMark, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs};
|
||||
@@ -11,11 +12,12 @@ use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::popover::DropVeil;
|
||||
use craft_ui::runtime::InstallSpec;
|
||||
use craft_ui::runtime::drag;
|
||||
use craft_ui::testing::access::AccessTree;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::trial;
|
||||
use craft_ui::testing::windows::FakeSystem;
|
||||
use craft_ui_test_kit::windows::Windows;
|
||||
use craft_ui_test_kit::windows::{Out, Windows};
|
||||
use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -257,6 +259,10 @@ struct NativeDock {
|
||||
/// The palette window's builder as the integration keeps it: each frame's builder patched onto it, which sends the
|
||||
/// window only the limits a builder carries.
|
||||
builder: Option<ViewportBuilder>,
|
||||
/// The palette's window: the first child window the dock opened.
|
||||
palette: Option<ViewportId>,
|
||||
/// The tree the palette window's pass produced in the last frame.
|
||||
palette_tree: Option<AccessTree>,
|
||||
}
|
||||
|
||||
impl NativeDock {
|
||||
@@ -278,7 +284,7 @@ impl NativeDock {
|
||||
windows.child_info(info(true, FLOAT_AT));
|
||||
let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])));
|
||||
let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped });
|
||||
let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None };
|
||||
let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None };
|
||||
for _ in 0..3 {
|
||||
dock.frame(vec![]);
|
||||
}
|
||||
@@ -300,7 +306,12 @@ impl NativeDock {
|
||||
let out = self.windows.frame(root, child, |ui| {
|
||||
actions.extend(DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui).actions);
|
||||
});
|
||||
for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) {
|
||||
if self.palette.is_none() {
|
||||
self.palette = out.builders.iter().map(|(viewport, _)| *viewport).find(|viewport| *viewport != ViewportId::ROOT);
|
||||
}
|
||||
let palette = self.palette;
|
||||
self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree);
|
||||
for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) {
|
||||
match self.builder.as_mut() {
|
||||
Some(kept) => {
|
||||
let _ = kept.patch(builder);
|
||||
@@ -308,7 +319,7 @@ impl NativeDock {
|
||||
None => self.builder = Some(builder),
|
||||
}
|
||||
}
|
||||
let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect();
|
||||
let commands = out.commands.into_iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command).collect();
|
||||
(actions, commands)
|
||||
}
|
||||
}
|
||||
@@ -717,6 +728,68 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only()
|
||||
assert_eq!(at.width(), width, "the window keeps the width the OS gave it");
|
||||
}
|
||||
|
||||
/// A native palette whose every group is minimized shrinks to its title row and tab strip at its place and width.
|
||||
/// The OS resizes its width and never its height: AppKit takes the height as fixed, and the app sends no size back
|
||||
/// for the width the OS gave it. The model keeps the expanded height throughout, and restored, the window takes that
|
||||
/// height back at the width it was given.
|
||||
#[trial]
|
||||
fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_height() {
|
||||
for os in [Os::Mac, Os::Windows] {
|
||||
let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new()));
|
||||
let expanded = FLOAT_AT.size();
|
||||
let mut at = FLOAT_AT;
|
||||
// The OS follows the window commands of each frame, within the limits in force, and the window reports where it is.
|
||||
let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| {
|
||||
let mut sent = Vec::new();
|
||||
for _ in 0..frames {
|
||||
let mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size);
|
||||
let commands = dock.frame(vec![]).1;
|
||||
for command in &commands {
|
||||
match command {
|
||||
ViewportCommand::MaxInnerSize(limit) => max = Some(*limit),
|
||||
ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, max.map_or(*size, |max| size.min(max))),
|
||||
ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
dock.windows.child_info(info(true, *at));
|
||||
sent.extend(commands);
|
||||
}
|
||||
sent
|
||||
};
|
||||
let recorded =
|
||||
|dock: &NativeDock| Vec2::from(dock.workspace.layout().floating[0].native.clone().expect("the model records the window").normal.size);
|
||||
Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, true), false, |_| Permissions::ALL).expect("the group minimizes");
|
||||
follow(&mut dock, &mut at, 3);
|
||||
let strips = at;
|
||||
assert!(strips.height() < expanded.y / 4.0, "{os:?}: the window shrinks to its title row and strip: {strips:?}");
|
||||
if let Err(fit) = fits_exactly(dock.palette_tree.as_ref().expect("the palette ran a pass"), strips.size(), Role::TAB_LIST) {
|
||||
panic!("{os:?}: the minimized window fits its title row and strip: {fit}");
|
||||
}
|
||||
assert_eq!((strips.min, strips.width()), (FLOAT_AT.min, expanded.x), "{os:?}: at its place and width");
|
||||
assert_eq!(recorded(&dock), expanded, "{os:?}: minimized, the model keeps the expanded size");
|
||||
let builder = dock.builder.clone().expect("the palette's window opened");
|
||||
let (least, most) = (builder.min_inner_size.expect("a least size"), builder.max_inner_size.expect("a most size"));
|
||||
assert!(least.y == most.y && (least.y - strips.height()).abs() <= 0.5, "{os:?}: the height is fixed: {least:?}..{most:?}, {strips:?}");
|
||||
assert!(least.x < most.x, "{os:?}: the width resizes: {least:?}..{most:?}");
|
||||
if os == Os::Mac {
|
||||
assert_eq!(builder.resizable, Some(true), "AppKit resizes the minimized window");
|
||||
}
|
||||
|
||||
// The OS widens the window.
|
||||
let width = expanded.x + 60.0;
|
||||
at = Rect::from_min_size(at.min, Vec2::new(width, at.height()));
|
||||
dock.windows.child_info(info(true, at));
|
||||
let sent = follow(&mut dock, &mut at, 3);
|
||||
assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::InnerSize(_))), "{os:?}: no size goes back: {sent:?}");
|
||||
assert_eq!(recorded(&dock), Vec2::new(width, expanded.y), "{os:?}: the model takes the width and keeps the expanded height");
|
||||
|
||||
Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, false), false, |_| Permissions::ALL).expect("the group restores");
|
||||
follow(&mut dock, &mut at, 3);
|
||||
assert_eq!(at, Rect::from_min_size(FLOAT_AT.min, Vec2::new(width, expanded.y)), "{os:?}: restored, the window takes its height back");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a display at 125 % (Windows), a click on the double arrow of a native palette collapsed to icons expands its
|
||||
/// column, and the OS window takes its expanded size.
|
||||
#[trial]
|
||||
@@ -751,6 +824,246 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() {
|
||||
assert_eq!(at.size(), FLOAT_AT.size(), "the OS window takes its expanded size");
|
||||
}
|
||||
|
||||
/// Panels whose palette panel's body records, in each of its real runs, the viewport it runs in.
|
||||
#[derive(Default)]
|
||||
struct BodyProbe(Vec<ViewportId>);
|
||||
|
||||
impl DockPanels<u32> for BodyProbe {
|
||||
fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
let ctx = ui.ctx();
|
||||
if *panel == 1 && !craft_ui::testing::is_measuring(ctx) {
|
||||
self.0.push(ctx.viewport_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The scale of the display the collapsed palette trials run on: Windows at 125 %, where the issue was reported.
|
||||
const COLLAPSED_SCALE: f32 = 1.25;
|
||||
|
||||
/// A native palette collapsed to icons on Windows at 125 %, and the rect its OS window shows the strip at.
|
||||
fn collapsed_palette() -> (NativeDock, Rect) {
|
||||
let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new()));
|
||||
// Both windows report the display at 125 % before the column collapses.
|
||||
dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE));
|
||||
let mut at = FLOAT_AT;
|
||||
dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE));
|
||||
collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]);
|
||||
Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses");
|
||||
for _ in 0..4 {
|
||||
collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]);
|
||||
}
|
||||
(dock, at)
|
||||
}
|
||||
|
||||
/// One frame of `dock` with `panels`, `root` events for the main window and `child` events for the palette's window,
|
||||
/// whose OS window follows its commands at `at`: the frame's output.
|
||||
fn collapsed_frame(dock: &mut NativeDock, panels: &mut dyn DockPanels<u32>, at: &mut Rect, root: Vec<Event>, child: Vec<Event>) -> Out {
|
||||
let workspace = &mut dock.workspace;
|
||||
let specs = &dock.specs;
|
||||
let out = dock.windows.frame(root, child, |ui| {
|
||||
let _ = DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui);
|
||||
});
|
||||
let palette = dock.palette;
|
||||
let commands: Vec<ViewportCommand> =
|
||||
out.commands.iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command.clone()).collect();
|
||||
*at = placed_by(&commands, *at);
|
||||
dock.windows.child_info(scaled(true, *at, COLLAPSED_SCALE));
|
||||
out
|
||||
}
|
||||
|
||||
/// The windows the frame showed other than the main window and the palette's: its popup windows.
|
||||
fn popups(dock: &NativeDock, out: &Out) -> Vec<ViewportId> {
|
||||
out.builders.iter().map(|(viewport, _)| *viewport).filter(|viewport| *viewport != ViewportId::ROOT && Some(*viewport) != dock.palette).collect()
|
||||
}
|
||||
|
||||
/// The rect of `viewport`'s window in desktop points, as the window system reports it.
|
||||
fn window_rect(dock: &NativeDock, viewport: ViewportId) -> Rect {
|
||||
dock.windows.facts(viewport).inner_rect.expect("the window reports its rect")
|
||||
}
|
||||
|
||||
/// The rect, in its window's points, of the node of `tree` named `name` whose role is `role`.
|
||||
fn node_rect(tree: &AccessTree, name: &str, role: Role) -> Option<Rect> {
|
||||
tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)).and_then(|key| tree.bounds_of(key))
|
||||
}
|
||||
|
||||
/// How far a node's edge may stray from the window's for float rounding: far under a pixel at any scale.
|
||||
const FIT_ROUNDING: f32 = 0.05;
|
||||
|
||||
/// Whether a window `size` big fits what its pass shows in `tree` exactly: every node lies inside it, and the lowest
|
||||
/// node of `role` ends at its bottom, within float rounding.
|
||||
fn fits_exactly(tree: &AccessTree, size: Vec2, role: Role) -> Result<(), String> {
|
||||
let window = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let outside: Vec<Rect> =
|
||||
tree.keys().into_iter().filter_map(|key| tree.bounds_of(key)).filter(|rect| !window.expand(FIT_ROUNDING).contains_rect(*rect)).collect();
|
||||
let bottom = tree.with_role(role).into_iter().filter_map(|key| tree.bounds_of(key)).map(|rect| rect.max.y).fold(f32::MIN, f32::max);
|
||||
if !outside.is_empty() {
|
||||
return Err(format!("nodes past the {size:?} window: {outside:?}"));
|
||||
}
|
||||
if (bottom - size.y).abs() > FIT_ROUNDING {
|
||||
return Err(format!("the content ends at {bottom}, the {size:?} window at {}", size.y));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The role and name of each named node of `tree`.
|
||||
fn nodes(tree: &AccessTree) -> Vec<(Option<Role>, String)> {
|
||||
let mut nodes: Vec<(Option<Role>, String)> =
|
||||
tree.keys().into_iter().filter_map(|key| tree.name_of(key).map(|name| (tree.role_of(key), name.to_owned()))).collect();
|
||||
nodes.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}")));
|
||||
nodes
|
||||
}
|
||||
|
||||
/// The tree the frame's pass of `viewport` produced.
|
||||
fn tree_of_viewport(out: &Out, viewport: ViewportId) -> &AccessTree {
|
||||
&out.trees.iter().find(|(shown, _)| *shown == viewport).expect("the viewport ran a pass").1
|
||||
}
|
||||
|
||||
/// Opens the flyout of the collapsed palette's panel by a click on its icon; returns the flyout's popup window.
|
||||
fn open_flyout(dock: &mut NativeDock, panels: &mut dyn DockPanels<u32>, at: &mut Rect) -> ViewportId {
|
||||
let out = collapsed_frame(dock, panels, at, vec![], vec![]);
|
||||
let palette = dock.palette.expect("the palette's window opened");
|
||||
let icon = node_rect(tree_of_viewport(&out, palette), PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon").center();
|
||||
for events in [vec![moved(icon)], vec![press(icon)], vec![release(icon)]] {
|
||||
collapsed_frame(dock, panels, at, vec![], events);
|
||||
}
|
||||
let out = collapsed_frame(dock, panels, at, vec![], vec![]);
|
||||
let opened = popups(dock, &out);
|
||||
assert_eq!(opened.len(), 1, "the click opens one popup window: {opened:?}");
|
||||
opened[0]
|
||||
}
|
||||
|
||||
/// A click on the icon of a native palette collapsed to icons opens the panel's flyout in a popup OS window of its
|
||||
/// own, beside the strip against its side away from the edge it keeps to, in desktop points: a palette-level window
|
||||
/// with no taskbar entry that takes the focus. The flyout's body runs in the popup's pass only, as often in each
|
||||
/// frame, never in the palette's.
|
||||
#[trial]
|
||||
fn a_click_on_an_icon_of_a_collapsed_native_palette_opens_its_flyout_in_an_os_window_beside_it() {
|
||||
let (mut dock, mut at) = collapsed_palette();
|
||||
let mut probe = BodyProbe::default();
|
||||
let palette = dock.palette.expect("the palette's window opened");
|
||||
let strip = nodes(tree_of_viewport(&collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]), palette));
|
||||
let popup = open_flyout(&mut dock, &mut probe, &mut at);
|
||||
let flyout = window_rect(&dock, popup);
|
||||
let end = at.max.x >= FLOAT_AT.max.x - 1.0;
|
||||
let outer = if end { (flyout.max.x - at.min.x).abs() } else { (flyout.min.x - at.max.x).abs() };
|
||||
assert!(outer <= 0.5, "the flyout stands against the strip's side away from its edge: {flyout:?} beside {at:?}");
|
||||
assert!(flyout.min.y >= at.min.y - 0.5 && flyout.min.y < at.max.y, "the flyout's top is level with the strip: {flyout:?}, {at:?}");
|
||||
let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]);
|
||||
let builder = &out.builders.iter().find(|(viewport, _)| *viewport == popup).expect("the popup shows").1;
|
||||
assert_eq!(builder.window_level, Some(egui::WindowLevel::AlwaysOnTop), "the popup stands as a palette of the active app");
|
||||
assert_eq!(builder.taskbar, Some(false), "the popup has no taskbar entry");
|
||||
assert_ne!(builder.active, Some(false), "the flyout takes the focus");
|
||||
assert_eq!(nodes(tree_of_viewport(&out, palette)), strip, "the palette's window shows none of the flyout");
|
||||
assert!(!tree_of_viewport(&out, popup).keys().is_empty(), "the popup window shows the flyout");
|
||||
let runs = |probe: &mut BodyProbe, dock: &mut NativeDock, at: &mut Rect| {
|
||||
probe.0.clear();
|
||||
collapsed_frame(dock, probe, at, vec![], vec![]);
|
||||
std::mem::take(&mut probe.0)
|
||||
};
|
||||
let (first, second) = (runs(&mut probe, &mut dock, &mut at), runs(&mut probe, &mut dock, &mut at));
|
||||
assert!(!first.is_empty() && first.iter().all(|viewport| *viewport == popup), "the body runs in the popup's pass: {first:?}");
|
||||
assert_eq!(first.len(), second.len(), "the body runs as often in each frame");
|
||||
}
|
||||
|
||||
/// The pointer rests on the double arrow of a collapsed native palette past the tooltip delay: the frame that follows.
|
||||
fn hovered_arrow(dock: &mut NativeDock, at: &mut Rect) -> (Out, Rect) {
|
||||
let end = at.max.x >= FLOAT_AT.max.x - 1.0 && at.min.x > FLOAT_AT.min.x + 1.0;
|
||||
let arrow = Pos2::new(if end { at.width() - 4.0 } else { 4.0 }, 4.0);
|
||||
collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![moved(arrow)]);
|
||||
// The tooltip shows after its delay, at 60 frames a second.
|
||||
let frames = (craft_ui::contract::tooltip::DELAY * 60.0).ceil() as usize + 2;
|
||||
for _ in 0..frames {
|
||||
collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]);
|
||||
}
|
||||
let out = collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]);
|
||||
let palette = dock.palette.expect("the palette's window opened");
|
||||
let name = tree_of_viewport(&out, palette).keys().into_iter().find_map(|key| {
|
||||
let tree = tree_of_viewport(&out, palette);
|
||||
tree.name_of(key)
|
||||
.filter(|name| name.starts_with("Expand"))
|
||||
.filter(|_| tree.role_of(key) == Some(Role::BUTTON))
|
||||
.and_then(|_| tree.bounds_of(key))
|
||||
});
|
||||
let arrow_rect = name.expect("the title row shows the double arrow");
|
||||
(out, arrow_rect)
|
||||
}
|
||||
|
||||
/// A native palette collapsed to icons paints the icons of its panels and no text cut by its window, also while the
|
||||
/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it, and the
|
||||
/// window fits the title row, its rule and the icons exactly.
|
||||
#[trial]
|
||||
fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() {
|
||||
let (mut dock, mut at) = collapsed_palette();
|
||||
let (out, _) = hovered_arrow(&mut dock, &mut at);
|
||||
let palette = dock.palette.expect("the palette's window opened");
|
||||
let tree = tree_of_viewport(&out, palette);
|
||||
let window = Rect::from_min_size(Pos2::ZERO, at.size());
|
||||
let icon = node_rect(tree, PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon");
|
||||
assert!(window.contains(icon.center()), "the icon shows in the strip: {icon:?} in {window:?}");
|
||||
assert!(tree.with_role(Role::TOOLTIP).is_empty(), "no tooltip shows inside the strip");
|
||||
if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) {
|
||||
panic!("the strip's window fits its icons: {fit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A native palette on a monitor at 1x while the main window is on one at 2x (a laptop with an external display):
|
||||
/// collapsed to icons, its window fits the title row, the rule under it and the icons exactly at its own scale.
|
||||
#[trial]
|
||||
fn a_collapsed_native_palette_on_a_1x_monitor_beside_a_2x_main_window_fits_its_icons_exactly() {
|
||||
let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new()));
|
||||
dock.windows.root_info(scaled(true, MAIN_AT, 2.0));
|
||||
let mut at = FLOAT_AT;
|
||||
dock.windows.child_info(scaled(true, at, 1.0));
|
||||
Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses");
|
||||
for _ in 0..4 {
|
||||
let commands = dock.frame(vec![]).1;
|
||||
at = placed_by(&commands, at);
|
||||
dock.windows.child_info(scaled(true, at, 1.0));
|
||||
}
|
||||
let tree = dock.palette_tree.as_ref().expect("the palette ran a pass");
|
||||
if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) {
|
||||
panic!("the strip's window fits its icons at its own scale: {fit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop
|
||||
/// points, on one line: the window takes no focus and lets the pointer through to the palette.
|
||||
#[trial]
|
||||
fn a_tooltip_from_a_native_palette_opens_in_a_popup_os_window() {
|
||||
let (mut dock, mut at) = collapsed_palette();
|
||||
let (out, arrow) = hovered_arrow(&mut dock, &mut at);
|
||||
let shown = popups(&dock, &out);
|
||||
let tip = shown
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::TOOLTIP).is_empty())
|
||||
.expect("the tooltip shows in a popup window");
|
||||
let builder = &out.builders.iter().find(|(viewport, _)| *viewport == tip).expect("the popup shows").1;
|
||||
assert_eq!(builder.active, Some(false), "the tooltip's window takes no focus");
|
||||
assert_eq!(builder.mouse_passthrough, Some(true), "the pointer passes through the tooltip's window");
|
||||
let rect = window_rect(&dock, tip);
|
||||
assert!(rect.min.y >= at.min.y + arrow.max.y - 0.5, "the tooltip stands below the arrow: {rect:?}, arrow {arrow:?} in {at:?}");
|
||||
assert!(rect.width() > at.width() && rect.height() < rect.width(), "the tooltip's text runs on one line, wider than the strip: {rect:?}");
|
||||
}
|
||||
|
||||
/// A press in the main window closes the flyout a collapsed native palette opened in a popup window.
|
||||
#[trial]
|
||||
fn a_press_in_the_main_window_closes_a_native_palettes_flyout() {
|
||||
let (mut dock, mut at) = collapsed_palette();
|
||||
let mut probe = BodyProbe::default();
|
||||
let popup = open_flyout(&mut dock, &mut probe, &mut at);
|
||||
let over = OVER_GROUP - MAIN_AT.min.to_vec2();
|
||||
for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] {
|
||||
collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]);
|
||||
}
|
||||
// The flyout fades out, then its window closes.
|
||||
let closed = (0..60).any(|_| {
|
||||
let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]);
|
||||
!popups(&dock, &out).contains(&popup)
|
||||
});
|
||||
assert!(closed, "the flyout's window closed");
|
||||
}
|
||||
|
||||
/// Palettes no smaller than `PALETTE_LEAST`.
|
||||
struct Least;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use craft_ui::patterns::form_dialogs::{
|
||||
HostedFormatOptions, JpegOptions, OutputPathRow, Resample, ScaleRow, ScaleSize, SizeEstimate,
|
||||
};
|
||||
use craft_ui::runtime::requests::PathRequest;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::RefCell;
|
||||
@@ -281,6 +282,36 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones()
|
||||
assert_eq!(again.scale_all, jpeg.scale_all, "and their Scale All rows");
|
||||
}
|
||||
|
||||
/// Export As lists the app's resample methods in the order it gives, and an unlisted opening method opens as Automatic
|
||||
/// when listed, else as the first listed one.
|
||||
#[trial]
|
||||
fn export_as_lists_resample_methods_in_the_hosts_order() {
|
||||
let methods = vec![Resample::Bicubic, Resample::BicubicSmoother, Resample::NearestNeighbor, Resample::PreserveDetails];
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(Vec2::new(1400.0, 1000.0));
|
||||
let mut start = ExportOptions::default();
|
||||
start.resample = Resample::Lanczos;
|
||||
host.borrow_mut().open(HostedExportAs::new("Poster", document(), start).methods(methods.clone()));
|
||||
fixture.idle(10);
|
||||
let opened = host.borrow_mut().get_mut::<HostedExportAs>().map(|dialog| dialog.options().resample).expect("the dialog is open");
|
||||
assert_eq!(opened, Resample::Bicubic, "without Automatic in the list, the first listed method opens");
|
||||
|
||||
let select = fixture.by_label("Resample").expect("the resample select");
|
||||
fixture.access(AccessActionKind::Focus, &select).idle(2);
|
||||
fixture.key(Key::Space, Modifiers::NONE).idle(3);
|
||||
let mut options = fixture.by_role(Role::LIST_BOX_OPTION);
|
||||
options.sort_by(|a, b| a.center().y.total_cmp(&b.center().y));
|
||||
let names: Vec<String> = options.iter().map(|option| fixture.tree().name_of(option.node).expect("the option has a name").to_owned()).collect();
|
||||
assert_eq!(names.len(), methods.len(), "the list offers the listed methods only");
|
||||
assert_eq!(
|
||||
names,
|
||||
["Bicubic (smooth gradients)", "Bicubic Smoother (enlargement)", "Nearest Neighbor (hard edges)", "Preserve Details"],
|
||||
"the list keeps the host's order"
|
||||
);
|
||||
}
|
||||
|
||||
/// Export As with the app's resample methods offers no other: an unlisted opening method opens as the first listed
|
||||
/// one, and automation cannot set an unlisted one.
|
||||
#[trial]
|
||||
|
||||
@@ -464,3 +464,120 @@ fn image_size_alt_digits_pick_resample_without_typing_into_a_field() {
|
||||
alt_digit(&mut fixture, Key::Num7, "7", alt);
|
||||
assert_eq!(resample(&host), Some(json!("nearestNeighbor")), "Alt+7 picks a listed method");
|
||||
}
|
||||
|
||||
/// Opens a dialog on a host.
|
||||
type Opener = fn(&mut DialogHost);
|
||||
|
||||
/// Image Size's and Canvas Size's Width and Height rows (a stack of fields beside the link) show as they measured, at
|
||||
/// 1x and 1.25x (#15483, #15538): each label sits beside its field, each field and unit select is as tall as a direct
|
||||
/// row's control (`reference`), and Height's label starts under Width's controls.
|
||||
#[trial]
|
||||
fn sizing_dialogs_show_width_and_height_beside_their_labels_at_full_height() {
|
||||
for scale in [1.0, 1.25] {
|
||||
let opens: [(Opener, &str); 2] = [
|
||||
(
|
||||
|host| {
|
||||
host.open(image_size());
|
||||
},
|
||||
"Resolution",
|
||||
),
|
||||
(
|
||||
|host| {
|
||||
host.open(canvas_size());
|
||||
},
|
||||
"Canvas extension color",
|
||||
),
|
||||
];
|
||||
for (open, reference) in opens {
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let mut fixture = fixture(&host);
|
||||
fixture.pixels_per_point(scale);
|
||||
open(&mut host.borrow_mut());
|
||||
fixture.settle();
|
||||
let rect = |name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect;
|
||||
let label_of = |name: &str| {
|
||||
// The field's label names the unit select's group, the number field's parent.
|
||||
let tree = fixture.tree();
|
||||
let mut node = fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).node;
|
||||
let label = loop {
|
||||
if let Some(label) = tree.labelled_by_key(node).into_iter().next() {
|
||||
break label;
|
||||
}
|
||||
node = tree.parent_of_key(node).unwrap_or_else(|| panic!("{name} is labelled"));
|
||||
};
|
||||
tree.bounds_of(label).unwrap_or_else(|| panic!("{name}'s label is shown"))
|
||||
};
|
||||
let full = rect(reference).height();
|
||||
for name in ["Width", "Height"] {
|
||||
let (label, field) = (label_of(name), rect(name));
|
||||
for part in [field, rect(&format!("{name} unit"))] {
|
||||
assert!(part.height() >= full - 0.5, "{name}'s controls are a full row tall at {scale}x ({reference}): {part:?} {full}");
|
||||
}
|
||||
assert!(label.max.x <= field.min.x + 0.5, "{name}'s label sits before its field at {scale}x ({reference}): {label:?} {field:?}");
|
||||
assert!(
|
||||
label.min.y < field.max.y && label.max.y > field.min.y,
|
||||
"{name}'s label is on its field's line at {scale}x: {label:?} {field:?}"
|
||||
);
|
||||
}
|
||||
let (width, height) = (rect("Width").union(rect("Width unit")), label_of("Height"));
|
||||
assert!(height.min.y >= width.max.y - 0.5, "Height's row starts under Width's at {scale}x ({reference}): {height:?} {width:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The horizontal line segments one frame of `fixture` paints, as (y, from x, to x).
|
||||
fn horizontal_lines(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> {
|
||||
fixture
|
||||
.frame_shapes()
|
||||
.into_iter()
|
||||
.filter_map(|shape| match shape {
|
||||
egui::Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < 0.5 => Some((a.y, a.x.min(b.x), a.x.max(b.x))),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Image Size as 0.23.1 lays it out: the chain sits halfway between Width's and Height's controls with the bracket
|
||||
/// drawn from each control to it, and Resample starts in the control column with the method on its line.
|
||||
#[trial]
|
||||
fn image_size_brackets_width_and_height_and_starts_resample_in_the_control_column() {
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let mut fixture = fixture(&host);
|
||||
host.borrow_mut().open(image_size());
|
||||
fixture.settle();
|
||||
let rect = |fixture: &Fixture, name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect;
|
||||
let (width, height, link) = (rect(&fixture, "Width unit"), rect(&fixture, "Height unit"), rect(&fixture, "Maintain aspect ratio"));
|
||||
let middle = (width.center().y + height.center().y) / 2.0;
|
||||
assert!((link.center().y - middle).abs() <= 0.5, "the chain sits halfway between Width and Height: {link:?} {middle}");
|
||||
let lines = horizontal_lines(&mut fixture);
|
||||
for (name, row) in [("Width", width), ("Height", height)] {
|
||||
assert!(
|
||||
lines.iter().any(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0),
|
||||
"a tick runs from {name}'s control to the chain: {lines:?}"
|
||||
);
|
||||
}
|
||||
let (number, check, method) = (rect(&fixture, "Width"), rect(&fixture, "Resample"), rect(&fixture, "Resample method"));
|
||||
assert!((check.min.x - number.min.x).abs() <= 0.5, "Resample starts at the control column: {check:?} {number:?}");
|
||||
assert!(
|
||||
method.min.x >= check.max.x - 0.5 && method.min.y < check.max.y && method.max.y > check.min.y,
|
||||
"the method follows Resample on its line: {method:?} {check:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Canvas Size draws one rule between its title and Current Size, the title's: the first section's rule above would
|
||||
/// stand right under it. The rule between the two sections stays.
|
||||
#[trial]
|
||||
fn canvas_size_draws_one_rule_under_its_title() {
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let mut fixture = fixture(&host);
|
||||
host.borrow_mut().open(canvas_size());
|
||||
fixture.settle();
|
||||
let text = |fixture: &Fixture, text: &str| {
|
||||
fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted"))
|
||||
};
|
||||
let (title, current, new) = (text(&fixture, "Canvas Size"), text(&fixture, "Current Size"), text(&fixture, "New Size"));
|
||||
let lines = horizontal_lines(&mut fixture);
|
||||
let across = |top: f32, bottom: f32| lines.iter().filter(|(y, from, to)| *y > top && *y < bottom && to - from > current.width()).count();
|
||||
assert_eq!(across(title.max.y, current.min.y), 1, "one rule between the title and Current Size: {lines:?}");
|
||||
assert_eq!(across(current.max.y, new.min.y), 1, "a rule between Current Size and New Size: {lines:?}");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Opens the Save Document Preset pane with the button below the fields, types `name` over the proposed one and saves.
|
||||
/// Opens the Save Document Preset pane with the icon on the Name row, types `name` over the proposed one and saves.
|
||||
fn save_preset(fixture: &mut Fixture, name: &str) {
|
||||
let save = fixture.by_label("Save Document Preset").expect("the Save Document Preset button");
|
||||
fixture.click(&save).idle(10);
|
||||
@@ -266,5 +266,38 @@ fn the_new_document_layout_places_presets_and_details_below_the_tabs() {
|
||||
assert!(recent.bottom() <= mode.top(), "tabs go above the details");
|
||||
assert!((mode.top() - depth.top()).abs() < 1.0, "color mode and depth share a row");
|
||||
assert!(mode.right() <= depth.left(), "depth follows color mode");
|
||||
assert!(mode.bottom() <= save.top() && save.bottom() <= create.top(), "Save Preset is between the fields and the footer");
|
||||
assert!(save.bottom() <= create.top(), "Save Preset is above the footer");
|
||||
}
|
||||
|
||||
/// The fields run Name, size, Color Mode, Background Contents, then the advanced Color Profile and Pixel Aspect Ratio; the
|
||||
/// save icon (no text) sits at the end of the Name row.
|
||||
#[trial]
|
||||
fn the_new_document_fields_run_background_before_the_advanced_ones_and_save_sits_on_the_name_row() {
|
||||
let mut options = DocumentOptions::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
|
||||
let top = |fixture: &Fixture, label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the {label} field")).rect.top();
|
||||
let (mode, background) = (top(&fixture, "Color Mode"), top(&fixture, "Background Contents"));
|
||||
let (profile, aspect) = (top(&fixture, "Color Profile"), top(&fixture, "Pixel Aspect Ratio"));
|
||||
assert!(mode < background && background < profile && profile < aspect, "Background Contents comes before the advanced fields");
|
||||
|
||||
let name = fixture.by_label("Name").expect("the Name field").rect;
|
||||
let save = fixture.by_label("Save Document Preset").expect("the save action").rect;
|
||||
assert!(save.top() < name.bottom() && name.top() < save.bottom(), "the save icon shares the Name row");
|
||||
assert!(name.right() <= save.left(), "the save icon is at the end of the Name field");
|
||||
assert!(!fixture.texts().iter().any(|run| run.text.starts_with("Save ")), "the save control is an icon, with no text");
|
||||
}
|
||||
|
||||
/// The caption role sets its text in capitals when it paints; the label stays as written.
|
||||
#[trial]
|
||||
fn section_captions_paint_in_capitals_and_keep_their_text() {
|
||||
let mut options = DocumentOptions::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
|
||||
assert!(shows(&fixture, "PRESET DETAILS"), "the caption paints in capitals");
|
||||
assert!(fixture.by_label("Preset Details").is_some(), "the accessible name keeps the text as written");
|
||||
}
|
||||
|
||||
@@ -84,6 +84,8 @@ impl Outcome for DocumentWindowOutput {
|
||||
/// - **Title and focus.** The title is the label given to `new`; it follows the document while the app changes it.
|
||||
/// [`raise`](DocumentWindow::raise) brings the window forward in the pass it is set. With
|
||||
/// [`in_list`](DocumentWindow::in_list) the window makes itself the list's active window when it gains OS focus.
|
||||
/// - **Body.** The body is laid out in the window's room and never scrolls, in the OS window and on the fallback
|
||||
/// layer alike; an app that wants scrolling puts a scroll region in the body.
|
||||
/// - **Fallback.** Where OS windows are unavailable the document shows on a movable, resizable layer with a title row.
|
||||
#[derive(crate::contract::Component, crate::contract::Props)]
|
||||
#[component(container)]
|
||||
@@ -138,7 +140,7 @@ impl<'a> DocumentWindow<'a> {
|
||||
|
||||
/// A window titled `title`, resizable, with the installed decision's frame.
|
||||
pub fn new(title: impl Into<Label>) -> Self {
|
||||
let fallback = Overlay::floating().resizable(true).fit(OverlayFit::Resizable);
|
||||
let fallback = Overlay::floating().resizable(true).fit(OverlayFit::Resizable).body_scroll(false);
|
||||
let props = ContainerProps::new()
|
||||
.surface(SurfaceKind::Background)
|
||||
.pad(Pad::None)
|
||||
|
||||
@@ -8,6 +8,7 @@ use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_behavior::placement::capped;
|
||||
use craft_behavior::{Monitor, MonitorKey};
|
||||
use craft_host::target::{Caps, ShellInfo};
|
||||
use craft_ui::contract::MAX_EXTENT;
|
||||
use craft_ui::contract::{Props as _, ShowContainer as _, SizeLimits};
|
||||
use craft_ui::runtime::InstallSpec;
|
||||
use craft_ui::shell::{DocumentWindow, Wrapped};
|
||||
@@ -154,3 +155,31 @@ fn a_wrapped_document_window_takes_the_document_between_its_minimum_and_the_scre
|
||||
assert_eq!(fallback.wrapped, None, "the fallback layer has no OS window to size");
|
||||
assert_eq!(fallback.size, None, "nothing goes out without OS windows");
|
||||
}
|
||||
|
||||
/// A body that fills its room gets the window's room, not a scroll region's unbounded extent, in the OS window and
|
||||
/// on the fallback layer.
|
||||
#[trial]
|
||||
fn a_document_window_body_fills_the_windows_room_and_does_not_scroll() {
|
||||
let inner = Rect::from_min_size(pos2(100.0, 100.0), vec2(600.0, 400.0));
|
||||
let layered_shell = {
|
||||
let shell = ShellInfo::default();
|
||||
shell.clone().caps(shell.caps.difference(Caps::VIEWPORTS))
|
||||
};
|
||||
let system = FakeSystem::new();
|
||||
system.set_monitors(vec![Monitor::new(MonitorKey::new("DP-1", [1920, 1080]), [0, 0], [1920, 1080], 1.0)]);
|
||||
for (mount, windows) in [
|
||||
("OS window", Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(system)))),
|
||||
("fallback layer", Windows::with(InstallSpec::new(layered_shell, Arc::new(FakeSystem::new())))),
|
||||
] {
|
||||
let mut height = f32::NAN;
|
||||
for _ in 0..4 {
|
||||
windows.child_info(normal(inner));
|
||||
windows.frame(vec![], vec![], |ui| {
|
||||
DocumentWindow::new("Landscape.psd").id_salt("landscape").show(ui, |ui, _| {
|
||||
height = ui.max_rect().height();
|
||||
});
|
||||
});
|
||||
}
|
||||
assert!(height < MAX_EXTENT / 2.0, "{mount}: the body's height is the window's room, got {height}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,11 @@ thread_local! {
|
||||
static CHILD_EVENTS: RefCell<Vec<Event>> = const { RefCell::new(Vec::new()) };
|
||||
/// The files hovering over and dropped on the child's window in the next child pass.
|
||||
static CHILD_FILES: RefCell<(Vec<HoveredFile>, Vec<String>)> = const { RefCell::new((Vec::new(), Vec::new())) };
|
||||
/// The window facts every child pass reports.
|
||||
/// The window facts every child opened from the root reports.
|
||||
static CHILD_INFO: RefCell<ViewportInfo> = RefCell::new(ViewportInfo::default());
|
||||
/// The window facts of each child opened from another child (a popup window): it opens where its builder puts it
|
||||
/// and follows its own commands.
|
||||
static OWN_INFO: RefCell<Vec<(ViewportId, ViewportInfo)>> = const { RefCell::new(Vec::new()) };
|
||||
/// The window facts the root reports.
|
||||
static ROOT_INFO: RefCell<ViewportInfo> = RefCell::new(ViewportInfo::default());
|
||||
/// The children whose windows are open: those that ran a pass and are still shown. Like an integration, every pass's
|
||||
@@ -43,14 +46,30 @@ thread_local! {
|
||||
/// Seconds between two frames.
|
||||
const FRAME_SECONDS: f64 = 1.0 / 60.0;
|
||||
|
||||
/// Runs `f` on the facts `id` reports: its own for a child opened from another child, else the ones every child
|
||||
/// opened from the root shares.
|
||||
fn with_facts<R>(id: ViewportId, f: impl FnOnce(&mut ViewportInfo) -> R) -> R {
|
||||
let own = OWN_INFO.with(|own| {
|
||||
let mut own = own.borrow_mut();
|
||||
own.iter().position(|(held, _)| *held == id).map(|at| own.swap_remove(at))
|
||||
});
|
||||
match own {
|
||||
Some((_, mut info)) => {
|
||||
let out = f(&mut info);
|
||||
OWN_INFO.with(|own| own.borrow_mut().push((id, info)));
|
||||
out
|
||||
}
|
||||
None => CHILD_INFO.with(|info| f(&mut info.borrow_mut())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The window system's answer to a move or a resize: the children's facts follow the commands (the fake window
|
||||
/// has no decoration, so its inner and outer rects are one). Every child shares one set of facts.
|
||||
/// has no decoration, so its inner and outer rects are one). The children opened from the root share one set of facts.
|
||||
fn os_applies(id: ViewportId, command: &ViewportCommand) {
|
||||
if id == ViewportId::ROOT {
|
||||
return;
|
||||
}
|
||||
CHILD_INFO.with(|info| {
|
||||
let mut info = info.borrow_mut();
|
||||
with_facts(id, |info| {
|
||||
let current = info.outer_rect.or(info.inner_rect).unwrap_or_else(|| Rect::from_min_size(Pos2::ZERO, CHILD_SIZE));
|
||||
let moved = match command {
|
||||
ViewportCommand::OuterPosition(pos) => Rect::from_min_size(*pos, current.size()),
|
||||
@@ -75,26 +94,40 @@ fn keep_commands(output: &FullOutput) {
|
||||
}
|
||||
|
||||
/// The window facts of every window the integration knows: the root and the children that ran, each with the
|
||||
/// facts the trial gave it.
|
||||
fn all_viewports(child: ViewportInfo) -> egui::ViewportIdMap<ViewportInfo> {
|
||||
/// facts the trial gave it or its own.
|
||||
fn all_viewports() -> egui::ViewportIdMap<ViewportInfo> {
|
||||
let mut all = egui::ViewportIdMap::default();
|
||||
all.insert(ViewportId::ROOT, ROOT_INFO.with(|info| info.borrow().clone()));
|
||||
CHILDREN.with(|children| {
|
||||
for id in children.borrow().iter() {
|
||||
all.insert(*id, child.clone());
|
||||
all.insert(*id, with_facts(*id, |info| info.clone()));
|
||||
}
|
||||
});
|
||||
all
|
||||
}
|
||||
|
||||
/// Patches the window of `id` with `builder`, as an integration does before the child's pass: the fields that
|
||||
/// changed go to the window as commands. The first builder opens the window.
|
||||
fn patch_window(id: ViewportId, builder: ViewportBuilder) {
|
||||
/// Patches the window of `ids.this` with `builder`, as an integration does before the child's pass: the fields that
|
||||
/// changed go to the window as commands. The first builder opens the window; a window opened from another child opens
|
||||
/// where the builder puts it, with focus unless the builder opens it inactive.
|
||||
fn patch_window(ids: egui::ViewportIdPair, builder: ViewportBuilder) {
|
||||
let id = ids.this;
|
||||
let commands = BUILDERS.with(|kept| {
|
||||
let mut kept = kept.borrow_mut();
|
||||
match kept.iter_mut().find(|(held, _)| *held == id) {
|
||||
Some((_, window)) => window.patch(builder).0,
|
||||
None => {
|
||||
if ids.parent != ViewportId::ROOT {
|
||||
let rect = Rect::from_min_size(builder.position.unwrap_or(Pos2::ZERO), builder.inner_size.unwrap_or(CHILD_SIZE));
|
||||
let scale = CHILD_INFO.with(|info| info.borrow().native_pixels_per_point);
|
||||
let info = ViewportInfo {
|
||||
focused: Some(builder.active.unwrap_or(true)),
|
||||
inner_rect: Some(rect),
|
||||
outer_rect: Some(rect),
|
||||
native_pixels_per_point: scale,
|
||||
..ViewportInfo::default()
|
||||
};
|
||||
OWN_INFO.with(|own| own.borrow_mut().push((id, info)));
|
||||
}
|
||||
kept.push((id, builder));
|
||||
Vec::new()
|
||||
}
|
||||
@@ -129,12 +162,12 @@ impl egui::DroppedFile for DroppedPath {
|
||||
}
|
||||
|
||||
fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) {
|
||||
patch_window(viewport.ids.this, viewport.builder);
|
||||
patch_window(viewport.ids, viewport.builder);
|
||||
let mut callback = viewport.viewport_ui_cb;
|
||||
let events = CHILD_EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut()));
|
||||
let (hovered_files, dropped) = CHILD_FILES.with(|files| std::mem::take(&mut *files.borrow_mut()));
|
||||
let dropped_files = dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect();
|
||||
let mut info = CHILD_INFO.with(|info| info.borrow().clone());
|
||||
let mut info = with_facts(viewport.ids.this, |info| info.clone());
|
||||
info.parent = Some(viewport.ids.parent);
|
||||
let mut input = RawInput {
|
||||
viewport_id: viewport.ids.this,
|
||||
@@ -152,7 +185,8 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) {
|
||||
children.push(viewport.ids.this);
|
||||
}
|
||||
});
|
||||
input.viewports = all_viewports(info);
|
||||
input.viewports = all_viewports();
|
||||
input.viewports.insert(viewport.ids.this, info);
|
||||
let mut output = ctx.run_ui(input, |ui| callback(ui));
|
||||
output.textures_delta.clear();
|
||||
keep_commands(&output);
|
||||
@@ -205,6 +239,7 @@ impl Windows {
|
||||
CHILD_EVENTS.with(|events| events.borrow_mut().clear());
|
||||
CHILD_FILES.with(|files| *files.borrow_mut() = Default::default());
|
||||
CHILD_INFO.with(|info| *info.borrow_mut() = ViewportInfo::default());
|
||||
OWN_INFO.with(|own| own.borrow_mut().clear());
|
||||
CHILDREN.with(|children| children.borrow_mut().clear());
|
||||
COMMANDS.with(|kept| kept.borrow_mut().clear());
|
||||
BUILDERS.with(|kept| kept.borrow_mut().clear());
|
||||
@@ -217,6 +252,12 @@ impl Windows {
|
||||
CHILD_INFO.with(|kept| *kept.borrow_mut() = info);
|
||||
}
|
||||
|
||||
/// The window facts `viewport` reports: its own for a child opened from another child, else those
|
||||
/// [`child_info`](Self::child_info) gave.
|
||||
pub fn facts(&self, viewport: ViewportId) -> ViewportInfo {
|
||||
with_facts(viewport, |info| info.clone())
|
||||
}
|
||||
|
||||
/// The window facts the root viewport reports from now on.
|
||||
pub fn root_info(&self, info: ViewportInfo) {
|
||||
*self.root_info.borrow_mut() = info;
|
||||
@@ -258,11 +299,15 @@ impl Windows {
|
||||
now.get()
|
||||
}));
|
||||
ROOT_INFO.with(|info| *info.borrow_mut() = self.root_info.borrow().clone());
|
||||
input.viewports = all_viewports(CHILD_INFO.with(|info| info.borrow().clone()));
|
||||
input.viewports = all_viewports();
|
||||
let mut output = self.ctx.run_ui(input, ui);
|
||||
// A child the frame no longer shows has closed: like an integration, the kit drops its window, so later inputs
|
||||
// stop listing it (and what its last pass left, such as a modal, stops counting).
|
||||
CHILDREN.with(|children| children.borrow_mut().retain(|id| output.viewport_output.contains_key(id)));
|
||||
// stop listing it (and what its last pass left, such as a modal, stops counting), and a window opened again
|
||||
// opens anew.
|
||||
let shown = |id: &ViewportId| output.viewport_output.contains_key(id);
|
||||
CHILDREN.with(|children| children.borrow_mut().retain(shown));
|
||||
OWN_INFO.with(|own| own.borrow_mut().retain(|(id, _)| shown(id)));
|
||||
BUILDERS.with(|kept| kept.borrow_mut().retain(|(id, _)| shown(id)));
|
||||
output.textures_delta.clear();
|
||||
keep_commands(&output);
|
||||
keep_tree(&mut output, ViewportId::ROOT);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! lays its children out (6.3).
|
||||
|
||||
use crate::contract::{
|
||||
Access, BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme,
|
||||
Access, BodyCx, Bracket, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme,
|
||||
LeastWidth, Pad, Role, Scroll, Sizing, ThemeScope, WrapWidth,
|
||||
};
|
||||
use crate::layout::{BodyLayout, CellAlign, GridFit, RowAlign};
|
||||
@@ -325,6 +325,14 @@ impl Row {
|
||||
self.props.layout = std::mem::replace(&mut self.props.layout, BodyLayout::Stack).align(align);
|
||||
self
|
||||
}
|
||||
|
||||
/// Links the labelled rows of the first child to the child after them (width and height to their chain): that
|
||||
/// child sits halfway between the first and the last row's controls, and `Bracket::Linked` draws the bracket
|
||||
/// from the controls to it.
|
||||
pub fn bracket(mut self, bracket: Bracket) -> Self {
|
||||
self.props = self.props.bracket(bracket);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Row {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//! Stories of the layout components `Row`, `Stack` and `Grid`.
|
||||
|
||||
use super::{Grid, Row, Stack};
|
||||
use crate::contract::{Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth};
|
||||
use crate::contract::{Bind, Bracket, Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth};
|
||||
use crate::display::Text;
|
||||
use crate::form::{Field, FieldGroup};
|
||||
use crate::layout::{CellAlign, GridFit, empty_cell};
|
||||
use crate::story_kit::sample::{outlined, words};
|
||||
use crate::testing::{StoryData, StoryOutput, story};
|
||||
use crate::text::{NumberField, link_toggle};
|
||||
use craft_behavior::ColumnWidth;
|
||||
use egui::Ui;
|
||||
|
||||
@@ -37,6 +39,29 @@ fn stack_footer(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
outlined(ui, |ui| Stack::new().gap(Gap::Stack).pad(Pad::Regular).footer(|ui, _| words(ui, 2..3)).show(ui, |ui, _| words(ui, 0..2)).into())
|
||||
}
|
||||
|
||||
/// A bracketed row: the width and height of a form linked to their chain, which sits halfway between the two fields'
|
||||
/// controls. The bracket is drawn while they are linked.
|
||||
#[story(Row, covers = [], title = "Linked rows")]
|
||||
fn row_bracket(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let linked = *data.choice("linked", true, &[("Linked", true), ("Unlinked", false)]);
|
||||
outlined(ui, |ui| {
|
||||
FieldGroup::new("Size")
|
||||
.show(ui, |ui, _| {
|
||||
Row::new().bracket(if linked { Bracket::Linked } else { Bracket::Unlinked }).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for name in ["Width", "Height"] {
|
||||
Field::new(name).show(ui, |ui, _| {
|
||||
NumberField::new(name, Bind::given(Some(800.0))).sizing(Sizing::Content).show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
link_toggle("Constrain proportions", Bind::given(linked)).show(ui);
|
||||
});
|
||||
})
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// A side menu beside a page: the menu as wide as its widest item and as tall as the row, its footer at the bottom.
|
||||
#[story(Stack<'static>, covers = [])]
|
||||
fn stack_fill_height(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
use super::view_words::UndoWords;
|
||||
use super::{ListRow, RowEvent};
|
||||
use crate::contract::{
|
||||
ActivateOn, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, Props as _,
|
||||
Role, RowState, SelectMode, Sizing,
|
||||
ActivateOn, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, HoverLead,
|
||||
Props as _, Role, RowState, SelectMode, Sizing,
|
||||
};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
@@ -141,7 +141,7 @@ impl<'a> UndoList<'a> {
|
||||
UndoList {
|
||||
common: Common::new(),
|
||||
props: ContainerProps::new().sizing(Sizing::Fill),
|
||||
items: CollectionProps::new().select(SelectMode::Single).activate(ActivateOn::Click).lead_follows_hover(true),
|
||||
items: CollectionProps::new().select(SelectMode::Single).activate(ActivateOn::Click).hover_lead(HoverLead::LeadAndSelection),
|
||||
selection: None,
|
||||
}
|
||||
.label(label)
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::predicate::{DropTest, RowTest, RowText};
|
||||
use super::{ListRow, RowEvent};
|
||||
use crate::contract::{
|
||||
Access, ActivateOn, Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnLayout, Common, Component, ContainerProps, Cx,
|
||||
DropKind, EdgePress, EditResponse, LeadOnOpen, ListDrag, Props as _, Role, RowState, SelectMode, Sizing,
|
||||
DropKind, EdgePress, EditResponse, HoverLead, LeadOnOpen, ListDrag, Props as _, Role, RowState, SelectMode, Sizing,
|
||||
};
|
||||
use crate::runtime::env::{Env, Label};
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
@@ -119,7 +119,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.lead_on_open(LeadOnOpen::First)
|
||||
.lead_follows_hover(true)
|
||||
.hover_lead(HoverLead::Lead)
|
||||
.focus_on_press(false)
|
||||
.type_ahead(true)
|
||||
.sizing(Sizing::Content)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
use super::select::Select;
|
||||
use crate::contract::{
|
||||
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, MeasureCx, Outcome, PaintUi, Props as _, Role, WordSetCx as _,
|
||||
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, MeasureCx, Outcome, PaintUi, Props as _, Resolved, Role, Sizing,
|
||||
WordSetCx as _,
|
||||
};
|
||||
use crate::runtime::env::{Label, UnitKind, Units};
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
@@ -14,7 +15,7 @@ use std::ops::{Deref, RangeInclusive};
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
/// The style of a unit select: the gap between the field and the select, and the number field's width.
|
||||
/// The style of a unit select: the gap between the field and the select, and the number field's widths.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct UnitSelectStyle {
|
||||
@@ -22,6 +23,8 @@ pub struct UnitSelectStyle {
|
||||
metrics: Metrics,
|
||||
/// The width of the number field; the select has the room after it.
|
||||
number: f32,
|
||||
/// The width of the number field of a content-sized unit select: one number cell.
|
||||
cell: f32,
|
||||
}
|
||||
|
||||
/// The output of a unit select: the number's edit, the unit's edit when a unit was picked, and the number field's
|
||||
@@ -63,6 +66,10 @@ impl Outcome for UnitSelectOutput {
|
||||
/// (its spellings: "12 mm") and shows its number with, and the kind sets the digits and the step of the number; the
|
||||
/// select names the unit, so the field shows the number alone. The number itself is the field's value, and the unit
|
||||
/// goes to its own binding, so the app converts the number when the unit changes.
|
||||
///
|
||||
/// Content-sized (`Sizing::Content`), the field is one number cell wide and the select as wide as its longest unit,
|
||||
/// as a compact form's rows show them (Image Size); otherwise the field takes a field's width and the select the room
|
||||
/// after it.
|
||||
#[derive(crate::contract::Component, crate::contract::Props)]
|
||||
#[component]
|
||||
pub struct UnitSelect<'a> {
|
||||
@@ -139,7 +146,7 @@ impl Component for UnitSelect<'_> {
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: UnitSelectStyleKey) -> UnitSelectStyle {
|
||||
let control = cx.control();
|
||||
UnitSelectStyle { metrics: Metrics::new().gap(control.gap), number: control.field }
|
||||
UnitSelectStyle { metrics: Metrics::new().gap(control.gap), number: control.field, cell: control.number }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
@@ -149,10 +156,10 @@ impl Component for UnitSelect<'_> {
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let group = cx.label();
|
||||
let mut number = self.number(group.clone(), shown_of(cx.value()), None);
|
||||
let mut select = Select::new(self.select_name(&group), Bind::<UnitKind>::given(Mixed::Mixed), self.units);
|
||||
let mut select = sized(Select::new(self.select_name(&group), Bind::<UnitKind>::given(Mixed::Mixed), self.units), cx.resolved);
|
||||
let number = cx.child("number", &mut number, Proposal::Ideal);
|
||||
let select = cx.child("unit", &mut select, Proposal::Ideal);
|
||||
Vec2::new(cx.style.number + cx.gap() + select.x, number.y.max(select.y))
|
||||
Vec2::new(number_width(cx.resolved, cx.style) + cx.gap() + select.x, number.y.max(select.y))
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, Option<f64>>> {
|
||||
@@ -164,7 +171,7 @@ impl Component for UnitSelect<'_> {
|
||||
/// is adopted as the component's own.
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let group = cx.label();
|
||||
let (number_rect, select_rect) = arrange(cx.rect.size(), cx.style.metrics.gap, cx.style.number);
|
||||
let (number_rect, select_rect) = arrange(cx.rect.size(), cx.style.metrics.gap, number_width(cx.resolved, cx.style));
|
||||
let flow = Flow::new(cx.rect, cx.flow.is_rtl());
|
||||
let place = |logical: Rect| flow.to_physical(logical.translate(cx.rect.min.to_vec2()));
|
||||
let kind = match self.unit.reborrow().get() {
|
||||
@@ -177,7 +184,7 @@ impl Component for UnitSelect<'_> {
|
||||
let number = ui.child("number", place(number_rect), self.number(group.clone(), shown, kind.map(|kind| (kind, &units))));
|
||||
cx.adopt(&number, &start, |value, mine| *mine = *value);
|
||||
self.out_of_range = number.out_of_range;
|
||||
let select = Select::new(self.select_name(&group), self.unit.reborrowed(), self.units);
|
||||
let select = sized(Select::new(self.select_name(&group), self.unit.reborrowed(), self.units), cx.resolved);
|
||||
self.unit_event = ui.child("unit", place(select_rect), select).events;
|
||||
}
|
||||
|
||||
@@ -186,6 +193,16 @@ impl Component for UnitSelect<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit select's select, content-sized as the unit select is: as wide as its longest unit.
|
||||
fn sized<'s>(select: Select<'s, UnitKind>, resolved: &Resolved<'_>) -> Select<'s, UnitKind> {
|
||||
if resolved.sizing() == Some(Sizing::Content) { select.sizing(Sizing::Content) } else { select }
|
||||
}
|
||||
|
||||
/// The width of the number field: one number cell in a content-sized unit select, a field's width otherwise.
|
||||
fn number_width(resolved: &Resolved<'_>, style: &UnitSelectStyle) -> f32 {
|
||||
if resolved.sizing() == Some(Sizing::Content) { style.cell } else { style.number }
|
||||
}
|
||||
|
||||
/// The number field's and the select's rects in a room of `size`, in logical coordinates from the start edge: the
|
||||
/// number field first, the select in the room after it.
|
||||
fn arrange(size: Vec2, gap: f32, number_width: f32) -> (Rect, Rect) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Stories of `UnitSelect`.
|
||||
|
||||
use super::UnitSelect;
|
||||
use crate::contract::{Bind, Entry, Show as _, Validity};
|
||||
use crate::contract::{Bind, Entry, Props as _, Show as _, Sizing, Validity};
|
||||
use crate::runtime::env::{Message, UnitKind};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use craft_behavior::Mixed;
|
||||
@@ -19,6 +19,16 @@ fn unit_select(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
UnitSelect::new("Width", width_at.bind(width), Bind::bound(unit), &units).show(ui).into()
|
||||
}
|
||||
|
||||
/// Content-sized, as a compact form's rows show it: the field one number cell wide, the select as wide as its
|
||||
/// longest unit.
|
||||
#[story(UnitSelect<'static>, covers = [], drive = Drive::Type("42"))]
|
||||
fn unit_select_content_sized(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let units = units();
|
||||
let (width, width_at) = data.value_at("compact_width_and_unit", (Some(210.0), UnitKind::Millimetres));
|
||||
let (width, unit) = (&mut width.0, &mut width.1);
|
||||
UnitSelect::new("Width", width_at.bind(width), Bind::bound(unit), &units).sizing(Sizing::Content).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(UnitSelect<'static>, covers = [Mixed], drive = Drive::Never)]
|
||||
fn unit_select_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let units = units();
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! A bracketed row and the row a check box starts: the chain halfway between its fields with the bracket drawn to
|
||||
//! their controls, and a check box that starts a row of a form in the form's control column.
|
||||
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Bracket, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::pickers::{Select, UnitSelect};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::text::{NumberField, link_toggle};
|
||||
use egui::{Rect, Shape, Vec2};
|
||||
|
||||
/// How far two edges may differ and still line up, in points.
|
||||
const SLACK: f32 = 0.5;
|
||||
|
||||
fn control(fixture: &Fixture, name: &str) -> Rect {
|
||||
fixture.by_label(name).unwrap_or_else(|| panic!("{name:?} names its control")).rect
|
||||
}
|
||||
|
||||
/// The horizontal line segments of one frame, as (y, from x, to x).
|
||||
fn ticks(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> {
|
||||
fixture
|
||||
.frame_shapes()
|
||||
.into_iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < SLACK => Some((a.y, a.x.min(b.x), a.x.max(b.x))),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A form with Width and Height (unit selects) stacked in a row with `bracket`, beside their link.
|
||||
fn linked(bracket: Bracket) -> Fixture {
|
||||
let units = [Entry::new(UnitKind::Pixels, "Pixels"), Entry::new(UnitKind::Percent, "Percent")];
|
||||
Fixture::new(move |ui| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
FieldGroup::new("Image size").show(ui, |ui, _| {
|
||||
Row::new().bracket(bracket).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for name in ["Width", "Height"] {
|
||||
Field::new(name).show(ui, |ui, _| {
|
||||
UnitSelect::new(name, Bind::given(Some(8.0)), Bind::given(UnitKind::Pixels), &units)
|
||||
.unit_label(format!("{name} unit"))
|
||||
.show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
link_toggle("Link", Bind::given(bracket == Bracket::Linked)).show(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/// A linked bracket runs from the end of Width's and Height's controls to the chain's centre line, at each control's
|
||||
/// centre, and the chain sits halfway between the two; unlinked, the chain keeps its place and no bracket is drawn.
|
||||
/// At 1x and 1.25x.
|
||||
#[trial]
|
||||
fn a_bracketed_row_centres_its_chain_between_the_rows_and_draws_the_bracket_while_linked() {
|
||||
for scale in [1.0, 1.25] {
|
||||
for bracket in [Bracket::Linked, Bracket::Unlinked] {
|
||||
let mut fixture = linked(bracket);
|
||||
fixture.room(Vec2::new(1000.0, 600.0)).pixels_per_point(scale);
|
||||
fixture.settle();
|
||||
let (width, height, link) = (control(&fixture, "Width unit"), control(&fixture, "Height unit"), control(&fixture, "Link"));
|
||||
let middle = (width.center().y + height.center().y) / 2.0;
|
||||
assert!((link.center().y - middle).abs() <= SLACK, "{bracket:?} at {scale}x: the chain sits halfway between the rows: {link:?} {middle}");
|
||||
let drawn = ticks(&mut fixture);
|
||||
for (name, row) in [("Width", width), ("Height", height)] {
|
||||
let tick = drawn.iter().find(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0);
|
||||
match bracket {
|
||||
Bracket::Linked => {
|
||||
assert!(tick.is_some(), "at {scale}x a tick runs from {name}'s control to the chain: {drawn:?} {row:?} {link:?}");
|
||||
}
|
||||
_ => assert!(tick.is_none(), "unlinked at {scale}x, no tick on {name}'s row: {tick:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A check box that starts a row of a form (Resample with its method after it) starts in the form's control column;
|
||||
/// one after another child of the row stays where the row puts it.
|
||||
#[trial]
|
||||
fn a_check_box_that_starts_a_row_of_a_form_starts_in_the_control_column() {
|
||||
let methods = [Entry::new(0_u8, "Automatic"), Entry::new(1_u8, "Bicubic")];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
FieldGroup::new("Size").show(ui, |ui, _| {
|
||||
Field::new("Resolution").show(ui, |ui, _| {
|
||||
NumberField::new("Resolution", Bind::given(Some(72.0))).show(ui);
|
||||
});
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::given(true)).label("Resample").show(ui);
|
||||
Select::new("Method", Bind::given(0_u8), &methods).show(ui);
|
||||
});
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new("Then").show(ui);
|
||||
Checkbox::new(Bind::given(false)).label("Second").show(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(1000.0, 600.0));
|
||||
fixture.settle();
|
||||
let (field, check, method) = (control(&fixture, "Resolution"), control(&fixture, "Resample"), control(&fixture, "Method"));
|
||||
assert!((check.min.x - field.min.x).abs() <= SLACK, "the check box starts at the form's control edge: {check:?} {field:?}");
|
||||
assert!(
|
||||
method.min.x >= check.max.x - SLACK && method.min.y < check.max.y && method.max.y > check.min.y,
|
||||
"the method follows on its line: {method:?} {check:?}"
|
||||
);
|
||||
let second = control(&fixture, "Second");
|
||||
assert!(second.min.x < field.min.x, "a check box after another child of the row is not moved to the control column: {second:?} {field:?}");
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub(crate) mod align;
|
||||
pub(crate) mod baseline;
|
||||
pub(crate) mod bracket;
|
||||
pub(crate) mod caption;
|
||||
pub mod group;
|
||||
pub(crate) mod hit;
|
||||
|
||||
@@ -8,10 +8,11 @@ use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, ContainerProps, Entry, LabelScheme, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::pickers::UnitSelect;
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial};
|
||||
use craft_ui::text::{NumberField, NumberPick};
|
||||
use egui::Rect;
|
||||
use craft_ui::text::{NumberField, NumberPick, link_toggle};
|
||||
use egui::{Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// How far two edges may differ and still line up, in points.
|
||||
@@ -194,3 +195,56 @@ fn a_field_before_the_groups_widest_value_shows_at_its_width() {
|
||||
let runs = last_pass_measuring_runs(fixture.ctx());
|
||||
assert!(runs.is_empty(), "a settled frame takes the kept measurements: {runs:?}");
|
||||
}
|
||||
|
||||
/// A field `caption` holding a unit select, its select named "`caption` unit".
|
||||
fn unit(ui: &mut egui::Ui, caption: &'static str, units: &[Entry<UnitKind>]) {
|
||||
Field::new(caption).show(ui, |ui, _| {
|
||||
UnitSelect::new(caption, Bind::given(Some(8.0)), Bind::given(UnitKind::Pixels), units).unit_label(format!("{caption} unit")).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// In a content-sized form, the labelled rows of a stack inside a row (Image Size's Width and Height beside their
|
||||
/// link) take the placement their measure took, at the form's final label column: each label sits beside its
|
||||
/// controls, each control is as tall as a direct row's, and the next row starts under the one before. At 1x and 1.25x.
|
||||
#[trial]
|
||||
fn a_stack_of_labelled_rows_in_a_row_lays_out_as_it_measured() {
|
||||
for scale in [1.0, 1.25] {
|
||||
let units = [Entry::new(UnitKind::Pixels, "Pixels"), Entry::new(UnitKind::Percent, "Percent")];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
FieldGroup::new("Image size").show(ui, |ui, _| {
|
||||
number(ui, "Size");
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
unit(ui, "Width", &units);
|
||||
unit(ui, "Height", &units);
|
||||
});
|
||||
link_toggle("Link", Bind::given(true)).show(ui);
|
||||
});
|
||||
unit(ui, "Resolution", &units);
|
||||
number(ui, "Canvas extension color");
|
||||
});
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).pixels_per_point(scale);
|
||||
fixture.settle();
|
||||
let reference = control(&fixture, "Resolution");
|
||||
let mut above = f32::NEG_INFINITY;
|
||||
for name in ["Width", "Height", "Resolution"] {
|
||||
let (label, field, select) = (caption(&fixture, name), control(&fixture, name), control(&fixture, &format!("{name} unit")));
|
||||
for part in [field, select] {
|
||||
assert!(part.height() >= reference.height() - SLACK, "{name}'s controls are a full row tall at {scale}x: {part:?} {reference:?}");
|
||||
}
|
||||
assert!(label.max.x <= field.min.x + SLACK, "{name}'s label sits before its field at {scale}x: {label:?} {field:?}");
|
||||
assert!(
|
||||
label.min.y < field.max.y && label.max.y > field.min.y,
|
||||
"{name}'s label sits on its field's line at {scale}x: {label:?} {field:?}"
|
||||
);
|
||||
assert!(label.min.y >= above - SLACK, "{name}'s row starts under the row before at {scale}x: {label:?} {above}");
|
||||
above = field.max.y.max(select.max.y);
|
||||
}
|
||||
let link = fixture.by_label("Link").expect("the link toggle is shown").rect;
|
||||
let select = control(&fixture, "Width unit");
|
||||
assert!(link.min.x >= select.max.x - SLACK, "the link starts clear of the selects at {scale}x: {link:?} {select:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,3 +297,27 @@ fn the_wheel_steps_the_open_select_a_line_an_entry_and_commits_when_it_stops() {
|
||||
assert!(!steps.contains(&"cancel"), "and puts nothing back: {steps:?}");
|
||||
assert_eq!(*value.borrow(), 4);
|
||||
}
|
||||
|
||||
/// The pointer over a row of an open list moves the lead only: the held value stays the selected option in every
|
||||
/// frame, and Enter then chooses the row the pointer is on.
|
||||
#[trial]
|
||||
fn hovering_a_row_moves_the_lead_and_leaves_the_selected_option_held() {
|
||||
use craft_ui::testing::pointer::moved;
|
||||
let mut fixture = focused();
|
||||
fixture.key(Key::ArrowDown, Modifiers::ALT);
|
||||
fixture.settle();
|
||||
assert!(list_open(&mut fixture), "Alt+Down opens the list");
|
||||
let options = fixture.by_role(Role::LIST_BOX_OPTION);
|
||||
assert_eq!(options.len(), 4, "the list shows its four options");
|
||||
let held = options[0].node;
|
||||
let under_pointer = options[2].center();
|
||||
for step in 0..3 {
|
||||
fixture.frame(if step == 0 { vec![moved(under_pointer)] } else { Vec::new() });
|
||||
let selected: Vec<_> =
|
||||
fixture.by_role(Role::LIST_BOX_OPTION).into_iter().filter(|row| fixture.tree().selected_of(row.node) == Some(true)).collect();
|
||||
assert!(selected.len() == 1 && selected[0].node == held, "frame {step}: the held row stays the selected option");
|
||||
}
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
assert_eq!(value(&mut fixture), 3, "the lead followed the pointer, so Enter chooses the row under it");
|
||||
}
|
||||
|
||||
@@ -113,6 +113,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords
|
||||
- Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides.
|
||||
- A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to its edge of the float area: `Floating::edge`, else the one nearer its rect. A move keeps the edge it began with. A collapsed window's move ends at the edge nearer its strip where it was dropped, with the rect that shows the strip there (`WindowColumn::dropped`), and the area records that edge (`Action::MoveFloating`'s `edge`); a unit dragged out of a collapsed column (`start_icon_drag`) floats collapsed the same way, its strip under the pointer (`Target::Float`'s `edge`). Collapsing a floating column and moving an expanded window clear the edge. A column that neither collapses nor has steps shows no double arrow and offers no collapse in its menu (`ColumnArrow::Fixed`).
|
||||
- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns; `DockGrid::rail` for a tool rail, sized by the dock). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone.
|
||||
- A floating window whose every group is minimized shows its title row and their tab strips, at its rect's place and width (`WindowColumn::minimized`). Its sides resize its width, never its height, and its rect, in the app window and in an OS window's recorded placement, keeps the expanded height, which the window takes back when a group is restored. A window with some groups open keeps its size, and its open groups share the room the strips leave.
|
||||
- Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is.
|
||||
- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives.
|
||||
- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window.
|
||||
|
||||
Reference in New Issue
Block a user