-
-
Notifications
You must be signed in to change notification settings - Fork 666
/
screen.rs
2977 lines (2872 loc) · 123 KB
/
screen.rs
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
//! Things related to [`Screen`]s.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc;
use std::str;
use zellij_utils::data::{Direction, PaneManifest, Resize, ResizeStrategy};
use zellij_utils::errors::prelude::*;
use zellij_utils::input::command::RunCommand;
use zellij_utils::input::options::Clipboard;
use zellij_utils::pane_size::{Size, SizeInPixels};
use zellij_utils::{
input::command::TerminalAction,
input::layout::{
FloatingPaneLayout, Layout, Run, RunPlugin, RunPluginLocation, SwapFloatingLayout,
SwapTiledLayout, TiledPaneLayout,
},
position::Position,
};
use crate::background_jobs::BackgroundJob;
use crate::os_input_output::ResizeCache;
use crate::panes::alacritty_functions::xparse_color;
use crate::panes::terminal_character::AnsiCode;
use crate::{
output::Output,
panes::sixel::SixelImageStore,
panes::PaneId,
plugins::PluginInstruction,
pty::{ClientOrTabIndex, PtyInstruction, VteBytes},
tab::Tab,
thread_bus::Bus,
ui::{
loading_indication::LoadingIndication,
overlay::{Overlay, OverlayWindow},
},
ClientId, ServerInstruction,
};
use zellij_utils::{
data::{Event, InputMode, ModeInfo, Palette, PaletteColor, PluginCapabilities, Style, TabInfo},
errors::{ContextType, ScreenContext},
input::{get_mode_info, options::Options},
ipc::{ClientAttributes, PixelDimensions, ServerToClientMsg},
};
/// Get the active tab and call a closure on it
///
/// If no active tab can be found, an error is logged instead.
///
/// # Parameters
///
/// - screen: An instance of `Screen` to operate on
/// - client_id: The client_id, usually taken from the `ScreenInstruction` that's being processed
/// - closure: A closure satisfying `|tab: &mut Tab| -> ()` OR `|tab: &mut Tab| -> Result<T>` (see
/// '?' below)
/// - ?: A literal "?", to append a `?` to the closure when it returns a `Result` type. This
/// argument is optional and not needed when the closure returns `()`
macro_rules! active_tab {
($screen:ident, $client_id:ident, $closure:expr) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
// This could be made more ergonomic by declaring the type of 'active_tab' in the
// closure, known as "Type Ascription". Then we could hint the type here and forego the
// "&mut Tab" in all the closures below...
// See: https://github.com/rust-lang/rust/issues/23416
$closure(active_tab);
},
Err(err) => Err::<(), _>(err).non_fatal(),
};
};
// Same as above, but with an added `?` for when the close returns a `Result` type.
($screen:ident, $client_id:ident, $closure:expr, ?) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
$closure(active_tab)?;
},
Err(err) => Err::<(), _>(err).non_fatal(),
};
};
}
macro_rules! active_tab_and_connected_client_id {
($screen:ident, $client_id:ident, $closure:expr) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
$closure(active_tab, $client_id);
},
Err(_) => {
if let Some(client_id) = $screen.get_first_client_id() {
match $screen.get_active_tab_mut(client_id) {
Ok(active_tab) => {
$closure(active_tab, client_id);
},
Err(err) => Err::<(), _>(err).non_fatal(),
}
} else {
log::error!("No client ids in screen found");
};
},
}
};
// Same as above, but with an added `?` for when the closure returns a `Result` type.
($screen:ident, $client_id:ident, $closure:expr, ?) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
$closure(active_tab, $client_id)?;
},
Err(_) => {
if let Some(client_id) = $screen.get_first_client_id() {
match $screen.get_active_tab_mut(client_id) {
Ok(active_tab) => {
$closure(active_tab, client_id)?;
},
Err(err) => Err::<(), _>(err).non_fatal(),
}
} else {
log::error!("No client ids in screen found");
};
},
}
};
}
type InitialTitle = String;
type ShouldFloat = bool;
type HoldForCommand = Option<RunCommand>;
/// Instructions that can be sent to the [`Screen`].
#[derive(Debug, Clone)]
pub enum ScreenInstruction {
PtyBytes(u32, VteBytes),
PluginBytes(Vec<(u32, ClientId, VteBytes)>), // u32 is plugin_id
Render,
NewPane(
PaneId,
Option<InitialTitle>,
Option<ShouldFloat>,
HoldForCommand,
ClientOrTabIndex,
),
OpenInPlaceEditor(PaneId, ClientId),
TogglePaneEmbedOrFloating(ClientId),
ToggleFloatingPanes(ClientId, Option<TerminalAction>),
HorizontalSplit(PaneId, Option<InitialTitle>, HoldForCommand, ClientId),
VerticalSplit(PaneId, Option<InitialTitle>, HoldForCommand, ClientId),
WriteCharacter(Vec<u8>, ClientId),
Resize(ClientId, ResizeStrategy),
SwitchFocus(ClientId),
FocusNextPane(ClientId),
FocusPreviousPane(ClientId),
MoveFocusLeft(ClientId),
MoveFocusLeftOrPreviousTab(ClientId),
MoveFocusDown(ClientId),
MoveFocusUp(ClientId),
MoveFocusRight(ClientId),
MoveFocusRightOrNextTab(ClientId),
MovePane(ClientId),
MovePaneBackwards(ClientId),
MovePaneUp(ClientId),
MovePaneDown(ClientId),
MovePaneRight(ClientId),
MovePaneLeft(ClientId),
Exit,
ClearScreen(ClientId),
DumpScreen(String, ClientId, bool),
EditScrollback(ClientId),
ScrollUp(ClientId),
ScrollUpAt(Position, ClientId),
ScrollDown(ClientId),
ScrollDownAt(Position, ClientId),
ScrollToBottom(ClientId),
ScrollToTop(ClientId),
PageScrollUp(ClientId),
PageScrollDown(ClientId),
HalfPageScrollUp(ClientId),
HalfPageScrollDown(ClientId),
ClearScroll(ClientId),
CloseFocusedPane(ClientId),
ToggleActiveTerminalFullscreen(ClientId),
TogglePaneFrames,
SetSelectable(PaneId, bool, usize),
ClosePane(PaneId, Option<ClientId>),
HoldPane(
PaneId,
Option<i32>,
RunCommand,
Option<usize>,
Option<ClientId>,
), // Option<i32> is the exit status, Option<usize> is the tab_index
UpdatePaneName(Vec<u8>, ClientId),
UndoRenamePane(ClientId),
NewTab(
Option<PathBuf>,
Option<TerminalAction>,
Option<TiledPaneLayout>,
Vec<FloatingPaneLayout>,
Option<String>,
(Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), // swap layouts
ClientId,
),
ApplyLayout(
TiledPaneLayout,
Vec<FloatingPaneLayout>,
Vec<(u32, HoldForCommand)>, // new pane pids
Vec<(u32, HoldForCommand)>, // new floating pane pids
HashMap<RunPluginLocation, Vec<u32>>,
usize, // tab_index
ClientId,
),
SwitchTabNext(ClientId),
SwitchTabPrev(ClientId),
ToggleActiveSyncTab(ClientId),
CloseTab(ClientId),
GoToTab(u32, Option<ClientId>), // this Option is a hacky workaround, please do not copy this behaviour
GoToTabName(
String,
(Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), // swap layouts
Option<TerminalAction>, // default_shell
bool,
Option<ClientId>,
),
ToggleTab(ClientId),
UpdateTabName(Vec<u8>, ClientId),
UndoRenameTab(ClientId),
TerminalResize(Size),
TerminalPixelDimensions(PixelDimensions),
TerminalBackgroundColor(String),
TerminalForegroundColor(String),
TerminalColorRegisters(Vec<(usize, String)>),
ChangeMode(ModeInfo, ClientId),
ChangeModeForAllClients(ModeInfo),
LeftClick(Position, ClientId),
RightClick(Position, ClientId),
MiddleClick(Position, ClientId),
LeftMouseRelease(Position, ClientId),
RightMouseRelease(Position, ClientId),
MiddleMouseRelease(Position, ClientId),
MouseHoldLeft(Position, ClientId),
MouseHoldRight(Position, ClientId),
MouseHoldMiddle(Position, ClientId),
Copy(ClientId),
AddClient(ClientId),
RemoveClient(ClientId),
AddOverlay(Overlay, ClientId),
RemoveOverlay(ClientId),
ConfirmPrompt(ClientId),
DenyPrompt(ClientId),
UpdateSearch(Vec<u8>, ClientId),
SearchDown(ClientId),
SearchUp(ClientId),
SearchToggleCaseSensitivity(ClientId),
SearchToggleWholeWord(ClientId),
SearchToggleWrap(ClientId),
AddRedPaneFrameColorOverride(Vec<PaneId>, Option<String>), // Option<String> => optional error text
ClearPaneFrameColorOverride(Vec<PaneId>),
PreviousSwapLayout(ClientId),
NextSwapLayout(ClientId),
QueryTabNames(ClientId),
NewTiledPluginPane(RunPlugin, Option<String>, ClientId), // Option<String> is
// optional pane title
NewFloatingPluginPane(RunPlugin, Option<String>, ClientId), // Option<String> is an
// optional pane title
StartOrReloadPluginPane(RunPlugin, Option<String>),
AddPlugin(
Option<bool>, // should_float
RunPlugin,
Option<String>, // pane title
usize, // tab index
u32, // plugin id
),
UpdatePluginLoadingStage(u32, LoadingIndication), // u32 - plugin_id
StartPluginLoadingIndication(u32, LoadingIndication), // u32 - plugin_id
ProgressPluginLoadingOffset(u32), // u32 - plugin id
RequestStateUpdateForPlugins,
LaunchOrFocusPlugin(RunPlugin, bool, ClientId), // bool is should_float
SuppressPane(PaneId, ClientId), // bool is should_float
FocusPaneWithId(PaneId, bool, ClientId), // bool is should_float
RenamePane(PaneId, Vec<u8>),
RenameTab(usize, Vec<u8>),
BreakPane(Box<Layout>, Option<TerminalAction>, ClientId),
BreakPaneRight(ClientId),
BreakPaneLeft(ClientId),
}
impl From<&ScreenInstruction> for ScreenContext {
fn from(screen_instruction: &ScreenInstruction) -> Self {
match *screen_instruction {
ScreenInstruction::PtyBytes(..) => ScreenContext::HandlePtyBytes,
ScreenInstruction::PluginBytes(..) => ScreenContext::PluginBytes,
ScreenInstruction::Render => ScreenContext::Render,
ScreenInstruction::NewPane(..) => ScreenContext::NewPane,
ScreenInstruction::OpenInPlaceEditor(..) => ScreenContext::OpenInPlaceEditor,
ScreenInstruction::TogglePaneEmbedOrFloating(..) => {
ScreenContext::TogglePaneEmbedOrFloating
},
ScreenInstruction::ToggleFloatingPanes(..) => ScreenContext::ToggleFloatingPanes,
ScreenInstruction::HorizontalSplit(..) => ScreenContext::HorizontalSplit,
ScreenInstruction::VerticalSplit(..) => ScreenContext::VerticalSplit,
ScreenInstruction::WriteCharacter(..) => ScreenContext::WriteCharacter,
ScreenInstruction::Resize(.., strategy) => match strategy {
ResizeStrategy {
resize: Resize::Increase,
direction,
..
} => match direction {
Some(Direction::Left) => ScreenContext::ResizeIncreaseLeft,
Some(Direction::Down) => ScreenContext::ResizeIncreaseDown,
Some(Direction::Up) => ScreenContext::ResizeIncreaseUp,
Some(Direction::Right) => ScreenContext::ResizeIncreaseRight,
None => ScreenContext::ResizeIncreaseAll,
},
ResizeStrategy {
resize: Resize::Decrease,
direction,
..
} => match direction {
Some(Direction::Left) => ScreenContext::ResizeDecreaseLeft,
Some(Direction::Down) => ScreenContext::ResizeDecreaseDown,
Some(Direction::Up) => ScreenContext::ResizeDecreaseUp,
Some(Direction::Right) => ScreenContext::ResizeDecreaseRight,
None => ScreenContext::ResizeDecreaseAll,
},
},
ScreenInstruction::SwitchFocus(..) => ScreenContext::SwitchFocus,
ScreenInstruction::FocusNextPane(..) => ScreenContext::FocusNextPane,
ScreenInstruction::FocusPreviousPane(..) => ScreenContext::FocusPreviousPane,
ScreenInstruction::MoveFocusLeft(..) => ScreenContext::MoveFocusLeft,
ScreenInstruction::MoveFocusLeftOrPreviousTab(..) => {
ScreenContext::MoveFocusLeftOrPreviousTab
},
ScreenInstruction::MoveFocusDown(..) => ScreenContext::MoveFocusDown,
ScreenInstruction::MoveFocusUp(..) => ScreenContext::MoveFocusUp,
ScreenInstruction::MoveFocusRight(..) => ScreenContext::MoveFocusRight,
ScreenInstruction::MoveFocusRightOrNextTab(..) => {
ScreenContext::MoveFocusRightOrNextTab
},
ScreenInstruction::MovePane(..) => ScreenContext::MovePane,
ScreenInstruction::MovePaneBackwards(..) => ScreenContext::MovePaneBackwards,
ScreenInstruction::MovePaneDown(..) => ScreenContext::MovePaneDown,
ScreenInstruction::MovePaneUp(..) => ScreenContext::MovePaneUp,
ScreenInstruction::MovePaneRight(..) => ScreenContext::MovePaneRight,
ScreenInstruction::MovePaneLeft(..) => ScreenContext::MovePaneLeft,
ScreenInstruction::Exit => ScreenContext::Exit,
ScreenInstruction::ClearScreen(..) => ScreenContext::ClearScreen,
ScreenInstruction::DumpScreen(..) => ScreenContext::DumpScreen,
ScreenInstruction::EditScrollback(..) => ScreenContext::EditScrollback,
ScreenInstruction::ScrollUp(..) => ScreenContext::ScrollUp,
ScreenInstruction::ScrollDown(..) => ScreenContext::ScrollDown,
ScreenInstruction::ScrollToBottom(..) => ScreenContext::ScrollToBottom,
ScreenInstruction::ScrollToTop(..) => ScreenContext::ScrollToTop,
ScreenInstruction::PageScrollUp(..) => ScreenContext::PageScrollUp,
ScreenInstruction::PageScrollDown(..) => ScreenContext::PageScrollDown,
ScreenInstruction::HalfPageScrollUp(..) => ScreenContext::HalfPageScrollUp,
ScreenInstruction::HalfPageScrollDown(..) => ScreenContext::HalfPageScrollDown,
ScreenInstruction::ClearScroll(..) => ScreenContext::ClearScroll,
ScreenInstruction::CloseFocusedPane(..) => ScreenContext::CloseFocusedPane,
ScreenInstruction::ToggleActiveTerminalFullscreen(..) => {
ScreenContext::ToggleActiveTerminalFullscreen
},
ScreenInstruction::TogglePaneFrames => ScreenContext::TogglePaneFrames,
ScreenInstruction::SetSelectable(..) => ScreenContext::SetSelectable,
ScreenInstruction::ClosePane(..) => ScreenContext::ClosePane,
ScreenInstruction::HoldPane(..) => ScreenContext::HoldPane,
ScreenInstruction::UpdatePaneName(..) => ScreenContext::UpdatePaneName,
ScreenInstruction::UndoRenamePane(..) => ScreenContext::UndoRenamePane,
ScreenInstruction::NewTab(..) => ScreenContext::NewTab,
ScreenInstruction::ApplyLayout(..) => ScreenContext::ApplyLayout,
ScreenInstruction::SwitchTabNext(..) => ScreenContext::SwitchTabNext,
ScreenInstruction::SwitchTabPrev(..) => ScreenContext::SwitchTabPrev,
ScreenInstruction::CloseTab(..) => ScreenContext::CloseTab,
ScreenInstruction::GoToTab(..) => ScreenContext::GoToTab,
ScreenInstruction::GoToTabName(..) => ScreenContext::GoToTabName,
ScreenInstruction::UpdateTabName(..) => ScreenContext::UpdateTabName,
ScreenInstruction::UndoRenameTab(..) => ScreenContext::UndoRenameTab,
ScreenInstruction::TerminalResize(..) => ScreenContext::TerminalResize,
ScreenInstruction::TerminalPixelDimensions(..) => {
ScreenContext::TerminalPixelDimensions
},
ScreenInstruction::TerminalBackgroundColor(..) => {
ScreenContext::TerminalBackgroundColor
},
ScreenInstruction::TerminalForegroundColor(..) => {
ScreenContext::TerminalForegroundColor
},
ScreenInstruction::TerminalColorRegisters(..) => ScreenContext::TerminalColorRegisters,
ScreenInstruction::ChangeMode(..) => ScreenContext::ChangeMode,
ScreenInstruction::ChangeModeForAllClients(..) => {
ScreenContext::ChangeModeForAllClients
},
ScreenInstruction::ToggleActiveSyncTab(..) => ScreenContext::ToggleActiveSyncTab,
ScreenInstruction::ScrollUpAt(..) => ScreenContext::ScrollUpAt,
ScreenInstruction::ScrollDownAt(..) => ScreenContext::ScrollDownAt,
ScreenInstruction::LeftClick(..) => ScreenContext::LeftClick,
ScreenInstruction::RightClick(..) => ScreenContext::RightClick,
ScreenInstruction::MiddleClick(..) => ScreenContext::MiddleClick,
ScreenInstruction::LeftMouseRelease(..) => ScreenContext::LeftMouseRelease,
ScreenInstruction::RightMouseRelease(..) => ScreenContext::RightMouseRelease,
ScreenInstruction::MiddleMouseRelease(..) => ScreenContext::MiddleMouseRelease,
ScreenInstruction::MouseHoldLeft(..) => ScreenContext::MouseHoldLeft,
ScreenInstruction::MouseHoldRight(..) => ScreenContext::MouseHoldRight,
ScreenInstruction::MouseHoldMiddle(..) => ScreenContext::MouseHoldMiddle,
ScreenInstruction::Copy(..) => ScreenContext::Copy,
ScreenInstruction::ToggleTab(..) => ScreenContext::ToggleTab,
ScreenInstruction::AddClient(..) => ScreenContext::AddClient,
ScreenInstruction::RemoveClient(..) => ScreenContext::RemoveClient,
ScreenInstruction::AddOverlay(..) => ScreenContext::AddOverlay,
ScreenInstruction::RemoveOverlay(..) => ScreenContext::RemoveOverlay,
ScreenInstruction::ConfirmPrompt(..) => ScreenContext::ConfirmPrompt,
ScreenInstruction::DenyPrompt(..) => ScreenContext::DenyPrompt,
ScreenInstruction::UpdateSearch(..) => ScreenContext::UpdateSearch,
ScreenInstruction::SearchDown(..) => ScreenContext::SearchDown,
ScreenInstruction::SearchUp(..) => ScreenContext::SearchUp,
ScreenInstruction::SearchToggleCaseSensitivity(..) => {
ScreenContext::SearchToggleCaseSensitivity
},
ScreenInstruction::SearchToggleWholeWord(..) => ScreenContext::SearchToggleWholeWord,
ScreenInstruction::SearchToggleWrap(..) => ScreenContext::SearchToggleWrap,
ScreenInstruction::AddRedPaneFrameColorOverride(..) => {
ScreenContext::AddRedPaneFrameColorOverride
},
ScreenInstruction::ClearPaneFrameColorOverride(..) => {
ScreenContext::ClearPaneFrameColorOverride
},
ScreenInstruction::PreviousSwapLayout(..) => ScreenContext::PreviousSwapLayout,
ScreenInstruction::NextSwapLayout(..) => ScreenContext::NextSwapLayout,
ScreenInstruction::QueryTabNames(..) => ScreenContext::QueryTabNames,
ScreenInstruction::NewTiledPluginPane(..) => ScreenContext::NewTiledPluginPane,
ScreenInstruction::NewFloatingPluginPane(..) => ScreenContext::NewFloatingPluginPane,
ScreenInstruction::StartOrReloadPluginPane(..) => {
ScreenContext::StartOrReloadPluginPane
},
ScreenInstruction::AddPlugin(..) => ScreenContext::AddPlugin,
ScreenInstruction::UpdatePluginLoadingStage(..) => {
ScreenContext::UpdatePluginLoadingStage
},
ScreenInstruction::ProgressPluginLoadingOffset(..) => {
ScreenContext::ProgressPluginLoadingOffset
},
ScreenInstruction::StartPluginLoadingIndication(..) => {
ScreenContext::StartPluginLoadingIndication
},
ScreenInstruction::RequestStateUpdateForPlugins => {
ScreenContext::RequestStateUpdateForPlugins
},
ScreenInstruction::LaunchOrFocusPlugin(..) => ScreenContext::LaunchOrFocusPlugin,
ScreenInstruction::SuppressPane(..) => ScreenContext::SuppressPane,
ScreenInstruction::FocusPaneWithId(..) => ScreenContext::FocusPaneWithId,
ScreenInstruction::RenamePane(..) => ScreenContext::RenamePane,
ScreenInstruction::RenameTab(..) => ScreenContext::RenameTab,
ScreenInstruction::BreakPane(..) => ScreenContext::BreakPane,
ScreenInstruction::BreakPaneRight(..) => ScreenContext::BreakPaneRight,
ScreenInstruction::BreakPaneLeft(..) => ScreenContext::BreakPaneLeft,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct CopyOptions {
pub command: Option<String>,
pub clipboard: Clipboard,
pub copy_on_select: bool,
}
impl CopyOptions {
pub(crate) fn new(
copy_command: Option<String>,
copy_clipboard: Clipboard,
copy_on_select: bool,
) -> Self {
Self {
command: copy_command,
clipboard: copy_clipboard,
copy_on_select,
}
}
#[cfg(test)]
pub(crate) fn default() -> Self {
Self {
command: None,
clipboard: Clipboard::default(),
copy_on_select: true,
}
}
}
/// A [`Screen`] holds multiple [`Tab`]s, each one holding multiple [`panes`](crate::client::panes).
/// It only directly controls which tab is active, delegating the rest to the individual `Tab`.
pub(crate) struct Screen {
/// A Bus for sending and receiving messages with the other threads.
pub bus: Bus<ScreenInstruction>,
/// An optional maximal amount of panes allowed per [`Tab`] in this [`Screen`] instance.
max_panes: Option<usize>,
/// A map between this [`Screen`]'s tabs and their ID/key.
tabs: BTreeMap<usize, Tab>,
/// The full size of this [`Screen`].
size: Size,
pixel_dimensions: PixelDimensions,
character_cell_size: Rc<RefCell<Option<SizeInPixels>>>,
sixel_image_store: Rc<RefCell<SixelImageStore>>,
/// The overlay that is drawn on top of [`Pane`]'s', [`Tab`]'s and the [`Screen`]
overlay: OverlayWindow,
terminal_emulator_colors: Rc<RefCell<Palette>>,
terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>,
connected_clients: Rc<RefCell<HashSet<ClientId>>>,
/// The indices of this [`Screen`]'s active [`Tab`]s.
active_tab_indices: BTreeMap<ClientId, usize>,
tab_history: BTreeMap<ClientId, Vec<usize>>,
mode_info: BTreeMap<ClientId, ModeInfo>,
default_mode_info: ModeInfo, // TODO: restructure ModeInfo to prevent this duplication
style: Style,
draw_pane_frames: bool,
auto_layout: bool,
session_is_mirrored: bool,
copy_options: CopyOptions,
debug: bool,
}
impl Screen {
/// Creates and returns a new [`Screen`].
pub fn new(
bus: Bus<ScreenInstruction>,
client_attributes: &ClientAttributes,
max_panes: Option<usize>,
mode_info: ModeInfo,
draw_pane_frames: bool,
auto_layout: bool,
session_is_mirrored: bool,
copy_options: CopyOptions,
debug: bool,
) -> Self {
Screen {
bus,
max_panes,
size: client_attributes.size,
pixel_dimensions: Default::default(),
character_cell_size: Rc::new(RefCell::new(None)),
sixel_image_store: Rc::new(RefCell::new(SixelImageStore::default())),
style: client_attributes.style,
connected_clients: Rc::new(RefCell::new(HashSet::new())),
active_tab_indices: BTreeMap::new(),
tabs: BTreeMap::new(),
overlay: OverlayWindow::default(),
terminal_emulator_colors: Rc::new(RefCell::new(Palette::default())),
terminal_emulator_color_codes: Rc::new(RefCell::new(HashMap::new())),
tab_history: BTreeMap::new(),
mode_info: BTreeMap::new(),
default_mode_info: mode_info,
draw_pane_frames,
auto_layout,
session_is_mirrored,
copy_options,
debug,
}
}
/// Returns the index where a new [`Tab`] should be created in this [`Screen`].
/// Currently, this is right after the last currently existing tab, or `0` if
/// no tabs exist in this screen yet.
fn get_new_tab_index(&self) -> usize {
if let Some(index) = self.tabs.keys().last() {
*index + 1
} else {
0
}
}
fn move_clients_from_closed_tab(
&mut self,
client_ids_and_mode_infos: Vec<(ClientId, ModeInfo)>,
) -> Result<()> {
let err_context = || "failed to move clients from closed tab".to_string();
if self.tabs.is_empty() {
Err::<(), _>(anyhow!(
"No tabs left, cannot move clients: {:?} from closed tab",
client_ids_and_mode_infos
))
.with_context(err_context)
.non_fatal();
return Ok(());
}
let first_tab_index = *self
.tabs
.keys()
.next()
.context("screen contained no tabs")
.with_context(err_context)?;
for (client_id, client_mode_info) in client_ids_and_mode_infos {
let client_tab_history = self.tab_history.entry(client_id).or_insert_with(Vec::new);
if let Some(client_previous_tab) = client_tab_history.pop() {
if let Some(client_active_tab) = self.tabs.get_mut(&client_previous_tab) {
self.active_tab_indices
.insert(client_id, client_previous_tab);
client_active_tab
.add_client(client_id, Some(client_mode_info))
.with_context(err_context)?;
continue;
}
}
self.active_tab_indices.insert(client_id, first_tab_index);
self.tabs
.get_mut(&first_tab_index)
.with_context(err_context)?
.add_client(client_id, Some(client_mode_info))
.with_context(err_context)?;
}
Ok(())
}
fn move_clients_between_tabs(
&mut self,
source_tab_index: usize,
destination_tab_index: usize,
update_mode_infos: bool,
clients_to_move: Option<Vec<ClientId>>,
) -> Result<()> {
let err_context = || {
format!(
"failed to move clients from tab {source_tab_index} to tab {destination_tab_index}"
)
};
// None ==> move all clients
let drained_clients = self
.get_indexed_tab_mut(source_tab_index)
.map(|t| t.drain_connected_clients(clients_to_move));
if let Some(client_mode_info_in_source_tab) = drained_clients {
let destination_tab = self
.get_indexed_tab_mut(destination_tab_index)
.context("failed to get destination tab by index")
.with_context(err_context)?;
destination_tab
.add_multiple_clients(client_mode_info_in_source_tab)
.with_context(err_context)?;
if update_mode_infos {
destination_tab
.update_input_modes()
.with_context(err_context)?;
}
destination_tab.set_force_render();
destination_tab.visible(true).with_context(err_context)?;
}
Ok(())
}
fn update_client_tab_focus(&mut self, client_id: ClientId, new_tab_index: usize) {
match self.active_tab_indices.remove(&client_id) {
Some(old_active_index) => {
self.active_tab_indices.insert(client_id, new_tab_index);
let client_tab_history = self.tab_history.entry(client_id).or_insert_with(Vec::new);
client_tab_history.retain(|&e| e != new_tab_index);
client_tab_history.push(old_active_index);
},
None => {
self.active_tab_indices.insert(client_id, new_tab_index);
},
}
}
/// A helper function to switch to a new tab at specified position.
fn switch_active_tab(
&mut self,
new_tab_pos: usize,
should_change_pane_focus: Option<Direction>,
update_mode_infos: bool,
client_id: ClientId,
) -> Result<()> {
let err_context = || {
format!(
"Failed to switch to active tab at position {new_tab_pos} for client id: {client_id:?}"
)
};
if let Some(new_tab) = self.tabs.values().find(|t| t.position == new_tab_pos) {
match self.get_active_tab(client_id) {
Ok(current_tab) => {
// If new active tab is same as the current one, do nothing.
if current_tab.position == new_tab_pos {
return Ok(());
}
let current_tab_index = current_tab.index;
let new_tab_index = new_tab.index;
if self.session_is_mirrored {
self.move_clients_between_tabs(
current_tab_index,
new_tab_index,
update_mode_infos,
None,
)
.with_context(err_context)?;
let all_connected_clients: Vec<ClientId> =
self.connected_clients.borrow().iter().copied().collect();
for client_id in all_connected_clients {
self.update_client_tab_focus(client_id, new_tab_index);
match (
should_change_pane_focus,
self.get_indexed_tab_mut(new_tab_index),
) {
(Some(direction), Some(new_tab)) => {
new_tab.focus_pane_on_edge(direction, client_id);
},
_ => {},
}
}
} else {
self.move_clients_between_tabs(
current_tab_index,
new_tab_index,
update_mode_infos,
Some(vec![client_id]),
)
.with_context(err_context)?;
match (
should_change_pane_focus,
self.get_indexed_tab_mut(new_tab_index),
) {
(Some(direction), Some(new_tab)) => {
new_tab.focus_pane_on_edge(direction, client_id);
},
_ => {},
}
self.update_client_tab_focus(client_id, new_tab_index);
}
if let Some(current_tab) = self.get_indexed_tab_mut(current_tab_index) {
if current_tab.has_no_connected_clients() {
current_tab.visible(false).with_context(err_context)?;
}
} else {
Err::<(), _>(anyhow!("Tab index {:?} not found", current_tab_index))
.with_context(err_context)
.non_fatal();
}
self.report_tab_state().with_context(err_context)?;
self.report_pane_state().with_context(err_context)?;
return self.render().with_context(err_context);
},
Err(err) => Err::<(), _>(err).with_context(err_context).non_fatal(),
}
}
Ok(())
}
/// A helper function to switch to a new tab with specified name. Return true if tab [name] has
/// been created, else false.
fn switch_active_tab_name(&mut self, name: String, client_id: ClientId) -> Result<bool> {
match self.tabs.values().find(|t| t.name == name) {
Some(new_tab) => {
self.switch_active_tab(new_tab.position, None, true, client_id)?;
Ok(true)
},
None => Ok(false),
}
}
/// Sets this [`Screen`]'s active [`Tab`] to the next tab.
pub fn switch_tab_next(
&mut self,
should_change_pane_focus: Option<Direction>,
update_mode_infos: bool,
client_id: ClientId,
) -> Result<()> {
let err_context = || format!("failed to switch to next tab for client {client_id}");
let client_id = if self.get_active_tab(client_id).is_ok() {
Some(client_id)
} else {
self.get_first_client_id()
};
if let Some(client_id) = client_id {
match self.get_active_tab(client_id) {
Ok(active_tab) => {
let active_tab_pos = active_tab.position;
let new_tab_pos = (active_tab_pos + 1) % self.tabs.len();
return self.switch_active_tab(
new_tab_pos,
should_change_pane_focus,
update_mode_infos,
client_id,
);
},
Err(err) => Err::<(), _>(err).with_context(err_context).non_fatal(),
}
}
Ok(())
}
/// Sets this [`Screen`]'s active [`Tab`] to the previous tab.
pub fn switch_tab_prev(
&mut self,
should_change_pane_focus: Option<Direction>,
update_mode_infos: bool,
client_id: ClientId,
) -> Result<()> {
let err_context = || format!("failed to switch to previous tab for client {client_id}");
let client_id = if self.get_active_tab(client_id).is_ok() {
Some(client_id)
} else {
self.get_first_client_id()
};
if let Some(client_id) = client_id {
match self.get_active_tab(client_id) {
Ok(active_tab) => {
let active_tab_pos = active_tab.position;
let new_tab_pos = if active_tab_pos == 0 {
self.tabs.len() - 1
} else {
active_tab_pos - 1
};
return self.switch_active_tab(
new_tab_pos,
should_change_pane_focus,
update_mode_infos,
client_id,
);
},
Err(err) => Err::<(), _>(err).with_context(err_context).non_fatal(),
}
}
Ok(())
}
pub fn go_to_tab(&mut self, tab_index: usize, client_id: ClientId) -> Result<()> {
self.switch_active_tab(tab_index.saturating_sub(1), None, true, client_id)
}
pub fn go_to_tab_name(&mut self, name: String, client_id: ClientId) -> Result<bool> {
self.switch_active_tab_name(name, client_id)
}
fn close_tab_at_index(&mut self, tab_index: usize) -> Result<()> {
let err_context = || format!("failed to close tab at index {tab_index:?}");
let mut tab_to_close = self.tabs.remove(&tab_index).with_context(err_context)?;
let pane_ids = tab_to_close.get_all_pane_ids();
// below we don't check the result of sending the CloseTab instruction to the pty thread
// because this might be happening when the app is closing, at which point the pty thread
// has already closed and this would result in an error
self.bus
.senders
.send_to_pty(PtyInstruction::CloseTab(pane_ids))
.with_context(err_context)?;
if self.tabs.is_empty() {
self.active_tab_indices.clear();
self.bus
.senders
.send_to_server(ServerInstruction::Render(None))
.with_context(err_context)
} else {
let client_mode_infos_in_closed_tab = tab_to_close.drain_connected_clients(None);
self.move_clients_from_closed_tab(client_mode_infos_in_closed_tab)
.with_context(err_context)?;
let visible_tab_indices: HashSet<usize> =
self.active_tab_indices.values().copied().collect();
for t in self.tabs.values_mut() {
if visible_tab_indices.contains(&t.index) {
t.set_force_render();
t.visible(true).with_context(err_context)?;
}
if t.position > tab_to_close.position {
t.position -= 1;
}
}
self.report_tab_state().with_context(err_context)?;
self.report_pane_state().with_context(err_context)?;
self.render().with_context(err_context)
}
}
// Closes the client_id's focused tab
pub fn close_tab(&mut self, client_id: ClientId) -> Result<()> {
let err_context = || format!("failed to close tab for client {client_id:?}");
let client_id = if self.get_active_tab(client_id).is_ok() {
Some(client_id)
} else {
self.get_first_client_id()
};
match client_id {
Some(client_id) => {
let active_tab_index = *self
.active_tab_indices
.get(&client_id)
.with_context(err_context)?;
self.close_tab_at_index(active_tab_index)
.with_context(err_context)
},
None => Ok(()),
}
}
pub fn resize_to_screen(&mut self, new_screen_size: Size) -> Result<()> {
let err_context = || format!("failed to resize to screen size: {new_screen_size:#?}");
self.size = new_screen_size;
for tab in self.tabs.values_mut() {
tab.resize_whole_tab(new_screen_size)
.with_context(err_context)?;
tab.set_force_render();
}
self.report_pane_state().with_context(err_context)?;
self.render().with_context(err_context)
}
pub fn update_pixel_dimensions(&mut self, pixel_dimensions: PixelDimensions) {
self.pixel_dimensions.merge(pixel_dimensions);
if let Some(character_cell_size) = self.pixel_dimensions.character_cell_size {
*self.character_cell_size.borrow_mut() = Some(character_cell_size);
} else if let Some(text_area_size) = self.pixel_dimensions.text_area_size {
let character_cell_size_height = text_area_size.height / self.size.rows;
let character_cell_size_width = text_area_size.width / self.size.cols;
let character_cell_size = SizeInPixels {
height: character_cell_size_height,
width: character_cell_size_width,
};
*self.character_cell_size.borrow_mut() = Some(character_cell_size);
}
}
pub fn update_terminal_background_color(&mut self, background_color_instruction: String) {
if let Some(AnsiCode::RgbCode((r, g, b))) =
xparse_color(background_color_instruction.as_bytes())
{
let bg_palette_color = PaletteColor::Rgb((r, g, b));
self.terminal_emulator_colors.borrow_mut().bg = bg_palette_color;
}
}
pub fn update_terminal_foreground_color(&mut self, foreground_color_instruction: String) {
if let Some(AnsiCode::RgbCode((r, g, b))) =
xparse_color(foreground_color_instruction.as_bytes())
{
let fg_palette_color = PaletteColor::Rgb((r, g, b));
self.terminal_emulator_colors.borrow_mut().fg = fg_palette_color;
}
}
pub fn update_terminal_color_registers(&mut self, color_registers: Vec<(usize, String)>) {
let mut terminal_emulator_color_codes = self.terminal_emulator_color_codes.borrow_mut();
for (color_register, color_sequence) in color_registers {
terminal_emulator_color_codes.insert(color_register, color_sequence);
}
}
/// Renders this [`Screen`], which amounts to rendering its active [`Tab`].
pub fn render(&mut self) -> Result<()> {
let err_context = "failed to render screen";
let mut output = Output::new(
self.sixel_image_store.clone(),
self.character_cell_size.clone(),
);
let mut tabs_to_close = vec![];
for (tab_index, tab) in &mut self.tabs {
if tab.has_selectable_tiled_panes() {
tab.render(&mut output).context(err_context)?;
} else if !tab.is_pending() {
tabs_to_close.push(*tab_index);
}
}
for tab_index in tabs_to_close {
self.close_tab_at_index(tab_index).context(err_context)?;
}
if output.is_dirty() {
let serialized_output = output.serialize().context(err_context)?;
self.bus
.senders
.send_to_server(ServerInstruction::Render(Some(serialized_output)))
.context(err_context)
} else {
Ok(())
}
}
/// Returns a mutable reference to this [`Screen`]'s tabs.
pub fn get_tabs_mut(&mut self) -> &mut BTreeMap<usize, Tab> {
&mut self.tabs
}
/// Returns an immutable reference to this [`Screen`]'s active [`Tab`].
pub fn get_active_tab(&self, client_id: ClientId) -> Result<&Tab> {
match self.active_tab_indices.get(&client_id) {
Some(tab) => self
.tabs
.get(tab)
.ok_or_else(|| anyhow!("active tab {} does not exist", tab)),
None => Err(anyhow!("active tab not found for client {:?}", client_id)),
}