bmux_cli 0.0.1-alpha.1

Command-line interface for bmux 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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use crate::input::RuntimeAction;
use crate::status::AttachStatusLine;
use bmux_attach_layout_protocol::{
    AttachInputModeState, AttachMouseProtocolState, AttachScene, AttachSurface,
};
pub use bmux_attach_pipeline::{
    AttachCursorState, AttachScrollbackCursor, AttachScrollbackPosition, PaneRect, PaneRenderBuffer,
};
use bmux_attach_pipeline::{FrameDamage, RetainedCompositor, TerminalGraphicsCache};
use bmux_client::AttachLayoutState;
use bmux_config::{MouseBehaviorConfig, StatusPosition};
use bmux_control_catalog_plugin_api::control_catalog_state::{
    ContextRow, ContextSessionBinding, SessionRow,
};
use bmux_plugin::{AttachInputHook, AttachVisualProjectionUpdate};
use bmux_windows_plugin_api::windows_commands::PaneResizeDirection;
use bmux_windows_plugin_api::windows_list::WindowListSnapshot;
use crossterm::event::MouseEvent;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use uuid::Uuid;

use super::prompt_ui::AttachPromptState;

pub enum AttachEventAction {
    Send(Vec<u8>),
    PluginCommand {
        plugin_id: String,
        command_name: String,
        args: Vec<String>,
    },
    Mouse(MouseEvent),
    Ui(RuntimeAction),
    Redraw,
    Detach,
    Ignore,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachUiMode {
    Normal,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachExitReason {
    Detached,
    StreamClosed,
    Quit,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachDirtySource {
    PaneOutput,
    LayoutChanged,
    FocusChanged,
    SceneChanged,
    StatusChanged,
    PromptOverlay,
    HelpOverlay,
    AppearanceChanged,
    ManualRedraw,
    SnapshotHydration,
    AlternateScreenTransition,
    PluginCommand,
    UserAction,
    ActionDispatch,
    Mouse,
    Scrollback,
    Selection,
    ProfileChanged,
    ControlCatalogChanged,
    PaneLifecycle,
    FollowTargetChanged,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachDirtyKind {
    Pane,
    Status,
    Overlay,
    FullFrame,
    Extension,
    PreciseDamage,
    LayoutRefresh,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AttachDirtyEvent {
    pub source: AttachDirtySource,
    pub kind: AttachDirtyKind,
    pub pane_id: Option<Uuid>,
}

#[allow(clippy::struct_excessive_bools)] // Dirty flags are independent repaint/fetch toggles.
#[derive(Debug, Clone)]
pub struct AttachDirtyFlags {
    pub status_needs_redraw: bool,
    pub layout_needs_refresh: bool,
    pub overlay_needs_redraw: bool,
    pub pane_dirty_ids: BTreeSet<Uuid>,
    pub full_pane_redraw: bool,
    /// Generic surface/plugin-render damage. This asks render
    /// extensions to repaint their damaged regions without invalidating
    /// pane content row caches.
    pub extension_needs_redraw: bool,
    /// Precise frame damage computed by scene/layout reconciliation.
    pub precise_frame_damage: FrameDamage,
    /// Low-cardinality reasons that accumulated before the next rendered frame.
    pub dirty_events: Vec<AttachDirtyEvent>,
}

impl Default for AttachDirtyFlags {
    fn default() -> Self {
        Self {
            status_needs_redraw: true,
            layout_needs_refresh: true,
            overlay_needs_redraw: false,
            pane_dirty_ids: BTreeSet::new(),
            full_pane_redraw: true,
            extension_needs_redraw: true,
            precise_frame_damage: FrameDamage::default(),
            dirty_events: Vec::new(),
        }
    }
}

impl AttachDirtyFlags {
    fn push_event(
        &mut self,
        source: AttachDirtySource,
        kind: AttachDirtyKind,
        pane_id: Option<Uuid>,
    ) {
        self.dirty_events.push(AttachDirtyEvent {
            source,
            kind,
            pane_id,
        });
    }

    pub fn mark_pane_dirty(&mut self, pane_id: Uuid, source: AttachDirtySource) {
        self.pane_dirty_ids.insert(pane_id);
        self.push_event(source, AttachDirtyKind::Pane, Some(pane_id));
    }

    pub fn mark_status_dirty(&mut self, source: AttachDirtySource) {
        self.status_needs_redraw = true;
        self.push_event(source, AttachDirtyKind::Status, None);
    }

    pub fn mark_overlay_dirty(&mut self, source: AttachDirtySource) {
        self.overlay_needs_redraw = true;
        self.push_event(source, AttachDirtyKind::Overlay, None);
    }

    pub fn mark_full_frame(&mut self, source: AttachDirtySource) {
        self.full_pane_redraw = true;
        self.push_event(source, AttachDirtyKind::FullFrame, None);
    }

    pub fn mark_extension_dirty(&mut self, source: AttachDirtySource) {
        self.extension_needs_redraw = true;
        self.push_event(source, AttachDirtyKind::Extension, None);
    }

    pub fn mark_surface_changed(&mut self, surface_id: Uuid, source: AttachDirtySource) {
        self.precise_frame_damage
            .mark_extension_surface_query(surface_id);
        self.push_event(source, AttachDirtyKind::PreciseDamage, None);
    }

    pub fn mark_layout_refresh(&mut self, source: AttachDirtySource) {
        self.layout_needs_refresh = true;
        self.push_event(source, AttachDirtyKind::LayoutRefresh, None);
    }

    pub fn mark_layout_frame_dirty(&mut self, source: AttachDirtySource) {
        self.mark_layout_refresh(source);
        self.mark_full_frame(source);
    }

    pub fn mark_layout_frame_and_status_dirty(&mut self, source: AttachDirtySource) {
        self.mark_layout_frame_dirty(source);
        self.mark_status_dirty(source);
    }

    pub fn mark_layout_refresh_and_status_dirty(&mut self, source: AttachDirtySource) {
        self.mark_layout_refresh(source);
        self.mark_status_dirty(source);
    }

    pub fn merge_precise_damage(&mut self, damage: &FrameDamage, source: AttachDirtySource) {
        if damage.is_empty() {
            return;
        }
        self.precise_frame_damage.merge_from(damage);
        self.push_event(source, AttachDirtyKind::PreciseDamage, None);
    }

    #[must_use]
    pub fn dirty_events(&self) -> &[AttachDirtyEvent] {
        &self.dirty_events
    }

    #[must_use]
    pub fn frame_damage(&self, scene: &AttachScene) -> FrameDamage {
        let mut damage = if self.full_pane_redraw {
            FrameDamage::full_frame()
        } else {
            FrameDamage::default()
        };
        damage.merge_from(&self.precise_frame_damage);
        for pane_id in &self.pane_dirty_ids {
            damage.mark_content_surface(*pane_id);
        }
        if self.extension_needs_redraw {
            let _ = scene;
            damage.mark_extension_query();
        }
        if self.status_needs_redraw {
            damage.mark_status();
        }
        if self.overlay_needs_redraw {
            damage.mark_overlay();
        }
        damage
    }

    #[must_use]
    pub fn needs_render(&self) -> bool {
        self.status_needs_redraw
            || self.full_pane_redraw
            || self.extension_needs_redraw
            || self.overlay_needs_redraw
            || !self.precise_frame_damage.is_empty()
            || !self.pane_dirty_ids.is_empty()
    }

    pub fn clear_frame_damage(&mut self) {
        self.full_pane_redraw = false;
        self.extension_needs_redraw = false;
        self.overlay_needs_redraw = false;
        self.precise_frame_damage = FrameDamage::default();
        self.pane_dirty_ids.clear();
        self.dirty_events.clear();
    }
}

#[allow(clippy::struct_excessive_bools)]
pub struct AttachViewState {
    pub self_client_id: Option<Uuid>,
    pub attached_id: Uuid,
    pub attached_context_id: Option<Uuid>,
    pub can_write: bool,
    pub ui_mode: AttachUiMode,
    pub active_mode_id: String,
    pub active_mode_label: String,
    pub scrollback_active: bool,
    pub scrollback_offset: usize,
    pub scrollback_cursor: Option<AttachScrollbackCursor>,
    pub selection_anchor: Option<AttachScrollbackPosition>,
    pub help_overlay_open: bool,
    pub help_overlay_scroll: usize,
    pub prompt: AttachPromptState,
    pub transient_status: Option<String>,
    pub transient_status_until: Option<Instant>,
    pub control_catalog_revision: u64,
    /// Latest ordered window list received from the windows-plugin
    /// `windows-list` state channel. `None` until the first snapshot
    /// arrives (or when the plugin is absent, in which case the tab
    /// bar falls back to rendering `cached_contexts` in raw server
    /// order). Updated by the attach loop whenever the plugin
    /// publishes a new value via `publish_window_list_snapshot`.
    pub cached_window_list: Option<Arc<WindowListSnapshot>>,
    pub cached_contexts: Vec<ContextRow>,
    pub cached_sessions: Vec<SessionRow>,
    pub cached_context_session_bindings: Vec<ContextSessionBinding>,
    pub pane_buffers: BTreeMap<Uuid, PaneRenderBuffer>,
    pub terminal_graphics_cache: TerminalGraphicsCache,
    pub pane_mouse_protocol_hints: BTreeMap<Uuid, AttachMouseProtocolState>,
    pub pane_input_mode_hints: BTreeMap<Uuid, AttachInputModeState>,
    pub status_position: StatusPosition,
    pub cached_status_line: Option<AttachStatusLine>,
    pub cached_layout_state: Option<AttachLayoutState>,
    pub retained_compositor: RetainedCompositor,
    pub last_help_overlay_surface: Option<AttachSurface>,
    pub last_prompt_overlay_surface: Option<AttachSurface>,
    pub last_cursor_state: Option<AttachCursorState>,
    pub force_cursor_move_next_frame: bool,
    pub mouse: AttachMouseState,
    pub visual_projection_updates: Vec<AttachVisualProjectionUpdate>,
    pub dirty: AttachDirtyFlags,

    // -- Image protocol support (feature-gated) --
    /// Per-pane image cache received from the server.
    #[cfg(any(
        feature = "image-sixel",
        feature = "image-kitty",
        feature = "image-iterm2"
    ))]
    pub pane_images: BTreeMap<Uuid, Vec<bmux_attach_image_protocol::AttachPaneImage>>,
    /// Per-pane last-seen image sequence numbers for delta queries.
    #[cfg(any(
        feature = "image-sixel",
        feature = "image-kitty",
        feature = "image-iterm2"
    ))]
    pub image_sequences: BTreeMap<Uuid, u64>,
    /// Detected host terminal image capabilities.
    #[cfg(any(
        feature = "image-sixel",
        feature = "image-kitty",
        feature = "image-iterm2"
    ))]
    pub host_image_caps: bmux_image::HostImageCapabilities,
    #[cfg(any(
        feature = "image-sixel",
        feature = "image-kitty",
        feature = "image-iterm2"
    ))]
    pub kitty_host_state: bmux_image::compositor::KittyHostState,
    /// Cached image decode mode from config (read once at attach time).
    #[cfg(any(
        feature = "image-sixel",
        feature = "image-kitty",
        feature = "image-iterm2"
    ))]
    pub image_decode_mode: bmux_image::config::ImageDecodeMode,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct AttachMouseState {
    pub config: MouseBehaviorConfig,
    pub tab_drag_enabled: bool,
    pub last_position: Option<(u16, u16)>,
    pub last_event_at: Option<Instant>,
    pub hover_started_at: Option<Instant>,
    pub hovered_pane_id: Option<Uuid>,
    pub last_focused_pane_id: Option<Uuid>,
    pub resize_drag: Option<AttachMouseResizeDrag>,
    pub floating_drag: Option<AttachMouseFloatingDrag>,
    pub selection_drag: Option<AttachMouseSelectionDrag>,
    pub tab_drag: Option<AttachMouseTabDrag>,
    pub input_capture: Option<AttachInputHookCapture>,
    pub input_hook_last_dispatched_at: BTreeMap<String, Instant>,
}

impl Default for AttachMouseState {
    fn default() -> Self {
        Self {
            config: MouseBehaviorConfig::default(),
            tab_drag_enabled: true,
            last_position: None,
            last_event_at: None,
            hover_started_at: None,
            hovered_pane_id: None,
            last_focused_pane_id: None,
            resize_drag: None,
            floating_drag: None,
            selection_drag: None,
            tab_drag: None,
            input_capture: None,
            input_hook_last_dispatched_at: BTreeMap::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachInputHookCapture {
    pub hook: AttachInputHook,
    pub pointer: bool,
    pub keyboard_keys: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachMouseTabDrag {
    pub source_context_id: Uuid,
    pub started_col: u16,
    pub started_row: u16,
    pub active: bool,
    pub drop_target: Option<AttachTabDropTarget>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachTabDropTarget {
    pub context_id: Uuid,
    pub placement: AttachTabDropPlacement,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachTabDropPlacement {
    Before,
    After,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachUiReduction {
    pub consumed: bool,
    pub effects: Vec<AttachUiEffect>,
}

impl AttachUiReduction {
    pub const fn ignored() -> Self {
        Self {
            consumed: false,
            effects: Vec::new(),
        }
    }

    pub const fn consumed() -> Self {
        Self {
            consumed: true,
            effects: Vec::new(),
        }
    }

    pub fn with_effect(effect: AttachUiEffect) -> Self {
        Self {
            consumed: true,
            effects: vec![effect],
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttachUiEffect {
    SwitchWindow {
        target_context_id: Uuid,
    },
    MoveWindow {
        source_context_id: Uuid,
        target_context_id: Uuid,
        placement: AttachTabDropPlacement,
    },
    ResizePane {
        pane_id: Uuid,
        direction: PaneResizeDirection,
        cells: u16,
    },
    FocusPane {
        pane_id: Uuid,
    },
    MoveFloatingPane {
        pane_id: Uuid,
        x: u16,
        y: u16,
    },
    ShowTransientStatus {
        message: String,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachMouseFloatingDrag {
    pub pane_id: Uuid,
    pub start_x: u16,
    pub start_y: u16,
    pub width: u16,
    pub height: u16,
    pub scene_max_x: u16,
    pub scene_max_y: u16,
    pub last_x: u16,
    pub last_y: u16,
    pub start_column: u16,
    pub start_row: u16,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachMouseSelectionDrag {
    pub pane_id: Uuid,
    pub anchor: AttachScrollbackPosition,
    pub active: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachMouseResizeDrag {
    pub horizontal: Option<AttachMouseResizeAxisDrag>,
    pub vertical: Option<AttachMouseResizeAxisDrag>,
    pub last_column: u16,
    pub last_row: u16,
    pub latest_column: u16,
    pub latest_row: u16,
    pub last_applied_at: Instant,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachMouseResizeAxisDrag {
    pub positive_target_pane_id: Uuid,
    pub positive_direction: PaneResizeDirection,
    pub negative_target_pane_id: Uuid,
    pub negative_direction: PaneResizeDirection,
}

impl AttachViewState {
    pub fn new(attach_info: bmux_client::AttachOpenInfo) -> Self {
        Self {
            self_client_id: None,
            attached_id: attach_info.session_id,
            attached_context_id: attach_info.context_id,
            can_write: attach_info.can_write,
            ui_mode: AttachUiMode::Normal,
            active_mode_id: "normal".to_string(),
            active_mode_label: "NORMAL".to_string(),
            scrollback_active: false,
            scrollback_offset: 0,
            scrollback_cursor: None,
            selection_anchor: None,
            help_overlay_open: false,
            help_overlay_scroll: 0,
            prompt: AttachPromptState::default(),
            transient_status: None,
            transient_status_until: None,
            control_catalog_revision: 0,
            cached_window_list: None,
            cached_contexts: Vec::new(),
            cached_sessions: Vec::new(),
            cached_context_session_bindings: Vec::new(),
            pane_buffers: BTreeMap::new(),
            terminal_graphics_cache: TerminalGraphicsCache::new(),
            pane_mouse_protocol_hints: BTreeMap::new(),
            pane_input_mode_hints: BTreeMap::new(),
            status_position: StatusPosition::Bottom,
            cached_status_line: None,
            cached_layout_state: None,
            retained_compositor: RetainedCompositor::new(),
            last_help_overlay_surface: None,
            last_prompt_overlay_surface: None,
            last_cursor_state: None,
            force_cursor_move_next_frame: false,
            mouse: AttachMouseState {
                config: MouseBehaviorConfig::default(),
                ..AttachMouseState::default()
            },
            visual_projection_updates: Vec::new(),
            dirty: AttachDirtyFlags::default(),
            #[cfg(any(
                feature = "image-sixel",
                feature = "image-kitty",
                feature = "image-iterm2"
            ))]
            pane_images: BTreeMap::new(),
            #[cfg(any(
                feature = "image-sixel",
                feature = "image-kitty",
                feature = "image-iterm2"
            ))]
            image_sequences: BTreeMap::new(),
            #[cfg(any(
                feature = "image-sixel",
                feature = "image-kitty",
                feature = "image-iterm2"
            ))]
            host_image_caps: bmux_image::HostImageCapabilities::default(),
            #[cfg(any(
                feature = "image-sixel",
                feature = "image-kitty",
                feature = "image-iterm2"
            ))]
            kitty_host_state: bmux_image::compositor::KittyHostState::default(),
            #[cfg(any(
                feature = "image-sixel",
                feature = "image-kitty",
                feature = "image-iterm2"
            ))]
            image_decode_mode: bmux_image::config::ImageDecodeMode::Passthrough,
        }
    }

    pub fn set_transient_status(
        &mut self,
        message: impl Into<String>,
        now: Instant,
        ttl: Duration,
    ) {
        self.transient_status = Some(message.into());
        self.transient_status_until = Some(now + ttl);
        self.dirty
            .mark_status_dirty(AttachDirtySource::StatusChanged);
    }

    pub fn clear_expired_transient_status(&mut self, now: Instant) -> bool {
        let Some(until) = self.transient_status_until else {
            return false;
        };
        if now < until {
            return false;
        }
        self.transient_status = None;
        self.transient_status_until = None;
        self.dirty
            .mark_status_dirty(AttachDirtySource::StatusChanged);
        true
    }

    pub fn transient_status_text(&self, now: Instant) -> Option<&str> {
        if self
            .transient_status_until
            .is_some_and(|until| now >= until)
        {
            return None;
        }
        self.transient_status.as_deref()
    }

    pub const fn exit_scrollback(&mut self) {
        self.scrollback_active = false;
        self.scrollback_offset = 0;
        self.scrollback_cursor = None;
        self.selection_anchor = None;
    }

    pub const fn selection_active(&self) -> bool {
        self.selection_anchor.is_some()
    }
}