rmux-proto 0.1.2

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
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use std::path::PathBuf;

use crate::{SessionName, WindowTarget};

/// Request payload for `new-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NewWindowRequest {
    /// The exact target session name.
    pub target: SessionName,
    /// The optional explicit window name.
    pub name: Option<String>,
    /// Whether the newly created window should remain inactive.
    pub detached: bool,
    /// Optional per-spawn environment overrides in `NAME=VALUE` form.
    #[serde(default)]
    pub environment: Option<Vec<String>>,
    /// Optional shell command argv. A single argument is executed via `$SHELL -c`.
    #[serde(default)]
    pub command: Option<Vec<String>>,
    /// Optional working-directory override.
    #[serde(default)]
    pub start_directory: Option<PathBuf>,
    /// Optional destination window index from `new-window -t session:index`.
    #[serde(default)]
    pub target_window_index: Option<u32>,
    /// Whether an occupied destination index should be opened by shifting windows upward.
    #[serde(default)]
    pub insert_at_target: bool,
}

/// Request payload for `kill-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KillWindowRequest {
    /// The exact target window.
    pub target: WindowTarget,
    /// Whether all other windows in the session should be removed instead.
    pub kill_all_others: bool,
}

/// Request payload for `select-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelectWindowRequest {
    /// The exact target window.
    pub target: WindowTarget,
}

/// Request payload for `rename-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RenameWindowRequest {
    /// The exact target window.
    pub target: WindowTarget,
    /// The new window name.
    pub name: String,
}

/// Request payload for `next-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NextWindowRequest {
    /// The exact target session name.
    pub target: SessionName,
    /// Whether only alerted windows should be considered.
    #[serde(default)]
    pub alerts_only: bool,
}

/// Request payload for `previous-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PreviousWindowRequest {
    /// The exact target session name.
    pub target: SessionName,
    /// Whether only alerted windows should be considered.
    #[serde(default)]
    pub alerts_only: bool,
}

/// Request payload for `last-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastWindowRequest {
    /// The exact target session name.
    pub target: SessionName,
}

/// Request payload for `list-windows`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListWindowsRequest {
    /// The exact target session name.
    pub target: SessionName,
    /// An optional server-side compatibility format template.
    pub format: Option<String>,
}

/// Request payload for `link-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LinkWindowRequest {
    /// The source window slot.
    pub source: WindowTarget,
    /// The destination window slot.
    pub target: WindowTarget,
    /// Whether to insert after the target slot (`-a`).
    #[serde(default)]
    pub after: bool,
    /// Whether to insert before the target slot (`-b`).
    #[serde(default)]
    pub before: bool,
    /// Whether an occupied destination should be replaced (`-k`).
    #[serde(default)]
    pub kill_destination: bool,
    /// Whether the destination session should keep its current active window (`-d`).
    #[serde(default)]
    pub detached: bool,
}

/// Target forms accepted by `move-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MoveWindowTarget {
    /// Applies to the addressed session during `move-window -r`.
    Session(SessionName),
    /// Applies to the addressed destination window slot.
    Window(WindowTarget),
}

/// Request payload for `move-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MoveWindowRequest {
    /// The optional source window being moved when not reindexing.
    pub source: Option<WindowTarget>,
    /// The destination window slot or reindex target session.
    pub target: MoveWindowTarget,
    /// Whether the session should be reindexed instead of moving one window.
    pub renumber: bool,
    /// Whether an occupied destination should be replaced.
    pub kill_destination: bool,
    /// Whether the destination session should keep its current active window.
    pub detached: bool,
}

/// Request payload for `swap-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SwapWindowRequest {
    /// The source window slot.
    pub source: WindowTarget,
    /// The destination window slot.
    pub target: WindowTarget,
    /// Whether the swapped destination slots should become active after the swap.
    pub detached: bool,
}

/// The supported pane rotation directions for `rotate-window`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RotateWindowDirection {
    /// Move the last pane to the head.
    Down,
    /// Move the first pane to the tail.
    Up,
}

/// Request payload for `rotate-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RotateWindowRequest {
    /// The addressed window.
    pub target: WindowTarget,
    /// The requested rotation direction.
    pub direction: RotateWindowDirection,
    /// Whether to save and restore zoom state around the rotation (`-Z`).
    #[serde(default)]
    pub restore_zoom: bool,
}

/// Request payload for `resize-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResizeWindowRequest {
    /// The addressed window.
    pub target: WindowTarget,
    /// Optional explicit width (`-x`).
    pub width: Option<u16>,
    /// Optional explicit height (`-y`).
    pub height: Option<u16>,
    /// Relative adjustment (from `-D`, `-U`, `-L`, `-R`).
    #[serde(default)]
    pub adjustment: Option<ResizeWindowAdjustment>,
}

/// Directional relative-size adjustment for `resize-window`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResizeWindowAdjustment {
    /// Shrink height (`-U`).
    Up(u16),
    /// Grow height (`-D`).
    Down(u16),
    /// Shrink width (`-L`).
    Left(u16),
    /// Grow width (`-R`).
    Right(u16),
}

/// Request payload for `respawn-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RespawnWindowRequest {
    /// The addressed window.
    pub target: WindowTarget,
    /// Whether to kill existing panes even when they are still running (`-k`).
    #[serde(default)]
    pub kill: bool,
    /// Optional per-spawn environment overrides in `NAME=VALUE` form.
    #[serde(default)]
    pub environment: Option<Vec<String>>,
    /// Optional shell command argv. A single argument is executed via `$SHELL -c`.
    #[serde(default)]
    pub command: Option<Vec<String>>,
    /// Optional working-directory override.
    #[serde(default)]
    pub start_directory: Option<PathBuf>,
}

impl<'de> Deserialize<'de> for NewWindowRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "NewWindowRequest",
            &[
                "target",
                "name",
                "detached",
                "environment",
                "command",
                "start_directory",
                "target_window_index",
                "insert_at_target",
            ],
            NewWindowRequestVisitor,
        )
    }
}

impl<'de> Deserialize<'de> for RespawnWindowRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "RespawnWindowRequest",
            &[
                "target",
                "kill",
                "environment",
                "command",
                "start_directory",
            ],
            RespawnWindowRequestVisitor,
        )
    }
}

struct NewWindowRequestVisitor;

impl<'de> Visitor<'de> for NewWindowRequestVisitor {
    type Value = NewWindowRequest;

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("a new-window request")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let target = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(0, &self))?;
        let name = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(1, &self))?;
        let detached = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(2, &self))?;
        let environment = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(3, &self))?;
        let command = compat_next_element(&mut seq)?;
        let start_directory = compat_next_element(&mut seq)?;
        let target_window_index = compat_next_element(&mut seq)?;
        let insert_at_target = compat_next_element(&mut seq)?;

        Ok(NewWindowRequest {
            target,
            name,
            detached,
            environment,
            command,
            start_directory,
            target_window_index,
            insert_at_target,
        })
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut target = None;
        let mut name = None;
        let mut detached = None;
        let mut environment = None;
        let mut command = None;
        let mut start_directory = None;
        let mut target_window_index = None;
        let mut insert_at_target = None;

        while let Some(key) = map.next_key::<String>()? {
            match key.as_str() {
                "target" => target = Some(map.next_value()?),
                "name" => name = Some(map.next_value()?),
                "detached" => detached = Some(map.next_value()?),
                "environment" => environment = Some(map.next_value()?),
                "command" => command = Some(map.next_value()?),
                "start_directory" => start_directory = Some(map.next_value()?),
                "target_window_index" => target_window_index = Some(map.next_value()?),
                "insert_at_target" => insert_at_target = Some(map.next_value()?),
                _ => {
                    let _: de::IgnoredAny = map.next_value()?;
                }
            }
        }

        Ok(NewWindowRequest {
            target: target.ok_or_else(|| de::Error::missing_field("target"))?,
            name: name.ok_or_else(|| de::Error::missing_field("name"))?,
            detached: detached.ok_or_else(|| de::Error::missing_field("detached"))?,
            environment: environment.ok_or_else(|| de::Error::missing_field("environment"))?,
            command: command.unwrap_or_default(),
            start_directory: start_directory.unwrap_or_default(),
            target_window_index: target_window_index.unwrap_or_default(),
            insert_at_target: insert_at_target.unwrap_or_default(),
        })
    }
}

struct RespawnWindowRequestVisitor;

impl<'de> Visitor<'de> for RespawnWindowRequestVisitor {
    type Value = RespawnWindowRequest;

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("a respawn-window request")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let target = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(0, &self))?;
        let kill = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(1, &self))?;
        let environment = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(2, &self))?;
        let command = compat_next_element(&mut seq)?;
        let start_directory = compat_next_element(&mut seq)?;

        Ok(RespawnWindowRequest {
            target,
            kill,
            environment,
            command,
            start_directory,
        })
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut target = None;
        let mut kill = None;
        let mut environment = None;
        let mut command = None;
        let mut start_directory = None;

        while let Some(key) = map.next_key::<String>()? {
            match key.as_str() {
                "target" => target = Some(map.next_value()?),
                "kill" => kill = Some(map.next_value()?),
                "environment" => environment = Some(map.next_value()?),
                "command" => command = Some(map.next_value()?),
                "start_directory" => start_directory = Some(map.next_value()?),
                _ => {
                    let _: de::IgnoredAny = map.next_value()?;
                }
            }
        }

        Ok(RespawnWindowRequest {
            target: target.ok_or_else(|| de::Error::missing_field("target"))?,
            kill: kill.ok_or_else(|| de::Error::missing_field("kill"))?,
            environment: environment.ok_or_else(|| de::Error::missing_field("environment"))?,
            command: command.unwrap_or_default(),
            start_directory: start_directory.unwrap_or_default(),
        })
    }
}

fn compat_next_element<'de, A, T>(seq: &mut A) -> Result<T, A::Error>
where
    A: SeqAccess<'de>,
    T: Deserialize<'de> + Default,
{
    match seq.next_element::<T>() {
        Ok(Some(value)) => Ok(value),
        Ok(None) => Ok(T::default()),
        Err(error) if is_truncated_compat_sequence(&error) => Ok(T::default()),
        Err(error) => Err(error),
    }
}

fn is_truncated_compat_sequence(error: &impl std::fmt::Display) -> bool {
    let message = error.to_string();
    message.contains("UnexpectedEof") || message.contains("unexpected end of file")
}