aboutsummaryrefslogtreecommitdiffstats
path: root/zellij-server/src/tab/swap_layouts.rs
blob: 0fc45bb97f61571b1839e94a8b2576f0a7bd5c93 (plain) (blame)
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
use crate::panes::{FloatingPanes, TiledPanes};
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
use zellij_utils::{
    input::layout::{
        FloatingPaneLayout, LayoutConstraint, SwapFloatingLayout, SwapTiledLayout, TiledPaneLayout,
    },
    pane_size::{PaneGeom, Size},
};

#[derive(Clone, Debug, Default)]
pub struct SwapLayouts {
    swap_tiled_layouts: Vec<SwapTiledLayout>,
    swap_floating_layouts: Vec<SwapFloatingLayout>,
    current_floating_layout_position: usize,
    current_tiled_layout_position: usize,
    is_floating_damaged: bool,
    is_tiled_damaged: bool,
    /// Positions of layouts synthesized for the responsive collapse.
    synthesized_tiled_positions: Vec<usize>,
    display_area: Rc<RefCell<Size>>, // includes all panes (including eg. the status bar and tab bar in the default layout)
}

impl SwapLayouts {
    pub fn new(
        swap_layouts: (Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>),
        display_area: Rc<RefCell<Size>>,
    ) -> Self {
        let display_area = display_area.clone();
        SwapLayouts {
            swap_tiled_layouts: swap_layouts.0,
            swap_floating_layouts: swap_layouts.1,
            is_floating_damaged: false,
            is_tiled_damaged: false,
            display_area,
            ..Default::default()
        }
    }
    pub fn set_base_layout(&mut self, layout: (TiledPaneLayout, Vec<FloatingPaneLayout>)) {
        let mut base_swap_tiled_layout = BTreeMap::new();
        let mut base_swap_floating_layout = BTreeMap::new();
        let tiled_panes_count = layout.0.pane_count();
        let floating_panes_count = layout.1.len();
        // we set ExactPanes to the current panes in the layout, because the base layout is not
        // intended to be progressive - i.e. to have additional panes added to it
        // we also don't want it to be applied for less than the expected amount of panes, because
        // then unintended things can happen
        // we still want to keep it around in case we'd like to swap layouts without adding panes
        base_swap_tiled_layout.insert(LayoutConstraint::ExactPanes(tiled_panes_count), layout.0);
        base_swap_floating_layout
            .insert(LayoutConstraint::ExactPanes(floating_panes_count), layout.1);
        self.swap_tiled_layouts
            .insert(0, (base_swap_tiled_layout, Some("BASE".into())));
        self.swap_floating_layouts
            .insert(0, (base_swap_floating_layout, Some("BASE".into())));
        self.current_tiled_layout_position = 0;
        self.current_floating_layout_position = 0;
    }
    pub fn set_swap_tiled_layouts(&mut self, new_swap_tiled_layouts: Vec<SwapTiledLayout>) {
        self.swap_tiled_layouts = new_swap_tiled_layouts;
        self.current_tiled_layout_position = 0;
    }
    pub fn set_swap_floating_layouts(
        &mut self,
        new_swap_floating_layouts: Vec<SwapFloatingLayout>,
    ) {
        self.swap_floating_layouts = new_swap_floating_layouts;
        self.current_floating_layout_position = 0;
    }
    pub fn set_is_floating_damaged(&mut self) {
        self.is_floating_damaged = true;
    }
    pub fn set_is_tiled_damaged(&mut self) {
        self.is_tiled_damaged = true;
    }
    pub fn reset_floating_damage(&mut self) {
        self.is_floating_damaged = false;
    }
    pub fn is_floating_damaged(&self) -> bool {
        self.is_floating_damaged
    }
    pub fn is_tiled_damaged(&self) -> bool {
        self.is_tiled_damaged
    }
    /// Append a synthesized "flatten into one stack" layout under `name`, and
    /// return its position.
    ///
    /// A custom layout file only gets swap layouts from a hand-written sibling
    /// `<layout>.swap.kdl`, so most layouts have none and the responsive
    /// collapse has nothing to select. Rather than require that file, synthesize
    /// the one layout the collapse actually needs.
    ///
    /// Appended rather than inserted so it cannot shift the position of the BASE
    /// layout at 0, which is what a collapse restores back to.
    pub fn append_synthesized_stack_layout(&mut self, name: &str) -> usize {
        // MinPanes(2) because a "stack" of one pane is just that pane, and
        // collapsing to it would be a no-op that still counted as collapsed
        self.append_synthesized_layout(
            name,
            LayoutConstraint::MinPanes(2),
            TiledPaneLayout::single_stack(),
        )
    }
    /// Append a synthesized "spread into a grid" layout, and return its position.
    ///
    /// The way back out of a collapse when the layout that was active before it
    /// no longer applies -- typically BASE, which is pinned to the pane count it
    /// was written with, so adding a single pane leaves the tab with nothing to
    /// expand into and stuck stacked.
    pub fn append_synthesized_grid_layout(&mut self, name: &str) -> usize {
        // NoConstraint: this is the fallback, so it must never be the thing that
        // fails to apply. Feasibility is still checked against the display area.
        self.append_synthesized_layout(
            name,
            LayoutConstraint::NoConstraint,
            TiledPaneLayout::single_grid(),
        )
    }
    fn append_synthesized_layout(
        &mut self,
        name: &str,
        constraint: LayoutConstraint,
        layout: TiledPaneLayout,
    ) -> usize {
        if let Some(existing) = self.position_of_tiled_layout_named(name) {
            return existing;
        }
        let mut constraints = BTreeMap::new();
        constraints.insert(constraint, layout);
        self.swap_tiled_layouts
            .push((constraints, Some(name.to_string())));
        let position = self.swap_tiled_layouts.len() - 1;
        self.synthesized_tiled_positions.push(position);
        position
    }
    /// Whether this tab has any tiled swap layout the USER defined.
    ///
    /// "BASE" is inserted from the tab's own layout, and the synthesized stack is
    /// ours, so neither says anything about user intent. Matters because the
    /// damaged flag means two different things: with user swap layouts it tracks
    /// "the arrangement was changed by hand", but with none it is set on the
    /// first pane added -- relayout finds nothing applicable and gives up -- and
    /// then never clears, which would disable the responsive collapse entirely
    /// for exactly the bare layouts it is most useful for.
    pub fn has_user_defined_tiled_layouts(&self) -> bool {
        self.swap_tiled_layouts
            .iter()
            .enumerate()
            .any(|(position, (_constraints, name))| {
                !self.synthesized_tiled_positions.contains(&position)
                    && name.as_deref() != Some("BASE")
            })
    }
    /// Position of the swap tiled layout with this name, if any.
    ///
    /// Used by the responsive-layout switch, which selects a layout BY NAME
    /// rather than by cycling. Deliberately name-based: adding a size variant to
    /// LayoutConstraint would change a type that crosses both the plugin
    /// protobuf API and the client/server contract, and the committed prost
    /// assets cannot be regenerated here (no protoc).
    pub fn position_of_tiled_layout_named(&self, name: &str) -> Option<usize> {
        self.swap_tiled_layouts
            .iter()
            .position(|(_constraints, layout_name)| {
                layout_name.as_deref().map(str::trim) == Some(name.trim())
            })
    }
    pub fn current_tiled_layout_position(&self) -> usize {
        self.current_tiled_layout_position
    }
    /// Jump straight to a swap layout position, instead of cycling to it.
    pub fn set_tiled_layout_position(&mut self, position: usize) {
        if position < self.swap_tiled_layouts.len() {
            self.current_tiled_layout_position = position;
        }
    }
    /// The layout at a given position, resolved against the current pane count
    /// and display area.
    ///
    /// Mirrors the per-position body of swap_tiled_panes (same constraint check,
    /// same position_panes_in_space feasibility check) but WITHOUT the cycling,
    /// so a specific layout can be selected directly.
    pub fn tiled_layout_at(
        &self,
        position: usize,
        tiled_panes: &TiledPanes,
    ) -> Option<TiledPaneLayout> {
        let swap_layout = self.swap_tiled_layouts.iter().nth(position)?;
        for (constraint, layout) in swap_layout.0.iter() {
            if self.state_fits_tiled_panes_constraint(constraint, tiled_panes) {
                let display_area = self.display_area.borrow();
                let pane_count = tiled_panes.visible_panes_count();
                let display_area = PaneGeom::from(&*display_area);
                if layout
                    .position_panes_in_space(&display_area, Some(pane_count), false, true)
                    .is_ok()
                {
                    return Some(layout.clone());
                }
            }
        }
        None
    }
    pub fn tiled_layout_info(&self) -> (Option<String>, bool) {
        // (swap_layout_name, is_swap_layout_dirty)
        match self
            .swap_tiled_layouts
            .iter()
            .nth(self.current_tiled_layout_position)
        {
            Some(current_tiled_layout) => (
                current_tiled_layout.1.clone().or_else(|| {
                    Some(format!(
                        "Layout #{}",
                        self.current_tiled_layout_position + 1
                    ))
                }),
                self.is_tiled_damaged,
            ),
            None => (None, self.is_tiled_damaged),
        }
    }
    pub fn floating_layout_info(&self) -> (Option<String>, bool) {
        // (swap_layout_name, is_swap_layout_dirty)
        match self
            .swap_floating_layouts
            .iter()
            .nth(self.current_floating_layout_position)
        {
            Some(current_floating_layout) => (
                current_floating_layout.1.clone().or_else(|| {
                    Some(format!(
                        "Layout #{}",
                        self.current_floating_layout_position + 1
                    ))
                }),
                self.is_floating_damaged,
            ),
            None => (None, self.is_floating_damaged),
        }
    }
    pub fn swap_floating_panes(
        &mut self,
        floating_panes: &FloatingPanes,
        search_backwards: bool,
    ) -> Option<Vec<FloatingPaneLayout>> {
        if self.swap_floating_layouts.is_empty() {
            return None;
        }
        let initial_position = self.current_floating_layout_position;

        macro_rules! progress_layout {
            () => {{
                if search_backwards {
                    if self.current_floating_layout_position == 0 {
                        self.current_floating_layout_position =
                            self.swap_floating_layouts.len().saturating_sub(1);
                    } else {
                        self.current_floating_layout_position -= 1;
                    }
                } else {
                    self.current_floating_layout_position += 1;
                }
            }};
        }

        if !self.is_floating_damaged
            && self
                .swap_floating_layouts
                .iter()
                .nth(self.current_floating_layout_position)
                .is_some()
        {
            progress_layout!();
        }
        self.is_floating_damaged = false;
        loop {
            match self
                .swap_floating_layouts
                .iter()
                .nth(self.current_floating_layout_position)
            {
                Some(swap_layout) => {
                    for (constraint, layout) in swap_layout.0.iter() {
                        if self.state_fits_floating_panes_constraint(constraint, floating_panes) {
                            return Some(layout.clone());
                        };
                    }
                    progress_layout!();
                },
                None => {
                    self.current_floating_layout_position = 0;
                },
            };
            if self.current_floating_layout_position == initial_position {
                break;
            }
        }
        None
    }
    fn state_fits_tiled_panes_constraint(
        &self,
        constraint: &LayoutConstraint,
        tiled_panes: &TiledPanes,
    ) -> bool {
        match constraint {
            LayoutConstraint::MaxPanes(max_panes) => {
                tiled_panes.visible_panes_count() <= *max_panes
            },
            LayoutConstraint::MinPanes(min_panes) => {
                tiled_panes.visible_panes_count() >= *min_panes
            },
            LayoutConstraint::ExactPanes(pane_count) => {
                tiled_panes.visible_panes_count() == *pane_count
            },
            LayoutConstraint::NoConstraint => true,
        }
    }
    fn state_fits_floating_panes_constraint(
        &self,
        constraint: &LayoutConstraint,
        floating_panes: &FloatingPanes,
    ) -> bool {
        match constraint {
            LayoutConstraint::MaxPanes(max_panes) => {
                floating_panes.visible_panes_count() <= *max_panes
            },
            LayoutConstraint::MinPanes(min_panes) => {
                floating_panes.visible_panes_count() >= *min_panes
            },
            LayoutConstraint::ExactPanes(pane_count) => {
                floating_panes.visible_panes_count() == *pane_count
            },
            LayoutConstraint::NoConstraint => true,
        }
    }
    pub fn swap_tiled_panes(
        &mut self,
        tiled_panes: &TiledPanes,
        search_backwards: bool,
    ) -> Option<TiledPaneLayout> {
        if self.swap_tiled_layouts.is_empty() {
            return None;
        }

        macro_rules! progress_layout {
            () => {{
                if search_backwards {
                    if self.current_tiled_layout_position == 0 {
                        self.current_tiled_layout_position =
                            self.swap_tiled_layouts.len().saturating_sub(1);
                    } else {
                        self.current_tiled_layout_position -= 1;
                    }
                } else {
                    self.current_tiled_layout_position += 1;
                }
            }};
        }

        let initial_position = self.current_tiled_layout_position;
        if !self.is_tiled_damaged
            && self
                .swap_tiled_layouts
                .iter()
                .nth(self.current_tiled_layout_position)
                .is_some()
        {
            progress_layout!();
        }
        self.is_tiled_damaged = false;
        loop {
            match self
                .swap_tiled_layouts
                .iter()
                .nth(self.current_tiled_layout_position)
            {
                Some(swap_layout) => {
                    for (constraint, layout) in swap_layout.0.iter() {
                        if self.state_fits_tiled_panes_constraint(constraint, tiled_panes) {
                            let focus_layout_if_not_focused = true;
                            let display_area = self.display_area.borrow();
                            // TODO: reuse the assets from position_panes_in_space here?
                            let pane_count = tiled_panes.visible_panes_count();
                            let display_area = PaneGeom::from(&*display_area);
                            if layout
                                .position_panes_in_space(
                                    &display_area,
                                    Some(pane_count),
                                    false,
                                    focus_layout_if_not_focused,
                                )
                                .is_ok()
                            {
                                return Some(layout.clone());
                            }
                        };
                    }
                    progress_layout!();
                },
                None => {
                    self.current_tiled_layout_position = 0;
                },
            };
            if self.current_tiled_layout_position == initial_position {
                break;
            }
        }
        None
    }
}