-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
lib.rs
1265 lines (1140 loc) · 39.9 KB
/
lib.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
//! encode and decode the frames for the mux protocol.
//! The frames include the length of a PDU as well as an identifier
//! that informs us how to decode it. The length, ident and serial
//! number are encoded using a variable length integer encoding.
//! Rather than rely solely on serde to serialize and deserialize an
//! enum, we encode the enum variants with a version/identifier tag
//! for ourselves. This will make it a little easier to manage
//! client and server instances that are built from different versions
//! of this code; in this way the client and server can more gracefully
//! manage unknown enum variants.
#![allow(dead_code)]
#![allow(clippy::range_plus_one)]
use anyhow::{bail, Context as _, Error};
use config::keyassignment::{PaneDirection, ScrollbackEraseMode};
use mux::client::{ClientId, ClientInfo};
use mux::pane::PaneId;
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::tab::{PaneNode, SerdeUrl, SplitRequest, TabId};
use mux::window::WindowId;
use portable_pty::CommandBuilder;
use rangeset::*;
use serde::{Deserialize, Serialize};
use smol::io::AsyncWriteExt;
use smol::prelude::*;
use std::collections::HashMap;
use std::convert::TryInto;
use std::io::Cursor;
use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
use termwiz::hyperlink::Hyperlink;
use termwiz::image::{ImageData, TextureCoordinate};
use termwiz::surface::{Line, SequenceNo};
use thiserror::Error;
use wezterm_term::color::ColorPalette;
use wezterm_term::{Alert, ClipboardSelection, StableRowIndex, TerminalSize};
#[derive(Error, Debug)]
#[error("Corrupt Response: {0}")]
pub struct CorruptResponse(String);
/// Returns the encoded length of the leb128 representation of value
fn encoded_length(value: u64) -> usize {
struct NullWrite {}
impl std::io::Write for NullWrite {
fn write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error> {
Ok(buf.len())
}
fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
Ok(())
}
}
leb128::write::unsigned(&mut NullWrite {}, value).unwrap()
}
const COMPRESSED_MASK: u64 = 1 << 63;
fn encode_raw_as_vec(
ident: u64,
serial: u64,
data: &[u8],
is_compressed: bool,
) -> anyhow::Result<Vec<u8>> {
let len = data.len() + encoded_length(ident) + encoded_length(serial);
let masked_len = if is_compressed {
(len as u64) | COMPRESSED_MASK
} else {
len as u64
};
// Double-buffer the data; since we run with nodelay enabled, it is
// desirable for the write to be a single packet (or at least, for
// the header portion to go out in a single packet)
let mut buffer = Vec::with_capacity(len + encoded_length(masked_len));
leb128::write::unsigned(&mut buffer, masked_len).context("writing pdu len")?;
leb128::write::unsigned(&mut buffer, serial).context("writing pdu serial")?;
leb128::write::unsigned(&mut buffer, ident).context("writing pdu ident")?;
buffer.extend_from_slice(data);
if is_compressed {
metrics::histogram!("pdu.encode.compressed.size").record(buffer.len() as f64);
} else {
metrics::histogram!("pdu.encode.size").record(buffer.len() as f64);
}
Ok(buffer)
}
/// Encode a frame. If the data is compressed, the high bit of the length
/// is set to indicate that. The data written out has the format:
/// tagged_len: leb128 (u64 msb is set if data is compressed)
/// serial: leb128
/// ident: leb128
/// data bytes
fn encode_raw<W: std::io::Write>(
ident: u64,
serial: u64,
data: &[u8],
is_compressed: bool,
mut w: W,
) -> anyhow::Result<usize> {
let buffer = encode_raw_as_vec(ident, serial, data, is_compressed)?;
w.write_all(&buffer).context("writing pdu data buffer")?;
Ok(buffer.len())
}
async fn encode_raw_async<W: Unpin + AsyncWriteExt>(
ident: u64,
serial: u64,
data: &[u8],
is_compressed: bool,
w: &mut W,
) -> anyhow::Result<usize> {
let buffer = encode_raw_as_vec(ident, serial, data, is_compressed)?;
w.write_all(&buffer)
.await
.context("writing pdu data buffer")?;
Ok(buffer.len())
}
/// Read a single leb128 encoded value from the stream
async fn read_u64_async<R>(r: &mut R) -> anyhow::Result<u64>
where
R: Unpin + AsyncRead + std::fmt::Debug,
{
let mut buf = vec![];
loop {
let mut byte = [0u8];
let nread = r.read(&mut byte).await?;
if nread == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"EOF while reading leb128 encoded value",
)
.into());
}
buf.push(byte[0]);
match leb128::read::unsigned(&mut buf.as_slice()) {
Ok(n) => {
return Ok(n);
}
Err(leb128::read::Error::IoError(_)) => continue,
Err(leb128::read::Error::Overflow) => anyhow::bail!("leb128 is too large"),
}
}
}
/// Read a single leb128 encoded value from the stream
fn read_u64<R: std::io::Read>(mut r: R) -> anyhow::Result<u64> {
leb128::read::unsigned(&mut r)
.map_err(|err| match err {
leb128::read::Error::IoError(ioerr) => anyhow::Error::new(ioerr),
err => anyhow::Error::new(err),
})
.context("reading leb128")
}
#[derive(Debug)]
struct Decoded {
ident: u64,
serial: u64,
data: Vec<u8>,
is_compressed: bool,
}
/// Decode a frame.
/// See encode_raw() for the frame format.
async fn decode_raw_async<R: Unpin + AsyncRead + std::fmt::Debug>(
r: &mut R,
max_serial: Option<u64>,
) -> anyhow::Result<Decoded> {
let len = read_u64_async(r)
.await
.context("decode_raw_async failed to read PDU length")?;
let (len, is_compressed) = if (len & COMPRESSED_MASK) != 0 {
(len & !COMPRESSED_MASK, true)
} else {
(len, false)
};
let serial = read_u64_async(r)
.await
.context("decode_raw_async failed to read PDU serial")?;
if let Some(max_serial) = max_serial {
if serial > max_serial && max_serial > 0 {
return Err(CorruptResponse(format!(
"decode_raw_async: serial {serial} is implausibly large \
(bigger than {max_serial})"
))
.into());
}
}
let ident = read_u64_async(r)
.await
.context("decode_raw_async failed to read PDU ident")?;
let data_len =
match (len as usize).overflowing_sub(encoded_length(ident) + encoded_length(serial)) {
(_, true) => {
return Err(CorruptResponse(format!(
"decode_raw_async: sizes don't make sense: \
len:{len} serial:{serial} (enc={}) ident:{ident} (enc={})",
encoded_length(serial),
encoded_length(ident)
))
.into());
}
(data_len, false) => data_len,
};
if is_compressed {
metrics::histogram!("pdu.decode.compressed.size").record(data_len as f64);
} else {
metrics::histogram!("pdu.decode.size").record(data_len as f64);
}
let mut data = vec![0u8; data_len];
r.read_exact(&mut data).await.with_context(|| {
format!(
"decode_raw_async failed to read {} bytes of data \
for PDU of length {} with serial={} ident={}",
data_len, len, serial, ident
)
})?;
Ok(Decoded {
ident,
serial,
data,
is_compressed,
})
}
/// Decode a frame.
/// See encode_raw() for the frame format.
fn decode_raw<R: std::io::Read>(mut r: R) -> anyhow::Result<Decoded> {
let len = read_u64(r.by_ref()).context("reading PDU length")?;
let (len, is_compressed) = if (len & COMPRESSED_MASK) != 0 {
(len & !COMPRESSED_MASK, true)
} else {
(len, false)
};
let serial = read_u64(r.by_ref()).context("reading PDU serial")?;
let ident = read_u64(r.by_ref()).context("reading PDU ident")?;
let data_len =
match (len as usize).overflowing_sub(encoded_length(ident) + encoded_length(serial)) {
(_, true) => {
anyhow::bail!(
"sizes don't make sense: len:{} serial:{} (enc={}) ident:{} (enc={})",
len,
serial,
encoded_length(serial),
ident,
encoded_length(ident)
);
}
(data_len, false) => data_len,
};
if is_compressed {
metrics::histogram!("pdu.decode.compressed.size").record(data_len as f64);
} else {
metrics::histogram!("pdu.decode.size").record(data_len as f64);
}
let mut data = vec![0u8; data_len];
r.read_exact(&mut data).with_context(|| {
format!(
"reading {} bytes of data for PDU of length {} with serial={} ident={}",
data_len, len, serial, ident
)
})?;
Ok(Decoded {
ident,
serial,
data,
is_compressed,
})
}
#[derive(Debug, PartialEq)]
pub struct DecodedPdu {
pub serial: u64,
pub pdu: Pdu,
}
/// If the serialized size is larger than this, then we'll consider compressing it
const COMPRESS_THRESH: usize = 32;
fn serialize<T: serde::Serialize>(t: &T) -> Result<(Vec<u8>, bool), Error> {
let mut uncompressed = Vec::new();
let mut encode = varbincode::Serializer::new(&mut uncompressed);
t.serialize(&mut encode)?;
if uncompressed.len() <= COMPRESS_THRESH {
return Ok((uncompressed, false));
}
// It's a little heavy; let's try compressing it
let mut compressed = Vec::new();
let mut compress = zstd::Encoder::new(&mut compressed, zstd::DEFAULT_COMPRESSION_LEVEL)?;
let mut encode = varbincode::Serializer::new(&mut compress);
t.serialize(&mut encode)?;
drop(encode);
compress.finish()?;
log::debug!(
"serialized+compress len {} vs {}",
compressed.len(),
uncompressed.len()
);
if compressed.len() < uncompressed.len() {
Ok((compressed, true))
} else {
Ok((uncompressed, false))
}
}
fn deserialize<T: serde::de::DeserializeOwned, R: std::io::Read>(
mut r: R,
is_compressed: bool,
) -> Result<T, Error> {
if is_compressed {
let mut decompress = zstd::Decoder::new(r)?;
let mut decode = varbincode::Deserializer::new(&mut decompress);
serde::Deserialize::deserialize(&mut decode).map_err(Into::into)
} else {
let mut decode = varbincode::Deserializer::new(&mut r);
serde::Deserialize::deserialize(&mut decode).map_err(Into::into)
}
}
macro_rules! pdu {
($( $name:ident:$vers:expr),* $(,)?) => {
#[derive(PartialEq, Debug)]
pub enum Pdu {
Invalid{ident: u64},
$(
$name($name)
,)*
}
impl Pdu {
pub fn encode<W: std::io::Write>(&self, w: W, serial: u64) -> Result<(), Error> {
match self {
Pdu::Invalid{..} => bail!("attempted to serialize Pdu::Invalid"),
$(
Pdu::$name(s) => {
let (data, is_compressed) = serialize(s)?;
let encoded_size = encode_raw($vers, serial, &data, is_compressed, w)?;
log::debug!("encode {} size={encoded_size}", stringify!($name));
metrics::histogram!("pdu.size", "pdu" => stringify!($name)).record(encoded_size as f64);
metrics::histogram!("pdu.size.rate", "pdu" => stringify!($name)).record(encoded_size as f64);
Ok(())
}
,)*
}
}
pub async fn encode_async<W: Unpin + AsyncWriteExt>(&self, w: &mut W, serial: u64) -> Result<(), Error> {
match self {
Pdu::Invalid{..} => bail!("attempted to serialize Pdu::Invalid"),
$(
Pdu::$name(s) => {
let (data, is_compressed) = serialize(s)?;
let encoded_size = encode_raw_async($vers, serial, &data, is_compressed, w).await?;
log::debug!("encode_async {} size={encoded_size}", stringify!($name));
metrics::histogram!("pdu.size", "pdu" => stringify!($name)).record(encoded_size as f64);
metrics::histogram!("pdu.size.rate", "pdu" => stringify!($name)).record(encoded_size as f64);
Ok(())
}
,)*
}
}
pub fn pdu_name(&self) -> &'static str {
match self {
Pdu::Invalid{..} => "Invalid",
$(
Pdu::$name(_) => {
stringify!($name)
}
,)*
}
}
pub fn decode<R: std::io::Read>(r: R) -> Result<DecodedPdu, Error> {
let decoded = decode_raw(r).context("decoding a PDU")?;
match decoded.ident {
$(
$vers => {
metrics::histogram!("pdu.size", "pdu" => stringify!($name)).record(decoded.data.len() as f64);
metrics::histogram!("pdu.size.rate", "pdu" => stringify!($name)).record(decoded.data.len() as f64);
Ok(DecodedPdu {
serial: decoded.serial,
pdu: Pdu::$name(deserialize(decoded.data.as_slice(), decoded.is_compressed)?)
})
}
,)*
_ => {
metrics::histogram!("pdu.size", "pdu" => "??").record(decoded.data.len() as f64);
metrics::histogram!("pdu.size.rate", "pdu" => "??").record(decoded.data.len() as f64);
Ok(DecodedPdu {
serial: decoded.serial,
pdu: Pdu::Invalid{ident:decoded.ident}
})
}
}
}
pub async fn decode_async<R>(r: &mut R, max_serial: Option<u64>) -> Result<DecodedPdu, Error>
where R: std::marker::Unpin,
R: AsyncRead,
R: std::fmt::Debug
{
let decoded = decode_raw_async(r, max_serial).await.context("decoding a PDU")?;
match decoded.ident {
$(
$vers => {
metrics::histogram!("pdu.size", "pdu" => stringify!($name)).record(decoded.data.len() as f64);
Ok(DecodedPdu {
serial: decoded.serial,
pdu: Pdu::$name(deserialize(decoded.data.as_slice(), decoded.is_compressed)?)
})
}
,)*
_ => {
metrics::histogram!("pdu.size", "pdu" => "??").record(decoded.data.len() as f64);
Ok(DecodedPdu {
serial: decoded.serial,
pdu: Pdu::Invalid{ident:decoded.ident}
})
}
}
}
}
}
}
/// The overall version of the codec.
/// This must be bumped when backwards incompatible changes
/// are made to the types and protocol.
pub const CODEC_VERSION: usize = 43;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
// This allows removal of obsolete structs,
// and defining newer structs as the protocol evolves.
pdu! {
ErrorResponse: 0,
Ping: 1,
Pong: 2,
ListPanes: 3,
ListPanesResponse: 4,
SpawnResponse: 8,
WriteToPane: 9,
UnitResponse: 10,
SendKeyDown: 11,
SendMouseEvent: 12,
SendPaste: 13,
Resize: 14,
SetClipboard: 20,
GetLines: 22,
GetLinesResponse: 23,
GetPaneRenderChanges: 24,
GetPaneRenderChangesResponse: 25,
GetCodecVersion: 26,
GetCodecVersionResponse: 27,
GetTlsCreds: 28,
GetTlsCredsResponse: 29,
LivenessResponse: 30,
SearchScrollbackRequest: 31,
SearchScrollbackResponse: 32,
SetPaneZoomed: 33,
SplitPane: 34,
KillPane: 35,
SpawnV2: 36,
PaneRemoved: 37,
SetPalette: 38,
NotifyAlert: 39,
SetClientId: 40,
GetClientList: 41,
GetClientListResponse: 42,
SetWindowWorkspace: 43,
WindowWorkspaceChanged: 44,
SetFocusedPane: 45,
GetImageCell: 46,
GetImageCellResponse: 47,
MovePaneToNewTab: 48,
MovePaneToNewTabResponse: 49,
ActivatePaneDirection: 50,
GetPaneRenderableDimensions: 51,
GetPaneRenderableDimensionsResponse: 52,
PaneFocused: 53,
TabResized: 54,
TabAddedToWindow: 55,
TabTitleChanged: 56,
WindowTitleChanged: 57,
RenameWorkspace: 58,
EraseScrollbackRequest: 59,
GetPaneDirection: 60,
GetPaneDirectionResponse: 61,
AdjustPaneSize: 62,
}
impl Pdu {
/// Returns true if this type of Pdu represents action taken
/// directly by a user, rather than background traffic on
/// a live connection
pub fn is_user_input(&self) -> bool {
match self {
Self::WriteToPane(_)
| Self::SendKeyDown(_)
| Self::SendMouseEvent(_)
| Self::SendPaste(_)
| Self::Resize(_)
| Self::SetClipboard(_)
| Self::SetPaneZoomed(_)
| Self::SpawnV2(_) => true,
_ => false,
}
}
pub fn stream_decode(buffer: &mut Vec<u8>) -> anyhow::Result<Option<DecodedPdu>> {
let mut cursor = Cursor::new(buffer.as_slice());
match Self::decode(&mut cursor) {
Ok(decoded) => {
let consumed = cursor.position() as usize;
let remain = buffer.len() - consumed;
// Remove `consumed` bytes from the start of the vec.
// This is safe because the vec is just bytes and we are
// constrained the offsets accordingly.
unsafe {
std::ptr::copy_nonoverlapping(
buffer.as_ptr().add(consumed),
buffer.as_mut_ptr(),
remain,
);
}
buffer.truncate(remain);
Ok(Some(decoded))
}
Err(err) => {
if let Some(ioerr) = err.root_cause().downcast_ref::<std::io::Error>() {
match ioerr.kind() {
std::io::ErrorKind::UnexpectedEof | std::io::ErrorKind::WouldBlock => {
return Ok(None);
}
_ => {}
}
} else {
log::error!("not an ioerror in stream_decode: {:?}", err);
}
Err(err)
}
}
}
pub fn try_read_and_decode<R: std::io::Read>(
r: &mut R,
buffer: &mut Vec<u8>,
) -> anyhow::Result<Option<DecodedPdu>> {
loop {
if let Some(decoded) =
Self::stream_decode(buffer).context("stream_decode of buffer for PDU")?
{
return Ok(Some(decoded));
}
let mut buf = [0u8; 4096];
let size = match r.read(&mut buf) {
Ok(size) => size,
Err(err) => {
if err.kind() == std::io::ErrorKind::WouldBlock {
return Ok(None);
}
return Err(err.into());
}
};
if size == 0 {
return Err(
std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "End Of File").into(),
);
}
buffer.extend_from_slice(&buf[0..size]);
}
}
pub fn pane_id(&self) -> Option<PaneId> {
match self {
Pdu::GetPaneRenderChangesResponse(GetPaneRenderChangesResponse { pane_id, .. })
| Pdu::SetPalette(SetPalette { pane_id, .. })
| Pdu::NotifyAlert(NotifyAlert { pane_id, .. })
| Pdu::SetClipboard(SetClipboard { pane_id, .. })
| Pdu::PaneFocused(PaneFocused { pane_id })
| Pdu::PaneRemoved(PaneRemoved { pane_id }) => Some(*pane_id),
_ => None,
}
}
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct UnitResponse {}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ErrorResponse {
pub reason: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetCodecVersion {}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetCodecVersionResponse {
pub codec_vers: usize,
pub version_string: String,
pub executable_path: PathBuf,
pub config_file_path: Option<PathBuf>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Ping {}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Pong {}
/// Requests a client certificate to authenticate against
/// the TLS based server
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetTlsCreds {}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetTlsCredsResponse {
/// The signing certificate
pub ca_cert_pem: String,
/// A client authentication certificate and private
/// key, PEM encoded
pub client_cert_pem: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ListPanes {}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ListPanesResponse {
pub tabs: Vec<PaneNode>,
pub tab_titles: Vec<String>,
pub window_titles: HashMap<WindowId, String>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SplitPane {
pub pane_id: PaneId,
pub split_request: SplitRequest,
pub command: Option<CommandBuilder>,
pub command_dir: Option<String>,
pub domain: config::keyassignment::SpawnTabDomain,
/// Instead of spawning a command, move the specified
/// pane into the new split target
pub move_pane_id: Option<PaneId>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct MovePaneToNewTab {
pub pane_id: PaneId,
pub window_id: Option<WindowId>,
pub workspace_for_new_window: Option<String>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct MovePaneToNewTabResponse {
pub tab_id: TabId,
pub window_id: WindowId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SpawnV2 {
pub domain: config::keyassignment::SpawnTabDomain,
/// If None, create a new window for this new tab
pub window_id: Option<WindowId>,
pub command: Option<CommandBuilder>,
pub command_dir: Option<String>,
pub size: TerminalSize,
pub workspace: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct PaneRemoved {
pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct KillPane {
pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SpawnResponse {
pub tab_id: TabId,
pub pane_id: PaneId,
pub window_id: WindowId,
pub size: TerminalSize,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct WriteToPane {
pub pane_id: PaneId,
pub data: Vec<u8>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SendPaste {
pub pane_id: PaneId,
pub data: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SendKeyDown {
pub pane_id: TabId,
pub event: termwiz::input::KeyEvent,
pub input_serial: InputSerial,
}
/// InputSerial is used to sequence input requests with output events.
/// It started life as a monotonic sequence number but evolved into
/// the number of milliseconds since the unix epoch.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Copy, PartialOrd, Ord)]
pub struct InputSerial(u64);
impl InputSerial {
pub const fn empty() -> Self {
Self(0)
}
pub fn now() -> Self {
std::time::SystemTime::now().into()
}
pub fn elapsed_millis(&self) -> u64 {
let now = InputSerial::now();
now.0 - self.0
}
}
impl From<std::time::SystemTime> for InputSerial {
fn from(val: std::time::SystemTime) -> Self {
let duration = val
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.expect("SystemTime before unix epoch?");
let millis: u64 = duration
.as_millis()
.try_into()
.expect("millisecond count to fit in u64");
InputSerial(millis)
}
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SendMouseEvent {
pub pane_id: PaneId,
pub event: wezterm_term::input::MouseEvent,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetClipboard {
pub pane_id: PaneId,
pub clipboard: Option<String>,
pub selection: ClipboardSelection,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetWindowWorkspace {
pub window_id: WindowId,
pub workspace: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct RenameWorkspace {
pub old_workspace: String,
pub new_workspace: String,
}
/// This is used both as a notification from server->client
/// and as a configuration request from client->server when
/// the client's preferred configuration changes
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetPalette {
pub pane_id: PaneId,
pub palette: ColorPalette,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct NotifyAlert {
pub pane_id: PaneId,
pub alert: Alert,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct TabAddedToWindow {
pub tab_id: TabId,
pub window_id: WindowId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct TabResized {
pub tab_id: TabId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct TabTitleChanged {
pub tab_id: TabId,
pub title: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct WindowTitleChanged {
pub window_id: WindowId,
pub title: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct PaneFocused {
pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct WindowWorkspaceChanged {
pub window_id: WindowId,
pub workspace: String,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetClientId {
pub client_id: ClientId,
pub is_proxy: bool,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetFocusedPane {
pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetClientList;
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetClientListResponse {
pub clients: Vec<ClientInfo>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Resize {
pub containing_tab_id: TabId,
pub pane_id: PaneId,
pub size: TerminalSize,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetPaneZoomed {
pub containing_tab_id: TabId,
pub pane_id: PaneId,
pub zoomed: bool,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetPaneDirection {
pub pane_id: PaneId,
pub direction: PaneDirection,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct AdjustPaneSize {
pub pane_id: PaneId,
pub direction: PaneDirection,
pub amount: usize,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetPaneDirectionResponse {
pub pane_id: Option<PaneId>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ActivatePaneDirection {
pub pane_id: PaneId,
pub direction: PaneDirection,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetPaneRenderChanges {
pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetPaneRenderableDimensions {
pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetPaneRenderableDimensionsResponse {
pub pane_id: PaneId,
pub cursor_position: StableCursorPosition,
pub dimensions: RenderableDimensions,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct LivenessResponse {
pub pane_id: PaneId,
pub is_alive: bool,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetPaneRenderChangesResponse {
pub pane_id: PaneId,
pub mouse_grabbed: bool,
pub cursor_position: StableCursorPosition,
pub dimensions: RenderableDimensions,
pub dirty_lines: Vec<Range<StableRowIndex>>,
pub title: String,
pub working_dir: Option<SerdeUrl>,
/// Lines that the server thought we'd almost certainly
/// want to fetch as soon as we received this response
pub bonus_lines: SerializedLines,
pub input_serial: Option<InputSerial>,
pub seqno: SequenceNo,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct GetLines {
pub pane_id: PaneId,
pub lines: Vec<Range<StableRowIndex>>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
struct CellCoordinates {
line_idx: usize,
cols: Range<usize>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
struct LineHyperlink {
link: Hyperlink,
coords: Vec<CellCoordinates>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct SerializedImageCell {
pub line_idx: StableRowIndex,
pub cell_idx: usize,
// The following fields are taken from termwiz::image::ImageCell
pub top_left: TextureCoordinate,
pub bottom_right: TextureCoordinate,
/// Image::data::hash() for the ImageCell::data field
pub data_hash: [u8; 32],
pub z_index: i32,
pub padding_left: u16,
pub padding_top: u16,
pub padding_right: u16,
pub padding_bottom: u16,
pub image_id: Option<u32>,
pub placement_id: Option<u32>,
}
/// What's all this?
/// Cells hold references to Arc<Hyperlink> and it is important to us to
/// maintain identity of the hyperlinks in the individual cells, while also
/// only sending a single copy of the associated URL.
/// This section of code extracts the hyperlinks from the cells and builds
/// up a mapping that can be used to restore the identity when the `lines()`
/// method is called.
#[derive(Deserialize, Serialize, PartialEq, Debug, Default)]
pub struct SerializedLines {
lines: Vec<(StableRowIndex, Line)>,
hyperlinks: Vec<LineHyperlink>,
images: Vec<SerializedImageCell>,
}
impl SerializedLines {
/// Reconsitute hyperlinks or other attributes that were decomposed for
/// serialization, and return the line data.
pub fn extract_data(self) -> (Vec<(StableRowIndex, Line)>, Vec<SerializedImageCell>) {
let lines = if self.hyperlinks.is_empty() {
self.lines
} else {
let mut lines = self.lines;
for link in self.hyperlinks {
let url = Arc::new(link.link);
for coord in link.coords {
if let Some((_, line)) = lines.get_mut(coord.line_idx) {
if let Some(cells) =
line.cells_mut_for_attr_changes_only().get_mut(coord.cols)
{
for cell in cells {
cell.attrs_mut().set_hyperlink(Some(Arc::clone(&url)));
}
}