cursive-multiplex 0.1.1

A tmux like multiplexer for gyscos/cursive views
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! # 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::{MuxBuilder, Mux};
//! use cursive::views::TextView;
//! use cursive::Cursive;
//!
//! fn main() {
//!     let (mut mux, node1) = MuxBuilder::new().build(TextView::new("Hello World".to_string()));
//!     let mut siv = Cursive::default();
//!     mux.add_horizontal_id(TextView::new("Hello from me too!".to_string()), node1);
//!     siv.add_fullscreen_layer(mux);
//!
//!     // When your finished setting up
//!     // siv.run();
//! }
//! ```

extern crate cursive;
extern crate failure;
extern crate indextree;
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate log;

mod error;

use cursive::direction::{Absolute, Direction};
use cursive::event::{Event, EventResult, Key};
use cursive::view::{Selector, View};
use cursive::Printer;
use cursive::Vec2;
use error::{AddViewError, RemoveViewError, SwitchError};
use std::convert::TryFrom;

/// Path is a recursive enum made to be able to identify a pane by it's actual location in the multiplexer. An upper Pane on the left side for example would have the path `Path::LeftOrUp(Box::new(Some(Path::LeftOrUp(Box::new(None)))))`.
#[derive(Debug)]
pub enum Path {
    LeftOrUp(Box<Option<Path>>),
    RightOrDown(Box<Option<Path>>),
}

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

#[derive(Debug, PartialEq)]
enum SearchPath {
    Left,
    Right,
    Up,
    Down,
}

/// Identifier for views in binary tree of mux, typically returned after adding a new view to the multiplexer.
pub type Id = indextree::NodeId;

/// 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,
}

/// Builder for the multiplexer, default values for actions are set, but can be modified by calling the corresponding methods of the builder instance.
/// ```rust
/// # fn main() {
/// let builder = cursive_multiplex::MuxBuilder::new();
/// # }
/// ```
pub struct MuxBuilder {
    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 MuxBuilder {
    pub fn new() -> Self {
        MuxBuilder {
            focus_up: Event::Shift(Key::Up),
            focus_down: Event::Shift(Key::Down),
            focus_left: Event::Shift(Key::Left),
            focus_right: Event::Shift(Key::Right),
            resize_up: Event::Ctrl(Key::Up),
            resize_down: Event::Ctrl(Key::Down),
            resize_left: Event::Ctrl(Key::Left),
            resize_right: Event::Ctrl(Key::Right),
        }
    }

    /// Initialization for a new mutliplexer view, view to be provided is the first view to be displayed. It's best to use the main view you want to use here later on, but if neccessary views can also be switched.
    /// Returned is a tuple consisting of the multiplexer view itself and the id assigend to the passed view.
    ///
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # fn main () {
    /// let builder = cursive_multiplex::MuxBuilder::new();
    /// let (mut mux, node1) = builder.build(cursive::views::DummyView);
    /// # }
    /// ```
    pub fn build<T>(&self, v: T) -> (Mux, Id)
    where
        T: View,
    {
        let root_node = Node {
            view: None,
            split_ratio_offset: 0,
            orientation: Orientation::Horizontal,
        };
        let mut new_tree = indextree::Arena::new();
        let new_root = new_tree.new_node(root_node);

        let mut new_mux = Mux {
            tree: new_tree,
            root: new_root,
            focus: new_root,
            focus_up: self.focus_up.clone(),
            focus_down: self.focus_down.clone(),
            focus_left: self.focus_left.clone(),
            focus_right: self.focus_right.clone(),
            resize_left: self.resize_left.clone(),
            resize_right: self.resize_right.clone(),
            resize_up: self.resize_up.clone(),
            resize_down: self.resize_down.clone(),
        };
        // borked if not succeeding
        let fst_view = new_mux.add_horizontal_id(v, new_root).unwrap();
        (new_mux, fst_view)
    }

    pub fn focus_up(&mut self, evt: Event) -> &mut Self {
        self.focus_up = evt;
        self
    }
    pub fn focus_down(&mut self, evt: Event) -> &mut Self {
        self.focus_down = evt;
        self
    }
    pub fn focus_left(&mut self, evt: Event) -> &mut Self {
        self.focus_left = evt;
        self
    }
    pub fn focus_right(&mut self, evt: Event) -> &mut Self {
        self.focus_right = evt;
        self
    }
    pub fn resize_left(&mut self, evt: Event) -> &mut Self {
        self.resize_left = evt;
        self
    }
    pub fn resize_right(&mut self, evt: Event) -> &mut Self {
        self.resize_right = evt;
        self
    }
    pub fn resize_up(&mut self, evt: Event) -> &mut Self {
        self.resize_up = evt;
        self
    }
    pub fn resize_down(&mut self, evt: Event) -> &mut Self {
        self.resize_down = evt;
        self
    }
}

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,
        }
    }
}

struct Node {
    view: Option<Box<dyn View>>,
    orientation: Orientation,
    split_ratio_offset: i16,
}

impl Node {
    fn new<T>(v: T, orit: Orientation) -> Self
    where
        T: View,
    {
        Self {
            view: Some(Box::new(v)),
            orientation: orit,
            split_ratio_offset: 0,
        }
    }

    fn has_view(&self) -> bool {
        match self.view {
            Some(_) => true,
            None => false,
        }
    }

    fn layout_view(&mut self, vec: Vec2) {
        if let Some(x) = self.view.as_mut() {
            x.layout(vec);
        }
    }

    fn on_event(&mut self, evt: Event) -> EventResult {
        if let Some(view) = self.view.as_mut() {
            view.on_event(evt)
        } else {
            EventResult::Ignored
        }
    }

    fn draw(&self, printer: &Printer) {
        match self.view {
            Some(ref view) => {
                view.draw(printer);
            }
            None => {}
        }
    }

    fn take_focus(&mut self) -> bool {
        if let Some(view) = self.view.as_mut() {
            view.take_focus(Direction::none())
        } else {
            false
        }
    }
}

impl Mux {
    /// 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::MuxBuilder::new().build(cursive::views::DummyView);
    /// let current_focus = mux.get_focus();
    /// assert_eq!(current_focus, node1);
    /// # }
    /// ```
    pub fn get_focus(&self) -> Id {
        self.focus
    }

    fn resize(&mut self, direction: Absolute) -> EventResult {
        let orit = {
            match direction {
                Absolute::Left | Absolute::Right => Orientation::Horizontal,
                Absolute::Up | Absolute::Down => Orientation::Vertical,
                _ => Orientation::Horizontal,
            }
        };

        let mut parent = self.focus.ancestors(&self.tree).nth(1);
        while parent.is_some() {
            if let Some(view) = self.tree.get_mut(parent.unwrap()) {
                if view.get().orientation == orit {
                    match direction {
                        Absolute::Left | Absolute::Up => {
                            view.get_mut().split_ratio_offset -= 1;
                            return EventResult::Consumed(None);
                        }
                        Absolute::Right | Absolute::Down => {
                            view.get_mut().split_ratio_offset += 1;
                            return EventResult::Consumed(None);
                        }
                        _ => {}
                    }
                } else {
                    parent = parent.unwrap().ancestors(&self.tree).nth(1);
                }
            }
        }
        EventResult::Ignored
    }

    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"),
        }
    }

    /// Add the given view to the tree based on the path, if the path is too specific it will be truncated, if not specific enough an error will be returned.
    /// When successful `Ok()` will contain the assigned `Id`
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # use cursive_multiplex::{Path};
    /// # fn main () {
    /// # let (mut mux, node1) = cursive_multiplex::MuxBuilder::new().build(cursive::views::DummyView);
    /// # let current_focus = mux.get_focus();
    /// # assert_eq!(current_focus, node1);
    /// let new_node = mux.add_horizontal_path(cursive::views::DummyView, Path::RightOrDown(Box::new(None))).unwrap();
    /// # }
    /// ```
    pub fn add_horizontal_path<T>(&mut self, v: T, path: Path) -> Result<Id, AddViewError>
    where
        T: View,
    {
        self.add_node_path(v, Some(path), Orientation::Horizontal, self.root)
    }

    /// Add the given view to the tree based on the path, if the path is too specific it will be truncated, if not specific enough an error will be returned.
    /// When successful `Ok()` will contain the assigned `Id`
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # use cursive_multiplex::{Path};
    /// # fn main () {
    /// # let (mut mux, node1) = cursive_multiplex::MuxBuilder::new().build(cursive::views::DummyView);
    /// # let current_focus = mux.get_focus();
    /// # assert_eq!(current_focus, node1);
    /// let new_node = mux.add_vertical_path(cursive::views::DummyView, Path::RightOrDown(Box::new(None))).unwrap();
    /// # }
    /// ```
    pub fn add_vertical_path<T>(&mut self, v: T, path: Path) -> Result<Id, AddViewError>
    where
        T: View,
    {
        self.add_node_path(v, Some(path), Orientation::Vertical, self.root)
    }

    fn add_node_path<T>(
        &mut self,
        v: T,
        path: Option<Path>,
        orientation: Orientation,
        cur_node: indextree::NodeId,
    ) -> Result<Id, AddViewError>
    where
        T: View,
    {
        match path {
            Some(path_val) => {
                match path_val {
                    Path::LeftOrUp(ch) => {
                        match cur_node.children(&self.tree).nth(0) {
                            Some(node) => self.add_node_path(v, *ch, orientation, node),
                            None => {
                                // Truncate
                                self.add_node_path(v, None, orientation, cur_node)
                            }
                        }
                    }
                    Path::RightOrDown(ch) => {
                        if cur_node.children(&self.tree).count() < 2 {
                            match cur_node.children(&self.tree).last() {
                                Some(node) => {
                                    self.add_node_path(v, *ch, orientation, node)
                                    // Ok(self)
                                }
                                None => {
                                    // Truncate, if too specific
                                    self.add_node_path(v, None, orientation, cur_node)
                                }
                            }
                        } else {
                            Err(AddViewError::InvalidPath { path: ch.unwrap() })
                        }
                    }
                }
            }
            None if cur_node.following_siblings(&self.tree).count()
                + cur_node.preceding_siblings(&self.tree).count()
                < 2 =>
            {
                let new_node = self.tree.new_node(Node::new(v, Orientation::Horizontal));
                cur_node.insert_after(new_node, &mut self.tree);
                self.focus = new_node;
                debug!("Changed Focus: {}", new_node);
                Ok(new_node)
            }
            None => {
                // First element is node itself, second direct parent
                let parent = cur_node.ancestors(&self.tree).nth(1).unwrap();
                cur_node.detach(&mut self.tree);

                let new_intermediate = self.tree.new_node(Node {
                    view: None,
                    split_ratio_offset: 0,
                    orientation: Orientation::Horizontal,
                });

                parent.append(new_intermediate, &mut self.tree);
                new_intermediate.append(cur_node, &mut self.tree);
                let new_node = self.tree.new_node(Node::new(v, Orientation::Horizontal));
                new_intermediate.append(new_node, &mut self.tree);
                self.focus = new_node;
                debug!("Changed Focus: {}", new_node);
                Ok(new_node)
            }
        }
    }

    /// Add the given view to the tree based on the path, if the path is too specific it will be truncated, if not specific enough an error will be returned.
    /// When successful `Ok()` will contain the assigned `Id`
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # use cursive_multiplex::{Path};
    /// # fn main () {
    /// let (mut mux, node1) = cursive_multiplex::MuxBuilder::new().build(cursive::views::DummyView);
    /// let new_node = mux.add_horizontal_id(cursive::views::DummyView, node1).unwrap();
    /// # }
    /// ```
    pub fn add_horizontal_id<T>(&mut self, v: T, id: Id) -> Result<Id, AddViewError>
    where
        T: View,
    {
        self.add_node_id(v, id, Orientation::Horizontal)
    }

    fn add_node_id<T>(&mut self, v: T, id: Id, orientation: Orientation) -> Result<Id, AddViewError>
    where
        T: View,
    {
        let new_node = self.tree.new_node(Node::new(v, Orientation::Horizontal));

        let mut node_id;
        if let Some(parent) = id.ancestors(&self.tree).nth(1) {
            node_id = parent;
        } else {
            node_id = id;
        }

        if node_id.children(&self.tree).count() < 2
            && !self.tree.get(node_id).unwrap().get().has_view()
        {
            node_id.append(new_node, &mut self.tree);
            self.tree.get_mut(node_id).unwrap().get_mut().orientation = orientation;
        } else {
            // First element is node itself, second direct parent
            let parent = node_id;
            node_id = id;

            let position: Path;
            if parent.children(&self.tree).next().unwrap() == node_id {
                position = Path::LeftOrUp(Box::new(None));
            } else {
                position = Path::RightOrDown(Box::new(None));
            }

            node_id.detach(&mut self.tree);

            let new_intermediate = self.tree.new_node(Node {
                view: None,
                split_ratio_offset: 0,
                orientation: orientation,
            });
            match position {
                Path::RightOrDown(_) => {
                    parent.append(new_intermediate, &mut self.tree);
                }
                Path::LeftOrUp(_) => {
                    parent.prepend(new_intermediate, &mut self.tree);
                }
            }
            new_intermediate.append(node_id, &mut self.tree);
            new_intermediate.append(new_node, &mut self.tree);
            debug!("Changed order");
        }

        self.focus = new_node;
        debug!("Changed Focus: {}", new_node);
        Ok(new_node)
    }

    /// Add the given view to the tree based on the path, if the path is too specific it will be truncated, if not specific enough an error will be returned.
    /// When successful `Ok()` will contain the assigned `Id`
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # use cursive_multiplex::{Path};
    /// # fn main () {
    /// let (mut mux, node1) = cursive_multiplex::MuxBuilder::new().build(cursive::views::DummyView);
    /// let new_node = mux.add_vertical_id(cursive::views::DummyView, node1).unwrap();
    /// # }
    /// ```
    pub fn add_vertical_id<T>(&mut self, v: T, id: Id) -> Result<Id, AddViewError>
    where
        T: View,
    {
        self.add_node_id(v, id, Orientation::Vertical)
    }

    /// Removes the given id from the multiplexer, returns an error if not a valid id contained in the tree or the lone root of the tree.
    /// When successful the Id of the removed Node is returned.
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # use cursive_multiplex::{Path};
    /// # fn main () {
    /// # let (mut mux, node1) = cursive_multiplex::MuxBuilder::new().build(cursive::views::DummyView);
    /// let new_node = mux.add_vertical_id(cursive::views::DummyView, node1).unwrap();
    /// mux.remove_id(new_node);
    /// # }
    /// ```
    pub fn remove_id(&mut self, id: Id) -> Result<Id, RemoveViewError> {
        let desc: Vec<Id> = self.root.descendants(&self.tree).collect();
        if desc.contains(&id) {
            let sib_id: Id;
            if id.preceding_siblings(&self.tree).count() > 1 {
                sib_id = id.preceding_siblings(&self.tree).nth(1).unwrap();
            } else if id.following_siblings(&self.tree).count() > 1 {
                sib_id = id.following_siblings(&self.tree).nth(1).unwrap();
            } else {
                return Err(RemoveViewError::Generic {});
            }
            let parent = id.ancestors(&self.tree).nth(1).unwrap();
            id.detach(&mut self.tree);

            if let Some(anker) = parent.ancestors(&self.tree).nth(1) {
                if anker.children(&self.tree).next().unwrap() == parent {
                    parent.detach(&mut self.tree);
                    anker.prepend(sib_id, &mut self.tree);
                    self.focus = sib_id;
                    Ok(id)
                } else {
                    parent.detach(&mut self.tree);
                    anker.append(sib_id, &mut self.tree);
                    self.focus = sib_id;
                    Ok(id)
                }
            } else {
                self.root = sib_id;
                self.focus = sib_id;
                Ok(id)
            }
        } else {
            Err(RemoveViewError::InvalidId { id: id })
        }
    }

    /// Allows for position switching of two views, returns error if ids not in multiplexer.
    /// When successful empty `Ok(())`
    /// # Example
    /// ```
    /// # extern crate cursive;
    /// # use cursive_multiplex::{Path};
    /// # fn main () {
    /// # let (mut mux, node1) = cursive_multiplex::MuxBuilder::new().build(cursive::views::DummyView);
    /// let daniel = mux.add_vertical_id(cursive::views::DummyView, node1).unwrap();
    /// let the_cooler_daniel = mux.add_vertical_id(cursive::views::DummyView, node1).unwrap();
    /// // Oops I wanted the cooler daniel in another spot
    /// mux.switch_views(daniel, the_cooler_daniel);
    /// # }
    /// ```
    pub fn switch_views(&mut self, fst: Id, snd: Id) -> Result<(), SwitchError> {
        if let Some(parent1) = fst.ancestors(&self.tree).nth(1) {
            if let Some(parent2) = snd.ancestors(&self.tree).nth(1) {
                if parent1.children(&self.tree).next().unwrap() == fst {
                    fst.detach(&mut self.tree);
                    if parent2.children(&self.tree).next().unwrap() == snd {
                        snd.detach(&mut self.tree);
                        parent1.prepend(snd, &mut self.tree);
                        parent2.prepend(fst, &mut self.tree);
                        Ok(())
                    } else {
                        snd.detach(&mut self.tree);
                        parent1.prepend(snd, &mut self.tree);
                        parent2.append(fst, &mut self.tree);
                        Ok(())
                    }
                } else {
                    fst.detach(&mut self.tree);
                    if parent2.children(&self.tree).next().unwrap() == snd {
                        snd.detach(&mut self.tree);
                        parent1.append(snd, &mut self.tree);
                        parent2.prepend(fst, &mut self.tree);
                        Ok(())
                    } else {
                        snd.detach(&mut self.tree);
                        parent1.append(snd, &mut self.tree);
                        parent2.append(fst, &mut self.tree);
                        Ok(())
                    }
                }
            } else {
                Err(SwitchError::NoParent { from: snd, to: fst })
            }
        } else {
            Err(SwitchError::NoParent { from: fst, to: snd })
        }
    }

    fn move_focus(&mut self, direction: Absolute) -> EventResult {
        match self.search_focus_path(
            direction,
            self.focus.ancestors(&self.tree).nth(1).unwrap(),
            self.focus,
        ) {
            Ok((path, turn_point)) => {
                // Traverse the path down again
                if let Some(focus) = self.traverse_search_path(path, turn_point) {
                    if self.tree.get_mut(focus).unwrap().get_mut().take_focus() {
                        self.focus = focus;
                        EventResult::Consumed(None)
                    } else {
                        debug!("Focus rejected by {}", focus);
                        EventResult::Ignored
                    }
                } else {
                    EventResult::Ignored
                }
            }
            Err(_) => EventResult::Ignored,
        }
    }

    fn traverse_search_path(&self, mut path: Vec<SearchPath>, turn_point: Id) -> Option<Id> {
        let mut cur_node = turn_point;

        // println!("Path Begin: {:?}", path);
        while let Some(step) = path.pop() {
            // println!("Next Step: {:?}", step);
            match self.traverse_single_node(step, turn_point, cur_node) {
                Some(node) => {
                    // println!("{}", node);
                    cur_node = node;
                }
                None => {
                    // Truncate remaining path
                    // cur_node = cur_node.children(&self.tree).next().unwrap();
                    break;
                }
            }
        }

        while !self.tree.get(cur_node).unwrap().get().has_view() {
            match cur_node.children(&self.tree).next() {
                Some(node) => cur_node = node,
                None => return None,
            }
        }

        Some(cur_node)
    }

    fn traverse_single_node(&self, action: SearchPath, turn_point: Id, cur_node: Id) -> Option<Id> {
        let left = || -> Option<Id> {
            if let Some(left) = cur_node.children(&self.tree).next() {
                Some(left)
            } else {
                None
            }
        };

        let right = || -> Option<Id> {
            if let Some(right) = cur_node.children(&self.tree).last() {
                Some(right)
            } else {
                None
            }
        };
        let up = left;
        let down = right;

        match self.tree.get(turn_point).unwrap().get().orientation {
            Orientation::Horizontal => {
                match action {
                    // Switching Sides for Left & Right
                    SearchPath::Right
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Horizontal =>
                    {
                        left()
                    }
                    SearchPath::Left
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Horizontal =>
                    {
                        right()
                    }
                    // Remain for Up & Down
                    SearchPath::Up
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Vertical =>
                    {
                        up()
                    }
                    SearchPath::Down
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Vertical =>
                    {
                        down()
                    }
                    _ => None,
                }
            }
            Orientation::Vertical => {
                match action {
                    // Remain for Left & Right
                    SearchPath::Right
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Horizontal =>
                    {
                        right()
                    }
                    SearchPath::Left
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Horizontal =>
                    {
                        left()
                    }
                    // Switch for Up & Down
                    SearchPath::Up
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Vertical =>
                    {
                        down()
                    }
                    SearchPath::Down
                        if self.tree.get(cur_node).unwrap().get().orientation
                            == Orientation::Vertical =>
                    {
                        up()
                    }
                    _ => None,
                }
            }
        }
    }

    fn search_focus_path(
        &self,
        direction: Absolute,
        nodeid: Id,
        fromid: Id,
    ) -> Result<(Vec<SearchPath>, Id), ()> {
        let mut cur_node = Some(nodeid);
        let mut from_node = fromid;

        let mut path = Vec::new();

        while cur_node.is_some() {
            // println!("Current node in search path: {}", cur_node.unwrap());
            // println!("Originating from node: {}", from_node);
            match self.tree.get(cur_node.unwrap()).unwrap().get().orientation {
                Orientation::Horizontal
                    if direction == Absolute::Left || direction == Absolute::Right =>
                {
                    if cur_node.unwrap().children(&self.tree).next().unwrap() == from_node {
                        // Originated from left
                        path.push(SearchPath::Left);
                        from_node = cur_node.unwrap();

                        if direction == Absolute::Left {
                            cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                        } else {
                            cur_node = None;
                        }
                    } else {
                        // Originated from right
                        path.push(SearchPath::Right);
                        from_node = cur_node.unwrap();
                        if direction == Absolute::Right {
                            cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                        } else {
                            cur_node = None;
                        }
                    }
                }
                Orientation::Vertical
                    if direction == Absolute::Up || direction == Absolute::Down =>
                {
                    if cur_node.unwrap().children(&self.tree).next().unwrap() == from_node {
                        // Originated from up
                        path.push(SearchPath::Up);
                        from_node = cur_node.unwrap();

                        if direction == Absolute::Up {
                            cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                        } else {
                            cur_node = None;
                        }
                    } else {
                        // Originated from down
                        path.push(SearchPath::Down);
                        from_node = cur_node.unwrap();
                        if direction == Absolute::Down {
                            cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                        } else {
                            cur_node = None;
                        }
                    }
                }
                Orientation::Horizontal => {
                    if cur_node.unwrap().children(&self.tree).next().unwrap() == from_node {
                        path.push(SearchPath::Left);
                        from_node = cur_node.unwrap();
                        cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                    } else {
                        path.push(SearchPath::Right);
                        from_node = cur_node.unwrap();
                        cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                    }
                }
                Orientation::Vertical => {
                    if cur_node.unwrap().children(&self.tree).next().unwrap() == from_node {
                        path.push(SearchPath::Up);
                        from_node = cur_node.unwrap();
                        cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                    } else {
                        path.push(SearchPath::Down);
                        from_node = cur_node.unwrap();
                        cur_node = cur_node.unwrap().ancestors(&self.tree).nth(1);
                    }
                }
            }
        }

        match self.tree.get(from_node).unwrap().get().orientation {
            Orientation::Horizontal if direction == Absolute::Up || direction == Absolute::Down => {
                Err(())
            }
            Orientation::Vertical
                if direction == Absolute::Left || direction == Absolute::Right =>
            {
                Err(())
            }
            _ => Ok((path, from_node)),
        }
    }
}

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

    #[test]
    fn test_remove() {
        // General Remove test
        let (mut test_mux, node1) = MuxBuilder::new().build(DummyView);
        let node2 = test_mux.add_vertical_id(DummyView, node1).unwrap();
        let node3 = test_mux.add_vertical_id(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) = MuxBuilder::new().build(DummyView);
        let node2 = mux.add_horizontal_id(DummyView, node1).unwrap();
        let node3 = mux.add_vertical_id(DummyView, node2).unwrap();

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

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

        let (mut mux, _) = MuxBuilder::new().build(DummyView);

        let mut nodes = Vec::new();

        for _ in 0..10 {
            print_tree(&mux);
            match mux.add_horizontal_id(
                DummyView,
                if let Some(x) = nodes.last() {
                    *x
                } else {
                    mux.root
                },
            ) {
                Ok(node) => {
                    nodes.push(node);
                }
                Err(_) => {
                    assert!(false);
                }
            }
            match mux.add_vertical_id(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));
    }
}