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
//! # cursive view multiplexer
//!
//! This crate provides a view for the [cursive tui crate](https://github.com/gyscos/cursive).
//! It provides an easier way to display nesting view structures as for example in tmux in cursive.
//! All that has to be done is to insert the view into cursive and later to operate on the reference of it, to add, remove, switch views.
//!
//! Similar to tmux the user is able to resize, and switch between the current views, given they are focusable.
//!
//! # Usage example
//! ```rust
//! extern crate cursive;
//! extern crate cursive_multiplex;
//!
//! use cursive_multiplex::Mux;
//! use cursive::views::TextView;
//! use cursive::Cursive;
//!
//! fn main() {
//!     let (mut mux, node1) = Mux::new(TextView::new("Hello World".to_string()));
//!     let mut siv = Cursive::default();
//!     mux.add_right_of(TextView::new("Hello from me too!".to_string()), node1);
//!     siv.add_fullscreen_layer(mux);
//!
//!     // When your finished setting up
//!     // siv.run();
//! }
//! ```
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate log;

mod actions;
mod error;
mod id;
mod node;
mod path;

use cursive::direction::{Absolute, Direction};
use cursive::event::{Event, EventResult, Key};
use cursive::view::{Selector, View};
use cursive::{Printer, Vec2};
pub use error::*;
pub use id::Id;
use node::Node;
pub use path::Path;
use std::convert::TryFrom;

#[derive(Debug, PartialEq, Clone)]
enum Orientation {
    Vertical,
    Horizontal,
}

/// View holding information and managing multiplexer.
pub struct Mux {
    tree: indextree::Arena<Node>,
    root: indextree::NodeId,
    focus: indextree::NodeId,
    focus_up: Event,
    focus_down: Event,
    focus_left: Event,
    focus_right: Event,
    resize_left: Event,
    resize_right: Event,
    resize_up: Event,
    resize_down: Event,
}

impl View for Mux {
    fn draw(&self, printer: &Printer) {
        debug!("Current Focus: {}", self.focus);
        // println!("Mux currently focused: {}", printer.focused);
        self.rec_draw(printer, self.root)
    }

    fn needs_relayout(&self) -> bool {
        true
    }

    fn required_size(&mut self, constraint: Vec2) -> Vec2 {
        constraint
    }

    fn layout(&mut self, constraint: Vec2) {
        self.rec_layout(self.root, constraint);
    }

    fn take_focus(&mut self, _source: Direction) -> bool {
        true
    }

    fn focus_view(&mut self, _: &Selector) -> Result<(), ()> {
        Ok(())
    }

    fn on_event(&mut self, evt: Event) -> EventResult {
        let result = self
            .tree
            .get_mut(self.focus)
            .unwrap()
            .get_mut()
            .on_event(evt.relativized(Vec2::new(0, 0)));
        match result {
            EventResult::Ignored => match evt {
                _ if self.focus_left == evt => self.move_focus(Absolute::Left),
                _ if self.focus_right == evt => self.move_focus(Absolute::Right),
                _ if self.focus_up == evt => self.move_focus(Absolute::Up),
                _ if self.focus_down == evt => self.move_focus(Absolute::Down),
                _ if self.resize_left == evt => self.resize(Absolute::Left),
                _ if self.resize_right == evt => self.resize(Absolute::Right),
                _ if self.resize_up == evt => self.resize(Absolute::Up),
                _ if self.resize_down == evt => self.resize(Absolute::Down),
                _ => EventResult::Ignored,
            },
            result => result,
        }
    }
}

impl Mux {
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # fn main () {
    /// let (mut mux, node1) = cursive_multiplex::Mux::new(cursive::views::DummyView);
    /// # }
    /// ```
    pub fn new<T>(v: T) -> (Self, Id)
    where
        T: View,
    {
        let mut new_tree = indextree::Arena::new();
        let new_root = new_tree.new_node(Node::new_empty(Orientation::Horizontal));
        let mut new_mux = Mux {
            tree: new_tree,
            root: new_root,
            focus: new_root,
            focus_up: Event::Key(Key::Up),
            focus_down: Event::Key(Key::Down),
            focus_left: Event::Key(Key::Left),
            focus_right: Event::Key(Key::Right),
            resize_left: Event::Ctrl(Key::Left),
            resize_right: Event::Ctrl(Key::Right),
            resize_up: Event::Ctrl(Key::Up),
            resize_down: Event::Ctrl(Key::Down),
        };
        // borked if not succeeding
        let fst_view = new_mux.add_below(v, new_root).unwrap();
        (new_mux, fst_view)
    }

    /// Chainable setter for action
    pub fn with_move_focus_up(mut self, evt: Event) -> Self {
        self.focus_up = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_move_focus_down(mut self, evt: Event) -> Self {
        self.focus_down = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_move_focus_left(mut self, evt: Event) -> Self {
        self.focus_left = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_move_focus_right(mut self, evt: Event) -> Self {
        self.focus_right = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_resize_up(mut self, evt: Event) -> Self {
        self.resize_up = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_resize_down(mut self, evt: Event) -> Self {
        self.resize_down = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_resize_left(mut self, evt: Event) -> Self {
        self.resize_left = evt;
        self
    }
    /// Chainable setter for action
    pub fn with_resize_right(mut self, evt: Event) -> Self {
        self.resize_right = evt;
        self
    }

    /// Setter for action
    pub fn set_move_focus_up(&mut self, evt: Event) {
        self.focus_up = evt;
    }
    /// Setter for action
    pub fn set_move_focus_down(&mut self, evt: Event) {
        self.focus_down = evt;
    }
    /// Setter for action
    pub fn set_move_focus_left(&mut self, evt: Event) {
        self.focus_left = evt;
    }
    /// Setter for action
    pub fn set_move_focus_right(&mut self, evt: Event) {
        self.focus_right = evt;
    }
    /// Setter for action
    pub fn set_resize_up(&mut self, evt: Event) {
        self.resize_up = evt;
    }
    /// Setter for action
    pub fn set_resize_down(&mut self, evt: Event) {
        self.resize_down = evt;
    }
    /// Setter for action
    pub fn set_resize_left(&mut self, evt: Event) {
        self.resize_left = evt;
    }
    /// Setter for action
    pub fn set_resize_right(&mut self, evt: Event) {
        self.resize_right = evt;
    }

    /// Chainable setter for the focus the mux should have
    pub fn with_focus(mut self, id: Id) -> Self {
        let nodes: Vec<Id> = self.root.descendants(&self.tree).collect();
        if nodes.contains(&id) {
            self.focus = id;
        }
        self
    }

    /// Setter for the focus the mux should have
    pub fn set_focus(&mut self, id: Id) {
        let nodes: Vec<Id> = self.root.descendants(&self.tree).collect();
        if nodes.contains(&id) {
            self.focus = id;
        }
    }

    /// Returns the current focused view id.
    /// By default the newest node added to the multiplexer gets focused.
    /// Focus can also be changed by the user.
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # fn main () {
    /// let (mut mux, node1) = cursive_multiplex::Mux::new(cursive::views::DummyView);
    /// let current_focus = mux.get_focus();
    /// assert_eq!(current_focus, node1);
    /// # }
    /// ```
    pub fn get_focus(&self) -> Id {
        self.focus
    }

    fn rec_layout(&mut self, root: Id, constraint: Vec2) {
        match root.children(&self.tree).count() {
            1 => self.rec_layout(root.children(&self.tree).next().unwrap(), constraint),
            2 => {
                let left = root.children(&self.tree).next().unwrap();
                let right = root.children(&self.tree).last().unwrap();
                let const1;
                let const2;
                let root_data = &self.tree.get(root).unwrap().get();
                match root_data.orientation {
                    Orientation::Horizontal => {
                        const1 = Vec2::new(
                            Mux::add_offset(constraint.x / 2, root_data.split_ratio_offset),
                            constraint.y,
                        );
                        const2 = Vec2::new(
                            Mux::add_offset(constraint.x / 2, -root_data.split_ratio_offset) + 1,
                            constraint.y,
                        );
                        // Precautions have to be taken here as modification of the split is not possible elsewhere
                        if const1.x <= 3 {
                            self.tree
                                .get_mut(root)
                                .unwrap()
                                .get_mut()
                                .split_ratio_offset += 1;
                        } else if const1.x >= constraint.x - 3 {
                            self.tree
                                .get_mut(root)
                                .unwrap()
                                .get_mut()
                                .split_ratio_offset -= 1;
                        }
                    }
                    Orientation::Vertical => {
                        const1 = Vec2::new(
                            constraint.x,
                            Mux::add_offset(constraint.y / 2, root_data.split_ratio_offset),
                        );
                        const2 = Vec2::new(
                            constraint.x,
                            Mux::add_offset(constraint.y / 2, -root_data.split_ratio_offset) + 1,
                        );
                        // Precautions have to be taken here as modification of the split is not possible elsewhere
                        if const1.y <= 3 {
                            self.tree
                                .get_mut(root)
                                .unwrap()
                                .get_mut()
                                .split_ratio_offset += 1;
                        } else if const1.y >= constraint.y - 3 {
                            self.tree
                                .get_mut(root)
                                .unwrap()
                                .get_mut()
                                .split_ratio_offset -= 1;
                        }
                    }
                }
                self.rec_layout(left, const1);
                self.rec_layout(right, const2);
            }
            0 => {
                self.tree
                    .get_mut(root)
                    .unwrap()
                    .get_mut()
                    .layout_view(constraint);
            }
            _ => debug!("Illegal Number of Child Nodes"),
        }
    }

    fn add_offset(split: usize, offset: i16) -> usize {
        if offset < 0 {
            match usize::try_from(offset.abs()) {
                Ok(u) => {
                    if split < u {
                        split
                    } else {
                        split - u
                    }
                }
                Err(_) => split,
            }
        } else {
            match usize::try_from(offset) {
                Ok(u) => split + u,
                Err(_) => split,
            }
        }
    }

    fn rec_draw(&self, printer: &Printer, root: Id) {
        match root.children(&self.tree).count() {
            1 => self.rec_draw(printer, root.children(&self.tree).next().unwrap()),
            2 => {
                debug!("Print Children Nodes");
                let left = root.children(&self.tree).next().unwrap();
                let right = root.children(&self.tree).last().unwrap();
                let printer1;
                let printer2;
                let root_data = &self.tree.get(root).unwrap().get();
                match root_data.orientation {
                    Orientation::Horizontal => {
                        printer1 = printer.cropped(Vec2::new(
                            Mux::add_offset(printer.size.x / 2, root_data.split_ratio_offset),
                            printer.size.y,
                        ));
                        printer2 = printer
                            .offset(Vec2::new(
                                Mux::add_offset(printer.size.x / 2, root_data.split_ratio_offset)
                                    + 1,
                                0,
                            ))
                            .cropped(Vec2::new(
                                Mux::add_offset(printer.size.x / 2, -root_data.split_ratio_offset),
                                printer.size.y,
                            ));
                    }
                    Orientation::Vertical => {
                        printer1 = printer.cropped(Vec2::new(
                            printer.size.x,
                            Mux::add_offset(printer.size.y / 2, root_data.split_ratio_offset),
                        ));
                        printer2 = printer
                            .offset(Vec2::new(
                                0,
                                Mux::add_offset(printer.size.y / 2, root_data.split_ratio_offset)
                                    + 1,
                            ))
                            .cropped(Vec2::new(
                                printer.size.x,
                                Mux::add_offset(printer.size.y / 2, -root_data.split_ratio_offset),
                            ));
                    }
                }
                self.rec_draw(&printer1, left);
                match self.tree.get(root).unwrap().get().orientation {
                    Orientation::Vertical => {
                        if printer.size.y > 1 {
                            printer.print_hline(
                                Vec2::new(
                                    0,
                                    Mux::add_offset(
                                        printer.size.y / 2,
                                        root_data.split_ratio_offset,
                                    ),
                                ),
                                printer.size.x,
                                "─",
                            );
                        }
                    }
                    Orientation::Horizontal => {
                        if printer.size.x > 1 {
                            printer.print_vline(
                                Vec2::new(
                                    Mux::add_offset(
                                        printer.size.x / 2,
                                        root_data.split_ratio_offset,
                                    ),
                                    0,
                                ),
                                printer.size.y,
                                "│",
                            );
                        }
                    }
                }
                self.rec_draw(&printer2, right);
            }
            0 => {
                self.tree
                    .get(root)
                    .unwrap()
                    .get()
                    .draw(&printer.focused(self.focus == root));
            }
            _ => debug!("Illegal Number of Child Nodes"),
        }
    }
}

#[cfg(test)]
mod tree {
    use super::Mux;
    use cursive::event::{Event, Key};
    use cursive::traits::View;
    use cursive::views::DummyView;

    #[test]
    fn test_remove() {
        // General Remove test
        let (mut test_mux, node1) = Mux::new(DummyView);
        let node2 = test_mux.add_below(DummyView, node1).unwrap();
        let node3 = test_mux.add_below(DummyView, node2).unwrap();

        print_tree(&test_mux);
        test_mux.remove_id(node3).unwrap();
        print_tree(&test_mux);
        match test_mux.remove_id(node3) {
            Ok(_) => {
                print_tree(&test_mux);
                println!("Delete should have removed: {}", node3);
                assert!(false);
            }
            Err(_) => {}
        }
    }

    #[test]
    fn test_switch() {
        let (mut mux, node1) = Mux::new(DummyView);
        let node2 = mux.add_right_of(DummyView, node1).unwrap();
        let node3 = mux.add_left_of(DummyView, node2).unwrap();

        mux.switch_views(node1, node3).unwrap();
    }

    #[test]
    fn test_nesting() {
        println!("Nesting Test");

        let (mut mux, _) = Mux::new(DummyView);

        let mut nodes = Vec::new();

        for _ in 0..10 {
            print_tree(&mux);
            match mux.add_right_of(
                DummyView,
                if let Some(x) = nodes.last() {
                    *x
                } else {
                    mux.root
                },
            ) {
                Ok(node) => {
                    nodes.push(node);
                }
                Err(_) => {
                    assert!(false);
                }
            }
            match mux.add_right_of(DummyView, *nodes.last().unwrap()) {
                Ok(node) => {
                    nodes.push(node);
                }
                Err(_) => {
                    assert!(false);
                }
            }
        }

        for node in nodes.iter() {
            mux.focus = *node;
            direction_test(&mut mux);
        }
    }

    fn print_tree(mux: &Mux) {
        print!("Current Tree: ");
        for node in mux.root.descendants(&mux.tree) {
            print!("{},", node);
        }
        println!("");
    }

    fn direction_test(mux: &mut Mux) {
        // This is a shotgun approach to have a look if any unforeseen focus moves could happen, resulting in a uncertain state
        mux.on_event(Event::Key(Key::Up));
        mux.on_event(Event::Key(Key::Left));
        mux.on_event(Event::Key(Key::Down));
        mux.on_event(Event::Key(Key::Right));
        mux.on_event(Event::Key(Key::Up));
        mux.on_event(Event::Key(Key::Left));
        mux.on_event(Event::Key(Key::Left));
        mux.on_event(Event::Key(Key::Down));
        mux.on_event(Event::Key(Key::Right));
        mux.on_event(Event::Key(Key::Up));
        mux.on_event(Event::Key(Key::Left));
    }
}