fux 0.12.0

A minimal trusted Bevy terminal multiplexer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Native hierarchy normalization and viewer-local navigation memory.
#[cfg(test)]
mod tests;
use crate::{control::Scope, model::*};
use bevy_ecs::{lifecycle::HookContext, prelude::*, world::DeferredWorld};
use bevy_ui::Node;

/// Set while a layout scene is being written into the world. Writing a scene
/// inserts components one at a time, so a tab briefly has its parent before it
/// has `Tab`. Normalizing in that window wraps the scene's own tab inside a
/// fresh one, and a tab nested in a tab makes the whole workspace
/// unextractable. `apply_layout` normalizes once when the write is complete.
#[derive(Resource, Default)]
pub struct ApplyingLayout(pub u32);

/// Suspends hierarchy normalization for the duration of a scene write.
pub struct ApplyGuard;
impl ApplyGuard {
    pub fn begin(world: &mut World) -> Self {
        let mut applying = world.get_resource_or_insert_with(ApplyingLayout::default);
        applying.0 = applying.0.saturating_add(1);
        Self
    }
    pub fn end(self, world: &mut World) {
        if let Some(mut applying) = world.get_resource_mut::<ApplyingLayout>() {
            applying.0 = applying.0.saturating_sub(1);
        }
    }
}
fn applying(applying: &Option<Res<ApplyingLayout>>) -> bool {
    applying.as_ref().is_some_and(|a| a.0 > 0)
}

pub fn workspaces(world: &mut World) -> Vec<Entity> {
    let mut roots: Vec<_> = world
        .query_filtered::<Entity, With<Workspace>>()
        .iter(world)
        .collect();
    roots.sort_by_key(|e| {
        (
            world.get::<WorkspaceOrder>(*e).map_or(0, |o| o.0),
            e.to_bits(),
        )
    });
    roots
}

pub fn tabs(world: &World, workspace: Entity) -> Vec<Entity> {
    world
        .get::<Children>(workspace)
        .map(|children| {
            children
                .iter()
                .filter(|e| world.get::<Tab>(*e).is_some())
                .collect()
        })
        .unwrap_or_default()
}

pub fn leaves(world: &World, root: Entity) -> Vec<Entity> {
    let mut result = Vec::new();
    fn visit(world: &World, entity: Entity, result: &mut Vec<Entity>) {
        if world.get::<PaneView>(entity).is_some() {
            result.push(entity);
        }
        if let Some(children) = world.get::<Children>(entity) {
            for child in children.iter() {
                visit(world, child, result);
            }
        }
    }
    visit(world, root, &mut result);
    result
}

/// Wrap legacy root children without rewriting their native layout properties.
/// Also handles unrestricted ECS additions of non-tab children to a workspace.
pub fn normalize_workspace(world: &mut World, root: Entity) {
    let loose: Vec<_> = world
        .get::<Children>(root)
        .map(|children| {
            children
                .iter()
                .filter(|e| world.get::<Tab>(*e).is_none())
                .collect()
        })
        .unwrap_or_default();
    let legacy = tabs(world, root).is_empty();
    if !loose.is_empty() || legacy {
        // Move, rather than duplicate, the old root's complete layout box into
        // the first tab. A neutral workspace wrapper preserves grid tracks,
        // margins and padding exactly once.
        let node = if legacy {
            world.get::<Node>(root).cloned().unwrap_or_else(tab_node)
        } else {
            tab_node()
        };
        let tab = world
            .spawn((Tab, Name::new("main"), node, ChildOf(root)))
            .id();
        if legacy {
            world.entity_mut(root).insert(tab_node());
            if world.get::<Split>(root).is_some() {
                world.entity_mut(tab).insert(Split);
            }
        }
        world.entity_mut(tab).add_children(&loose);
    }
}

pub enum Pick {
    Entity(Entity),
    Next,
    Previous,
}

/// Opens a new tab with a fresh pane in the viewer's workspace and selects it.
pub fn tab_new(world: &mut World, id: Entity, name: Option<String>) -> Result<(), String> {
    let root = viewing(world, id).ok_or(DETACHED)?;
    let title = name.unwrap_or_else(|| format!("tab-{}", tabs(world, root).len() + 1));
    let tab = world.spawn((Tab, Name::new(title), ChildOf(root))).id();
    let settings = world.resource::<crate::assets::Settings>().clone();
    let leaf = crate::server::spawn_pane(world, &settings, tab, None, None)?;
    world
        .get_entity_mut(id)
        .map_err(|_| DETACHED)?
        .insert((OnTab(tab), Focused(leaf)));
    world.get_mut::<Viewer>(id).ok_or(DETACHED)?.zoom = false;
    Ok(())
}

/// Returns focus to the pane this viewer focused before the current one.
pub fn focus_last(world: &mut World, id: Entity) -> Result<(), String> {
    let tab = on_tab(world, id).ok_or("no active tab")?;
    let previous = world
        .get::<Memory>(id)
        .and_then(|memory| memory.previous.get(&tab).copied());
    if let Some(previous) = previous
        .filter(|e| leaves(world, tab).contains(e) && crate::frame::visible_leaf(world, id, *e))
    {
        world
            .get_entity_mut(id)
            .map_err(|_| DETACHED)?
            .insert(Focused(previous));
    }
    Ok(())
}

/// Selects a tab or workspace for this viewer, by identity or by cycling. The
/// dependent relationships are dropped; `repair` restores them from memory.
pub fn select(world: &mut World, id: Entity, scope: Scope, pick: Pick) -> Result<(), String> {
    let root = viewing(world, id).ok_or(DETACHED)?;
    let tab = on_tab(world, id).ok_or("no active tab")?;
    let (all, current) = match scope {
        Scope::Workspace => (workspaces(world), root),
        Scope::Tab => (tabs(world, root), tab),
    };
    let index = all
        .iter()
        .position(|e| *e == current)
        .ok_or("target disappeared")?;
    let selected = match pick {
        Pick::Entity(entity) => all
            .iter()
            .copied()
            .find(|e| *e == entity)
            .ok_or("selection target no longer exists")?,
        // `index` was found in `all`, so it is nonempty.
        Pick::Previous => all
            .get((index + all.len() - 1) % all.len())
            .copied()
            .ok_or("target disappeared")?,
        Pick::Next => all
            .get((index + 1) % all.len())
            .copied()
            .ok_or("target disappeared")?,
    };
    let mut entity = world.get_entity_mut(id).map_err(|_| DETACHED)?;
    match scope {
        Scope::Workspace => {
            entity
                .remove::<(OnTab, Focused)>()
                .insert(Viewing(selected));
        }
        Scope::Tab => {
            entity.remove::<Focused>().insert(OnTab(selected));
        }
    }
    world.get_mut::<Viewer>(id).ok_or(DETACHED)?.reset_view();
    Ok(())
}

/// Every workspace keeps at least one tab, whichever code path emptied it.
pub(crate) fn normalize_on_tab_removed(
    removed: On<Remove<Tab>>,
    parents: Query<&ChildOf>,
    in_progress: Option<Res<ApplyingLayout>>,
    mut commands: Commands,
) {
    if applying(&in_progress) {
        return;
    }
    if let Ok(parent) = parents.get(removed.entity) {
        let workspace = parent.parent();
        commands.queue(move |world: &mut World| {
            if world.get::<Workspace>(workspace).is_some() {
                normalize_workspace(world, workspace);
            }
        });
    }
}

/// A child placed directly under a workspace by any caller is wrapped into a tab.
pub(crate) fn normalize_on_child_added(
    added: On<Insert<ChildOf>>,
    parents: Query<&ChildOf>,
    workspaces: Query<(), With<Workspace>>,
    tabs: Query<(), With<Tab>>,
    in_progress: Option<Res<ApplyingLayout>>,
    mut commands: Commands,
) {
    let entity = added.entity;
    // A raw `ChildOf` pointing into the entity's own subtree makes the
    // hierarchy a cycle: layout extraction, cache invalidation and closes
    // then never terminate. Bevy rejects only self-parenting; reject the
    // rest here, leaving the entity unparented like a self-parented one.
    if let Ok(parent) = parents.get(entity) {
        let mut cursor = parent.parent();
        for _ in 0..u16::MAX {
            if cursor == entity {
                bevy_log::warn!(
                    "The ChildOf relationship on entity {entity} points into its own descendants. The cyclic ChildOf relationship has been removed."
                );
                commands.entity(entity).try_remove::<ChildOf>();
                return;
            }
            match parents.get(cursor) {
                Ok(next) => cursor = next.parent(),
                Err(_) => break,
            }
        }
    }
    if applying(&in_progress) {
        return;
    }
    // A tab parented under anything but a workspace by a raw edit leaves its
    // viewers looking at a tab their workspace no longer lists; repair moves
    // them, as after a despawn.
    if tabs.contains(entity)
        && parents
            .get(entity)
            .is_ok_and(|parent| !workspaces.contains(parent.parent()))
    {
        commands.queue(repair);
    }
    if let Ok(parent) = parents.get(entity)
        && workspaces.contains(parent.parent())
        && !tabs.contains(entity)
    {
        let workspace = parent.parent();
        commands.queue(move |world: &mut World| {
            if world.get::<Workspace>(workspace).is_some() {
                normalize_workspace(world, workspace);
            }
        });
    }
}

/// A tab unlinked from its workspace by a raw edit stays where it is, but
/// the viewers on it must not: they are repaired onto a listed tab.
pub(crate) fn repair_on_tab_unlinked(
    removed: On<Remove<ChildOf>>,
    tabs: Query<(), With<Tab>>,
    in_progress: Option<Res<ApplyingLayout>>,
    mut commands: Commands,
) {
    if applying(&in_progress) || !tabs.contains(removed.entity) {
        return;
    }
    commands.queue(repair);
}

/// Repair's own scheduling state. While a pass runs, every request for repair,
/// from a relationship hook or from a queued command flushed inside the pass,
/// only marks `again` instead of queueing or recursing. When the pass ends,
/// `repair` runs another if anything was marked; a pass over consistent viewers
/// changes nothing and marks nothing, so a settled world costs one quiet pass.
/// `MAX_PASSES` bounds the loop, so a viewer that can never become consistent
/// costs a warning rather than the process.
#[derive(Resource, Default)]
pub(crate) struct Repairing {
    running: bool,
    again: bool,
}

const MAX_PASSES: usize = 16;

/// Records a request made while `repair` runs. Returns whether it was absorbed.
fn absorbed(world: &mut DeferredWorld) -> bool {
    match world.get_resource_mut::<Repairing>() {
        Some(mut state) if state.running => {
            state.again = true;
            true
        }
        _ => false,
    }
}

/// Insertion or removal of a viewer relationship, by any code path, repairs
/// every viewer once the change has completed.
pub(crate) fn repair_later(mut world: DeferredWorld, _: HookContext) {
    if !absorbed(&mut world) {
        world.commands().queue(repair);
    }
}

/// A `Viewer` on a layout node makes that node look like a viewer to every
/// pass over viewers: `repair` gives it relationships whose hooks queue repair
/// again, and it never becomes consistent. Like a cyclic `ChildOf`, the state
/// is removed where it is created, whichever of the two roles arrives second.
/// The layout role wins; the node keeps its children, processes and layout,
/// and loses the viewer-only state it gained: the relationships `repair` may
/// have given it, the navigation memory and paste ownership `Viewer` requires,
/// and any presentation, prefix, overlay or selection.
pub(crate) fn reject_viewer_on_layout(
    inserted: On<Insert<(Viewer, LayoutNode)>>,
    mixed: Query<(), (With<Viewer>, LayoutRole)>,
    mut commands: Commands,
) {
    let entity = inserted.entity;
    if !mixed.contains(entity) {
        return;
    }
    bevy_log::warn!(
        "Entity {entity} is a layout node and cannot also be a viewer. The Viewer component has been removed."
    );
    commands.entity(entity).try_remove::<(
        Viewer,
        Viewing,
        OnTab,
        Focused,
        Memory,
        crate::paste::Ownership,
        crate::presentation::Presentation,
        crate::interaction::Prefix,
        crate::interaction::Overlay,
        crate::selection::Selection,
    )>();
}

/// A viewer that changes tab remembers it for the workspace it is looking at.
pub(crate) fn remember_tab(mut world: DeferredWorld, context: HookContext) {
    if let (Some(viewing), Some(tab)) = (
        viewing(&world, context.entity),
        on_tab(&world, context.entity),
    ) && let Some(mut memory) = world.get_mut::<Memory>(context.entity)
    {
        memory.tabs.insert(viewing, tab);
    }
    repair_later(world, context);
}

/// A viewer that changes focus remembers it for its tab, and keeps the pane it
/// left as the tab's previous focus for `focus_last`. Restoring a remembered
/// focus after a tab switch is not a change and records nothing.
pub(crate) fn remember_focus(mut world: DeferredWorld, context: HookContext) {
    if let (Some(tab), Some(focus)) = (
        on_tab(&world, context.entity),
        focused(&world, context.entity),
    ) && let Some(mut memory) = world.get_mut::<Memory>(context.entity)
        && let Some(old) = memory.focus.insert(tab, focus)
        && old != focus
        && std::iter::successors(world.get::<ChildOf>(old), |parent| {
            world.get::<ChildOf>(parent.parent())
        })
        .any(|parent| parent.parent() == tab)
        && let Some(mut memory) = world.get_mut::<Memory>(context.entity)
    {
        memory.previous.insert(tab, old);
    }
    repair_later(world, context);
}

/// Memory entries die with the entities they name, and viewers that relied
/// on the removed component are repaired.
pub(crate) fn forget<C: Component>(
    removed: On<Remove<C>>,
    mut viewers: Query<&mut Memory>,
    mut commands: Commands,
) {
    let gone = removed.entity;
    commands.queue(repair);
    for mut memory in &mut viewers {
        memory
            .tabs
            .retain(|key, value| *key != gone && *value != gone);
        memory
            .focus
            .retain(|key, value| *key != gone && *value != gone);
        memory
            .previous
            .retain(|key, value| *key != gone && *value != gone);
    }
}

/// Registers the observers that keep viewer relationships and memory valid.
pub(crate) fn observe(world: &mut World) {
    world.add_observer(reject_viewer_on_layout);
    world.add_observer(normalize_on_tab_removed);
    world.add_observer(normalize_on_child_added);
    world.add_observer(repair_on_tab_unlinked);
    world.add_observer(forget::<Workspace>);
    world.add_observer(forget::<Tab>);
    world.add_observer(forget::<PaneView>);
}

/// Gives every viewer a workspace, a tab in it and a pane in that, filling
/// what is missing from memory or the first available. Consistent viewers are
/// left untouched, and the insertions here queue no further repair (see
/// `Repairing`), so one pass is all any change costs.
pub fn repair(world: &mut World) {
    let mut state = world.get_resource_or_insert_with(Repairing::default);
    if state.running {
        state.again = true;
        return;
    }
    state.running = true;
    let mut passes = 0;
    loop {
        world.get_resource_or_insert_with(Repairing::default).again = false;
        repair_viewers(world);
        passes += 1;
        if !world.get_resource_or_insert_with(Repairing::default).again {
            break;
        }
        if passes == MAX_PASSES {
            bevy_log::warn!(
                "Viewer repair did not settle after {MAX_PASSES} passes; the remaining inconsistency is left for the next change."
            );
            break;
        }
    }
    let mut state = world.get_resource_or_insert_with(Repairing::default);
    state.running = false;
    state.again = false;
}

fn repair_viewers(world: &mut World) {
    let roots = workspaces(world);
    let viewers: Vec<_> = world
        .query_filtered::<Entity, IsViewer>()
        .iter(world)
        .collect();
    for id in viewers {
        let workspace = match viewing(world, id).filter(|w| roots.contains(w)) {
            Some(workspace) => workspace,
            None => {
                let Some(&root) = roots.first() else {
                    world.despawn(id);
                    continue;
                };
                world.entity_mut(id).insert(Viewing(root));
                root
            }
        };
        let mut available = tabs(world, workspace);
        if available.is_empty() {
            // The tab removal that emptied this workspace has queued its
            // replacement; do not wait for it when a viewer needs a tab now.
            normalize_workspace(world, workspace);
            available = tabs(world, workspace);
        }
        let remembered =
            |world: &World,
             key: Entity,
             which: fn(&Memory) -> &bevy_ecs::entity::EntityHashMap<Entity>| {
                world
                    .get::<Memory>(id)
                    .and_then(|m| which(m).get(&key).copied())
            };
        let tab = match on_tab(world, id).filter(|t| available.contains(t)) {
            Some(tab) => tab,
            None => {
                // normalize_workspace guarantees every workspace has a tab.
                let Some(tab) = remembered(world, workspace, |m| &m.tabs)
                    .filter(|t| available.contains(t))
                    .or_else(|| available.first().copied())
                else {
                    continue;
                };
                world.entity_mut(id).insert(OnTab(tab));
                tab
            }
        };
        let visible = leaves(world, tab);
        if focused(world, id).is_none_or(|f| !visible.contains(&f)) {
            let focus = remembered(world, tab, |m| &m.focus)
                .filter(|e| visible.contains(e))
                .or_else(|| visible.first().copied());
            let mut entity = world.entity_mut(id);
            match focus {
                Some(focus) => {
                    entity.insert(Focused(focus));
                }
                None => {
                    entity.remove::<Focused>();
                }
            }
            if let Some(mut v) = world.get_mut::<Viewer>(id) {
                v.reset_view();
            }
        }
    }
}