-
-
Notifications
You must be signed in to change notification settings - Fork 651
/
data.rs
1896 lines (1780 loc) · 62.7 KB
/
data.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
use crate::input::actions::Action;
use crate::input::config::ConversionError;
use crate::input::keybinds::Keybinds;
use crate::input::layout::{RunPlugin, SplitSize};
use clap::ArgEnum;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt;
use std::fs::Metadata;
use std::path::{Path, PathBuf};
use std::str::{self, FromStr};
use std::time::Duration;
use strum_macros::{Display, EnumDiscriminants, EnumIter, EnumString, ToString};
#[cfg(not(target_family = "wasm"))]
use termwiz::{
escape::csi::KittyKeyboardFlags,
input::{KeyCode, KeyCodeEncodeModes, KeyboardEncoding, Modifiers},
};
pub type ClientId = u16; // TODO: merge with crate type?
pub fn client_id_to_colors(
client_id: ClientId,
colors: Palette,
) -> Option<(PaletteColor, PaletteColor)> {
// (primary color, secondary color)
match client_id {
1 => Some((colors.magenta, colors.black)),
2 => Some((colors.blue, colors.black)),
3 => Some((colors.purple, colors.black)),
4 => Some((colors.yellow, colors.black)),
5 => Some((colors.cyan, colors.black)),
6 => Some((colors.gold, colors.black)),
7 => Some((colors.red, colors.black)),
8 => Some((colors.silver, colors.black)),
9 => Some((colors.pink, colors.black)),
10 => Some((colors.brown, colors.black)),
_ => None,
}
}
pub fn single_client_color(colors: Palette) -> (PaletteColor, PaletteColor) {
(colors.green, colors.black)
}
impl FromStr for KeyWithModifier {
type Err = Box<dyn std::error::Error>;
fn from_str(key_str: &str) -> Result<Self, Self::Err> {
let mut key_string_parts: Vec<&str> = key_str.split_ascii_whitespace().collect();
let bare_key: BareKey = BareKey::from_str(key_string_parts.pop().ok_or("empty key")?)?;
let mut key_modifiers: BTreeSet<KeyModifier> = BTreeSet::new();
for stringified_modifier in key_string_parts {
key_modifiers.insert(KeyModifier::from_str(stringified_modifier)?);
}
Ok(KeyWithModifier {
bare_key,
key_modifiers,
})
}
}
#[derive(Debug, Clone, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct KeyWithModifier {
pub bare_key: BareKey,
pub key_modifiers: BTreeSet<KeyModifier>,
}
impl PartialEq for KeyWithModifier {
fn eq(&self, other: &Self) -> bool {
match (self.bare_key, other.bare_key) {
(BareKey::Char(self_char), BareKey::Char(other_char))
if self_char.to_ascii_lowercase() == other_char.to_ascii_lowercase() =>
{
let mut self_cloned = self.clone();
let mut other_cloned = other.clone();
if self_char.is_ascii_uppercase() {
self_cloned.bare_key = BareKey::Char(self_char.to_ascii_lowercase());
self_cloned.key_modifiers.insert(KeyModifier::Shift);
}
if other_char.is_ascii_uppercase() {
other_cloned.bare_key = BareKey::Char(self_char.to_ascii_lowercase());
other_cloned.key_modifiers.insert(KeyModifier::Shift);
}
self_cloned.bare_key == other_cloned.bare_key
&& self_cloned.key_modifiers == other_cloned.key_modifiers
},
_ => self.bare_key == other.bare_key && self.key_modifiers == other.key_modifiers,
}
}
}
impl Hash for KeyWithModifier {
fn hash<H: Hasher>(&self, state: &mut H) {
match self.bare_key {
BareKey::Char(character) if character.is_ascii_uppercase() => {
let mut to_hash = self.clone();
to_hash.bare_key = BareKey::Char(character.to_ascii_lowercase());
to_hash.key_modifiers.insert(KeyModifier::Shift);
to_hash.bare_key.hash(state);
to_hash.key_modifiers.hash(state);
},
_ => {
self.bare_key.hash(state);
self.key_modifiers.hash(state);
},
}
}
}
impl fmt::Display for KeyWithModifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.key_modifiers.is_empty() {
write!(f, "{}", self.bare_key)
} else {
write!(
f,
"{} {}",
self.key_modifiers
.iter()
.map(|m| m.to_string())
.collect::<Vec<_>>()
.join(" "),
self.bare_key
)
}
}
}
#[cfg(not(target_family = "wasm"))]
impl Into<Modifiers> for &KeyModifier {
fn into(self) -> Modifiers {
match self {
KeyModifier::Shift => Modifiers::SHIFT,
KeyModifier::Alt => Modifiers::ALT,
KeyModifier::Ctrl => Modifiers::CTRL,
KeyModifier::Super => Modifiers::SUPER,
}
}
}
#[derive(Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
pub enum BareKey {
PageDown,
PageUp,
Left,
Down,
Up,
Right,
Home,
End,
Backspace,
Delete,
Insert,
F(u8),
Char(char),
Tab,
Esc,
Enter,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
Menu,
}
impl fmt::Display for BareKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BareKey::PageDown => write!(f, "PgDn"),
BareKey::PageUp => write!(f, "PgUp"),
BareKey::Left => write!(f, "←"),
BareKey::Down => write!(f, "↓"),
BareKey::Up => write!(f, "↑"),
BareKey::Right => write!(f, "→"),
BareKey::Home => write!(f, "HOME"),
BareKey::End => write!(f, "END"),
BareKey::Backspace => write!(f, "BACKSPACE"),
BareKey::Delete => write!(f, "DEL"),
BareKey::Insert => write!(f, "INS"),
BareKey::F(index) => write!(f, "F{}", index),
BareKey::Char(' ') => write!(f, "SPACE"),
BareKey::Char(character) => write!(f, "{}", character),
BareKey::Tab => write!(f, "TAB"),
BareKey::Esc => write!(f, "ESC"),
BareKey::Enter => write!(f, "ENTER"),
BareKey::CapsLock => write!(f, "CAPSlOCK"),
BareKey::ScrollLock => write!(f, "SCROLLlOCK"),
BareKey::NumLock => write!(f, "NUMLOCK"),
BareKey::PrintScreen => write!(f, "PRINTSCREEN"),
BareKey::Pause => write!(f, "PAUSE"),
BareKey::Menu => write!(f, "MENU"),
}
}
}
impl FromStr for BareKey {
type Err = Box<dyn std::error::Error>;
fn from_str(key_str: &str) -> Result<Self, Self::Err> {
match key_str.to_ascii_lowercase().as_str() {
"pagedown" => Ok(BareKey::PageDown),
"pageup" => Ok(BareKey::PageUp),
"left" => Ok(BareKey::Left),
"down" => Ok(BareKey::Down),
"up" => Ok(BareKey::Up),
"right" => Ok(BareKey::Right),
"home" => Ok(BareKey::Home),
"end" => Ok(BareKey::End),
"backspace" => Ok(BareKey::Backspace),
"delete" => Ok(BareKey::Delete),
"insert" => Ok(BareKey::Insert),
"f1" => Ok(BareKey::F(1)),
"f2" => Ok(BareKey::F(2)),
"f3" => Ok(BareKey::F(3)),
"f4" => Ok(BareKey::F(4)),
"f5" => Ok(BareKey::F(5)),
"f6" => Ok(BareKey::F(6)),
"f7" => Ok(BareKey::F(7)),
"f8" => Ok(BareKey::F(8)),
"f9" => Ok(BareKey::F(9)),
"f10" => Ok(BareKey::F(10)),
"f11" => Ok(BareKey::F(11)),
"f12" => Ok(BareKey::F(12)),
"tab" => Ok(BareKey::Tab),
"esc" => Ok(BareKey::Esc),
"enter" => Ok(BareKey::Enter),
"capsLock" => Ok(BareKey::CapsLock),
"scrollLock" => Ok(BareKey::ScrollLock),
"numlock" => Ok(BareKey::NumLock),
"printscreen" => Ok(BareKey::PrintScreen),
"pause" => Ok(BareKey::Pause),
"menu" => Ok(BareKey::Menu),
"space" => Ok(BareKey::Char(' ')),
_ => {
if key_str.chars().count() == 1 {
if let Some(character) = key_str.chars().next() {
return Ok(BareKey::Char(character));
}
}
Err("unsupported key".into())
},
}
}
}
#[derive(
Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord, ToString,
)]
pub enum KeyModifier {
Ctrl,
Alt,
Shift,
Super,
}
impl FromStr for KeyModifier {
type Err = Box<dyn std::error::Error>;
fn from_str(key_str: &str) -> Result<Self, Self::Err> {
match key_str.to_ascii_lowercase().as_str() {
"shift" => Ok(KeyModifier::Shift),
"alt" => Ok(KeyModifier::Alt),
"ctrl" => Ok(KeyModifier::Ctrl),
"super" => Ok(KeyModifier::Super),
_ => Err("unsupported modifier".into()),
}
}
}
impl BareKey {
pub fn from_bytes_with_u(bytes: &[u8]) -> Option<Self> {
match str::from_utf8(bytes) {
Ok("27") => Some(BareKey::Esc),
Ok("13") => Some(BareKey::Enter),
Ok("9") => Some(BareKey::Tab),
Ok("127") => Some(BareKey::Backspace),
Ok("57358") => Some(BareKey::CapsLock),
Ok("57359") => Some(BareKey::ScrollLock),
Ok("57360") => Some(BareKey::NumLock),
Ok("57361") => Some(BareKey::PrintScreen),
Ok("57362") => Some(BareKey::Pause),
Ok("57363") => Some(BareKey::Menu),
Ok("57399") => Some(BareKey::Char('0')),
Ok("57400") => Some(BareKey::Char('1')),
Ok("57401") => Some(BareKey::Char('2')),
Ok("57402") => Some(BareKey::Char('3')),
Ok("57403") => Some(BareKey::Char('4')),
Ok("57404") => Some(BareKey::Char('5')),
Ok("57405") => Some(BareKey::Char('6')),
Ok("57406") => Some(BareKey::Char('7')),
Ok("57407") => Some(BareKey::Char('8')),
Ok("57408") => Some(BareKey::Char('9')),
Ok("57409") => Some(BareKey::Char('.')),
Ok("57410") => Some(BareKey::Char('/')),
Ok("57411") => Some(BareKey::Char('*')),
Ok("57412") => Some(BareKey::Char('-')),
Ok("57413") => Some(BareKey::Char('+')),
Ok("57414") => Some(BareKey::Enter),
Ok("57415") => Some(BareKey::Char('=')),
Ok("57417") => Some(BareKey::Left),
Ok("57418") => Some(BareKey::Right),
Ok("57419") => Some(BareKey::Up),
Ok("57420") => Some(BareKey::Down),
Ok("57421") => Some(BareKey::PageUp),
Ok("57422") => Some(BareKey::PageDown),
Ok("57423") => Some(BareKey::Home),
Ok("57424") => Some(BareKey::End),
Ok("57425") => Some(BareKey::Insert),
Ok("57426") => Some(BareKey::Delete),
Ok(num) => u8::from_str_radix(num, 10)
.ok()
.map(|n| BareKey::Char((n as char).to_ascii_lowercase())),
_ => None,
}
}
pub fn from_bytes_with_tilde(bytes: &[u8]) -> Option<Self> {
match str::from_utf8(bytes) {
Ok("2") => Some(BareKey::Insert),
Ok("3") => Some(BareKey::Delete),
Ok("5") => Some(BareKey::PageUp),
Ok("6") => Some(BareKey::PageDown),
Ok("7") => Some(BareKey::Home),
Ok("8") => Some(BareKey::End),
Ok("11") => Some(BareKey::F(1)),
Ok("12") => Some(BareKey::F(2)),
Ok("13") => Some(BareKey::F(3)),
Ok("14") => Some(BareKey::F(4)),
Ok("15") => Some(BareKey::F(5)),
Ok("17") => Some(BareKey::F(6)),
Ok("18") => Some(BareKey::F(7)),
Ok("19") => Some(BareKey::F(8)),
Ok("20") => Some(BareKey::F(9)),
Ok("21") => Some(BareKey::F(10)),
Ok("23") => Some(BareKey::F(11)),
Ok("24") => Some(BareKey::F(12)),
_ => None,
}
}
pub fn from_bytes_with_no_ending_byte(bytes: &[u8]) -> Option<Self> {
match str::from_utf8(bytes) {
Ok("1D") | Ok("D") => Some(BareKey::Left),
Ok("1C") | Ok("C") => Some(BareKey::Right),
Ok("1A") | Ok("A") => Some(BareKey::Up),
Ok("1B") | Ok("B") => Some(BareKey::Down),
Ok("1H") | Ok("H") => Some(BareKey::Home),
Ok("1F") | Ok("F") => Some(BareKey::End),
Ok("1P") | Ok("P") => Some(BareKey::F(1)),
Ok("1Q") | Ok("Q") => Some(BareKey::F(2)),
Ok("1S") | Ok("S") => Some(BareKey::F(4)),
_ => None,
}
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ModifierFlags: u8 {
const SHIFT = 0b0000_0001;
const ALT = 0b0000_0010;
const CONTROL = 0b0000_0100;
const SUPER = 0b0000_1000;
// we don't actually use the below, left here for completeness in case we want to add them
// later
const HYPER = 0b0001_0000;
const META = 0b0010_0000;
const CAPS_LOCK = 0b0100_0000;
const NUM_LOCK = 0b1000_0000;
}
}
impl KeyModifier {
pub fn from_bytes(bytes: &[u8]) -> BTreeSet<KeyModifier> {
let modifier_flags = str::from_utf8(bytes)
.ok() // convert to string: (eg. "16")
.and_then(|s| u8::from_str_radix(&s, 10).ok()) // convert to u8: (eg. 16)
.map(|s| s.saturating_sub(1)) // subtract 1: (eg. 15)
.and_then(|b| ModifierFlags::from_bits(b)); // bitflags: (0b0000_1111: Shift, Alt, Control, Super)
let mut key_modifiers = BTreeSet::new();
if let Some(modifier_flags) = modifier_flags {
for name in modifier_flags.iter() {
match name {
ModifierFlags::SHIFT => key_modifiers.insert(KeyModifier::Shift),
ModifierFlags::ALT => key_modifiers.insert(KeyModifier::Alt),
ModifierFlags::CONTROL => key_modifiers.insert(KeyModifier::Ctrl),
ModifierFlags::SUPER => key_modifiers.insert(KeyModifier::Super),
_ => false,
};
}
}
key_modifiers
}
}
impl KeyWithModifier {
pub fn new(bare_key: BareKey) -> Self {
KeyWithModifier {
bare_key,
key_modifiers: BTreeSet::new(),
}
}
pub fn new_with_modifiers(bare_key: BareKey, key_modifiers: BTreeSet<KeyModifier>) -> Self {
KeyWithModifier {
bare_key,
key_modifiers,
}
}
pub fn with_shift_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Shift);
self
}
pub fn with_alt_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Alt);
self
}
pub fn with_ctrl_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Ctrl);
self
}
pub fn with_super_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Super);
self
}
pub fn from_bytes_with_u(number_bytes: &[u8], modifier_bytes: &[u8]) -> Option<Self> {
// CSI number ; modifiers u
let bare_key = BareKey::from_bytes_with_u(number_bytes);
match bare_key {
Some(bare_key) => {
let key_modifiers = KeyModifier::from_bytes(modifier_bytes);
Some(KeyWithModifier {
bare_key,
key_modifiers,
})
},
_ => None,
}
}
pub fn from_bytes_with_tilde(number_bytes: &[u8], modifier_bytes: &[u8]) -> Option<Self> {
// CSI number ; modifiers ~
let bare_key = BareKey::from_bytes_with_tilde(number_bytes);
match bare_key {
Some(bare_key) => {
let key_modifiers = KeyModifier::from_bytes(modifier_bytes);
Some(KeyWithModifier {
bare_key,
key_modifiers,
})
},
_ => None,
}
}
pub fn from_bytes_with_no_ending_byte(
number_bytes: &[u8],
modifier_bytes: &[u8],
) -> Option<Self> {
// CSI 1; modifiers [ABCDEFHPQS]
let bare_key = BareKey::from_bytes_with_no_ending_byte(number_bytes);
match bare_key {
Some(bare_key) => {
let key_modifiers = KeyModifier::from_bytes(modifier_bytes);
Some(KeyWithModifier {
bare_key,
key_modifiers,
})
},
_ => None,
}
}
pub fn strip_common_modifiers(&self, common_modifiers: &Vec<KeyModifier>) -> Self {
let common_modifiers: BTreeSet<&KeyModifier> = common_modifiers.into_iter().collect();
KeyWithModifier {
bare_key: self.bare_key.clone(),
key_modifiers: self
.key_modifiers
.iter()
.filter(|m| !common_modifiers.contains(m))
.cloned()
.collect(),
}
}
pub fn is_key_without_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.is_empty()
}
pub fn is_key_with_ctrl_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Ctrl)
}
pub fn is_key_with_alt_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Alt)
}
pub fn is_key_with_shift_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Shift)
}
pub fn is_key_with_super_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Super)
}
#[cfg(not(target_family = "wasm"))]
pub fn to_termwiz_modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
for modifier in &self.key_modifiers {
modifiers.set(modifier.into(), true);
}
modifiers
}
#[cfg(not(target_family = "wasm"))]
pub fn to_termwiz_keycode(&self) -> KeyCode {
match self.bare_key {
BareKey::PageDown => KeyCode::PageDown,
BareKey::PageUp => KeyCode::PageUp,
BareKey::Left => KeyCode::LeftArrow,
BareKey::Down => KeyCode::DownArrow,
BareKey::Up => KeyCode::UpArrow,
BareKey::Right => KeyCode::RightArrow,
BareKey::Home => KeyCode::Home,
BareKey::End => KeyCode::End,
BareKey::Backspace => KeyCode::Backspace,
BareKey::Delete => KeyCode::Delete,
BareKey::Insert => KeyCode::Insert,
BareKey::F(index) => KeyCode::Function(index),
BareKey::Char(character) => KeyCode::Char(character),
BareKey::Tab => KeyCode::Tab,
BareKey::Esc => KeyCode::Escape,
BareKey::Enter => KeyCode::Enter,
BareKey::CapsLock => KeyCode::CapsLock,
BareKey::ScrollLock => KeyCode::ScrollLock,
BareKey::NumLock => KeyCode::NumLock,
BareKey::PrintScreen => KeyCode::PrintScreen,
BareKey::Pause => KeyCode::Pause,
BareKey::Menu => KeyCode::Menu,
}
}
#[cfg(not(target_family = "wasm"))]
pub fn serialize_non_kitty(&self) -> Option<String> {
let modifiers = self.to_termwiz_modifiers();
let key_code_encode_modes = KeyCodeEncodeModes {
encoding: KeyboardEncoding::Xterm,
// all these flags are false because they have been dealt with before this
// serialization
application_cursor_keys: false,
newline_mode: false,
modify_other_keys: None,
};
self.to_termwiz_keycode()
.encode(modifiers, key_code_encode_modes, true)
.ok()
}
#[cfg(not(target_family = "wasm"))]
pub fn serialize_kitty(&self) -> Option<String> {
let modifiers = self.to_termwiz_modifiers();
let key_code_encode_modes = KeyCodeEncodeModes {
encoding: KeyboardEncoding::Kitty(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES),
// all these flags are false because they have been dealt with before this
// serialization
application_cursor_keys: false,
newline_mode: false,
modify_other_keys: None,
};
self.to_termwiz_keycode()
.encode(modifiers, key_code_encode_modes, true)
.ok()
}
pub fn has_no_modifiers(&self) -> bool {
self.key_modifiers.is_empty()
}
pub fn has_modifiers(&self, modifiers: &[KeyModifier]) -> bool {
for modifier in modifiers {
if !self.key_modifiers.contains(modifier) {
return false;
}
}
true
}
}
#[derive(Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
pub enum Direction {
Left,
Right,
Up,
Down,
}
impl Direction {
pub fn invert(&self) -> Direction {
match *self {
Direction::Left => Direction::Right,
Direction::Down => Direction::Up,
Direction::Up => Direction::Down,
Direction::Right => Direction::Left,
}
}
pub fn is_horizontal(&self) -> bool {
matches!(self, Direction::Left | Direction::Right)
}
pub fn is_vertical(&self) -> bool {
matches!(self, Direction::Down | Direction::Up)
}
}
impl fmt::Display for Direction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Direction::Left => write!(f, "←"),
Direction::Right => write!(f, "→"),
Direction::Up => write!(f, "↑"),
Direction::Down => write!(f, "↓"),
}
}
}
impl FromStr for Direction {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Left" | "left" => Ok(Direction::Left),
"Right" | "right" => Ok(Direction::Right),
"Up" | "up" => Ok(Direction::Up),
"Down" | "down" => Ok(Direction::Down),
_ => Err(format!(
"Failed to parse Direction. Unknown Direction: {}",
s
)),
}
}
}
/// Resize operation to perform.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum Resize {
Increase,
Decrease,
}
impl Resize {
pub fn invert(&self) -> Self {
match self {
Resize::Increase => Resize::Decrease,
Resize::Decrease => Resize::Increase,
}
}
}
impl fmt::Display for Resize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Resize::Increase => write!(f, "+"),
Resize::Decrease => write!(f, "-"),
}
}
}
impl FromStr for Resize {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Increase" | "increase" | "+" => Ok(Resize::Increase),
"Decrease" | "decrease" | "-" => Ok(Resize::Decrease),
_ => Err(format!(
"failed to parse resize type. Unknown specifier '{}'",
s
)),
}
}
}
/// Container type that fully describes resize operations.
///
/// This is best thought of as follows:
///
/// - `resize` commands how the total *area* of the pane will change as part of this resize
/// operation.
/// - `direction` has two meanings:
/// - `None` means to resize all borders equally
/// - Anything else means to move the named border to achieve the change in area
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct ResizeStrategy {
/// Whether to increase or resize total area
pub resize: Resize,
/// With which border, if any, to change area
pub direction: Option<Direction>,
/// If set to true (default), increasing resizes towards a viewport border will be inverted.
/// I.e. a scenario like this ("increase right"):
///
/// ```text
/// +---+---+
/// | | X |->
/// +---+---+
/// ```
///
/// turns into this ("decrease left"):
///
/// ```text
/// +---+---+
/// | |-> |
/// +---+---+
/// ```
pub invert_on_boundaries: bool,
}
impl From<Direction> for ResizeStrategy {
fn from(direction: Direction) -> Self {
ResizeStrategy::new(Resize::Increase, Some(direction))
}
}
impl From<Resize> for ResizeStrategy {
fn from(resize: Resize) -> Self {
ResizeStrategy::new(resize, None)
}
}
impl ResizeStrategy {
pub fn new(resize: Resize, direction: Option<Direction>) -> Self {
ResizeStrategy {
resize,
direction,
invert_on_boundaries: true,
}
}
pub fn invert(&self) -> ResizeStrategy {
let resize = match self.resize {
Resize::Increase => Resize::Decrease,
Resize::Decrease => Resize::Increase,
};
let direction = match self.direction {
Some(direction) => Some(direction.invert()),
None => None,
};
ResizeStrategy::new(resize, direction)
}
pub fn resize_type(&self) -> Resize {
self.resize
}
pub fn direction(&self) -> Option<Direction> {
self.direction
}
pub fn direction_horizontal(&self) -> bool {
matches!(
self.direction,
Some(Direction::Left) | Some(Direction::Right)
)
}
pub fn direction_vertical(&self) -> bool {
matches!(self.direction, Some(Direction::Up) | Some(Direction::Down))
}
pub fn resize_increase(&self) -> bool {
self.resize == Resize::Increase
}
pub fn resize_decrease(&self) -> bool {
self.resize == Resize::Decrease
}
pub fn move_left_border_left(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Left))
}
pub fn move_left_border_right(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Left))
}
pub fn move_lower_border_down(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Down))
}
pub fn move_lower_border_up(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Down))
}
pub fn move_upper_border_up(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Up))
}
pub fn move_upper_border_down(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Up))
}
pub fn move_right_border_right(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Right))
}
pub fn move_right_border_left(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Right))
}
pub fn move_all_borders_out(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == None)
}
pub fn move_all_borders_in(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == None)
}
}
impl fmt::Display for ResizeStrategy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let resize = match self.resize {
Resize::Increase => "increase",
Resize::Decrease => "decrease",
};
let border = match self.direction {
Some(Direction::Left) => "left",
Some(Direction::Down) => "bottom",
Some(Direction::Up) => "top",
Some(Direction::Right) => "right",
None => "every",
};
write!(f, "{} size on {} border", resize, border)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
// FIXME: This should be extended to handle different button clicks (not just
// left click) and the `ScrollUp` and `ScrollDown` events could probably be
// merged into a single `Scroll(isize)` event.
pub enum Mouse {
ScrollUp(usize), // number of lines
ScrollDown(usize), // number of lines
LeftClick(isize, usize), // line and column
RightClick(isize, usize), // line and column
Hold(isize, usize), // line and column
Release(isize, usize), // line and column
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FileMetadata {
pub is_dir: bool,
pub is_file: bool,
pub is_symlink: bool,
pub len: u64,
}
impl From<Metadata> for FileMetadata {
fn from(metadata: Metadata) -> Self {
FileMetadata {
is_dir: metadata.is_dir(),
is_file: metadata.is_file(),
is_symlink: metadata.is_symlink(),
len: metadata.len(),
}
}
}
/// These events can be subscribed to with subscribe method exported by `zellij-tile`.
/// Once subscribed to, they will trigger the `update` method of the `ZellijPlugin` trait.
#[derive(Debug, Clone, PartialEq, EnumDiscriminants, ToString, Serialize, Deserialize)]
#[strum_discriminants(derive(EnumString, Hash, Serialize, Deserialize))]
#[strum_discriminants(name(EventType))]
#[non_exhaustive]
pub enum Event {
ModeUpdate(ModeInfo),
TabUpdate(Vec<TabInfo>),
PaneUpdate(PaneManifest),
/// A key was pressed while the user is focused on this plugin's pane
Key(KeyWithModifier),
/// A mouse event happened while the user is focused on this plugin's pane
Mouse(Mouse),
/// A timer expired set by the `set_timeout` method exported by `zellij-tile`.
Timer(f64),
/// Text was copied to the clipboard anywhere in the app
CopyToClipboard(CopyDestination),
/// Failed to copy text to clipboard anywhere in the app
SystemClipboardFailure,
/// Input was received anywhere in the app
InputReceived,
/// This plugin became visible or invisible
Visible(bool),
/// A message from one of the plugin's workers
CustomMessage(
String, // message
String, // payload
),
/// A file was created somewhere in the Zellij CWD folder
FileSystemCreate(Vec<(PathBuf, Option<FileMetadata>)>),
/// A file was accessed somewhere in the Zellij CWD folder
FileSystemRead(Vec<(PathBuf, Option<FileMetadata>)>),
/// A file was modified somewhere in the Zellij CWD folder
FileSystemUpdate(Vec<(PathBuf, Option<FileMetadata>)>),
/// A file was deleted somewhere in the Zellij CWD folder
FileSystemDelete(Vec<(PathBuf, Option<FileMetadata>)>),
/// A Result of plugin permission request
PermissionRequestResult(PermissionStatus),
SessionUpdate(
Vec<SessionInfo>,
Vec<(String, Duration)>, // resurrectable sessions
),
RunCommandResult(Option<i32>, Vec<u8>, Vec<u8>, BTreeMap<String, String>), // exit_code, STDOUT, STDERR,
// context
WebRequestResult(
u16,
BTreeMap<String, String>,
Vec<u8>,
BTreeMap<String, String>,
), // status,
// headers,
// body,
// context
CommandPaneOpened(u32, Context), // u32 - terminal_pane_id
CommandPaneExited(u32, Option<i32>, Context), // u32 - terminal_pane_id, Option<i32> -
// exit_code
PaneClosed(PaneId),
EditPaneOpened(u32, Context), // u32 - terminal_pane_id
EditPaneExited(u32, Option<i32>, Context), // u32 - terminal_pane_id, Option<i32> - exit code
CommandPaneReRun(u32, Context), // u32 - terminal_pane_id, Option<i32> -
FailedToWriteConfigToDisk(Option<String>), // String -> the file path we failed to write
ListClients(Vec<ClientInfo>),
}
#[derive(
Debug,
PartialEq,
Eq,
Hash,
Copy,
Clone,
EnumDiscriminants,
ToString,
Serialize,
Deserialize,
PartialOrd,
Ord,
)]
#[strum_discriminants(derive(EnumString, Hash, Serialize, Deserialize, Display, PartialOrd, Ord))]
#[strum_discriminants(name(PermissionType))]
#[non_exhaustive]
pub enum Permission {
ReadApplicationState,
ChangeApplicationState,
OpenFiles,
RunCommands,
OpenTerminalsOrPlugins,
WriteToStdin,
WebAccess,
ReadCliPipes,
MessageAndLaunchOtherPlugins,
Reconfigure,
}
impl PermissionType {
pub fn display_name(&self) -> String {
match self {
PermissionType::ReadApplicationState => {
"Access Zellij state (Panes, Tabs and UI)".to_owned()
},
PermissionType::ChangeApplicationState => {
"Change Zellij state (Panes, Tabs and UI) and run commands".to_owned()
},
PermissionType::OpenFiles => "Open files (eg. for editing)".to_owned(),
PermissionType::RunCommands => "Run commands".to_owned(),
PermissionType::OpenTerminalsOrPlugins => "Start new terminals and plugins".to_owned(),
PermissionType::WriteToStdin => "Write to standard input (STDIN)".to_owned(),
PermissionType::WebAccess => "Make web requests".to_owned(),
PermissionType::ReadCliPipes => "Control command line pipes and output".to_owned(),
PermissionType::MessageAndLaunchOtherPlugins => {
"Send messages to and launch other plugins".to_owned()
},
PermissionType::Reconfigure => "Change Zellij runtime configuration".to_owned(),
}
}
}
#[derive(Debug, Clone)]
pub struct PluginPermission {
pub name: String,
pub permissions: Vec<PermissionType>,
}
impl PluginPermission {
pub fn new(name: String, permissions: Vec<PermissionType>) -> Self {
PluginPermission { name, permissions }
}
}
/// Describes the different input modes, which change the way that keystrokes will be interpreted.
#[derive(
Debug,
PartialEq,
Eq,
Hash,
Copy,
Clone,
EnumIter,
Serialize,
Deserialize,
ArgEnum,
PartialOrd,
Ord,
)]
pub enum InputMode {
/// In `Normal` mode, input is always written to the terminal, except for the shortcuts leading
/// to other modes
#[serde(alias = "normal")]