rmux-proto 0.1.0

RMUX detached IPC protocol DTOs, framing, and wire-safe error types.
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
//! Shared protocol value types.
//!
//! Identity newtypes (`SessionName`, `SessionId`, `WindowId`, `PaneId`)
//! are defined exactly once in [`crate::identity`]; this module
//! re-exports `SessionName` so legacy import paths continue to resolve.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

pub use crate::identity::SessionName;
use crate::RmuxError;
pub use rmux_types::TerminalSize;

#[path = "types/hooks.rs"]
mod hooks;
#[path = "types/options.rs"]
mod options;

pub use hooks::{HookLifecycle, HookName};
pub use options::{OptionName, SetOptionMode};

/// Stable identifier for one pane-output subscription on a live server
/// connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PaneOutputSubscriptionId(u64);

impl PaneOutputSubscriptionId {
    /// Wraps a raw subscription identifier.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the raw subscription identifier.
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

/// Opaque owner token for daemon-backed SDK waits.
///
/// The SDK assigns one owner token to each transport connection and then
/// allocates [`SdkWaitId`] values within that owner. The server treats the
/// owner as an opaque cancellation key; actual connection teardown cleanup is
/// still keyed by the server's private connection identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SdkWaitOwnerId(u64);

impl SdkWaitOwnerId {
    /// Wraps a raw SDK wait owner identifier.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the raw SDK wait owner identifier.
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

/// Stable identifier for one daemon-backed SDK wait under an
/// [`SdkWaitOwnerId`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SdkWaitId(u64);

impl SdkWaitId {
    /// Wraps a raw SDK wait identifier.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the raw SDK wait identifier.
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

/// A parsed exact target.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Target {
    /// A session target in the form `session-name`.
    Session(SessionName),
    /// A window target in the form `session-name:window-index`.
    Window(WindowTarget),
    /// A pane target in the form `session-name:window-index.pane-index`.
    Pane(PaneTarget),
}

impl Target {
    /// Parses the exact detached target forms supported by the detached server.
    pub fn parse(value: &str) -> Result<Self, RmuxError> {
        if let Some((session_name, tail)) = value.split_once(':') {
            let session_name = SessionName::new(session_name.to_owned())?;

            if !tail.is_empty() && tail.chars().all(|character| character.is_ascii_digit()) {
                let window_index = parse_window_index(value, tail)?;
                return Ok(Self::Window(WindowTarget::with_window(
                    session_name,
                    window_index,
                )));
            }

            if let Some((window_index, pane_index)) = tail.split_once('.') {
                let window_index = parse_window_index(value, window_index)?;
                let pane_index = parse_pane_index(value, pane_index)?;
                return Ok(Self::Pane(PaneTarget::with_window(
                    session_name,
                    window_index,
                    pane_index,
                )));
            }

            return Err(RmuxError::invalid_target(
                value,
                "targets must match 'session', 'session:window', or 'session:window.pane'",
            ));
        }

        Ok(Self::Session(SessionName::new(value.to_owned())?))
    }

    /// Returns the session name addressed by the target.
    #[must_use]
    pub fn session_name(&self) -> &SessionName {
        match self {
            Self::Session(session_name) => session_name,
            Self::Window(target) => target.session_name(),
            Self::Pane(target) => target.session_name(),
        }
    }
}

impl fmt::Display for Target {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Session(session_name) => session_name.fmt(formatter),
            Self::Window(target) => target.fmt(formatter),
            Self::Pane(target) => target.fmt(formatter),
        }
    }
}

impl FromStr for Target {
    type Err = RmuxError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::parse(value)
    }
}

/// A validated window target.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WindowTarget {
    session_name: SessionName,
    window_index: u32,
}

impl WindowTarget {
    /// Creates a V1-compatible window target for window `0`.
    #[must_use]
    pub const fn new(session_name: SessionName) -> Self {
        Self::with_window(session_name, 0)
    }

    /// Creates a window target for the provided window index.
    #[must_use]
    pub const fn with_window(session_name: SessionName, window_index: u32) -> Self {
        Self {
            session_name,
            window_index,
        }
    }

    /// Returns the session name component.
    #[must_use]
    pub const fn session_name(&self) -> &SessionName {
        &self.session_name
    }

    /// Returns the addressed window index.
    #[must_use]
    pub const fn window_index(&self) -> u32 {
        self.window_index
    }
}

impl fmt::Display for WindowTarget {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}:{}", self.session_name, self.window_index)
    }
}

/// A validated pane target.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PaneTarget {
    session_name: SessionName,
    window_index: u32,
    pane_index: u32,
}

impl PaneTarget {
    /// Creates a V1-compatible pane target anchored to window `0`.
    #[must_use]
    pub const fn new(session_name: SessionName, pane_index: u32) -> Self {
        Self::with_window(session_name, 0, pane_index)
    }

    /// Creates a pane target for the provided window and pane indices.
    #[must_use]
    pub const fn with_window(
        session_name: SessionName,
        window_index: u32,
        pane_index: u32,
    ) -> Self {
        Self {
            session_name,
            window_index,
            pane_index,
        }
    }

    /// Returns the session name component.
    #[must_use]
    pub const fn session_name(&self) -> &SessionName {
        &self.session_name
    }

    /// Returns the addressed window index.
    #[must_use]
    pub const fn window_index(&self) -> u32 {
        self.window_index
    }

    /// Returns the pane index component.
    #[must_use]
    pub const fn pane_index(&self) -> u32 {
        self.pane_index
    }
}

impl fmt::Display for PaneTarget {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{}:{}.{}",
            self.session_name, self.window_index, self.pane_index
        )
    }
}

/// A global-or-session selector used by detached mutations.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ScopeSelector {
    /// Global scope.
    Global,
    /// Session-local scope.
    Session(SessionName),
    /// Window-local scope.
    Window(WindowTarget),
    /// Pane-local scope.
    Pane(PaneTarget),
}

/// Explicit option mutation scope for the open option model.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OptionScopeSelector {
    /// Server-global options.
    ServerGlobal,
    /// Session-global options.
    SessionGlobal,
    /// Window-global options.
    WindowGlobal,
    /// Session-local options.
    Session(SessionName),
    /// Window-local options.
    Window(WindowTarget),
    /// Pane-local options.
    Pane(PaneTarget),
}

/// The detached layout name subset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LayoutName {
    /// The required `main-vertical` layout.
    MainVertical,
    /// Internal `split-window -h` geometry using a top main pane.
    MainHorizontal,
    /// The tmux `even-horizontal` left-to-right layout.
    EvenHorizontal,
    /// The tmux `even-vertical` top-to-bottom layout.
    EvenVertical,
    /// The tmux `tiled` grid layout.
    Tiled,
    /// The tmux `main-horizontal-mirrored` layout.
    MainHorizontalMirrored,
    /// The tmux `main-vertical-mirrored` layout.
    MainVerticalMirrored,
}

impl fmt::Display for LayoutName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MainVertical => formatter.write_str("main-vertical"),
            Self::MainHorizontal => formatter.write_str("main-horizontal"),
            Self::EvenHorizontal => formatter.write_str("even-horizontal"),
            Self::EvenVertical => formatter.write_str("even-vertical"),
            Self::Tiled => formatter.write_str("tiled"),
            Self::MainHorizontalMirrored => formatter.write_str("main-horizontal-mirrored"),
            Self::MainVerticalMirrored => formatter.write_str("main-vertical-mirrored"),
        }
    }
}

impl FromStr for LayoutName {
    type Err = RmuxError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "main-vertical" => Ok(Self::MainVertical),
            "main-horizontal" => Ok(Self::MainHorizontal),
            "even-horizontal" => Ok(Self::EvenHorizontal),
            "even-vertical" => Ok(Self::EvenVertical),
            "tiled" => Ok(Self::Tiled),
            "main-horizontal-mirrored" => Ok(Self::MainHorizontalMirrored),
            "main-vertical-mirrored" => Ok(Self::MainVerticalMirrored),
            _ => Err(RmuxError::Server(format!("unknown layout: {value}"))),
        }
    }
}

/// Wire-level split orientation accepted by `split-window`.
///
/// The variant names follow tmux's flag convention (pane arrangement), not
/// the divider-line convention: `Horizontal` means "panes arranged
/// horizontally" (side by side), `Vertical` means "panes arranged
/// vertically" (stacked). New SDK code should prefer
/// [`rmux_sdk::SplitDirection`](https://docs.rs/rmux-sdk/latest/rmux_sdk/enum.SplitDirection.html)
/// (`Right`/`Left`/`Up`/`Down`), which avoids this ambiguity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SplitDirection {
    /// Stacked panes (top + bottom). Matches tmux `split-window -v`,
    /// the tmux default when no flag is passed.
    #[default]
    Vertical,
    /// Side-by-side panes (left + right). Matches tmux `split-window -h`.
    Horizontal,
}

/// The detached resize semantics supported in V1.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResizePaneAdjustment {
    /// Sets the absolute pane width in columns.
    AbsoluteWidth {
        /// The requested pane width in columns.
        columns: u16,
    },
    /// Sets the absolute pane height in rows.
    AbsoluteHeight {
        /// The requested pane height in rows.
        rows: u16,
    },
    /// Toggles zoom for the targeted pane's window.
    Zoom,
    /// Shrinks the pane height upward by a relative amount.
    Up {
        /// The requested row delta.
        cells: u16,
    },
    /// Grows the pane height downward by a relative amount.
    Down {
        /// The requested row delta.
        cells: u16,
    },
    /// Shrinks the pane width leftward by a relative amount.
    Left {
        /// The requested column delta.
        cells: u16,
    },
    /// Grows the pane width rightward by a relative amount.
    Right {
        /// The requested column delta.
        cells: u16,
    },
    /// Resolves the target and reports success without changing layout.
    NoOp,
}

fn parse_pane_index(target: &str, pane_index: &str) -> Result<u32, RmuxError> {
    if pane_index.is_empty() {
        return Err(RmuxError::invalid_target(
            target,
            "pane index must be an unsigned integer",
        ));
    }

    pane_index
        .parse::<u32>()
        .map_err(|_| RmuxError::invalid_target(target, "pane index must be an unsigned integer"))
}

fn parse_window_index(target: &str, window_index: &str) -> Result<u32, RmuxError> {
    if window_index.is_empty() {
        return Err(RmuxError::invalid_target(
            target,
            "window index must be an unsigned integer",
        ));
    }

    window_index
        .parse::<u32>()
        .map_err(|_| RmuxError::invalid_target(target, "window index must be an unsigned integer"))
}

#[cfg(test)]
mod tests;