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
//! One source of identity, labels, groups, and availability for every action.
use crate::{
    control::{Axis, Chooser, Command, Order, Scope, Subject},
    interaction::MoveTo,
    model::*,
    navigation,
    protocol::Direction,
};
use bevy_ecs::prelude::*;
use bevy_reflect::Reflect;
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Reflect)]
pub struct Target {
    pub workspace: Entity,
    pub tab: Option<Entity>,
    pub leaf: Option<Entity>,
}
impl Target {
    /// The viewer's current relationships; a detached viewer has no target.
    pub fn of(world: &World, id: Entity) -> Option<Self> {
        Some(Self {
            workspace: viewing(world, id)?,
            tab: on_tab(world, id),
            leaf: focused(world, id),
        })
    }
    pub(crate) fn multiple_tabs(self, world: &World) -> Result<(), &'static str> {
        (navigation::tabs(world, self.workspace).len() >= 2)
            .then_some(())
            .ok_or("only one tab")
    }
    pub(crate) fn multiple_panes(self, world: &World) -> Result<(), &'static str> {
        self.tab
            .is_some_and(|tab| navigation::leaves(world, tab).len() >= 2)
            .then_some(())
            .ok_or("only one pane")
    }
    pub fn valid(self, world: &World) -> bool {
        world.get::<Workspace>(self.workspace).is_some()
            && self
                .tab
                .is_none_or(|tab| navigation::tabs(world, self.workspace).contains(&tab))
            && self.leaf.is_none_or(|leaf| {
                self.tab
                    .is_some_and(|tab| navigation::leaves(world, tab).contains(&leaf))
            })
    }
}

macro_rules! actions {
    (
        $($group:literal: [$($variant:ident $id:literal => $label:literal),* $(,)?]),* $(,)?
    ) => {
        /// The wire form is the snake_case identifier, unchanged from the string API.
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
        #[serde(rename_all = "snake_case")]
        pub enum Action {
            $($($variant,)*)*
        }
        /// Bindable actions in help/menu order.
        pub const ALL: &[Action] = &[$($(Action::$variant,)*)*];
        impl Action {
            /// The identifier used in configuration.
            pub const fn id(self) -> &'static str {
                match self {
                    $($(Self::$variant => $id,)*)*
                }
            }
            pub fn group(self) -> &'static str {
                match self {
                    $($(Self::$variant => $group,)*)*
                }
            }
            pub fn label(self) -> &'static str {
                match self {
                    $($(Self::$variant => $label,)*)*
                }
            }
        }
    }
}
actions! {
    "Panes": [
        SplitHorizontal "split_horizontal" => "split side by side", SplitVertical "split_vertical" => "split stacked",
        PaneMenu "pane_menu" => "pane actions", RenamePane "rename_pane" => "rename pane", Close "close" => "close pane",
        Terminate "terminate" => "terminate process", Zoom "zoom" => "zoom or restore",
        GrowWidth "grow_width" => "grow width", ShrinkWidth "shrink_width" => "shrink width",
        GrowHeight "grow_height" => "grow height", ShrinkHeight "shrink_height" => "shrink height",
        ReorderPrev "reorder_prev" => "reorder previous", ReorderNext "reorder_next" => "reorder next",
        SwapChoose "swap_choose" => "swap with pane", SwapLeft "swap_left" => "swap left", SwapRight "swap_right" => "swap right",
        SwapUp "swap_up" => "swap up", SwapDown "swap_down" => "swap down",
        MoveLeft "move_left" => "move left", MoveRight "move_right" => "move right", MoveUp "move_up" => "move up", MoveDown "move_down" => "move down",
        MoveTab "move_tab" => "move to tab", MoveNewTab "move_new_tab" => "move to new tab",
        MoveWorkspace "move_workspace" => "move to workspace", MoveNewWorkspace "move_new_workspace" => "move to new workspace",
        CopyMode "copy_mode" => "history and selection", ScrollUp "scroll_up" => "scroll older output",
        ScrollDown "scroll_down" => "scroll newer output", Copy "copy" => "copy visible text"
    ],
    "Focus": [FocusNext "focus_next" => "next pane", FocusPrevious "focus_previous" => "previous pane", FocusLast "focus_last" => "last pane",
        FocusLeft "focus_left" => "focus left", FocusRight "focus_right" => "focus right", FocusUp "focus_up" => "focus up", FocusDown "focus_down" => "focus down"],
    "Tabs": [TabNew "tab_new" => "new tab", TabNext "tab_next" => "next tab", TabPrevious "tab_previous" => "previous tab",
        TabChoose "tab_choose" => "choose tab", RenameTab "rename_tab" => "rename tab", TabClose "tab_close" => "close tab",
        TabMenu "tab_menu" => "tab actions", TabReorderPrevious "tab_reorder_previous" => "reorder tab previous", TabReorderNext "tab_reorder_next" => "reorder tab next"],
    "Workspaces": [WorkspaceNew "workspace_new" => "new workspace", WorkspaceNext "workspace_next" => "next workspace",
        WorkspacePrevious "workspace_previous" => "previous workspace", WorkspaceChoose "workspace_choose" => "choose workspace",
        RenameWorkspace "rename_workspace" => "rename workspace", WorkspaceClose "workspace_close" => "close workspace", WorkspaceMenu "workspace_menu" => "workspace actions",
        WorkspaceReorderPrevious "workspace_reorder_previous" => "reorder workspace previous", WorkspaceReorderNext "workspace_reorder_next" => "reorder workspace next"],
    "Session": [SaveLayout "save_layout" => "save layout", LoadLayout "load_layout" => "load layout", Help "help" => "command help", Detach "detach" => "detach"]
}

impl std::fmt::Display for Action {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.id())
    }
}

impl Action {
    /// Pane and focus actions act on a pane, except splits, which can seed an empty tab.
    pub fn needs_pane(self) -> bool {
        matches!(self.group(), "Panes" | "Focus")
            && !matches!(self, Self::SplitHorizontal | Self::SplitVertical)
    }
    /// The command a bound action means for this viewer state, or `None` for
    /// actions that first need a prompt or a confirmation.
    pub fn command(self, target: Target) -> Option<Command> {
        use Action::*;
        let pane = target.leaf.map(Subject::Pane);
        let tab = target.tab.map(Subject::Tab);
        let workspace = Subject::Workspace(target.workspace);
        let scope = match self {
            TabNext | TabPrevious | TabReorderPrevious | TabReorderNext => Scope::Tab,
            _ => Scope::Workspace,
        };
        Some(match self {
            SplitHorizontal => Command::Split {
                axis: Axis::Horizontal,
                program: None,
            },
            SplitVertical => Command::Split {
                axis: Axis::Vertical,
                program: None,
            },
            PaneMenu => Command::Menu { subject: pane? },
            TabMenu => Command::Menu { subject: tab? },
            WorkspaceMenu => Command::Menu { subject: workspace },
            Close => Command::Close { subject: pane? },
            TabClose => Command::Close { subject: tab? },
            WorkspaceClose => Command::Close { subject: workspace },
            Terminate => Command::Terminate,
            Zoom => Command::Zoom,
            GrowWidth | ShrinkWidth => Command::Resize {
                axis: Axis::Horizontal,
                grow: self == GrowWidth,
            },
            GrowHeight | ShrinkHeight => Command::Resize {
                axis: Axis::Vertical,
                grow: self == GrowHeight,
            },
            ReorderPrev => Command::ReorderPane {
                order: Order::Previous,
            },
            ReorderNext => Command::ReorderPane { order: Order::Next },
            SwapChoose => Command::Choose {
                chooser: Chooser::SwapTarget,
            },
            SwapLeft | SwapRight | SwapUp | SwapDown => Command::SwapDirection {
                direction: self.direction()?,
            },
            MoveLeft | MoveRight | MoveUp | MoveDown => Command::MoveDirection {
                direction: self.direction()?,
            },
            MoveTab => Command::Choose {
                chooser: Chooser::MoveToTab,
            },
            MoveNewTab => Command::Move {
                to: MoveTo::NewTab { name: None },
            },
            MoveWorkspace => Command::Choose {
                chooser: Chooser::MoveToWorkspace,
            },
            MoveNewWorkspace => Command::Move {
                to: MoveTo::NewWorkspace { name: None },
            },
            CopyMode => Command::CopyMode,
            ScrollUp => Command::Scroll {
                order: Order::Previous,
            },
            ScrollDown => Command::Scroll { order: Order::Next },
            Copy => Command::Copy,
            FocusNext => Command::FocusNext,
            FocusPrevious => Command::FocusPrevious,
            FocusLast => Command::FocusLast,
            FocusLeft | FocusRight | FocusUp | FocusDown => Command::FocusDirection {
                direction: self.direction()?,
            },
            TabNew => Command::TabNew { name: None },
            TabNext | WorkspaceNext => Command::Next { scope },
            TabPrevious | WorkspacePrevious => Command::Previous { scope },
            TabChoose => Command::Choose {
                chooser: Chooser::Tab,
            },
            TabReorderPrevious | WorkspaceReorderPrevious => Command::Reorder {
                scope,
                order: Order::Previous,
            },
            TabReorderNext | WorkspaceReorderNext => Command::Reorder {
                scope,
                order: Order::Next,
            },
            WorkspaceNew => Command::WorkspaceNew { name: None },
            WorkspaceChoose => Command::Choose {
                chooser: Chooser::Workspace,
            },
            Help => Command::Help,
            Detach => Command::Detach,
            RenamePane | RenameTab | RenameWorkspace | SaveLayout | LoadLayout => return None,
        })
    }
    /// The command a text prompt for this action produces once `value` is typed.
    pub fn with_text(self, target: Target, value: String) -> Option<Command> {
        use Action::*;
        Some(match self {
            RenamePane => Command::Rename {
                subject: Subject::Pane(target.leaf?),
                name: value,
            },
            RenameTab => Command::Rename {
                subject: Subject::Tab(target.tab?),
                name: value,
            },
            RenameWorkspace => Command::Rename {
                subject: Subject::Workspace(target.workspace),
                name: value,
            },
            SaveLayout => Command::SaveLayout {
                workspace: target.workspace,
                path: value,
            },
            LoadLayout => Command::LoadLayout {
                workspace: target.workspace,
                path: value,
                mapping: Vec::new(),
            },
            _ => return None,
        })
    }
    /// The direction of a directional focus, swap or move action.
    pub fn direction(self) -> Option<Direction> {
        use Action::*;
        match self {
            FocusLeft | SwapLeft | MoveLeft => Some(Direction::Left),
            FocusRight | SwapRight | MoveRight => Some(Direction::Right),
            FocusUp | SwapUp | MoveUp => Some(Direction::Up),
            FocusDown | SwapDown | MoveDown => Some(Direction::Down),
            _ => None,
        }
    }
}

pub const TARGET_GONE: &str = "target no longer exists here";

pub fn unavailable(world: &World, target: Target, action: Action) -> Option<&'static str> {
    use Action::*;
    if !target.valid(world) {
        return Some(TARGET_GONE);
    }
    if action == Copy
        && let Some(reason) = world
            .get_resource::<crate::assets::Settings>()
            .and_then(|s| crate::selection::validate_clipboard(s, "").err())
    {
        return Some(reason);
    }
    if action.needs_pane() && target.leaf.is_none() {
        return Some("no pane");
    }
    if action.group() == "Tabs" && target.tab.is_none() {
        return Some("no tab");
    }
    if matches!(
        action,
        TabNext | TabPrevious | TabReorderPrevious | TabReorderNext
    ) {
        return target.multiple_tabs(world).err();
    }
    if matches!(
        action,
        SwapChoose
            | SwapLeft
            | SwapRight
            | SwapUp
            | SwapDown
            | MoveLeft
            | MoveRight
            | MoveUp
            | MoveDown
            | FocusNext
            | FocusPrevious
            | FocusLast
            | ReorderPrev
            | ReorderNext
    ) {
        return target.multiple_panes(world).err();
    }
    if action == Terminate
        && target
            .leaf
            .and_then(|leaf| world.get::<PaneView>(leaf))
            .is_none_or(|view| world.get::<crate::terminal::Terminal>(view.pane).is_none())
    {
        return Some("process is not running");
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn availability_matrix_preserves_captured_targets_and_error_order() -> crate::testing::Outcome {
        use crate::assets::{ClipboardPolicy, Settings};
        use Action::*;
        let mut world = World::new();
        world.insert_resource(Settings::default());
        let root = world.spawn(Workspace).id();
        let tab = world.spawn((Tab, ChildOf(root))).id();
        let process = world.spawn_empty().id();
        let pane = world.spawn((PaneView { pane: process }, ChildOf(tab))).id();
        let target = Target {
            workspace: root,
            tab: Some(tab),
            leaf: Some(pane),
        };
        let pane_peers = [
            SwapChoose,
            SwapLeft,
            SwapRight,
            SwapUp,
            SwapDown,
            MoveLeft,
            MoveRight,
            MoveUp,
            MoveDown,
            FocusNext,
            FocusPrevious,
            FocusLast,
            ReorderPrev,
            ReorderNext,
        ];
        let tab_peers = [TabNext, TabPrevious, TabReorderPrevious, TabReorderNext];
        for action in ALL.iter().copied() {
            let expected = if action == Copy {
                Some("clipboard disabled; configure clipboard: write-only")
            } else if pane_peers.contains(&action) {
                Some("only one pane")
            } else if tab_peers.contains(&action) {
                Some("only one tab")
            } else if action == Terminate {
                Some("process is not running")
            } else {
                None
            };
            assert_eq!(unavailable(&world, target, action), expected, "{action}");
            let empty = Target {
                leaf: None,
                ..target
            };
            let expected_empty = if action == Copy {
                expected
            } else if matches!(action.group(), "Panes" | "Focus")
                && !matches!(action, SplitHorizontal | SplitVertical)
            {
                Some("no pane")
            } else {
                expected
            };
            assert_eq!(
                unavailable(&world, empty, action),
                expected_empty,
                "{action}"
            );
        }
        // Extra tabs/panes in another workspace cannot enable this captured menu.
        let other = world.spawn(Workspace).id();
        world.spawn((Tab, ChildOf(other)));
        assert_eq!(target.multiple_tabs(&world), Err("only one tab"));
        world.spawn((Tab, ChildOf(root)));
        world.spawn((PaneView { pane: process }, ChildOf(tab)));
        assert!(target.multiple_tabs(&world).is_ok());
        assert!(target.multiple_panes(&world).is_ok());
        world.resource_mut::<Settings>().clipboard = ClipboardPolicy::WriteOnly;
        for action in ALL.iter().copied() {
            let expected = (action == Terminate).then_some("process is not running");
            assert_eq!(unavailable(&world, target, action), expected, "{action}");
        }
        world.remove_resource::<Settings>();
        assert_eq!(unavailable(&world, target, Copy), None);
        world.despawn(root);
        for action in ALL.iter().copied() {
            assert_eq!(unavailable(&world, target, action), Some(TARGET_GONE));
        }
        Ok(())
    }

    #[test]
    fn wire_names_round_trip_and_unknown_names_are_rejected() -> crate::testing::Outcome {
        for action in ALL.iter().copied() {
            let id = action.to_string();
            assert!(id.chars().all(|c| c.is_ascii_lowercase() || c == '_'));
            // The literal in the table and the serde name must never drift.
            let wire = serde_json::Value::String(id);
            assert_eq!(serde_json::to_value(action)?, wire);
            assert_eq!(serde_json::from_value::<Action>(wire)?, action);
        }
        assert_eq!(ALL.len(), 59);
        assert_eq!(Action::SplitHorizontal.to_string(), "split_horizontal");
        assert_eq!(Action::ReorderPrev.to_string(), "reorder_prev");
        assert!(
            serde_json::from_value::<Action>(serde_json::Value::String("nope".into())).is_err()
        );
        assert!(Action::FocusLeft.needs_pane());
        assert!(!Action::SplitVertical.needs_pane());
        assert_eq!(Action::MoveDown.direction(), Some(Direction::Down));
        Ok(())
    }
}