mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 09:08:11 +00:00
ui-contract: share runtime lookup and component step bodies
This commit is contained in:
@@ -31,6 +31,19 @@ fn lang(i: &I18n, code: &str) -> Lang {
|
||||
i.from_code(code).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translated_labels_share_storage_across_clones_and_follow_their_own_overlay() {
|
||||
let word = Word::plain("Save");
|
||||
let words = Words::new(|_| Some("Enregistrer".to_owned()));
|
||||
let first = words.translated_label(word).unwrap();
|
||||
let cloned = words.clone().translated_label(word).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&first, &cloned));
|
||||
|
||||
let overlay = words.overlay(&WordRows::new().row(word, "Sauvegarder"));
|
||||
assert_eq!(overlay.translated_label(word).as_deref(), Some("Sauvegarder"));
|
||||
assert_eq!(words.translated_label(word).as_deref(), Some("Enregistrer"));
|
||||
}
|
||||
|
||||
static P: &Embedded = &[
|
||||
("fr", "@plural\t{n} page|{n} pages\t{n} page|{n} pages\n", ""),
|
||||
("ru", "@plural\t{n} file|{n} files\t{n} файл|{n} файла|{n} файлов\n", ""),
|
||||
|
||||
@@ -63,7 +63,10 @@ impl Counted {
|
||||
}
|
||||
}
|
||||
|
||||
type Lookup = Arc<dyn Fn(Word) -> Option<String> + Send + Sync>;
|
||||
struct Lookup {
|
||||
translate: Box<dyn Fn(Word) -> Option<String> + Send + Sync>,
|
||||
labels: Mutex<HashMap<Word, Option<Arc<str>>>>,
|
||||
}
|
||||
type Plural = Arc<dyn Fn(&'static str, u64, &'static str, &'static str) -> Option<String> + Send + Sync>;
|
||||
|
||||
/// The rows a `Words` scope adds over the words it inherits: a word and the text shown for it.
|
||||
@@ -97,7 +100,7 @@ impl WordRows {
|
||||
/// The lookup of an app: its catalog in its language, or English.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Words {
|
||||
lookup: Option<Lookup>,
|
||||
lookup: Option<Arc<Lookup>>,
|
||||
plural: Option<Plural>,
|
||||
sets: SetCache,
|
||||
/// Unique per translator: equal words have equal generations (`generation`).
|
||||
@@ -135,7 +138,11 @@ impl Words {
|
||||
|
||||
/// Words translated by `lookup`, which returns `None` where it has no text.
|
||||
pub fn new(lookup: impl Fn(Word) -> Option<String> + Send + Sync + 'static) -> Words {
|
||||
Words { lookup: Some(Arc::new(lookup)), plural: None, sets: SetCache::default(), generation: next_generation() }
|
||||
Words {
|
||||
lookup: Some(Arc::new(Lookup { translate: Box::new(lookup), labels: Mutex::default() })),
|
||||
generation: next_generation(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Which translator these words are: words with the same generation read every word the same (a clone keeps it),
|
||||
@@ -176,7 +183,7 @@ impl Words {
|
||||
let rows = rows.clone();
|
||||
let mut over = Words::new(move |word| match rows.text(word) {
|
||||
Some(text) => Some(text.to_owned()),
|
||||
None => inner.lookup.as_ref().and_then(|lookup| lookup(word)),
|
||||
None => inner.lookup.as_ref().and_then(|lookup| (lookup.translate)(word)),
|
||||
});
|
||||
over.plural = self.plural.clone();
|
||||
over
|
||||
@@ -189,7 +196,7 @@ impl Words {
|
||||
let Some(lookup) = &self.lookup else {
|
||||
return Cow::Borrowed(word.english);
|
||||
};
|
||||
match lookup(word) {
|
||||
match (lookup.translate)(word) {
|
||||
Some(text) if text.is_empty() => Cow::Borrowed(word.english),
|
||||
Some(text) if !keeps_placeholders(word.english, &text) => {
|
||||
warn_once(word, &text);
|
||||
@@ -200,6 +207,21 @@ impl Words {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared translation of a label, or `None` when it displays its static English text.
|
||||
/// Clones of this translator share translations. An overlay has its own lookup and cache.
|
||||
pub fn translated_label(&self, word: Word) -> Option<Arc<str>> {
|
||||
let cache = &self.lookup.as_ref()?.labels;
|
||||
if let Some(label) = cache.lock().unwrap_or_else(PoisonError::into_inner).get(&word) {
|
||||
return label.clone();
|
||||
}
|
||||
// The lookup is supplied by the app. Run it outside the cache lock.
|
||||
let label = match self.get(word) {
|
||||
Cow::Owned(text) => Some(Arc::from(text)),
|
||||
Cow::Borrowed(_) => None,
|
||||
};
|
||||
cache.lock().unwrap_or_else(PoisonError::into_inner).entry(word).or_insert(label).clone()
|
||||
}
|
||||
|
||||
/// The English set `L` translated by these words, built on the first call and shared after it.
|
||||
pub fn set<L: WordSet + Send + Sync + 'static>(&self) -> Arc<L> {
|
||||
let mut cache = self.sets.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
|
||||
@@ -15,6 +15,7 @@ use super::scroll::{
|
||||
use super::size::MeasureKey;
|
||||
use super::window::{WindowMode, os_window, window_instance};
|
||||
use super::{BodyHooks, BodyView};
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::contract::cx::{BodyCx, BodyOwner, RegionShare};
|
||||
use crate::contract::label::{self, LabelIn};
|
||||
use crate::contract::run::{Measuring, ShapeHooks, ShowAt};
|
||||
@@ -502,7 +503,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
}
|
||||
|
||||
fn sensed(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) {
|
||||
self.reorder_keys(comp.props(Internal::new()), cx);
|
||||
self.reorder_keys(comp.props(Internal::new()), cx.core);
|
||||
}
|
||||
|
||||
fn updated(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) {
|
||||
@@ -537,21 +538,21 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
if props.collapse.is_some() && cx.activation().is_some_and(|activation| activation.by_key) {
|
||||
self.open = !self.open;
|
||||
}
|
||||
self.band_double(cx);
|
||||
self.surface_press(comp.sense().contains(craft_behavior::Sense::SURFACE), cx);
|
||||
self.band_double(cx.core);
|
||||
self.surface_press(comp.sense().contains(craft_behavior::Sense::SURFACE), cx.core);
|
||||
let band = props.header.is_some_and(|header| header.band == DragBand::Move);
|
||||
if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. }))
|
||||
&& let Some(viewport) = os_window(props, cx.core.memory.ctx(), cx.core.id, &cx.core.env)
|
||||
{
|
||||
self.window_os(viewport, props, cx);
|
||||
self.window_movable(viewport, cx);
|
||||
self.window_movable(viewport, cx.core);
|
||||
}
|
||||
self.pane_drag(props, cx);
|
||||
self.pane_drag(props, cx.core);
|
||||
if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(cx.core.memory.ctx(), cx.core.id)) {
|
||||
self.window_keys(props, cx);
|
||||
self.window_drag(props, cx);
|
||||
}
|
||||
self.window_placed(props, cx);
|
||||
self.window_placed(props, cx.core);
|
||||
// The body moves and resizes the layer in screen space; the caller places it in its parent's layer space.
|
||||
let from_screen = crate::runtime::overlay::parent_space(&cx.core.ctx, cx.core.id).inverse();
|
||||
for mut change in std::mem::take(&mut self.reports) {
|
||||
@@ -581,10 +582,10 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
self.footer_slot_step(comp, ui, cx, &mut plan);
|
||||
}
|
||||
// B2 label: the control gets the rect the label leaves; the label column adds to the container's extent.
|
||||
self.label_step(ui, env, cx, &mut plan);
|
||||
self.label_step(ui, env, cx.core, &mut plan);
|
||||
// B3 body, if open, under the body env; the gate is read after the header changed it.
|
||||
if plan.is_open {
|
||||
self.body_step(ui, env, cx, &mut plan);
|
||||
self.body_step(ui, env, cx.core, &mut plan);
|
||||
self.after_body(ui, env, &mut plan);
|
||||
if plan.real && props.end.is_some() {
|
||||
self.end_step(comp, ui, cx, &mut plan);
|
||||
@@ -1155,7 +1156,7 @@ impl BodyHooks<'_> {
|
||||
/// B2: the body's place beside the regions measured so far, the label step and the body's env.
|
||||
// Kept out of the recursive frame above it: opt-level 2 inlines it there, so its locals stay on the stack while children run.
|
||||
#[inline(never)]
|
||||
fn label_step<C: Container>(&mut self, ui: &mut Ui, env: &Env, cx: &Cx<'_, C>, plan: &mut BodyPlan<'_>) {
|
||||
fn label_step(&mut self, ui: &mut Ui, env: &Env, core: &CxCore<'_>, plan: &mut BodyPlan<'_>) {
|
||||
let props = plan.props;
|
||||
let (ctx, id, real) = (&plan.ctx, plan.id, plan.real);
|
||||
let beside =
|
||||
@@ -1200,7 +1201,7 @@ impl BodyHooks<'_> {
|
||||
plan.ran_top = plan.body_rect.min.y;
|
||||
plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl);
|
||||
// The body's control shows an inside label in its slot, in the measuring run and the real run alike.
|
||||
let inside = props.label.as_ref().and_then(|side| label::inside(env.view(), side, cx.core.resolved.enabled));
|
||||
let inside = props.label.as_ref().and_then(|side| label::inside(env.view(), side, core.resolved.enabled));
|
||||
// In an inspector the control beside its label fills the width the label leaves.
|
||||
let cell_fills = props.label.as_ref().is_some_and(|side| side.layout == label::FieldLayout::Beside)
|
||||
&& env.values.get::<label::LabelScheme>() == label::LabelScheme::Inspector;
|
||||
@@ -1224,7 +1225,7 @@ impl BodyHooks<'_> {
|
||||
|
||||
/// B3: the body region, on the body layer when the container transforms its body.
|
||||
#[expect(clippy::expect_used, reason = "the label step sets the body env before the body step")]
|
||||
fn body_step<C: Container>(&mut self, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) {
|
||||
fn body_step(&mut self, ui: &mut Ui, env: &Env, core: &mut CxCore<'_>, plan: &mut BodyPlan<'_>) {
|
||||
let props = plan.props;
|
||||
let body_env = plan.body_env.as_ref().expect("the label step ran");
|
||||
let reveal_clip = (plan.animated && self.presence.t < 1.0).then(|| {
|
||||
@@ -1253,19 +1254,11 @@ impl BodyHooks<'_> {
|
||||
};
|
||||
let body_rect = plan.body_rect;
|
||||
let share = plan.share(false);
|
||||
let mut bcx = BodyCx::new(
|
||||
plan.body_id,
|
||||
body_env.view(),
|
||||
plan.resolved,
|
||||
body_rect,
|
||||
&mut *cx.core.memory,
|
||||
&mut plan.open,
|
||||
plan.gate.as_mut(),
|
||||
Some(share),
|
||||
);
|
||||
let mut bcx =
|
||||
BodyCx::new(plan.body_id, body_env.view(), plan.resolved, body_rect, &mut *core.memory, &mut plan.open, plan.gate.as_mut(), Some(share));
|
||||
let mut bars = Vec2::ZERO;
|
||||
self.body_size = match props.transform {
|
||||
Some(transform) => self.run_transformed(&run, ui, (transform, cx.core.root_sense, plan.rect, body_rect), &mut bcx, &mut bars),
|
||||
Some(transform) => self.run_transformed(&run, ui, (transform, core.root_sense, plan.rect, body_rect), &mut bcx, &mut bars),
|
||||
None => self.run_body(&run, ui, body_rect, &mut bcx, &mut bars),
|
||||
};
|
||||
plan.close = plan.close.or(bcx.close_requested());
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! The grip of an edge pane and its drag.
|
||||
|
||||
use super::BodyHooks;
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::contract::mount::{PaneGrip, pane_extent_id, pane_grip_id};
|
||||
use crate::contract::overlay::{PlacementChange, PlacementKind};
|
||||
use crate::contract::{Container, ContainerProps, Cx, Mount, PaneEdge, PartsCx};
|
||||
use crate::contract::{Container, ContainerProps, Mount, PaneEdge, PartsCx};
|
||||
use crate::runtime::layout_memory;
|
||||
use crate::runtime::windows::ResizeEdge;
|
||||
use craft_behavior::{CursorIcon, GesturePhase, HitLevel, HitPriority, PartKey, PressPhase};
|
||||
@@ -49,9 +50,9 @@ impl BodyHooks<'_> {
|
||||
/// is reported as a `PlacementKind::Size` change of the pane's rect. While the gesture runs the pane host shows its
|
||||
/// extent (`PaneGrip`); at the commit a pane with no fixed extent keeps it in pane memory, and one whose caller fixes
|
||||
/// the extent shows the caller's from the next pass. Escape, which cancels the press, restores the extent.
|
||||
pub(super) fn pane_drag<C: Container>(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
pub(super) fn pane_drag(&mut self, props: &ContainerProps, core: &mut CxCore<'_>) {
|
||||
let (Mount::Pane(pane), Some((edge, least))) = (&props.mount, self.pane_grip) else { return };
|
||||
let Some(phase) = cx.core.results.get(&(PANE_GRIP, None)).map(|result| result.press.phase) else { return };
|
||||
let Some(phase) = core.results.get(&(PANE_GRIP, None)).map(|result| result.press.phase) else { return };
|
||||
let (origin, pos, gesture) = match phase {
|
||||
PressPhase::DragStart { start, pos, .. } => (start.origin, Some(pos), GesturePhase::Begin),
|
||||
PressPhase::Drag { start, pos, .. } => (start.origin, Some(pos), GesturePhase::Update),
|
||||
@@ -59,10 +60,10 @@ impl BodyHooks<'_> {
|
||||
PressPhase::Cancel { start, .. } => (start.origin, None, GesturePhase::Cancel),
|
||||
_ => return,
|
||||
};
|
||||
let (ctx, id, rect) = (cx.core.ctx.clone(), cx.core.id, cx.core.rect);
|
||||
let (ctx, id, rect) = (core.ctx.clone(), core.id, core.rect);
|
||||
let horizontal = matches!(edge, ResizeEdge::Left | ResizeEdge::Right);
|
||||
let along = |size: Vec2| if horizontal { size.x } else { size.y };
|
||||
let slot = cx.core.memory.shown::<PaneGrip>(pane_grip_id(id));
|
||||
let slot = core.memory.shown::<PaneGrip>(pane_grip_id(id));
|
||||
let shown = slot.extent;
|
||||
let began = match slot.began {
|
||||
Some(began) if gesture != GesturePhase::Begin => began,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::BodyHooks;
|
||||
use super::window::MOVE_BAND;
|
||||
use crate::contract::cx::BodyCx;
|
||||
use crate::contract::{Container, Cx};
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::runtime::egui::areas;
|
||||
use crate::runtime::memory::sub;
|
||||
use crate::runtime::pointer;
|
||||
@@ -69,30 +69,30 @@ impl BodyHooks<'_> {
|
||||
/// (`BodyCx::surface_pressed`): no shape of last pass under the press takes it, and the press lies in the
|
||||
/// container's rect on its layer; and whether that press is the second of a double click
|
||||
/// (`BodyCx::surface_double_pressed`), read from the same press's click count.
|
||||
pub(super) fn surface_press<C: Container>(&self, sensed: bool, cx: &mut Cx<'_, C>) {
|
||||
let ctx = cx.core.ctx.clone();
|
||||
pub(super) fn surface_press(&self, sensed: bool, core: &mut CxCore<'_>) {
|
||||
let ctx = core.ctx.clone();
|
||||
let surface = if sensed {
|
||||
let pass = pointer::pass_pointer(&ctx);
|
||||
pass.frame.as_ref().and_then(|frame| frame.press).filter(|press| press.button == craft_behavior::PointerButton::Primary).filter(|press| {
|
||||
let layer = cx.core.response.layer_id;
|
||||
let layer = core.response.layer_id;
|
||||
let at = areas::layer_map(&ctx, layer).map_or(press.origin, |map| map.to_layer(press.origin));
|
||||
areas::layer_at(&ctx, press.origin) == Some(layer)
|
||||
&& cx.core.rect.contains(at)
|
||||
&& core.rect.contains(at)
|
||||
&& pointer::press_winner(&ctx, press.origin, pass.press_targets).is_none()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let shown = cx.core.memory.shown::<SurfacePress>(sub(sub(cx.core.id, "body"), "surface_press"));
|
||||
let shown = core.memory.shown::<SurfacePress>(sub(sub(core.id, "body"), "surface_press"));
|
||||
shown.pressed = surface.is_some();
|
||||
shown.double = surface.is_some_and(|press| press.clicks >= 2);
|
||||
}
|
||||
|
||||
/// Records for the container's header hooks whether the second press of a double click went down on the move
|
||||
/// band in this pass (`BodyCx::band_double_pressed`).
|
||||
pub(super) fn band_double<C: Container>(&self, cx: &mut Cx<'_, C>) {
|
||||
let Some(band) = cx.core.results.get(&(MOVE_BAND, None)) else { return };
|
||||
pub(super) fn band_double(&self, core: &mut CxCore<'_>) {
|
||||
let Some(band) = core.results.get(&(MOVE_BAND, None)) else { return };
|
||||
let double = band.press.double_pressed();
|
||||
cx.core.memory.shown::<BandDouble>(sub(sub(cx.core.id, "body"), "band_double")).0 = double;
|
||||
core.memory.shown::<BandDouble>(sub(sub(core.id, "body"), "band_double")).0 = double;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The reorder band: a section header whose section the stacking keys move.
|
||||
|
||||
use super::BodyHooks;
|
||||
use crate::contract::{Container, ContainerProps, Cx, DragBand};
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::contract::{ContainerProps, DragBand};
|
||||
use crate::runtime::commands;
|
||||
use crate::runtime::keys;
|
||||
use craft_behavior::{PartKey, keys as key_table};
|
||||
@@ -17,11 +18,11 @@ impl BodyHooks<'_> {
|
||||
/// The stacking keys (`keys::REORDER_KEYS`) while focus is anywhere in a section whose header is a reorder band. A
|
||||
/// section has no stop of its own, so the keys would reach the stops in it: the container holds the chords for
|
||||
/// itself and turns them into `Intent::MoveItem` for its own update.
|
||||
pub(super) fn reorder_keys<C: Container>(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
pub(super) fn reorder_keys(&mut self, props: &ContainerProps, core: &mut CxCore<'_>) {
|
||||
if !props.header.is_some_and(|header| header.band == DragBand::Reorder) {
|
||||
return;
|
||||
}
|
||||
let (id, ctx) = (cx.core.id, cx.core.ctx.clone());
|
||||
let (id, ctx) = (core.id, core.ctx.clone());
|
||||
let within = commands::focus_within(&ctx, id);
|
||||
for chord in key_table::REORDER_KEYS {
|
||||
if within {
|
||||
@@ -29,7 +30,7 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
while keys::take_claimed(&ctx, id, chord) {
|
||||
if let Some(intent) = key_table::reorder_intent(chord.key, chord.mods) {
|
||||
cx.core.intents.push(intent);
|
||||
core.intents.push(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::BodyHooks;
|
||||
use super::inherit::own_surface;
|
||||
use super::placement::overlay_of;
|
||||
use super::regions::rect_of;
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::contract::{Container, ContainerProps, Cx, Scroll};
|
||||
use crate::primitives::{HiddenContent, ScrollBar};
|
||||
use crate::runtime::egui::pass;
|
||||
@@ -230,7 +231,7 @@ impl BodyHooks<'_> {
|
||||
if let Some(range) = cx.scroll_moved(SCROLL_X) {
|
||||
offset.x = range.start;
|
||||
}
|
||||
self.access_scroll(scroll, &mut offset, cx);
|
||||
self.access_scroll(scroll, &mut offset, cx.core);
|
||||
let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size());
|
||||
let offset = self.clamped(scroll, view, offset);
|
||||
if offset != self.offset {
|
||||
@@ -239,11 +240,11 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
|
||||
/// AccessKit scroll actions aimed at the container's node, applied to `offset`: a page along an axis, or an offset.
|
||||
fn access_scroll<C: Container>(&self, scroll: Scroll, offset: &mut ScrollPos, cx: &mut Cx<'_, C>) {
|
||||
fn access_scroll(&self, scroll: Scroll, offset: &mut ScrollPos, core: &mut CxCore<'_>) {
|
||||
use craft_behavior::{AccessAction as Action, AccessData as ActionData};
|
||||
let rtl = cx.core.env.direction().is_rtl();
|
||||
let rtl = core.env.direction().is_rtl();
|
||||
let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size());
|
||||
while let Some(request) = cx.core.intents.take_scroll_access(false) {
|
||||
while let Some(request) = core.intents.take_scroll_access(false) {
|
||||
let (vertical, toward_end) = match request.action {
|
||||
Action::ScrollUp => (true, false),
|
||||
Action::ScrollDown => (true, true),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::BodyHooks;
|
||||
use super::placement::{Placement, PlacementSlot, overlay_of};
|
||||
use super::regions::Regions;
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::contract::overlay::{PlacementChange, PlacementKind, ResizeEdges};
|
||||
use crate::contract::{Container, ContainerProps, Cx, Mount, PartsCx};
|
||||
use crate::runtime::commands::{self, CommandSet as _, WindowCommand};
|
||||
@@ -483,7 +484,7 @@ impl BodyHooks<'_> {
|
||||
if by_caller {
|
||||
let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, cx.style.metrics().min_size)));
|
||||
if let Some(limits) = limits {
|
||||
self.window_resize(viewport, &limits, cx);
|
||||
self.window_resize(viewport, &limits, cx.core);
|
||||
}
|
||||
}
|
||||
if answered_by_platform(&cx.core.ctx, viewport) {
|
||||
@@ -491,7 +492,7 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
let app_moves = windows::app_moves(&cx.core.ctx, viewport);
|
||||
if app_moves {
|
||||
self.window_move(viewport, cx);
|
||||
self.window_move(viewport, cx.core);
|
||||
}
|
||||
// The parts stand only by `WindowParts`, and the results of a part not registered this pass are gone.
|
||||
let started =
|
||||
@@ -511,11 +512,11 @@ impl BodyHooks<'_> {
|
||||
/// resize is, from Begin to Commit or Cancel. The app sends the window no size: the caller places the size it
|
||||
/// makes of the steps. The press holds the pointer, so its moves arrive while it is outside the window. A pointer
|
||||
/// move of this pass is relative to where the window reports itself now, as in [`Self::window_move`].
|
||||
fn window_resize<C: Container>(&mut self, viewport: ViewportId, limits: &Limits, cx: &mut Cx<'_, C>) {
|
||||
let ctx = cx.core.ctx.clone();
|
||||
fn window_resize(&mut self, viewport: ViewportId, limits: &Limits, core: &mut CxCore<'_>) {
|
||||
let ctx = core.ctx.clone();
|
||||
let Some(facts) = windows::WindowHost::of(&ctx).facts(viewport) else { return };
|
||||
let outer = facts.outer.unwrap_or(facts.inner);
|
||||
let phase = |index: usize| cx.core.results.get(&(GRIP, Some(index as u64))).map(|result| result.press.phase);
|
||||
let phase = |index: usize| core.results.get(&(GRIP, Some(index as u64))).map(|result| result.press.phase);
|
||||
let change = |rect: Rect, phase: GesturePhase, grip: usize| {
|
||||
let (dx, dy, _) = GRIPS[grip];
|
||||
PlacementChange { rect, phase, pointer: None, kind: PlacementKind::Size(edge_of(dx, dy)) }
|
||||
@@ -571,9 +572,9 @@ impl BodyHooks<'_> {
|
||||
/// host adds once the system tells the button is up. Elsewhere the move starts past the click distance, the app
|
||||
/// moves the window to this pass's pointer, relative to where the window reports itself, and Escape puts it back.
|
||||
/// The drag's desktop pointer is the pressed point of the window where the move put it.
|
||||
fn window_move<C: Container>(&mut self, viewport: ViewportId, cx: &mut Cx<'_, C>) {
|
||||
let ctx = cx.core.ctx.clone();
|
||||
let Some(phase) = cx.core.results.get(&(MOVE_BAND, None)).map(|result| result.press.phase) else { return };
|
||||
fn window_move(&mut self, viewport: ViewportId, core: &mut CxCore<'_>) {
|
||||
let ctx = core.ctx.clone();
|
||||
let Some(phase) = core.results.get(&(MOVE_BAND, None)).map(|result| result.press.phase) else { return };
|
||||
let host = windows::WindowHost::of(&ctx);
|
||||
let Some(facts) = host.facts(viewport) else { return };
|
||||
let outer = facts.outer.unwrap_or(facts.inner);
|
||||
@@ -672,14 +673,14 @@ impl BodyHooks<'_> {
|
||||
/// `placement_changed` a layer reports its own through: one `Commit` per change, as the platform tells no gesture
|
||||
/// phase. The first facts are the window's placement, not a change; the steps of a move the app runs are that
|
||||
/// move's own ([`Self::window_move`]).
|
||||
pub(super) fn window_placed<C: Container>(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
pub(super) fn window_placed(&mut self, props: &ContainerProps, core: &mut CxCore<'_>) {
|
||||
if !matches!(props.mount, Mount::Viewport { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(viewport) = os_window(props, &cx.core.ctx, cx.core.id, &cx.core.env) else { return };
|
||||
let Some(facts) = windows::WindowHost::of(&cx.core.ctx).facts(viewport) else { return };
|
||||
let Some(viewport) = os_window(props, &core.ctx, core.id, &core.env) else { return };
|
||||
let Some(facts) = windows::WindowHost::of(&core.ctx).facts(viewport) else { return };
|
||||
let now = facts.outer.unwrap_or(facts.inner);
|
||||
let placed = &mut cx.core.memory.shown::<WindowPlaced>(sub(sub(cx.core.id, "body"), "window_placed")).0;
|
||||
let placed = &mut core.memory.shown::<WindowPlaced>(sub(sub(core.id, "body"), "window_placed")).0;
|
||||
let before = placed.replace(now);
|
||||
if self.mode.moving.is_some() || self.mode.sizing.is_some() {
|
||||
return;
|
||||
@@ -777,9 +778,9 @@ impl BodyHooks<'_> {
|
||||
/// nothing: its move starts from the band's press, and macOS keeps such a window movable, which AppKit needs to
|
||||
/// move it for the hand-off and to resize it from its edges. A pass with no band writes nothing; `AppShell` writes
|
||||
/// `false` for a pass with no title bar.
|
||||
pub(super) fn window_movable<C: Container>(&self, viewport: ViewportId, cx: &Cx<'_, C>) {
|
||||
let Some(band) = cx.core.results.get(&(MOVE_BAND, None)) else { return };
|
||||
let ctx = &cx.core.ctx;
|
||||
pub(super) fn window_movable(&self, viewport: ViewportId, core: &CxCore<'_>) {
|
||||
let Some(band) = core.results.get(&(MOVE_BAND, None)) else { return };
|
||||
let ctx = &core.ctx;
|
||||
if windows::app_moves(ctx, viewport) {
|
||||
return;
|
||||
}
|
||||
@@ -787,7 +788,7 @@ impl BodyHooks<'_> {
|
||||
&& pointer::with_hover(ctx, pass::current_viewport(ctx), |under, _| {
|
||||
under
|
||||
.and_then(|under| under.press.click.or(under.press.drag))
|
||||
.is_some_and(|(winner, root)| root == cx.core.id && winner.part.is_some_and(|part| part.key == MOVE_BAND))
|
||||
.is_some_and(|(winner, root)| root == core.id && winner.part.is_some_and(|part| part.key == MOVE_BAND))
|
||||
});
|
||||
let this_pass = viewports::pass_number(ctx);
|
||||
let allowed = viewports::movable_record(ctx).is_some_and(|(pass, movable)| pass == this_pass && movable);
|
||||
|
||||
@@ -879,29 +879,11 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
let editor = comp.rename_editor(row_ui, Bind::bound(&mut draft), label, &name);
|
||||
self.renaming.draft = draft;
|
||||
if let Some(editor) = editor {
|
||||
if !self.renaming.focused {
|
||||
focus::request_now(ctx, focus::FocusTarget::Id(editor.response.id));
|
||||
self.renaming.focused = true;
|
||||
}
|
||||
let gesture = self.renaming.gesture;
|
||||
let before = Mixed::Same(Rename { key: key.clone(), name: name.clone() });
|
||||
// The editor's gesture end, if the pass has one, ends the rename.
|
||||
let end = editor.events.iter().rev().find(|event| matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. })).cloned();
|
||||
let edited = !editor.events.is_empty();
|
||||
if end.is_some() {
|
||||
self.refocus = focus::is_focused(ctx, editor.response.id);
|
||||
}
|
||||
// The editor claims Escape for the whole rename, as a text part with a draft does: Escape does not leave the
|
||||
// row. One the editor leaves untaken (it holds no draft yet) cancels the rename.
|
||||
keys::hold_escape(ctx, editor.response.id);
|
||||
let escaped = !edited && focus::is_focused(ctx, editor.response.id) && {
|
||||
let mut intents = keys::intents_of(ctx, Some(editor.response.id), rtl);
|
||||
let left = intents.take(Intent::Cancel);
|
||||
keys::settle(ctx, Some(editor.response.id), &intents);
|
||||
left
|
||||
};
|
||||
let (end, escaped) = rename_input(ctx, &editor, rtl, &mut self.renaming.focused, &mut self.refocus);
|
||||
match end {
|
||||
None if edited => {}
|
||||
None if !editor.events.is_empty() => {}
|
||||
None if escaped => {
|
||||
self.events.push(CollectionEvent::Rename(EditEvent::cancel(gesture, CancelReason::Escape, Some(before))));
|
||||
self.ended_rename = true;
|
||||
@@ -945,6 +927,33 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus and Escape belong to the editor until the rename ends, independent of the row's key type.
|
||||
fn rename_input(
|
||||
ctx: &Context,
|
||||
editor: &crate::contract::EditResponse<String>,
|
||||
rtl: bool,
|
||||
focused: &mut bool,
|
||||
refocus: &mut bool,
|
||||
) -> (Option<EditEvent<String>>, bool) {
|
||||
let id = editor.response.id;
|
||||
if !*focused {
|
||||
focus::request_now(ctx, focus::FocusTarget::Id(id));
|
||||
*focused = true;
|
||||
}
|
||||
let end = editor.events.iter().rev().find(|event| matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. })).cloned();
|
||||
if end.is_some() {
|
||||
*refocus = focus::is_focused(ctx, id);
|
||||
}
|
||||
keys::hold_escape(ctx, id);
|
||||
let escaped = editor.events.is_empty() && focus::is_focused(ctx, id) && {
|
||||
let mut intents = keys::intents_of(ctx, Some(id), rtl);
|
||||
let left = intents.take(Intent::Cancel);
|
||||
keys::settle(ctx, Some(id), &intents);
|
||||
left
|
||||
};
|
||||
(end, escaped)
|
||||
}
|
||||
|
||||
/// The height of the first `rows` rows of `layout` over `len` items: the rows it lays out, and the row height `row` for
|
||||
/// each one it does not have.
|
||||
fn rows_height(layout: &impl ItemLayout, len: usize, rows: u16, row: f32) -> f32 {
|
||||
|
||||
@@ -739,31 +739,31 @@ pub trait Show: Component + Meta<Shape = shape::Leaf> + sealed::Show {
|
||||
/// Shows a container with its body.
|
||||
pub trait ShowContainer: Container + sealed::ShowContainer {
|
||||
/// Shows the container in the flow of `ui`.
|
||||
fn show<R>(self, ui: &mut Ui, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Flow, body, None)
|
||||
fn show<R>(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Flow, &mut body, None)
|
||||
}
|
||||
|
||||
/// Shows the container at `rect`, with no allocation: a frame over a split or a layer the parent places.
|
||||
fn show_at<R>(self, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), body, None)
|
||||
fn show_at<R>(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), &mut body, None)
|
||||
}
|
||||
|
||||
/// Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies
|
||||
/// past it, as after [`show`](Self::show).
|
||||
fn show_at_taking_room<R>(self, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
run::show_container_taking(&mut Some(self), ui, rect, body)
|
||||
fn show_at_taking_room<R>(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
run::show_container_taking(&mut Some(self), ui, rect, &mut body)
|
||||
}
|
||||
|
||||
/// Measures the container with `body` without allocating: steps 1 to 5 under the id `show` would use next, with
|
||||
/// the body, header, footer and end regions run once in an invisible sizing pass, laid out as `show` lays them
|
||||
/// out. The size comes from this pass's content alone; along an axis the body scrolls on it is at most the room.
|
||||
fn measure_in<R>(&mut self, ui: &Ui, proposal: Proposal, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Vec2 {
|
||||
run::measure_container(self, ui, proposal, body)
|
||||
fn measure_in<R>(&mut self, ui: &Ui, proposal: Proposal, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Vec2 {
|
||||
run::measure_container(self, ui, proposal, &mut body)
|
||||
}
|
||||
|
||||
/// Shows the container with rich tooltip content.
|
||||
fn show_with_tip<R>(self, ui: &mut Ui, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Flow, body, Some(Box::new(tip)))
|
||||
fn show_with_tip<R>(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Flow, &mut body, Some(Box::new(tip)))
|
||||
}
|
||||
|
||||
/// Shows the container at `rect` with rich tooltip content.
|
||||
@@ -771,10 +771,10 @@ pub trait ShowContainer: Container + sealed::ShowContainer {
|
||||
self,
|
||||
ui: &mut Ui,
|
||||
rect: Rect,
|
||||
body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
tip: impl FnOnce(&mut Ui),
|
||||
) -> Inner<Self::Output, R> {
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), body, Some(Box::new(tip)))
|
||||
run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), &mut body, Some(Box::new(tip)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,11 @@ impl<'a> OverlayUi<'a> {
|
||||
/// placed, so a popup whose content changes is placed by its new size in the pass that shows it. A child that fills
|
||||
/// the width takes the width the popup settles on, not the window's. The popup's memory belongs to the component
|
||||
/// that shows it (or to the opener its overlay names), so what its body keeps lasts while that component shows.
|
||||
pub fn show<R>(&mut self, popup: PopupHandle, overlay: Overlay, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Option<R> {
|
||||
pub fn show<R>(&mut self, popup: PopupHandle, overlay: Overlay, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Option<R> {
|
||||
self.show_with(popup, overlay, &mut body)
|
||||
}
|
||||
|
||||
fn show_with<R>(&mut self, popup: PopupHandle, overlay: Overlay, body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Option<R> {
|
||||
let Some(open) = self.open.get(&popup.id).copied() else {
|
||||
debug_assert!(false, "popup {:?} is shown but was not registered with `cx.popup` this pass", popup.name);
|
||||
return None;
|
||||
@@ -116,7 +120,7 @@ impl<'a> OverlayUi<'a> {
|
||||
let label = self.resolved.label_value.clone();
|
||||
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).mount(Mount::Layer(overlay));
|
||||
let container = PopupBody { common: Common::new(), props: ContainerProps { owner: Some(owner), ..props } }.label(label);
|
||||
self.show_container(popup, container, body).and_then(|shown| shown.inner)
|
||||
self.show_container_with(popup, container, body).and_then(|shown| shown.inner)
|
||||
}
|
||||
|
||||
/// Shows `container` as the layer of `popup`, through the container pipeline: its body step with the move band
|
||||
@@ -130,7 +134,16 @@ impl<'a> OverlayUi<'a> {
|
||||
&mut self,
|
||||
popup: PopupHandle,
|
||||
container: C,
|
||||
body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
) -> Option<Inner<C::Output, R>> {
|
||||
self.show_container_with(popup, container, &mut body)
|
||||
}
|
||||
|
||||
fn show_container_with<C: ShowContainer, R>(
|
||||
&mut self,
|
||||
popup: PopupHandle,
|
||||
container: C,
|
||||
body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
) -> Option<Inner<C::Output, R>> {
|
||||
let Some(open) = self.open.get(&popup.id).copied() else {
|
||||
debug_assert!(false, "popup {:?} is shown but was not registered with `cx.popup` this pass", popup.name);
|
||||
|
||||
@@ -542,7 +542,7 @@ pub(crate) fn show_container_taking<C: Container, R>(
|
||||
slot: &mut Option<C>,
|
||||
ui: &mut Ui,
|
||||
rect: Rect,
|
||||
body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> 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::runtime::egui::alloc::advance_past(ui, rect);
|
||||
@@ -553,7 +553,7 @@ pub(crate) fn show_container<C: Container, R>(
|
||||
slot: &mut Option<C>,
|
||||
ui: &mut Ui,
|
||||
at: ShowAt,
|
||||
mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
tip: Option<TipFn<'_>>,
|
||||
) -> Inner<C::Output, R> {
|
||||
if let Some(output) = unshown(held(slot), ui) {
|
||||
@@ -643,7 +643,7 @@ pub(crate) fn measure_container<C: Container, R>(
|
||||
comp: &mut C,
|
||||
ui: &Ui,
|
||||
proposal: Proposal,
|
||||
mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
) -> Vec2 {
|
||||
let mut call = |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
body(ui, cx);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Step 9's scrub: a drag on the side label, the body or a part changes the value.
|
||||
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::contract::{Component, Cx};
|
||||
use crate::runtime::access::scope;
|
||||
use crate::runtime::memory::sub;
|
||||
@@ -16,17 +17,17 @@ pub(super) fn scrub_press<C: Component>(comp: &C, cx: &Cx<'_, C>) -> Option<(cra
|
||||
let press = cx.core.results.get(&(part.key, part.index)).map(|result| result.press)?;
|
||||
pressed(&press).then(|| (press, drag.clone()))
|
||||
});
|
||||
let label = || scrub.by_label.then(|| side_label(cx)).flatten().map(|(press, _)| press).filter(pressed);
|
||||
let label = || scrub.by_label.then(|| side_label(cx.core)).flatten().map(|(press, _)| press).filter(pressed);
|
||||
let field = || (scrub.on_field && !cx.core.text_takes_pointer).then_some(cx.core.press).filter(pressed);
|
||||
part.or_else(|| label().or_else(field).map(|press| (press, scrub.drag.clone())))
|
||||
}
|
||||
|
||||
/// The press and hover of the side label a `by_label` scrub reads: the inside label's part when the control declared
|
||||
/// one (`PartsCx::label_part`), else the label scope's label.
|
||||
fn side_label<C: Component>(cx: &Cx<'_, C>) -> Option<(craft_behavior::PressState, bool)> {
|
||||
match cx.core.results.get(&(crate::contract::InsideLabel::PART, None)) {
|
||||
fn side_label(core: &CxCore<'_>) -> Option<(craft_behavior::PressState, bool)> {
|
||||
match core.results.get(&(crate::contract::InsideLabel::PART, None)) {
|
||||
Some(part) => Some((part.press, part.hovered)),
|
||||
None => scope::field_label(&cx.core.ctx).map(|label| (label.press, label.hovered)),
|
||||
None => scope::field_label(&core.ctx).map(|label| (label.press, label.hovered)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,13 +42,13 @@ struct ScrubWarp(DragWarp);
|
||||
/// The total warp of the running scrub. A scrub that warps moves the pointer to the other side of the window when
|
||||
/// it reaches an edge, once the pointer from the last warp has shown up at its new place; a platform that cannot
|
||||
/// warp leaves the drag as it is.
|
||||
fn scrub_warp<C: Component>(cx: &mut Cx<'_, C>, drag: &ValueDrag, pos: Pos2) -> Vec2 {
|
||||
fn scrub_warp(core: &mut CxCore<'_>, drag: &ValueDrag, pos: Pos2) -> Vec2 {
|
||||
if !drag.warps() {
|
||||
return Vec2::ZERO;
|
||||
}
|
||||
let id = sub(cx.core.id, "scrub_warp");
|
||||
let ctx = cx.core.ctx.clone();
|
||||
let warp = &mut cx.core.memory.shown::<ScrubWarp>(id).0;
|
||||
let id = sub(core.id, "scrub_warp");
|
||||
let ctx = core.ctx.clone();
|
||||
let warp = &mut core.memory.shown::<ScrubWarp>(id).0;
|
||||
let shift = warp.shift(pos);
|
||||
if warp.pending() {
|
||||
return shift;
|
||||
@@ -79,7 +80,7 @@ pub(crate) fn scrub_by_label<C: Component>(comp: &C, cx: &mut Cx<'_, C>) {
|
||||
if scrub.by_label && scope::field_label(&cx.core.ctx).is_some() {
|
||||
scope::register_scrub(&cx.core.ctx);
|
||||
}
|
||||
let label = scrub.by_label.then(|| side_label(cx)).flatten();
|
||||
let label = scrub.by_label.then(|| side_label(cx.core)).flatten();
|
||||
// A scrub's source shows the horizontal resize cursor under the pointer.
|
||||
let part_hovered = scrub.parts.iter().any(|(part, _)| cx.core.results.get(&(part.key, part.index)).is_some_and(|result| result.hovered));
|
||||
let field_hovered = scrub.on_field && !cx.core.text_takes_pointer && cx.core.response.hovered();
|
||||
@@ -93,13 +94,13 @@ pub(crate) fn scrub_by_label<C: Component>(comp: &C, cx: &mut Cx<'_, C>) {
|
||||
PressPhase::DragStart { .. } => {
|
||||
cx.core.memory.shown::<ScrubStart>(start_id).0 = cx.value().map_or(0.0, |value| (scrub.read)(value));
|
||||
*cx.core.memory.shown::<ScrubWarp>(sub(cx.core.id, "scrub_warp")) = ScrubWarp::default();
|
||||
hide_scrub_cursor(cx, &drag);
|
||||
hide_scrub_cursor(cx.core, &drag);
|
||||
cx.begin();
|
||||
}
|
||||
PressPhase::Drag { pos, .. } => {
|
||||
hide_scrub_cursor(cx, &drag);
|
||||
hide_scrub_cursor(cx.core, &drag);
|
||||
let start = cx.core.memory.shown::<ScrubStart>(start_id).0;
|
||||
let shift = scrub_warp(cx, &drag, pos);
|
||||
let shift = scrub_warp(cx.core, &drag, pos);
|
||||
if let Some(next) = drag.value_shifted(start, &press, rtl, shift) {
|
||||
cx.propose((scrub.write)(next));
|
||||
}
|
||||
@@ -115,8 +116,8 @@ pub(crate) fn scrub_by_label<C: Component>(comp: &C, cx: &mut Cx<'_, C>) {
|
||||
}
|
||||
|
||||
/// A scrub that hides the pointer asks for no cursor while it runs.
|
||||
fn hide_scrub_cursor<C: Component>(cx: &Cx<'_, C>, drag: &ValueDrag) {
|
||||
fn hide_scrub_cursor(core: &CxCore<'_>, drag: &ValueDrag) {
|
||||
if drag.hides_cursor() {
|
||||
crate::runtime::cursor::request(&cx.core.ctx, Cursor::Painted(PaintedCursor::Hidden), CursorPriority::Drag);
|
||||
crate::runtime::cursor::request(&core.ctx, Cursor::Painted(PaintedCursor::Hidden), CursorPriority::Drag);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,18 +507,15 @@ fn shrink_widths_in_turn(units: &[ShrinkUnit], first: &[bool], fixed: f32, room:
|
||||
fn run_shrinking<R>(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> R {
|
||||
let ctx = ui.ctx().clone();
|
||||
let layout = *ui.layout();
|
||||
let sweep = |ui: &mut Ui, shrink: Shrink, body: &mut dyn FnMut(&mut Ui) -> R| {
|
||||
let installed = Env::install_for(
|
||||
ui,
|
||||
Env::of(ui).derive_local(|scoped| {
|
||||
scoped.shrink = Some(shrink);
|
||||
// The least of a body is what it takes in no room.
|
||||
if matches!(shrink, Shrink::Least(_)) {
|
||||
scoped.unbounded.0 = true;
|
||||
scoped.least = true;
|
||||
}
|
||||
}),
|
||||
);
|
||||
let mut env = Env::of(ui);
|
||||
let inherited = (env.unbounded.0, env.least);
|
||||
let mut sweep = |ui: &mut Ui, shrink: Shrink, body: &mut dyn FnMut(&mut Ui) -> R| {
|
||||
let scoped = env.local_mut();
|
||||
scoped.shrink = Some(shrink);
|
||||
let least = matches!(shrink, Shrink::Least(_));
|
||||
scoped.unbounded.0 = inherited.0 || least;
|
||||
scoped.least = inherited.1 || least;
|
||||
let installed = Env::install_for(ui, env.clone());
|
||||
let inner = body(ui);
|
||||
Env::restore(&ctx, installed);
|
||||
inner
|
||||
@@ -627,7 +624,7 @@ fn run_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo
|
||||
let share = layout_memory::measured(&ctx, key)
|
||||
.filter(|found| found.took.y >= 1.0 && room.is_finite())
|
||||
.map(|found| ((room - found.took.x) / found.took.y).max(0.0));
|
||||
share_sweep(ui, env, id, axis, share, &mut body)
|
||||
share_sweep(ui, &mut env.clone(), id, axis, share, &mut body)
|
||||
})
|
||||
.0
|
||||
}
|
||||
@@ -653,14 +650,11 @@ fn share_room(ui: &Ui, axis: Axis) -> f32 {
|
||||
}
|
||||
|
||||
/// One sweep of the children of the sharing body `id` in `ui`, each child that fills `axis` given `share`.
|
||||
fn share_sweep<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, share: Option<f32>, body: &mut dyn FnMut(&mut Ui) -> R) -> R {
|
||||
let installed = Env::install_for(
|
||||
ui,
|
||||
env.derive_local(|scoped| {
|
||||
scoped.fill_body = Some((id, axis));
|
||||
scoped.fill_share = share;
|
||||
}),
|
||||
);
|
||||
fn share_sweep<R>(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option<f32>, body: &mut dyn FnMut(&mut Ui) -> R) -> R {
|
||||
let scoped = env.local_mut();
|
||||
scoped.fill_body = Some((id, axis));
|
||||
scoped.fill_share = share;
|
||||
let installed = Env::install_for(ui, env.clone());
|
||||
let inner = body(ui);
|
||||
Env::restore(ui.ctx(), installed);
|
||||
inner
|
||||
@@ -684,12 +678,13 @@ fn measure_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::
|
||||
}
|
||||
let key = sub(id, "share");
|
||||
let along = |size: Vec2| if axis == Axis::Y { size.y } else { size.x };
|
||||
let mut sweep_env = env.clone();
|
||||
let first = crate::contract::keeping_ids(&ctx, || {
|
||||
let (inner, rect, room) = {
|
||||
let mut first = laid_out_child(ui, layout);
|
||||
let room = share_room(&first, axis);
|
||||
pass_state::with::<FillCounts, _>(&ctx, |counts| counts.0.insert(id, 0));
|
||||
let inner = share_sweep(&mut first, env, id, axis, None, body);
|
||||
let inner = share_sweep(&mut first, &mut sweep_env, id, axis, None, body);
|
||||
(inner, first.min_rect(), room)
|
||||
};
|
||||
let fills = pass_state::with::<FillCounts, _>(&ctx, |counts| counts.0.remove(&id)).unwrap_or(0);
|
||||
@@ -699,7 +694,7 @@ fn measure_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::
|
||||
((inner, rect, share), share.is_some())
|
||||
});
|
||||
match first {
|
||||
(_, _, Some(share)) => in_child(ui, &mut |ui| share_sweep(ui, env, id, axis, Some(share), body)),
|
||||
(_, _, Some(share)) => in_child(ui, &mut |ui| share_sweep(ui, &mut sweep_env, id, axis, Some(share), body)),
|
||||
(inner, rect, None) => (inner, rect),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,11 @@ pub(crate) fn take_raw<T: Any + Send + Sync>(data: &mut Map, id: Id) -> Option<R
|
||||
|
||||
/// Moves the slot of type `T` under `id` out of context data as the box it is stored in.
|
||||
pub(crate) fn take_boxed<T: Any + Send + Sync>(ctx: &Context, id: Id) -> Option<Removed> {
|
||||
ctx.data_mut(|data| take_raw::<T>(data, id))
|
||||
remove(ctx, RawKey::new::<T>(id))
|
||||
}
|
||||
|
||||
fn remove(ctx: &Context, key: RawKey) -> Option<Removed> {
|
||||
ctx.data_mut(|data| data.remove_temp_raw(key))
|
||||
}
|
||||
|
||||
/// Moves the slot of type `T` under `id` out of context data.
|
||||
@@ -77,7 +81,11 @@ pub(crate) fn peek_clone<T: Any + Clone + Send + Sync>(ctx: &Context, id: Id) ->
|
||||
|
||||
/// Whether a slot of type `T` is stored under `id`.
|
||||
pub(crate) fn exists<T: Any + Send + Sync>(ctx: &Context, id: Id) -> bool {
|
||||
ctx.data(|data| data.get_temp_raw(RawKey::new::<T>(id)).is_some())
|
||||
contains(ctx, RawKey::new::<T>(id))
|
||||
}
|
||||
|
||||
fn contains(ctx: &Context, key: RawKey) -> bool {
|
||||
ctx.data(|data| data.get_temp_raw(key).is_some())
|
||||
}
|
||||
|
||||
/// Runs `f` on the context's data under its lock; `f` runs no app code and makes no call that reaches the context.
|
||||
|
||||
@@ -605,6 +605,11 @@ impl Env {
|
||||
Env { scoped: Arc::new(scoped) }
|
||||
}
|
||||
|
||||
/// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot.
|
||||
pub(crate) fn local_mut(&mut self) -> &mut Scoped {
|
||||
Arc::make_mut(&mut self.scoped)
|
||||
}
|
||||
|
||||
/// This env's container scope on top of `root`, the root env of the viewport the scope now runs in: the scale,
|
||||
/// active state, window facts and OS are the viewport's, everything else stays.
|
||||
pub(crate) fn rebase(&self, root: &Env) -> Env {
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ impl Label {
|
||||
#[doc(hidden)]
|
||||
pub fn resolved(&self, words: &Words) -> Label {
|
||||
match self {
|
||||
Label::Word(word) => Label::from_cow(words.get(*word)),
|
||||
Label::Word(word) => words.translated_label(*word).map_or(Label::Static(word.english), Label::Shared),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::runtime::egui::focus as egui_focus;
|
||||
use crate::runtime::egui::memory::FastMap;
|
||||
use crate::runtime::frame::PerViewport;
|
||||
use craft_behavior::{DocKey, OwnerClass, PartRef};
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use egui::{Context, Id, IdSet, ViewportId};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
@@ -127,6 +127,7 @@ pub(crate) struct RowGroups {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct State {
|
||||
pub(crate) stops: Vec<StopRec>,
|
||||
stop_ids: IdSet,
|
||||
pub(crate) last_stops: Vec<StopRec>,
|
||||
pub(crate) scopes: FastMap<Id, ScopeRec>,
|
||||
pub(crate) last_scopes: FastMap<Id, ScopeRec>,
|
||||
@@ -201,6 +202,7 @@ pub(crate) fn apply(ctx: &Context, acts: Vec<Act>) {
|
||||
pub(crate) fn register_stop(ctx: &Context, stop: Stop) {
|
||||
with(ctx, |state| {
|
||||
let scope = state.open.last().map(|(id, _)| *id);
|
||||
state.stop_ids.insert(stop.id);
|
||||
state.stops.push(StopRec { stop, scope });
|
||||
});
|
||||
}
|
||||
@@ -320,7 +322,10 @@ pub(crate) fn replay(ctx: &Context, transcript: &Transcript) {
|
||||
state.seen.insert(*id, frame);
|
||||
}
|
||||
}
|
||||
state.stops.extend(transcript.stops.iter().map(|rec| StopRec { stop: rec.stop.clone(), scope: place(rec.scope) }));
|
||||
state.stops.extend(transcript.stops.iter().map(|rec| {
|
||||
state.stop_ids.insert(rec.stop.id);
|
||||
StopRec { stop: rec.stop.clone(), scope: place(rec.scope) }
|
||||
}));
|
||||
for group in &transcript.groups {
|
||||
state.groups.insert(group.id, *group);
|
||||
}
|
||||
@@ -338,7 +343,7 @@ pub(crate) fn targets(ctx: &Context) -> [Option<Id>; 2] {
|
||||
/// `from` (a `stop_count`), which a component inside it holds.
|
||||
pub(crate) fn first_stop_inside(ctx: &Context, id: Id, from: usize) -> Option<FocusTarget> {
|
||||
with(ctx, |state| {
|
||||
if state.stops.iter().any(|rec| rec.stop.id == id) {
|
||||
if state.stop_ids.contains(&id) {
|
||||
return None;
|
||||
}
|
||||
let rec = state.stops.get(from..)?.first()?;
|
||||
|
||||
@@ -117,6 +117,7 @@ impl Lists<'_> {
|
||||
impl State {
|
||||
pub(super) fn rotate(&mut self) {
|
||||
self.last_stops = std::mem::take(&mut self.stops);
|
||||
self.stop_ids.clear();
|
||||
self.last_scopes = std::mem::take(&mut self.scopes);
|
||||
self.last_scope_order = std::mem::take(&mut self.scope_order);
|
||||
self.last_groups = std::mem::take(&mut self.groups);
|
||||
|
||||
@@ -234,12 +234,27 @@ impl<T: Stored> Stored for Stamped<T> {
|
||||
impl<T: Stored> PerViewport<T> {
|
||||
/// Runs `f` on the record of `viewport`, created on first use.
|
||||
pub(crate) fn with<R>(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut T) -> R) -> R {
|
||||
let mut f = Some(f);
|
||||
let mut out = None;
|
||||
Self::visit(ctx, viewport, &mut |value| {
|
||||
if let Some(f) = f.take() {
|
||||
out = Some(f(value));
|
||||
}
|
||||
});
|
||||
#[expect(clippy::expect_used, reason = "visit calls its visitor once on the viewport's record")]
|
||||
out.expect("the viewport record was visited")
|
||||
}
|
||||
|
||||
fn visit(ctx: &Context, viewport: ViewportId, f: &mut dyn FnMut(&mut T)) {
|
||||
// The prune registration runs outside the records' borrow: it reaches the context.
|
||||
let (registered, out) = T::records(ctx, |records| (std::mem::replace(&mut records.pruning, true), f(records.record(viewport))));
|
||||
let registered = T::records(ctx, |records| {
|
||||
let registered = std::mem::replace(&mut records.pruning, true);
|
||||
f(records.record(viewport));
|
||||
registered
|
||||
});
|
||||
if !registered {
|
||||
Self::register_prune(ctx);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `f` on the record of every viewport that has one.
|
||||
|
||||
@@ -505,36 +505,41 @@ impl MemoryStage {
|
||||
store::peek_copy::<Seen>(&self.ctx, base).is_none_or(|seen| seen.0 == frame)
|
||||
}
|
||||
|
||||
#[allow(clippy::unreachable, reason = "the entry key holds the lifetime and the type, so the downcast cannot fail")]
|
||||
fn slot<const TIER: u8, T: Slot>(&mut self, id: Id) -> &mut T {
|
||||
let ctx = &self.ctx;
|
||||
let peek = self.peek_only;
|
||||
let key = (TIER, TypeId::of::<T>(), id);
|
||||
fn entry(&mut self, key: (u8, TypeId, Id), create: fn(&Context, bool, Id) -> Entry) -> &mut Entry {
|
||||
let at = match self.entries.iter().position(|entry| entry.key == key) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
let (value, recorded): (Box<dyn Any + Send + Sync>, bool) = if peek {
|
||||
(Box::new(store::peek_clone::<Wrapped<TIER, T>>(ctx, id).unwrap_or_default()), false)
|
||||
} else {
|
||||
// The box the slot was stored in stays the entry's value.
|
||||
match store::locked(ctx, |data| take_raw::<Wrapped<TIER, T>>(data, id)) {
|
||||
Some(boxed) if boxed.is::<Wrapped<TIER, T>>() => (boxed, true),
|
||||
_ => (Box::new(Wrapped::<TIER, T>::default()), false),
|
||||
}
|
||||
};
|
||||
self.entries.push(Entry {
|
||||
key,
|
||||
value,
|
||||
write_back: write_back::<TIER, T>,
|
||||
remove: remove_slot::<TIER, T>,
|
||||
ended: None,
|
||||
recorded,
|
||||
persist: None,
|
||||
});
|
||||
self.entries.push(create(&self.ctx, self.peek_only, key.2));
|
||||
self.entries.len() - 1
|
||||
}
|
||||
};
|
||||
match self.entries[at].value.downcast_mut::<Wrapped<TIER, T>>() {
|
||||
&mut self.entries[at]
|
||||
}
|
||||
|
||||
#[allow(clippy::unreachable, reason = "the entry key holds the lifetime and the type, so the downcast cannot fail")]
|
||||
fn slot<const TIER: u8, T: Slot>(&mut self, id: Id) -> &mut T {
|
||||
fn create<const TIER: u8, T: Slot>(ctx: &Context, peek: bool, id: Id) -> Entry {
|
||||
let (value, recorded): (Box<dyn Any + Send + Sync>, bool) = if peek {
|
||||
(Box::new(store::peek_clone::<Wrapped<TIER, T>>(ctx, id).unwrap_or_default()), false)
|
||||
} else {
|
||||
// The box the slot was stored in stays the entry's value.
|
||||
match store::take_boxed::<Wrapped<TIER, T>>(ctx, id) {
|
||||
Some(boxed) if boxed.is::<Wrapped<TIER, T>>() => (boxed, true),
|
||||
_ => (Box::new(Wrapped::<TIER, T>::default()), false),
|
||||
}
|
||||
};
|
||||
Entry {
|
||||
key: (TIER, TypeId::of::<T>(), id),
|
||||
value,
|
||||
write_back: write_back::<TIER, T>,
|
||||
remove: remove_slot::<TIER, T>,
|
||||
ended: None,
|
||||
recorded,
|
||||
persist: None,
|
||||
}
|
||||
}
|
||||
let entry = self.entry((TIER, TypeId::of::<T>(), id), create::<TIER, T>);
|
||||
match entry.value.downcast_mut::<Wrapped<TIER, T>>() {
|
||||
Some(wrapped) => &mut wrapped.0,
|
||||
None => unreachable!("an entry's value has the type its key names"),
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
use crate::runtime::egui::memory::Service;
|
||||
use crate::runtime::frame::{self, PerViewport, Stamped, Stored};
|
||||
use egui::{Context, IdSet};
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A service the pipeline touches on every run: a field of [`PassState`].
|
||||
@@ -148,9 +148,27 @@ struct Held {
|
||||
state: Box<PassState>,
|
||||
}
|
||||
|
||||
struct HeldStates {
|
||||
entries: Vec<Held>,
|
||||
current: Cell<usize>,
|
||||
}
|
||||
|
||||
impl HeldStates {
|
||||
/// Service reads in the same context reuse its slot. A nested context or a swap on release
|
||||
/// can change the slot, so verify its owner before reusing it.
|
||||
fn get(&self, ctx: &Context) -> Option<&PassState> {
|
||||
if let Some(entry) = self.entries.get(self.current.get()).filter(|entry| entry.ctx == *ctx) {
|
||||
return Some(&entry.state);
|
||||
}
|
||||
let at = self.entries.iter().position(|entry| entry.ctx == *ctx)?;
|
||||
self.current.set(at);
|
||||
Some(&self.entries[at].state)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The pass states this thread holds: one per context with a pass running here, and one a panic left behind.
|
||||
static HELD: RefCell<Vec<Held>> = const { RefCell::new(Vec::new()) };
|
||||
static HELD: RefCell<HeldStates> = const { RefCell::new(HeldStates { entries: Vec::new(), current: Cell::new(0) }) };
|
||||
}
|
||||
|
||||
/// The state of a context between passes; `None` while a thread holds it.
|
||||
@@ -166,32 +184,41 @@ impl Default for Parked {
|
||||
pub(crate) fn with<S: PassLocal, R>(ctx: &Context, f: impl FnOnce(&mut S) -> R) -> R {
|
||||
#[cfg(feature = "testing")]
|
||||
crate::runtime::layout_memory::guard::touch::<S>();
|
||||
let held = HELD.with(|held| {
|
||||
let held = held.borrow();
|
||||
match held.iter().find(|held| held.ctx == *ctx) {
|
||||
Some(held) => Ok(f(&mut S::cell(&held.state).borrow_mut())),
|
||||
None => Err(f),
|
||||
let mut call = Some(f);
|
||||
let mut out = None;
|
||||
visit(ctx, &mut |state| {
|
||||
if let Some(f) = call.take() {
|
||||
out = Some(f(&mut S::cell(state).borrow_mut()));
|
||||
}
|
||||
});
|
||||
match held {
|
||||
Ok(out) => out,
|
||||
Err(f) => {
|
||||
// Outside every pass of the context: hold the state for this read alone.
|
||||
struct Release<'a>(&'a Context);
|
||||
impl Drop for Release<'_> {
|
||||
fn drop(&mut self) {
|
||||
release(self.0);
|
||||
}
|
||||
#[expect(clippy::expect_used, reason = "visit calls its callback once on both the held and parked paths")]
|
||||
out.expect("the pass state was visited")
|
||||
}
|
||||
|
||||
/// The thread-local lookup and the parked-state slow path are shared by every service and caller.
|
||||
fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) {
|
||||
let found = HELD.with(|held| {
|
||||
let held = held.borrow();
|
||||
let Some(state) = held.get(ctx) else { return false };
|
||||
f(state);
|
||||
true
|
||||
});
|
||||
if !found {
|
||||
// Outside every pass of the context: hold the state for this read alone.
|
||||
struct Release<'a>(&'a Context);
|
||||
impl Drop for Release<'_> {
|
||||
fn drop(&mut self) {
|
||||
release(self.0);
|
||||
}
|
||||
hold(ctx);
|
||||
let _release = Release(ctx);
|
||||
HELD.with(|held| {
|
||||
let held = held.borrow();
|
||||
#[expect(clippy::expect_used, reason = "`hold` has just moved the context's state into this thread")]
|
||||
let held = held.iter().find(|held| held.ctx == *ctx).expect("the state was just taken");
|
||||
f(&mut S::cell(&held.state).borrow_mut())
|
||||
})
|
||||
}
|
||||
hold(ctx);
|
||||
let _release = Release(ctx);
|
||||
HELD.with(|held| {
|
||||
let held = held.borrow();
|
||||
#[expect(clippy::expect_used, reason = "`hold` has just moved the context's state into this thread")]
|
||||
let state = held.get(ctx).expect("the state was just taken");
|
||||
f(state)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,20 +227,24 @@ pub(crate) fn with<S: PassLocal, R>(ctx: &Context, f: impl FnOnce(&mut S) -> R)
|
||||
pub(crate) fn hold(ctx: &Context) {
|
||||
let stale: Vec<Held> = HELD.with(|held| {
|
||||
let mut held = held.borrow_mut();
|
||||
let (stale, kept) = std::mem::take(&mut *held).into_iter().partition(|held| held.ctx != *ctx && frame::running(&held.ctx).is_none());
|
||||
*held = kept;
|
||||
let (stale, kept) = std::mem::take(&mut held.entries).into_iter().partition(|held| held.ctx != *ctx && frame::running(&held.ctx).is_none());
|
||||
held.entries = kept;
|
||||
stale
|
||||
});
|
||||
for held in stale {
|
||||
park(held);
|
||||
}
|
||||
if HELD.with(|held| held.borrow().iter().any(|held| held.ctx == *ctx)) {
|
||||
if HELD.with(|held| held.borrow().get(ctx).is_some()) {
|
||||
return;
|
||||
}
|
||||
let state = Service::<Parked>::run(ctx, |parked| parked.0.take());
|
||||
debug_assert!(state.is_some(), "another thread holds this context's pass state");
|
||||
let state = state.unwrap_or_default();
|
||||
HELD.with(|held| held.borrow_mut().push(Held { ctx: ctx.clone(), state }));
|
||||
HELD.with(|held| {
|
||||
let mut held = held.borrow_mut();
|
||||
held.current.set(held.entries.len());
|
||||
held.entries.push(Held { ctx: ctx.clone(), state });
|
||||
});
|
||||
}
|
||||
|
||||
/// Moves the context's state back into its context data unless a pass of it still runs on this thread: the end hook.
|
||||
@@ -223,7 +254,7 @@ pub(crate) fn release(ctx: &Context) {
|
||||
}
|
||||
let held = HELD.with(|held| {
|
||||
let mut held = held.borrow_mut();
|
||||
held.iter().position(|held| held.ctx == *ctx).map(|at| held.swap_remove(at))
|
||||
held.entries.iter().position(|held| held.ctx == *ctx).map(|at| held.entries.swap_remove(at))
|
||||
});
|
||||
if let Some(held) = held {
|
||||
park(held);
|
||||
|
||||
Reference in New Issue
Block a user