rmux-core 0.10.0

Core session, pane, layout, format, hook, and buffer model for the RMUX terminal multiplexer.
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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Unbounded};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use rmux_proto::{RmuxError, SessionName, SplitDirection, TerminalSize};

use crate::{AlertFlags, Pane, PaneGeometry, PaneId, SessionId, Window, WindowId};

#[path = "session/accessors.rs"]
mod accessors;
#[path = "session/layout_cycle.rs"]
mod layout_cycle;
#[path = "session/pane_transfer.rs"]
mod pane_transfer;
#[path = "session/pane_transfer_cross.rs"]
mod pane_transfer_cross;
#[path = "session/pane_transfer_shared.rs"]
mod pane_transfer_shared;
#[path = "session/recency.rs"]
mod recency;
#[path = "session/resize.rs"]
mod resize;
#[path = "session/store.rs"]
mod store;
#[path = "session/target_error.rs"]
mod target_error;
#[path = "session/types.rs"]
mod types;
#[path = "session/window_ops.rs"]
mod window_ops;

pub use recency::SessionRecency;
pub use store::SessionStore;
use target_error::{invalid_pane_target, invalid_window_target};
pub(crate) use types::WindowIdAllocator;
pub use types::{
    BreakPaneOptions, KillPaneOutcome, PaneJoinOptions, PaneSwapOptions, SessionPaneTarget,
};

/// A single detached RMUX session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Session {
    id: SessionId,
    name: SessionName,
    group_name: Option<SessionName>,
    terminal_size: TerminalSize,
    windows: BTreeMap<u32, Window>,
    winlink_alert_flags: BTreeMap<u32, AlertFlags>,
    active_window: u32,
    last_window: Option<u32>,
    /// First grouped-peer winlink by stable identity, retained until real local navigation.
    group_initial_window_id: Option<WindowId>,
    next_pane_id: u32,
    next_window_id: WindowIdAllocator,
    created_at: i64,
    activity_at: i64,
    last_attached_at: Option<i64>,
    /// Internal total order behind the whole-second `activity_at`/`created_at`
    /// pair, so same-second lifetime and interaction events stay orderable.
    recency: SessionRecency,
    cwd: Option<PathBuf>,
}

impl Session {
    /// Creates a new session with its initial pane active.
    #[must_use]
    pub fn new(name: SessionName, size: TerminalSize) -> Self {
        Self::new_with_initial_window(name, size, 0, PaneId::new(0), WindowId::new(0))
    }

    /// Creates a new session with an explicitly seeded initial window and pane identity.
    #[must_use]
    pub(crate) fn new_with_initial_window(
        name: SessionName,
        size: TerminalSize,
        window_index: u32,
        pane_id: PaneId,
        window_id: WindowId,
    ) -> Self {
        let now = current_unix_timestamp();
        Self {
            id: SessionId::new(0),
            name,
            group_name: None,
            terminal_size: size,
            windows: BTreeMap::from([(
                window_index,
                Window::new_with_initial_pane(size, pane_id, window_id),
            )]),
            winlink_alert_flags: BTreeMap::from([(window_index, AlertFlags::empty())]),
            active_window: window_index,
            last_window: None,
            group_initial_window_id: None,
            next_pane_id: pane_id.as_u32().saturating_add(1),
            next_window_id: WindowIdAllocator::new(window_id.as_u32().saturating_add(1)),
            created_at: now,
            activity_at: now,
            last_attached_at: None,
            recency: SessionRecency::next(),
            cwd: None,
        }
    }

    /// Splits the current active pane and returns the new pane index, making the new pane active.
    pub fn split_active_pane(&mut self) -> Result<u32, RmuxError> {
        self.split_active_pane_with_direction(SplitDirection::Vertical)
    }

    /// Splits the current active pane in the requested direction.
    pub fn split_active_pane_with_direction(
        &mut self,
        direction: SplitDirection,
    ) -> Result<u32, RmuxError> {
        self.split_pane_with_direction(self.active_pane_index(), direction)
    }

    /// Splits the addressed pane, inserting the new pane immediately after the split target in window order.
    pub fn split_pane(&mut self, pane_index: u32) -> Result<u32, RmuxError> {
        self.split_pane_with_direction(pane_index, SplitDirection::Vertical)
    }

    /// Splits the addressed pane in the active window using the requested direction.
    pub fn split_pane_with_direction(
        &mut self,
        pane_index: u32,
        direction: SplitDirection,
    ) -> Result<u32, RmuxError> {
        self.split_pane_in_window_with_direction(self.active_window, pane_index, direction)
    }

    /// Splits the addressed pane in the addressed window and returns the new pane index.
    pub fn split_pane_in_window(
        &mut self,
        window_index: u32,
        pane_index: u32,
    ) -> Result<u32, RmuxError> {
        self.split_pane_in_window_with_direction(window_index, pane_index, SplitDirection::Vertical)
    }

    /// Splits the addressed pane in the addressed window using the requested direction.
    pub fn split_pane_in_window_with_direction(
        &mut self,
        window_index: u32,
        pane_index: u32,
        direction: SplitDirection,
    ) -> Result<u32, RmuxError> {
        self.split_pane_in_window_with_direction_before(window_index, pane_index, direction, false)
    }

    /// Splits the addressed pane in the addressed window using the requested
    /// direction, controlling whether the new pane is inserted before the
    /// target on the chosen axis (tmux `-b`).
    pub fn split_pane_in_window_with_direction_before(
        &mut self,
        window_index: u32,
        pane_index: u32,
        direction: SplitDirection,
        before: bool,
    ) -> Result<u32, RmuxError> {
        let pane_id = self.allocate_pane_id();
        self.split_pane_in_window_with_id_and_direction_before(
            window_index,
            pane_index,
            pane_id,
            direction,
            before,
        )
    }

    /// Splits the addressed pane in the addressed window using the provided pane identity.
    ///
    /// The new pane is inserted after the target on the chosen axis. Callers
    /// that need tmux `-b` semantics (insert before) should use
    /// [`Session::split_pane_in_window_with_id_and_direction_before`].
    pub fn split_pane_in_window_with_id_and_direction(
        &mut self,
        window_index: u32,
        pane_index: u32,
        pane_id: PaneId,
        direction: SplitDirection,
    ) -> Result<u32, RmuxError> {
        self.split_pane_in_window_with_id_and_direction_before(
            window_index,
            pane_index,
            pane_id,
            direction,
            false,
        )
    }

    /// Splits the addressed pane, controlling whether the new pane lands
    /// before (`-b`) or after the target on the chosen axis.
    pub fn split_pane_in_window_with_id_and_direction_before(
        &mut self,
        window_index: u32,
        pane_index: u32,
        pane_id: PaneId,
        direction: SplitDirection,
        before: bool,
    ) -> Result<u32, RmuxError> {
        self.split_pane_in_window_with_id_and_direction_before_detached(
            window_index,
            pane_index,
            pane_id,
            direction,
            before,
            false,
        )
    }

    /// Splits like [`Self::split_pane_in_window_with_id_and_direction_before`]
    /// but honors tmux `-d`: a detached spawn leaves the active pane, the
    /// last pane, and the active_point counters untouched.
    pub fn split_pane_in_window_with_id_and_direction_before_detached(
        &mut self,
        window_index: u32,
        pane_index: u32,
        pane_id: PaneId,
        direction: SplitDirection,
        before: bool,
        detached: bool,
    ) -> Result<u32, RmuxError> {
        let window = self
            .window_at(window_index)
            .ok_or_else(|| invalid_window_target(&self.name, window_index))?;
        let position = window.pane_position(pane_index).ok_or_else(|| {
            invalid_pane_target(
                &self.name,
                window_index,
                pane_index,
                "pane index does not exist in session",
            )
        })?;
        if !window.can_split_pane(pane_index, direction) {
            return Err(RmuxError::Message("no space for new pane".to_owned()));
        }
        Ok(self
            .window_at_mut(window_index)
            .expect("addressed session window must exist")
            .split_at_position_with_id_and_direction_detached(
                position, pane_id, direction, before, detached,
            ))
    }

    /// Splits the full addressed window root and returns the new pane index.
    pub fn split_pane_full_size_in_window_with_id_and_direction_before(
        &mut self,
        window_index: u32,
        pane_index: u32,
        pane_id: PaneId,
        direction: SplitDirection,
        before: bool,
    ) -> Result<u32, RmuxError> {
        self.split_pane_full_size_in_window_with_id_and_direction_before_detached(
            window_index,
            pane_index,
            pane_id,
            direction,
            before,
            false,
        )
    }

    /// Full-size split honoring tmux `-d` like
    /// [`Self::split_pane_in_window_with_id_and_direction_before_detached`].
    pub fn split_pane_full_size_in_window_with_id_and_direction_before_detached(
        &mut self,
        window_index: u32,
        pane_index: u32,
        pane_id: PaneId,
        direction: SplitDirection,
        before: bool,
        detached: bool,
    ) -> Result<u32, RmuxError> {
        let window = self
            .window_at(window_index)
            .ok_or_else(|| invalid_window_target(&self.name, window_index))?;
        if window.pane(pane_index).is_none() {
            return Err(invalid_pane_target(
                &self.name,
                window_index,
                pane_index,
                "pane index does not exist in session",
            ));
        }

        let window = self
            .window_at_mut(window_index)
            .expect("addressed session window must exist");
        let previous_active_pane_id = window.active_pane().map(Pane::id);
        let previous_last_pane_id = window
            .last_pane_index()
            .and_then(|pane_index| window.pane(pane_index))
            .map(Pane::id);
        let new_index = window
            .panes()
            .iter()
            .map(Pane::index)
            .max()
            .unwrap_or(0)
            .saturating_add(1);
        window.insert_pane_full_size(
            Pane::new_with_id(pane_id, new_index, PaneGeometry::new(0, 0, 0, 0)),
            direction,
            before,
        )?;
        window.commit_split_renumber(
            pane_id,
            previous_active_pane_id,
            previous_last_pane_id,
            detached,
        );
        window
            .panes()
            .iter()
            .find(|pane| pane.id() == pane_id)
            .map(Pane::index)
            .ok_or_else(|| {
                RmuxError::Server(format!(
                    "pane id {} disappeared after full-size split",
                    pane_id.as_u32()
                ))
            })
    }

    /// Removes the addressed pane in the active window.
    pub fn kill_pane(&mut self, pane_index: u32) -> Result<KillPaneOutcome, RmuxError> {
        self.kill_pane_in_window(self.active_window, pane_index)
    }

    /// Removes the addressed pane or destroys its window when it is the last pane there.
    pub fn kill_pane_in_window(
        &mut self,
        window_index: u32,
        pane_index: u32,
    ) -> Result<KillPaneOutcome, RmuxError> {
        let window = self
            .window_at(window_index)
            .ok_or_else(|| invalid_window_target(&self.name, window_index))?;
        let pane_id = window.pane_id(pane_index).ok_or_else(|| {
            invalid_pane_target(
                &self.name,
                window_index,
                pane_index,
                "pane index does not exist in session",
            )
        })?;

        if window.pane_count() == 1 {
            let removed_window = self.remove_window(window_index)?;
            let removed_pane_ids = removed_window.panes().iter().map(Pane::id).collect();
            return Ok(KillPaneOutcome::new(removed_pane_ids, true));
        }

        let removed_pane = self
            .window_at_mut(window_index)
            .expect("addressed session window must exist")
            .remove_pane(pane_index)
            .expect("prevalidated pane removal must succeed");
        debug_assert_eq!(removed_pane.id(), pane_id);

        Ok(KillPaneOutcome::new(vec![removed_pane.id()], false))
    }

    /// Removes every pane except the addressed pane, matching `kill-pane -a`.
    pub fn kill_other_panes_in_window(
        &mut self,
        window_index: u32,
        pane_index: u32,
    ) -> Result<KillPaneOutcome, RmuxError> {
        let window = self
            .window_at(window_index)
            .ok_or_else(|| invalid_window_target(&self.name, window_index))?;
        if window.pane(pane_index).is_none() {
            return Err(invalid_pane_target(
                &self.name,
                window_index,
                pane_index,
                "pane index does not exist in session",
            ));
        }

        let removed_pane_ids = self
            .window_at_mut(window_index)
            .expect("addressed session window must exist")
            .remove_other_panes(pane_index)
            .expect("prevalidated pane removal must succeed");

        Ok(KillPaneOutcome::new(removed_pane_ids, false))
    }

    /// Selects the active pane for the session.
    pub fn select_pane(&mut self, pane_index: u32) -> Result<(), RmuxError> {
        self.select_pane_in_window(self.active_window, pane_index)
    }

    /// Selects the active pane for the addressed window.
    pub fn select_pane_in_window(
        &mut self,
        window_index: u32,
        pane_index: u32,
    ) -> Result<(), RmuxError> {
        self.select_pane_in_window_with_zoom(window_index, pane_index, false)
    }

    /// Selects the active pane for the addressed window, preserving zoom when requested.
    pub fn select_pane_in_window_with_zoom(
        &mut self,
        window_index: u32,
        pane_index: u32,
        preserve_zoom: bool,
    ) -> Result<(), RmuxError> {
        if self.window_at(window_index).is_none() {
            return Err(invalid_window_target(&self.name, window_index));
        }

        if self
            .window_at(window_index)
            .expect("addressed session window must exist")
            .pane(pane_index)
            .is_none()
        {
            return Err(invalid_pane_target(
                &self.name,
                window_index,
                pane_index,
                "pane index does not exist in session",
            ));
        }

        let window = self
            .window_at_mut(window_index)
            .expect("addressed session window must exist");
        if preserve_zoom {
            let _ = window.push_zoom(true);
        }
        let selected = window.select_pane(pane_index);
        if preserve_zoom {
            window.pop_zoom();
        }
        debug_assert!(selected, "validated pane target must be selectable");
        Ok(())
    }

    /// Selects the pane adjacent to the addressed pane in the requested direction.
    pub fn select_adjacent_pane_in_window(
        &mut self,
        window_index: u32,
        pane_index: u32,
        direction: rmux_proto::SelectPaneDirection,
    ) -> Result<u32, RmuxError> {
        self.select_adjacent_pane_in_window_with_zoom(window_index, pane_index, direction, false)
    }

    /// Selects an adjacent pane, preserving zoom when requested.
    pub fn select_adjacent_pane_in_window_with_zoom(
        &mut self,
        window_index: u32,
        pane_index: u32,
        direction: rmux_proto::SelectPaneDirection,
        preserve_zoom: bool,
    ) -> Result<u32, RmuxError> {
        if self.window_at(window_index).is_none() {
            return Err(invalid_window_target(&self.name, window_index));
        }

        if self
            .window_at(window_index)
            .expect("addressed session window must exist")
            .pane(pane_index)
            .is_none()
        {
            return Err(invalid_pane_target(
                &self.name,
                window_index,
                pane_index,
                "pane index does not exist in session",
            ));
        }

        let window = self
            .window_at_mut(window_index)
            .expect("addressed session window must exist");
        let was_zoomed = window.is_zoomed();
        let original_active_pane = window.active_pane_index();
        if was_zoomed {
            let _ = window.push_zoom(false);
        }
        let selected = window
            .select_adjacent_pane(pane_index, direction)
            .expect("validated adjacent pane anchor must be selectable");
        let moved = selected != original_active_pane;
        if was_zoomed && (preserve_zoom || !moved) {
            let _ = window.toggle_zoom(window.active_pane_index());
        }
        Ok(selected)
    }

    /// Updates the terminal and content sizes together for all windows.
    ///
    /// This is the explicit/manual-size path. Attached clients should use
    /// [`Session::resize_active_window_geometry`] so status rows never enter a
    /// window layout.
    pub fn resize_terminal(&mut self, size: TerminalSize) {
        self.terminal_size = size;
        for window in self.windows.values_mut() {
            window.set_size(size);
        }
    }

    /// Updates only the external terminal size used to render this session.
    pub fn set_terminal_size(&mut self, size: TerminalSize) {
        self.terminal_size = size;
    }

    /// Updates the external terminal and active-window content geometry.
    ///
    /// Attached clients drive the size of the window they are currently viewing. Inactive
    /// windows can have independent policies and may share a runtime with another session, so
    /// resizing every window here would leak the active window's size into unrelated runtimes.
    pub fn resize_active_window_geometry(
        &mut self,
        terminal_size: TerminalSize,
        content_size: TerminalSize,
    ) {
        self.terminal_size = terminal_size;
        self.window_mut().set_size(content_size);
    }

    fn resolve_window_target_mut(&mut self, window_index: u32) -> Result<&mut Window, RmuxError> {
        if !self.windows.contains_key(&window_index) {
            return Err(invalid_window_target(&self.name, window_index));
        }

        Ok(self
            .window_at_mut(window_index)
            .expect("addressed session window must exist"))
    }

    pub(crate) fn lowest_available_window_index_at_or_above(
        &self,
        minimum_index: u32,
    ) -> Result<u32, RmuxError> {
        let mut next_index = minimum_index;

        for window_index in self.windows.keys().copied() {
            if window_index < next_index {
                continue;
            }
            if window_index > next_index {
                break;
            }

            if window_index == next_index {
                next_index = next_index.checked_add(1).ok_or_else(|| {
                    RmuxError::Server(format!(
                        "window index space exhausted for session {}",
                        self.name
                    ))
                })?;
            }
        }

        Ok(next_index)
    }

    fn next_active_window_after_removal(&self, removed_index: u32) -> u32 {
        if let Some(last_window) = self.last_window {
            if last_window != removed_index && self.windows.contains_key(&last_window) {
                return last_window;
            }
        }

        if let Some(group_initial_window_id) = self.group_initial_window_id {
            if let Some((window_index, _)) = self.windows.iter().find(|(window_index, window)| {
                **window_index != removed_index && window.id() == group_initial_window_id
            }) {
                return *window_index;
            }
        }

        cyclic_previous_window_index(&self.windows, removed_index)
            .expect("a non-empty session must have a replacement window")
    }

    fn allocate_pane_id(&mut self) -> PaneId {
        let mut next_pane_id = self.next_pane_id;

        loop {
            let pane_id = PaneId::new(next_pane_id);
            if !self.contains_pane_id(pane_id) {
                self.next_pane_id = next_pane_id.saturating_add(1);
                return pane_id;
            }

            assert_ne!(next_pane_id, u32::MAX, "pane id space exhausted");
            next_pane_id += 1;
        }
    }

    fn contains_pane_id(&self, pane_id: PaneId) -> bool {
        self.windows
            .values()
            .flat_map(Window::panes)
            .any(|pane| pane.id() == pane_id)
    }

    /// Resolves the owning window index for the given pane identity when present.
    pub fn window_index_for_pane_id(&self, pane_id: PaneId) -> Option<u32> {
        self.windows.iter().find_map(|(window_index, window)| {
            window
                .panes()
                .iter()
                .any(|pane| pane.id() == pane_id)
                .then_some(*window_index)
        })
    }

    fn allocate_window_id(&self) -> WindowId {
        self.next_window_id.allocate()
    }
}

fn synchronized_active_window(
    windows: &BTreeMap<u32, Window>,
    previous_active: u32,
    previous_last: Option<u32>,
) -> u32 {
    if windows.contains_key(&previous_active) {
        return previous_active;
    }

    if let Some(last_window) = previous_last {
        if last_window != previous_active && windows.contains_key(&last_window) {
            return last_window;
        }
    }

    cyclic_previous_window_index(windows, previous_active)
        .expect("group synchronization requires at least one window")
}

fn cyclic_previous_window_index(
    windows: &BTreeMap<u32, Window>,
    removed_index: u32,
) -> Option<u32> {
    windows
        .range(..removed_index)
        .next_back()
        .or_else(|| {
            windows
                .range((Excluded(removed_index), Unbounded))
                .next_back()
        })
        .map(|(window_index, _)| *window_index)
}

fn current_unix_timestamp() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|duration| i64::try_from(duration.as_secs()).ok())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests;

#[cfg(test)]
#[path = "session/zoom_tests.rs"]
mod zoom_tests;

#[cfg(test)]
#[path = "session/layout_tests.rs"]
mod layout_tests;