panels-w1: review fixes (review-1)

This commit is contained in:
aiongg
2026-11-14 17:56:00 +00:00
parent ee5be1ccdd
commit be96f04af2
5 changed files with 115 additions and 54 deletions
+25 -6
View File
@@ -85,8 +85,8 @@ impl<P> Workspace<P> {
}
impl<P: Clone + Eq + Hash> Workspace<P> {
/// Check the version, the layout and that every hidden panel is hidden once and absent
/// from the layout.
/// Check the version, the layout, that every hidden panel is hidden once and absent
/// from the layout, and that the floated records are bounded and one per panel.
pub fn validate(&self) -> Result<(), DockError> {
if self.version > Self::VERSION {
return Err(DockError::UnsupportedVersion);
@@ -102,6 +102,13 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
return Err(DockError::DuplicatePanel);
}
}
if self.floated.len() > MAX_PANELS {
return Err(DockError::LimitExceeded);
}
let mut recorded = HashSet::new();
if !self.floated.iter().all(|(panel, _)| recorded.insert(panel)) {
return Err(DockError::DuplicatePanel);
}
Ok(())
}
@@ -133,7 +140,7 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
let before = proposed.layout.clone();
// Opening a hidden panel puts it back where it was.
let reopened = match &action {
Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel)?,
Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?,
_ => false,
};
if !reopened {
@@ -191,14 +198,26 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
}
/// Restore a hidden `panel` to its recorded place and make it the active tab. `Ok(false)` when the record
/// cannot be restored, which leaves the workspace as it was.
fn reopen(&mut self, panel: &P) -> Result<bool, DockError> {
/// cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace stays
/// as it was and the caller opens the panel by the ordinary, checked path.
fn reopen(&mut self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Result<bool, DockError> {
// The restore also rewrites the records of the hidden panels it passed, so it runs on a copy.
let mut trial = self.clone();
let mut layout = self.layout.clone();
if self.restore_from_hidden(&mut layout, panel).is_err() {
if trial.restore_from_hidden(&mut layout, panel).is_err() {
return Ok(false);
}
let allowed = layout
.location(panel)
.ok()
.and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor), floats(&layout, &anchor))))
.unwrap_or(true);
if !allowed {
return Ok(false);
}
layout.apply(Action::Activate { panel: panel.clone() })?;
self.layout = layout;
self.hidden = trial.hidden;
self.hidden.retain(|(p, _)| p != panel);
Ok(true)
}
+4 -20
View File
@@ -11,8 +11,8 @@ use crate::contract::BodyCx;
use crate::contract::SizeLimits;
use crate::contract::overlay::{PlacementChange, PlacementKind, Popup};
use crate::contract::{
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, DropMark, DropOperation, HeaderRegion, Inner, Mount, NoValue, OsFiles,
Outcome, Overlay, Pad, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, WindowDropTarget, WordSetCx as _,
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, OsFiles, Outcome, Overlay, Pad,
Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::runtime::drag::OsFile;
use crate::runtime::env::{Env, Label};
@@ -21,6 +21,7 @@ use crate::runtime::windows::WindowSpec;
use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow};
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::{GesturePhase, Metrics, Sense};
use craft_ui_widgets::popover::WholeWindow;
use egui::{Id, Rect, Response, Ui, Vec2};
use std::cell::RefCell;
use std::hash::Hash;
@@ -31,23 +32,6 @@ mod stories;
/// The actions a floating group's title row shows unless `actions` says otherwise.
const ACTIONS: [HeaderAction; 3] = [HeaderAction::Menu, HeaderAction::Float, HeaderAction::Close];
/// The whole window of a native floating group as a target for files from the OS.
struct OsWindowFiles {
rect: Rect,
}
impl WindowDropTarget<OsFiles> for OsWindowFiles {
type Drop = OsFiles;
fn accept(&self, payload: &OsFiles, _op: DropOperation) -> Option<OsFiles> {
(!payload.files.is_empty()).then(|| payload.clone())
}
fn mark(&self, _drop: &OsFiles) -> DropMark {
DropMark::Into(self.rect)
}
}
/// The style of a floating group: the surface and padding come from the container.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
@@ -276,7 +260,7 @@ impl Component for FloatingGroup<'_> {
}
// A layer float lies in the app window, whose own targets take those drops.
if self.native.is_some() {
let target = OsWindowFiles { rect: cx.rect };
let target = WholeWindow::new(cx.rect);
if let Some(dropped) = cx.window_drop_target::<OsFiles, _>(&target) {
self.files = dropped.files;
}
+48 -22
View File
@@ -4,9 +4,10 @@
use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, Workspace};
use craft_behavior::placement::Placement;
use craft_host::target::{Backend, Caps, Os, ShellInfo};
use craft_ui::contract::{Bind, BodyCx};
use craft_ui::contract::{Bind, BodyCx, Show as _};
use craft_ui::docking::{DockConfig, DockPanels, PanelSpec};
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::input::key_press;
@@ -14,7 +15,7 @@ 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 egui::{Event, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use egui::{DroppedFile, Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use std::sync::Arc;
/// The root window and the palette overlap; the palette is the larger.
@@ -349,28 +350,53 @@ fn an_app_change_of_a_native_floats_place_moves_its_window_once() {
assert_eq!(placing, [&ViewportCommand::OuterPosition(to.min), &ViewportCommand::InnerSize(to.size())], "one move and one size");
}
/// OS files reach `DockAreaOutput::window_files` only from a drop on a native float's own window: with the float's
/// OS window open and nothing dropped, the dock reports no files.
// PLAN: the drop itself cannot be driven yet: the `Windows` kit (`crates/ui-test-kit/src/windows.rs`, outside this
// set) gives a child pass only `Event`s, never `RawInput::dropped_files`. Once the kit lets a frame give the child
// files, this trial drops one file no target takes and one a target takes, and asserts that only the first arrives.
/// Palettes whose body is a veil over the window: a target inside the window that takes dropped files.
struct Veiled;
impl DockPanels<u32> for Veiled {
fn spec(&self, _: &u32) -> PanelSpec {
PanelSpec::new(PALETTE_TITLE)
}
fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
let _ = DropVeil::new("Drop").show(ui, |_, _| {});
}
}
/// Files dropped on a native float's own OS window reach `DockAreaOutput::window_files` once, unless a target inside
/// that window took them.
#[trial]
fn a_file_dropped_on_a_native_float_reaches_window_files_once() {
let windows = Windows::new();
windows.root_info(info(true, ROOT_AT));
windows.child_info(info(true, PALETTE_AT));
let mut workspace = Workspace::new(Layout::new(None, vec![float()]));
let mut opened = false;
let mut files = 0;
for _ in 0..4 {
let out = windows.frame(vec![], vec![], |ui| {
let shown = DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui);
files += shown.window_files.len();
});
opened |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT);
}
assert!(opened, "the float has its own OS window");
assert_eq!(files, 0, "no drop, no files");
let reached = |veiled: bool| {
let windows = Windows::new();
windows.root_info(info(true, ROOT_AT));
windows.child_info(info(true, PALETTE_AT));
let mut workspace = Workspace::new(Layout::new(None, vec![float()]));
let mut frame = |hovered: Vec<HoveredFile>, dropped: Vec<DroppedFile>| {
let mut files = 0;
windows.frame_with_files(vec![], vec![], hovered, dropped, |ui| {
let config = DockConfig::default();
let shown = if veiled {
DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Veiled, config).show(ui)
} else {
DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), config).show(ui)
};
files += shown.window_files.len();
});
files
};
for _ in 0..4 {
frame(vec![], vec![]);
}
let mut total = frame(vec![HoveredFile::default()], vec![]);
total += frame(vec![], vec![DroppedFile { name: "a.png".into(), ..DroppedFile::default() }]);
for _ in 0..2 {
total += frame(vec![], vec![]);
}
total
};
assert_eq!(reached(false), 1, "a file no target took arrives once");
assert_eq!(reached(true), 0, "a file a target in the window took does not");
}
/// A palette float made in the app window.
+27 -3
View File
@@ -10,7 +10,7 @@ use craft_ui::testing::Frames;
use craft_ui::testing::access::{AccessTree, tree_of};
use craft_ui::testing::windows::FakeSystem;
use craft_ui::testing::windows::{FullOutput, RawInput};
use egui::{Context, Event, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportId, ViewportInfo};
use egui::{Context, DroppedFile, Event, HoveredFile, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportId, ViewportInfo};
use std::cell::{Cell, RefCell};
use std::sync::Arc;
@@ -20,6 +20,8 @@ const CHILD_SIZE: Vec2 = Vec2::new(400.0, 300.0);
thread_local! {
/// The events the next child pass receives (the renderer runs on the trial's thread).
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<DroppedFile>)> = const { RefCell::new((Vec::new(), Vec::new())) };
/// The window facts every child pass reports.
static CHILD_INFO: RefCell<ViewportInfo> = RefCell::new(ViewportInfo::default());
/// The window facts the root reports.
@@ -109,10 +111,17 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) {
patch_window(viewport.ids.this, 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_files) = CHILD_FILES.with(|files| std::mem::take(&mut *files.borrow_mut()));
let mut info = CHILD_INFO.with(|info| info.borrow().clone());
info.parent = Some(viewport.ids.parent);
let mut input =
RawInput { viewport_id: viewport.ids.this, events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, CHILD_SIZE)), ..RawInput::default() };
let mut input = RawInput {
viewport_id: viewport.ids.this,
events,
hovered_files,
dropped_files,
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, CHILD_SIZE)),
..RawInput::default()
};
input.time = Some(NOW.with(Cell::get));
CHILDREN.with(|children| {
let mut children = children.borrow_mut();
@@ -171,6 +180,7 @@ impl Windows {
assert!(craft_ui::install(&ctx, spec).is_ok(), "the context takes the runtime once");
Context::set_immediate_viewport_renderer(render_child);
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());
CHILDREN.with(|children| children.borrow_mut().clear());
COMMANDS.with(|kept| kept.borrow_mut().clear());
@@ -192,7 +202,21 @@ impl Windows {
/// One frame: `root` events go to the root viewport, `child` events to the child's next pass. Returns the
/// window commands of the frame.
pub fn frame(&self, root: Vec<Event>, child: Vec<Event>, ui: impl FnMut(&mut Ui)) -> Out {
self.frame_with_files(root, child, Vec::new(), Vec::new(), ui)
}
/// [`frame`](Self::frame) where the child's next pass also gets the OS files hovering over its window and the
/// files dropped on it.
pub fn frame_with_files(
&self,
root: Vec<Event>,
child: Vec<Event>,
hovered: Vec<HoveredFile>,
dropped: Vec<DroppedFile>,
ui: impl FnMut(&mut Ui),
) -> Out {
CHILD_EVENTS.with(|events| *events.borrow_mut() = child);
CHILD_FILES.with(|files| *files.borrow_mut() = (hovered, dropped));
TREES.with(|kept| kept.borrow_mut().clear());
set_input(&self.ctx, FrameInput::new(RootEnv::default()));
let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)), events: root, ..RawInput::default() };
+11 -3
View File
@@ -113,11 +113,19 @@ impl Outcome for DropVeilOutput {
}
}
/// The accepting side of a veil: any files, anywhere in the window, by any operation.
struct WholeWindow {
/// The accepting side of a veil: any files, anywhere in the window, by any operation. Other containers that report
/// the files nothing else in their window took use it too.
pub struct WholeWindow {
rect: Rect,
}
impl WholeWindow {
/// A target over the window, marked with `rect` while files hover.
pub fn new(rect: Rect) -> Self {
WholeWindow { rect }
}
}
impl WindowDropTarget<OsFiles> for WholeWindow {
type Drop = OsFiles;
@@ -186,7 +194,7 @@ impl Component for DropVeil {
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let held = drag::active::<OsFiles>(&cx.ctx).is_some_and(|files| !files.files.is_empty());
let target = WholeWindow { rect: cx.rect };
let target = WholeWindow::new(cx.rect);
let (id, ordinal) = (cx.id, drag::next_ordinal(&cx.ctx, cx.id));
self.dropped = cx.window_drop_target::<OsFiles, _>(&target);
// The veil shows only while it is the target that would take the drop.