zellij-client 0.44.3

The client-side library for Zellij
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
// This is a converter from the old yaml layout to the new KDL layout.
//
// It is supposed to be mostly self containing - please refrain from adding to it, importing
// from it or changing it
use super::old_config::{config_yaml_to_config_kdl, OldConfigFromYaml, OldRunCommand};
use serde::{Deserialize, Serialize};
use std::vec::Vec;
use std::{fmt, path::PathBuf};
use url::Url;

fn pane_line(
    pane_name: Option<&String>,
    split_size: Option<OldSplitSize>,
    focus: Option<bool>,
    borderless: bool,
) -> String {
    let mut pane_line = format!("pane");
    if let Some(pane_name) = pane_name {
        // we use debug print here so that quotes and backslashes will be escaped
        pane_line.push_str(&format!(" name={:?}", pane_name));
    }
    if let Some(split_size) = split_size {
        pane_line.push_str(&format!(" size={}", split_size));
    }
    if let Some(focus) = focus {
        pane_line.push_str(&format!(" focus={}", focus));
    }
    if borderless {
        pane_line.push_str(" borderless=true");
    }
    pane_line
}

fn tab_line(
    pane_name: Option<&String>,
    split_size: Option<OldSplitSize>,
    focus: Option<bool>,
    borderless: bool,
) -> String {
    let mut pane_line = format!("tab");
    if let Some(pane_name) = pane_name {
        // we use debug print here so that quotes and backslashes will be escaped
        pane_line.push_str(&format!(" name={:?}", pane_name));
    }
    if let Some(split_size) = split_size {
        pane_line.push_str(&format!(" size={}", split_size));
    }
    if let Some(focus) = focus {
        pane_line.push_str(&format!(" focus={}", focus));
    }
    if borderless {
        pane_line.push_str(" borderless=true");
    }
    pane_line
}

fn pane_line_with_children(
    pane_name: Option<&String>,
    split_size: Option<OldSplitSize>,
    focus: Option<bool>,
    borderless: bool,
    split_direction: OldDirection,
) -> String {
    let mut pane_line = format!("pane");
    if let Some(pane_name) = pane_name {
        // we use debug print here so that quotes and backslashes will be escaped
        pane_line.push_str(&format!(" name={:?}", pane_name));
    }
    if let Some(split_size) = split_size {
        pane_line.push_str(&format!(" size={}", split_size));
    }
    if let Some(focus) = focus {
        pane_line.push_str(&format!(" focus={}", focus));
    }
    pane_line.push_str(&format!(" split_direction=\"{}\"", split_direction));
    if borderless {
        pane_line.push_str(" borderless=true");
    }
    pane_line
}

fn pane_command_line(
    pane_name: Option<&String>,
    split_size: Option<OldSplitSize>,
    focus: Option<bool>,
    borderless: bool,
    command: &PathBuf,
) -> String {
    let mut pane_line = format!("pane command={:?}", command);
    if let Some(pane_name) = pane_name {
        // we use debug print here so that quotes and backslashes will be escaped
        pane_line.push_str(&format!(" name={:?}", pane_name));
    }
    if let Some(split_size) = split_size {
        pane_line.push_str(&format!(" size={}", split_size));
    }
    if let Some(focus) = focus {
        pane_line.push_str(&format!(" focus={}", focus));
    }
    if borderless {
        pane_line.push_str(" borderless=true");
    }
    pane_line
}

fn tab_line_with_children(
    pane_name: Option<&String>,
    split_size: Option<OldSplitSize>,
    focus: Option<bool>,
    borderless: bool,
    split_direction: OldDirection,
) -> String {
    let mut pane_line = format!("tab");
    if let Some(pane_name) = pane_name {
        // we use debug print here so that quotes and backslashes will be escaped
        pane_line.push_str(&format!(" name={:?}", pane_name));
    }
    if let Some(split_size) = split_size {
        pane_line.push_str(&format!(" size={}", split_size));
    }
    if let Some(focus) = focus {
        pane_line.push_str(&format!(" focus={}", focus));
    }
    pane_line.push_str(&format!(" split_direction=\"{}\"", split_direction));
    if borderless {
        pane_line.push_str(" borderless=true");
    }
    pane_line
}

fn stringify_template(
    template: &OldLayoutTemplate,
    indentation: String,
    has_no_tabs: bool,
    is_base: bool,
) -> String {
    let mut stringified = if is_base {
        String::new()
    } else {
        String::from("\n")
    };
    if is_base && !template.parts.is_empty() && template.direction == OldDirection::Vertical {
        // we don't support specifying the split direction in the layout node
        // eg. layout split_direction="Vertical" { .. }  <== this is not supported!!
        // so we need to add a child wrapper with the split direction instead:
        // layout {
        //     pane split_direction="Vertical" { .. }
        // }
        let child_indentation = format!("{}    ", &indentation);
        stringified.push_str(&stringify_template(
            template,
            child_indentation,
            has_no_tabs,
            false,
        ));
    } else if !template.parts.is_empty() {
        if !is_base {
            stringified.push_str(&format!(
                "{}{} {{",
                indentation,
                pane_line_with_children(
                    template.pane_name.as_ref(),
                    template.split_size,
                    template.focus,
                    template.borderless,
                    template.direction
                )
            ));
        }
        for part in &template.parts {
            let child_indentation = format!("{}    ", &indentation);
            stringified.push_str(&stringify_template(
                &part,
                child_indentation,
                has_no_tabs,
                false,
            ));
        }
        if !is_base {
            stringified.push_str(&format!("\n{}}}", indentation));
        }
    } else if template.body && !has_no_tabs {
        stringified.push_str(&format!("{}children", indentation));
    } else {
        match template.run.as_ref() {
            Some(OldRunFromYaml::Plugin(plugin_from_yaml)) => {
                stringified.push_str(&format!(
                    "{}{} {{\n",
                    &indentation,
                    pane_line(
                        template.pane_name.as_ref(),
                        template.split_size,
                        template.focus,
                        template.borderless
                    )
                ));
                stringified.push_str(&format!(
                    "{}    plugin location=\"{}\"\n",
                    &indentation, plugin_from_yaml.location
                ));
                stringified.push_str(&format!("{}}}", &indentation));
            },
            Some(OldRunFromYaml::Command(command_from_yaml)) => {
                stringified.push_str(&format!(
                    "{}{}",
                    &indentation,
                    &pane_command_line(
                        template.pane_name.as_ref(),
                        template.split_size,
                        template.focus,
                        template.borderless,
                        &command_from_yaml.command
                    )
                ));
                if let Some(cwd) = command_from_yaml.cwd.as_ref() {
                    stringified.push_str(&format!(" cwd={:?}", cwd));
                }
                if !command_from_yaml.args.is_empty() {
                    stringified.push_str(" {\n");
                    stringified.push_str(&format!(
                        "{}    args {}\n",
                        &indentation,
                        command_from_yaml
                            .args
                            .iter()
                            // we use debug print here so that quotes and backslashes will be
                            // escaped
                            .map(|s| format!("{:?}", s))
                            .collect::<Vec<String>>()
                            .join(" ")
                    ));
                    stringified.push_str(&format!("{}}}", &indentation));
                }
            },
            None => {
                stringified.push_str(&format!(
                    "{}{}",
                    &indentation,
                    pane_line(
                        template.pane_name.as_ref(),
                        template.split_size,
                        template.focus,
                        template.borderless
                    )
                ));
            },
        };
    }
    stringified
}

fn stringify_tabs(tabs: Vec<OldTabLayout>) -> String {
    let mut stringified = String::new();
    for tab in tabs {
        let child_indentation = String::from("    ");
        if !tab.parts.is_empty() {
            stringified.push_str(&format!(
                "\n{}{} {{",
                child_indentation,
                tab_line_with_children(
                    tab.pane_name.as_ref(),
                    tab.split_size,
                    tab.focus,
                    tab.borderless,
                    tab.direction
                )
            ));
            let tab_template = OldLayoutTemplate::from(tab);
            stringified.push_str(&stringify_template(
                &tab_template,
                child_indentation.clone(),
                true,
                true,
            ));
            stringified.push_str(&format!("\n{}}}", child_indentation));
        } else {
            stringified.push_str(&format!(
                "\n{}{}",
                child_indentation,
                tab_line(
                    tab.pane_name.as_ref(),
                    tab.split_size,
                    tab.focus,
                    tab.borderless
                )
            ));
        }
    }
    stringified
}

pub fn layout_yaml_to_layout_kdl(raw_yaml_layout: &str) -> Result<String, String> {
    // returns the raw kdl config
    let layout_from_yaml: OldLayoutFromYamlIntermediate = serde_yaml::from_str(raw_yaml_layout)
        .map_err(|e| format!("Failed to parse yaml: {:?}", e))?;
    let mut kdl_layout = String::new();
    kdl_layout.push_str("layout {");
    let template = layout_from_yaml.template;
    let tabs = layout_from_yaml.tabs;
    let has_no_tabs = tabs.is_empty()
        || tabs.len() == 1 && tabs.get(0).map(|t| t.parts.is_empty()).unwrap_or(false);
    if has_no_tabs {
        let indentation = String::from("");
        kdl_layout.push_str(&stringify_template(
            &template,
            indentation,
            has_no_tabs,
            true,
        ));
    } else {
        kdl_layout.push_str("\n    default_tab_template {");
        let indentation = String::from("    ");
        kdl_layout.push_str(&stringify_template(
            &template,
            indentation,
            has_no_tabs,
            true,
        ));
        kdl_layout.push_str("\n    }");
        kdl_layout.push_str(&stringify_tabs(tabs));
    }
    kdl_layout.push_str("\n}");
    let layout_config = config_yaml_to_config_kdl(raw_yaml_layout, true)?;
    if let Some(session_name) = layout_from_yaml.session.name {
        // we use debug print here so that quotes and backslashes will be escaped
        kdl_layout.push_str(&format!("\nsession_name {:?}", session_name));
        if let Some(attach_to_session) = layout_from_yaml.session.attach {
            kdl_layout.push_str(&format!("\nattach_to_session {}", attach_to_session));
        }
    }
    if !layout_config.is_empty() {
        kdl_layout.push('\n');
    }
    kdl_layout.push_str(&layout_config);
    Ok(kdl_layout)
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Copy)]
pub enum OldDirection {
    #[serde(alias = "horizontal")]
    Horizontal,
    #[serde(alias = "vertical")]
    Vertical,
}

impl fmt::Display for OldDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            Self::Horizontal => write!(f, "Horizontal"),
            Self::Vertical => write!(f, "Vertical"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum OldSplitSize {
    #[serde(alias = "percent")]
    Percent(u64), // 1 to 100
    #[serde(alias = "fixed")]
    Fixed(usize), // An absolute number of columns or rows
}

impl fmt::Display for OldSplitSize {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            Self::Percent(percent) => write!(f, "\"{}%\"", percent),
            Self::Fixed(fixed_size) => write!(f, "{}", fixed_size),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum OldRunFromYaml {
    #[serde(rename = "plugin")]
    Plugin(OldRunPluginFromYaml),
    #[serde(rename = "command")]
    Command(OldRunCommand),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct OldRunPluginFromYaml {
    #[serde(default)]
    pub _allow_exec_host_cmd: bool,
    pub location: Url,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(default)]
pub struct OldLayoutFromYamlIntermediate {
    #[serde(default)]
    pub template: OldLayoutTemplate,
    #[serde(default)]
    pub borderless: bool,
    #[serde(default)]
    pub tabs: Vec<OldTabLayout>,
    #[serde(default)]
    pub session: OldSessionFromYaml,
    #[serde(flatten)]
    pub config: Option<OldConfigFromYaml>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(default)]
pub struct OldLayoutFromYaml {
    #[serde(default)]
    pub session: OldSessionFromYaml,
    #[serde(default)]
    pub template: OldLayoutTemplate,
    #[serde(default)]
    pub borderless: bool,
    #[serde(default)]
    pub tabs: Vec<OldTabLayout>,
}

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct OldSessionFromYaml {
    pub name: Option<String>,
    #[serde(default = "default_as_some_true")]
    pub attach: Option<bool>,
}

fn default_as_some_true() -> Option<bool> {
    Some(true)
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct OldLayoutTemplate {
    pub direction: OldDirection,
    #[serde(default)]
    pub pane_name: Option<String>,
    #[serde(default)]
    pub borderless: bool,
    #[serde(default)]
    pub parts: Vec<OldLayoutTemplate>,
    #[serde(default)]
    pub body: bool,
    pub split_size: Option<OldSplitSize>,
    pub focus: Option<bool>,
    pub run: Option<OldRunFromYaml>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct OldTabLayout {
    #[serde(default)]
    pub direction: OldDirection,
    pub pane_name: Option<String>,
    #[serde(default)]
    pub borderless: bool,
    #[serde(default)]
    pub parts: Vec<OldTabLayout>,
    pub split_size: Option<OldSplitSize>,
    #[serde(default)]
    pub name: String,
    pub focus: Option<bool>,
    pub run: Option<OldRunFromYaml>,
}

impl From<OldTabLayout> for OldLayoutTemplate {
    fn from(old_tab_layout: OldTabLayout) -> Self {
        OldLayoutTemplate {
            direction: old_tab_layout.direction,
            pane_name: old_tab_layout.pane_name.clone(),
            borderless: old_tab_layout.borderless,
            parts: old_tab_layout.parts.iter().map(|o| o.into()).collect(),
            split_size: old_tab_layout.split_size,
            focus: old_tab_layout.focus,
            run: old_tab_layout.run.clone(),
            body: false,
        }
    }
}

impl From<&OldTabLayout> for OldLayoutTemplate {
    fn from(old_tab_layout: &OldTabLayout) -> Self {
        OldLayoutTemplate {
            direction: old_tab_layout.direction,
            pane_name: old_tab_layout.pane_name.clone(),
            borderless: old_tab_layout.borderless,
            parts: old_tab_layout.parts.iter().map(|o| o.into()).collect(),
            split_size: old_tab_layout.split_size,
            focus: old_tab_layout.focus,
            run: old_tab_layout.run.clone(),
            body: false,
        }
    }
}

impl From<&mut OldTabLayout> for OldLayoutTemplate {
    fn from(old_tab_layout: &mut OldTabLayout) -> Self {
        OldLayoutTemplate {
            direction: old_tab_layout.direction,
            pane_name: old_tab_layout.pane_name.clone(),
            borderless: old_tab_layout.borderless,
            parts: old_tab_layout.parts.iter().map(|o| o.into()).collect(),
            split_size: old_tab_layout.split_size,
            focus: old_tab_layout.focus,
            run: old_tab_layout.run.clone(),
            body: false,
        }
    }
}

impl From<OldLayoutFromYamlIntermediate> for OldLayoutFromYaml {
    fn from(layout_from_yaml_intermediate: OldLayoutFromYamlIntermediate) -> Self {
        Self {
            template: layout_from_yaml_intermediate.template,
            borderless: layout_from_yaml_intermediate.borderless,
            tabs: layout_from_yaml_intermediate.tabs,
            session: layout_from_yaml_intermediate.session,
        }
    }
}

impl From<OldLayoutFromYaml> for OldLayoutFromYamlIntermediate {
    fn from(layout_from_yaml: OldLayoutFromYaml) -> Self {
        Self {
            template: layout_from_yaml.template,
            borderless: layout_from_yaml.borderless,
            tabs: layout_from_yaml.tabs,
            config: None,
            session: layout_from_yaml.session,
        }
    }
}

impl Default for OldLayoutFromYamlIntermediate {
    fn default() -> Self {
        OldLayoutFromYaml::default().into()
    }
}

impl Default for OldLayoutTemplate {
    fn default() -> Self {
        Self {
            direction: OldDirection::Horizontal,
            pane_name: None,
            body: false,
            borderless: false,
            parts: vec![OldLayoutTemplate {
                direction: OldDirection::Horizontal,
                pane_name: None,
                body: true,
                borderless: false,
                split_size: None,
                focus: None,
                run: None,
                parts: vec![],
            }],
            split_size: None,
            focus: None,
            run: None,
        }
    }
}

impl Default for OldDirection {
    fn default() -> Self {
        OldDirection::Horizontal
    }
}

// The unit test location.
#[path = "./unit/convert_layout_tests.rs"]
#[cfg(test)]
mod convert_layout_test;