fux 0.7.0

Minimal persistent terminal multiplexer built on bevy_ecs
Documentation
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Helpers shared by the ordered systems: id lookups, effect/event emission, reply routing,
//! layout membership edits and explicit ownership cascades.

use super::components::{
    Creation, Pane, PaneState, Retiring, Selection, Tab, TabOf, Tabs, Viewer, Workspace,
};
use super::messages::{Effect, Requester};
use super::resources::{Clock, Ids, Limits, Registry};
use crate::ids::{PaneId, TabId, ViewerId};
use crate::layout::Rect;
use crate::proto::attach::ServerMessage;
use crate::proto::control::{self, ErrorCode, Reply, RequestId};
use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemParam;

pub fn effect(world: &mut World, effect: Effect) {
    world.resource_mut::<Messages<Effect>>().write(effect);
}

/// The step's read-only context: clock, limits and the identity registry.
#[derive(SystemParam)]
pub struct Step<'w> {
    pub clock: Res<'w, Clock>,
    pub limits: Res<'w, Limits>,
    pub ids: Res<'w, Ids>,
}

/// Deferred viewer removal for typed systems: the entity goes at the next sync point, its id is
/// released now, and the outbox is closed after the messages already queued for it.
#[derive(SystemParam)]
pub struct ViewerExit<'w, 's> {
    commands: Commands<'w, 's>,
}

impl ViewerExit<'_, '_> {
    pub fn despawn(
        &mut self,
        ids: &mut Ids,
        viewer: Entity,
        id: ViewerId,
        workspace: Entity,
        name: &str,
        effects: &mut Effects,
    ) {
        ids.viewers.remove(&id);
        self.commands.entity(viewer).despawn();
        effects.emit(Effect::CloseViewer { viewer: id });
        effects.event(
            workspace,
            name,
            control::Event::ClientDetached {
                id: 0,
                client: id.0,
            },
        );
    }
}

/// The effect outlet of a typed system: effects and control events, the latter named by the
/// workspace they concern.
#[derive(SystemParam)]
pub struct Effects<'w, 's> {
    logs: Query<'w, 's, &'static mut super::events::EventLog>,
    writer: MessageWriter<'w, Effect>,
}

impl Effects<'_, '_> {
    pub fn emit(&mut self, effect: Effect) {
        self.writer.write(effect);
    }

    /// Publishes a control event for the workspace called `workspace`.
    pub fn event(&mut self, workspace: Entity, name: &str, event: control::Event) {
        let Ok(mut log) = self.logs.get_mut(workspace) else {
            return;
        };
        let Some((entry, size)) = log.push_sized(event) else {
            return;
        };
        self.writer.write(Effect::Event {
            cursor: entry.cursor,
            workspace: name.to_owned(),
            event: entry.event,
            size,
        });
    }
}

pub fn event(world: &mut World, workspace: Entity, event: control::Event) {
    let Some(name) = world
        .get::<Workspace>(workspace)
        .map(|workspace| workspace.name.clone())
    else {
        return;
    };
    let Some((entry, size)) = world
        .get_mut::<super::events::EventLog>(workspace)
        .and_then(|mut log| log.push_sized(event))
    else {
        return;
    };
    effect(
        world,
        Effect::Event {
            cursor: entry.cursor,
            workspace: name,
            event: entry.event,
            size,
        },
    );
}

/// Routes a reply to whoever asked. Viewer replies wait for the next frame so an acknowledgement
/// never overtakes the state it promises.
pub fn reply(world: &mut World, requester: Requester, reply: Reply) {
    match requester {
        Requester::Viewer(id) => {
            if let Some(entity) = viewer_entity(world, id)
                && let Some(mut viewer) = world.get_mut::<Viewer>(entity)
            {
                if let Reply::Failed { error, .. } = &reply {
                    viewer.notice = Some(sanitize_notice(&error.message));
                }
                viewer.after_frame.push(ServerMessage::Reply { reply });
                viewer.dirty = true;
            }
        }
        Requester::Control(token) => effect(world, Effect::ControlReply { token, reply }),
        Requester::Manager(token) => {
            let outcome = match reply {
                Reply::Completed {
                    result: control::CommandResult::Workspace { name },
                    ..
                } => super::messages::ManagerOutcome::Attach {
                    stream: workspace_entity(world, &name)
                        .and_then(|entity| world.get::<super::events::EventLog>(entity))
                        .map(|log| log.cursor().stream)
                        .unwrap_or(0),
                    name,
                    created: true,
                },
                Reply::Failed { error, .. } => {
                    super::messages::ManagerOutcome::Failed(error.message)
                }
                other => super::messages::ManagerOutcome::Failed(format!(
                    "unexpected manager result {other:?}"
                )),
            };
            effect(world, Effect::Manager { token, outcome });
        }
    }
}

pub fn failed(id: RequestId, code: ErrorCode, message: impl Into<String>) -> Reply {
    Reply::failed(id, code, message)
}

/// Answers every waiting requester with the reply `make` builds for its request id.
pub fn reply_all(
    world: &mut World,
    requesters: impl IntoIterator<Item = (Requester, RequestId)>,
    make: impl Fn(RequestId) -> Reply,
) {
    for (requester, id) in requesters {
        reply(world, requester, make(id));
    }
}

pub fn sanitize_notice(message: &str) -> String {
    crate::view::printable(message, crate::view::MAX_MESSAGE_BYTES / 4)
}

pub fn viewer_entity(world: &World, id: ViewerId) -> Option<Entity> {
    world.resource::<Ids>().viewer(id)
}

pub fn pane_entity(world: &World, id: PaneId) -> Option<Entity> {
    world.resource::<Ids>().pane(id)
}

pub fn tab_entity(world: &World, id: TabId) -> Option<Entity> {
    world.resource::<Ids>().tab(id)
}

pub fn workspace_entity(world: &World, name: &str) -> Option<Entity> {
    world.resource::<Ids>().workspace(name)
}

pub fn pane_id(world: &World, pane: Entity) -> Option<PaneId> {
    world.get::<Pane>(pane).map(|pane| pane.id)
}

pub fn tab_id(world: &World, tab: Entity) -> Option<TabId> {
    world.get::<Tab>(tab).map(|tab| tab.id)
}

pub fn pane_tab(world: &World, pane: Entity) -> Option<Entity> {
    world.get::<Pane>(pane).map(|pane| pane.tab)
}

pub fn tab_workspace(world: &World, tab: Entity) -> Option<Entity> {
    world.get::<Tab>(tab).map(|tab| tab.workspace)
}

/// A workspace's member tabs in order (empty when it has none).
pub fn member_tabs(world: &World, workspace: Entity) -> Vec<Entity> {
    world
        .get::<Tabs>(workspace)
        .map(|tabs| tabs.to_vec())
        .unwrap_or_default()
}

/// Whether `tab` is a member of `workspace` (reservations are not until they complete).
pub fn is_member(world: &World, workspace: Entity, tab: Entity) -> bool {
    world
        .get::<TabOf>(tab)
        .is_some_and(|member| member.0 == workspace)
}

/// The workspace a pane belongs to, through its tab.
pub fn pane_workspace(world: &World, pane: Entity) -> Option<Entity> {
    tab_workspace(world, pane_tab(world, pane)?)
}

/// True when `pane` is a leaf of its tab's layout (visible somewhere).
pub fn pane_in_layout(world: &World, pane: Entity) -> bool {
    pane_tab(world, pane)
        .and_then(|tab| world.get::<Tab>(tab))
        .is_some_and(|tab| tab.layout.contains(pane))
}

/// Every pane reserved in this workspace lifetime, including panes whose tab already closed.
pub fn panes_in_workspace(world: &mut World, workspace: Entity) -> Vec<Entity> {
    let Some(stream) = world
        .get::<super::events::EventLog>(workspace)
        .map(|log| log.cursor().stream)
    else {
        return Vec::new();
    };
    world
        .query::<(Entity, &Pane)>()
        .iter(world)
        .filter(|(_, pane)| pane.workspace_stream == stream)
        .map(|(entity, _)| entity)
        .collect()
}

/// The viewers `keep` selects, in entity order.
pub fn viewers_where(world: &mut World, keep: impl Fn(&Viewer) -> bool) -> Vec<Entity> {
    world
        .query::<(Entity, &Viewer)>()
        .iter(world)
        .filter(|(_, viewer)| keep(viewer))
        .map(|(entity, _)| entity)
        .collect()
}

/// Applies `apply` to every viewer `keep` selects, in one pass.
pub fn each_viewer(
    world: &mut World,
    keep: impl Fn(&Viewer) -> bool,
    mut apply: impl FnMut(&mut Viewer),
) {
    for mut viewer in world.query::<&mut Viewer>().iter_mut(world) {
        if keep(&viewer) {
            apply(&mut viewer);
        }
    }
}

pub fn viewers_of_workspace(world: &mut World, workspace: Entity) -> Vec<Entity> {
    viewers_where(world, |viewer| {
        viewer.workspace == workspace && !viewer.detaching
    })
}

pub fn mark_workspace_dirty(world: &mut World, workspace: Entity) {
    event(world, workspace, control::Event::WorkspaceChanged { id: 0 });
    each_viewer(
        world,
        |viewer| viewer.workspace == workspace && !viewer.detaching,
        |viewer| viewer.dirty = true,
    );
}

pub fn mark_tab_dirty(world: &mut World, tab: Entity) {
    if let Some(workspace) = tab_workspace(world, tab) {
        event(world, workspace, control::Event::WorkspaceChanged { id: 0 });
    }
    each_viewer(
        world,
        |viewer| viewer.selection.tab == Some(tab) && !viewer.detaching,
        |viewer| viewer.dirty = true,
    );
}

/// Viewers waiting on `pane`'s creation may proceed.
pub fn clear_barriers(world: &mut World, pane: Entity) {
    each_viewer(
        world,
        |viewer| viewer.barrier == Some(pane),
        |viewer| viewer.barrier = None,
    );
}

/// Every viewer looking at `tab` whose focus is `old` now focuses `next`; the workspace default
/// follows too. Focus entries for a removed pane are dropped when there is no successor.
pub fn retarget_focus(world: &mut World, tab: Entity, old: Entity, next: Option<Entity>) {
    each_viewer(
        world,
        |viewer| viewer.selection.focus.get(&tab) == Some(&old),
        |viewer| {
            viewer.selection.retarget(tab, next);
            viewer.dirty = true;
        },
    );
    if let Some(workspace) = tab_workspace(world, tab)
        && let Some(mut workspace) = world.get_mut::<Workspace>(workspace)
        && workspace.selection.focus.get(&tab) == Some(&old)
    {
        workspace.selection.retarget(tab, next);
    }
}

/// Starts a workspace's retirement with `exit_code`; false when one is already under way.
pub fn retire(world: &mut World, workspace: Entity, now_ms: u64, exit_code: Option<u32>) -> bool {
    match world.get_mut::<Workspace>(workspace) {
        Some(mut component) if component.retiring.is_none() => {
            component.retiring = Some(Retiring {
                since_ms: now_ms,
                exit_code,
            });
            true
        }
        _ => false,
    }
}

/// Publishes `pane.closed` for `workspace`.
pub fn pane_closed(world: &mut World, workspace: Entity, pane: PaneId, code: Option<u32>) {
    let exit_status = code.map(|code| i32::try_from(code).unwrap_or(i32::MAX));
    event(
        world,
        workspace,
        control::Event::PaneClosed {
            id: 0,
            pane,
            exit_status,
        },
    );
}

/// Removes a tab entity and its id; its panes must already be gone or re-homed.
pub fn despawn_tab(world: &mut World, tab: Entity) {
    if let Some(id) = tab_id(world, tab) {
        world.resource_mut::<Ids>().tabs.remove(&id);
    }
    world.despawn(tab);
}

/// Removes a workspace entity and its name; its tabs and panes must already be gone.
pub fn despawn_workspace(world: &mut World, workspace: Entity) {
    if let Some(name) = world
        .get::<Workspace>(workspace)
        .map(|workspace| workspace.name.clone())
    {
        world.resource_mut::<Ids>().workspaces.remove(&name);
    }
    world.despawn(workspace);
}

/// The pane a selection focuses in `tab`, falling back to the tab's first leaf.
pub fn focus_in_tab(world: &World, selection: &Selection, tab: Entity) -> Option<Entity> {
    let layout = &world.get::<Tab>(tab)?.layout;
    selection
        .focus
        .get(&tab)
        .copied()
        .filter(|pane| layout.contains(*pane))
        .or_else(|| layout.leaves().first().copied())
}

/// Removes `pane` from its tab's layout and returns the pane that inherits focus.
pub fn remove_from_layout(world: &mut World, pane: Entity) -> Option<Option<Entity>> {
    let tab = pane_tab(world, pane)?;
    let next = {
        let mut tab_component = world.get_mut::<Tab>(tab)?;
        if !tab_component.layout.contains(pane) {
            return None;
        }
        let next = tab_component.layout.close(pane).ok()?;
        tab_component.layout_changed = true;
        next
    };
    retarget_focus(world, tab, pane, next);
    mark_tab_dirty(world, tab);
    Some(next)
}

/// Despawns a pane and tells the adapter to drop its handles. The tab's layout must no longer
/// reference it.
pub fn despawn_pane(world: &mut World, pane: Entity) {
    super::systems::final_records::remember(world, pane);
    let Some(id) = pane_id(world, pane) else {
        return;
    };
    world.resource_mut::<Ids>().panes.remove(&id);
    clear_barriers(world, pane);
    world.despawn(pane);
    effect(world, Effect::ReleasePane { pane: id });
}

/// Requests termination of a pane's process if it is running.
pub fn terminate_pane(world: &mut World, pane: Entity, now_ms: u64, grace_ms: u64) {
    let Some(mut component) = world.get_mut::<Pane>(pane) else {
        return;
    };
    let id = component.id;
    match component.state {
        PaneState::Live { pid } | PaneState::Eof { pid } => {
            component.state = PaneState::Terminating {
                pid,
                since_ms: now_ms,
            };
            effect(world, Effect::Terminate { pane: id, grace_ms });
        }
        PaneState::Starting => {
            // The spawn has not been reported; the completion step rolls it back.
        }
        PaneState::Terminating { .. } | PaneState::Exited { .. } => {}
    }
}

/// Moves viewers showing `tab` to a neighbouring tab and removes the tab from its workspace.
/// Panes still in the layout are terminated (their exit reports finish the cleanup).
pub fn close_tab(world: &mut World, tab: Entity, now_ms: u64, grace_ms: u64) {
    let Some((workspace, id)) = world
        .get::<Tab>(tab)
        .map(|component| (component.workspace, component.id))
    else {
        return;
    };
    if world.get::<Workspace>(workspace).is_none() {
        return;
    }
    let (index, neighbour) = {
        let members = member_tabs(world, workspace);
        let index = members.iter().position(|entry| *entry == tab);
        let neighbour = index.and_then(|index| {
            members
                .get(index.wrapping_sub(1))
                .or_else(|| members.get(index + 1))
                .copied()
        });
        (index, neighbour)
    };
    let panes: Vec<Entity> = world
        .get::<Tab>(tab)
        .map(|component| component.layout.leaves())
        .unwrap_or_default();
    for pane in &panes {
        if let Some(mut component) = world.get_mut::<Tab>(tab) {
            let _ = component.layout.close(*pane);
        }
        terminate_pane(world, *pane, now_ms, grace_ms);
    }
    if index.is_some() {
        world.entity_mut(tab).remove::<TabOf>();
    }
    let first = member_tabs(world, workspace).first().copied();
    if let Some(mut component) = world.get_mut::<Workspace>(workspace) {
        component.selection.forget_tab(tab);
        if component.selection.tab.is_none() {
            component.selection.tab = neighbour.or(first);
        }
    }
    each_viewer(
        world,
        |viewer| viewer.workspace == workspace,
        |viewer| {
            let was_showing = viewer.selection.tab == Some(tab);
            viewer.selection.forget_tab(tab);
            if was_showing {
                viewer.selection.tab = neighbour;
            }
            viewer.dirty = true;
        },
    );
    for pane in panes {
        // Panes that already exited leave immediately; running ones wait for their exit report
        // and are despawned by the lifecycle system when it arrives.
        if world
            .get::<Pane>(pane)
            .is_some_and(|component| matches!(component.state, PaneState::Exited { .. }))
        {
            despawn_pane(world, pane);
        }
    }
    let pending: Vec<Entity> = world
        .query_filtered::<(Entity, &Pane), With<Creation>>()
        .iter(world)
        .filter(|(_, pane)| pane.tab == tab)
        .map(|(entity, _)| entity)
        .collect();
    fail_creations(world, &pending, "tab closed before the pane started", true);
    despawn_tab(world, tab);
    if index.is_some() {
        event(
            world,
            workspace,
            control::Event::TabClosed { id: 0, tab: id },
        );
    }
    mark_workspace_dirty(world, workspace);
}

/// Releases the reservations among `panes` that are still starting: their requesters get a
/// failure now and a late spawn report is stopped by the completion phase (with `despawn`, the
/// pane id is no longer registered; otherwise the caller despawns the panes itself).
pub fn fail_creations(world: &mut World, panes: &[Entity], reason: &str, despawn: bool) {
    for &entity in panes {
        let Some(creation) = world.entity_mut(entity).take::<Creation>() else {
            continue;
        };
        clear_barriers(world, entity);
        reply_all(world, creation.requesters, |id| {
            failed(id, control::ErrorCode::Conflict, reason)
        });
        if despawn {
            despawn_pane(world, entity);
        }
    }
}

/// Bounded pane input: chunks the bytes into attachment-sized writes.
pub fn write_pane(world: &mut World, pane: Entity, bytes: &[u8]) -> bool {
    let Some(mut component) = world.get_mut::<Pane>(pane) else {
        return false;
    };
    if !component.state.accepts_input() {
        return false;
    }
    if !bytes.is_empty() {
        let Some(sequence) = component.input_sequence.checked_add(1) else {
            return false;
        };
        component.input_sequence = sequence;
    }
    let id = component.id;
    if !bytes.is_empty()
        && let Some(workspace) = pane_workspace(world, pane)
    {
        event(world, workspace, control::Event::WorkspaceChanged { id: 0 });
    }
    for chunk in bytes.chunks(crate::proto::attach::MAX_INPUT_CHUNK) {
        effect(
            world,
            Effect::WriteInput {
                pane: id,
                bytes: chunk.to_vec(),
            },
        );
    }
    true
}

pub fn default_command(world: &World) -> Vec<String> {
    world.resource::<Registry>().default_command.clone()
}

/// Body area available to a tab for a viewer of the given size.
/// The pane area of a viewer: everything above the always-present one-row bar, which is the last
/// row.
pub fn tab_area(rows: u16, cols: u16) -> Rect {
    Rect {
        x: 0,
        y: 0,
        width: cols,
        height: rows.saturating_sub(1),
    }
}