monade-mprocs 0.3.0

A fork of the popular mprocs utility, includable via cargo as a library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use std::fmt::Write;

use anyhow::Result;
use crossterm::event::{
  KeyCode, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};

use crate::key::Key;

pub const CSI: &str = "\x1b[";
pub const SS3: &str = "\x1bO";

/// Specifies terminal modes/configuration that can influence how a KeyCode
/// is encoded when being sent to and application via the pty.
#[derive(Debug, Clone, Copy)]
pub struct KeyCodeEncodeModes {
  pub enable_csi_u_key_encoding: bool,
  pub application_cursor_keys: bool,
  pub newline_mode: bool,
}

impl Default for KeyCodeEncodeModes {
  fn default() -> Self {
    KeyCodeEncodeModes {
      enable_csi_u_key_encoding: false,
      application_cursor_keys: false,
      newline_mode: false,
    }
  }
}

/// Returns the xterm compatible byte sequence that represents this KeyCode
/// and Modifier combination.
pub fn encode_key(key: &Key, modes: KeyCodeEncodeModes) -> Result<String> {
  use KeyCode::*;

  #[cfg(windows)]
  if let Some(encoded) = encode_key_win32(key, modes) {
    return Ok(encoded);
  }

  let code = key.code().clone();
  let mods = key.mods().clone();

  let mut buf = String::new();

  let code = normalize_shift_to_upper_case(code, &mods);
  // Normalize the modifier state for Char's that are uppercase; remove
  // the SHIFT modifier so that reduce ambiguity below
  let mods = match code {
    Char(c)
      if (c.is_ascii_punctuation() || c.is_ascii_uppercase())
        && mods.contains(KeyModifiers::SHIFT) =>
    {
      mods.clone().difference(KeyModifiers::SHIFT)
    }
    _ => mods,
  };

  // Normalize Backspace and Delete
  let code = match code {
    Char('\x7f') => KeyCode::Backspace,
    Char('\x08') => KeyCode::Delete,
    c => c,
  };

  // TODO: also respect self.application_keypad

  match code {
    Char(c)
      if is_ambiguous_ascii_ctrl(c)
        && mods.contains(KeyModifiers::CONTROL)
        && modes.enable_csi_u_key_encoding =>
    {
      csi_u_encode(&mut buf, c, mods, modes.enable_csi_u_key_encoding)?;
    }
    Char(c)
      if c.is_ascii_uppercase() && mods.contains(KeyModifiers::CONTROL) =>
    {
      csi_u_encode(&mut buf, c, mods, modes.enable_csi_u_key_encoding)?;
    }

    Char(c)
      if mods.contains(KeyModifiers::CONTROL) && ctrl_mapping(c).is_some() =>
    {
      let c = ctrl_mapping(c).unwrap();
      if mods.contains(KeyModifiers::ALT) {
        buf.push(0x1b as char);
      }
      buf.push(c);
    }

    // When alt is pressed, send escape first to indicate to the peer that
    // ALT is pressed.  We do this only for ascii alnum characters because
    // eg: on macOS generates altgr style glyphs and keeps the ALT key
    // in the modifier set.  This confuses eg: zsh which then just displays
    // <fffffffff> as the input, so we want to avoid that.
    Char(c)
      if (c.is_ascii_alphanumeric() || c.is_ascii_punctuation())
        && mods.contains(KeyModifiers::ALT) =>
    {
      buf.push(0x1b as char);
      buf.push(c);
    }

    Enter | Esc | Backspace => {
      let c = match code {
        Enter => '\r',
        Esc => '\x1b',
        // Backspace sends the default VERASE which is confusingly
        // the DEL ascii codepoint
        Backspace => '\x7f',
        _ => unreachable!(),
      };
      if mods.contains(KeyModifiers::SHIFT)
        || mods.contains(KeyModifiers::CONTROL)
      {
        csi_u_encode(&mut buf, c, mods, modes.enable_csi_u_key_encoding)?;
      } else {
        if mods.contains(KeyModifiers::ALT) {
          buf.push(0x1b as char);
        }
        buf.push(c);
        if modes.newline_mode && code == Enter {
          buf.push(0x0a as char);
        }
      }
    }

    Tab => {
      if mods.contains(KeyModifiers::ALT) {
        buf.push(0x1b as char);
      }
      let mods = mods & !KeyModifiers::ALT;
      if mods == KeyModifiers::CONTROL {
        buf.push_str("\x1b[9;5u");
      } else if mods == KeyModifiers::CONTROL | KeyModifiers::SHIFT {
        buf.push_str("\x1b[1;5Z");
      } else if mods == KeyModifiers::SHIFT {
        buf.push_str("\x1b[Z");
      } else {
        buf.push('\t');
      }
    }

    Char(c) => {
      if mods.is_empty() {
        buf.push(c);
      } else {
        csi_u_encode(&mut buf, c, mods, modes.enable_csi_u_key_encoding)?;
      }
    }

    Home | End | Up | Down | Right | Left => {
      let (force_app, c) = match code {
        Up => (false, 'A'),
        Down => (false, 'B'),
        Right => (false, 'C'),
        Left => (false, 'D'),
        Home => (false, 'H'),
        End => (false, 'F'),
        _ => unreachable!(),
      };

      let csi_or_ss3 = if force_app
        || (
          modes.application_cursor_keys
          // Strict reading of DECCKM suggests that application_cursor_keys
          // only applies when DECANM and DECKPAM are active, but that seems
          // to break unmodified cursor keys in vim
          /* && self.dec_ansi_mode && self.application_keypad */
        ) {
        // Use SS3 in application mode
        SS3
      } else {
        // otherwise use regular CSI
        CSI
      };

      if mods.contains(KeyModifiers::ALT)
        || mods.contains(KeyModifiers::SHIFT)
        || mods.contains(KeyModifiers::CONTROL)
      {
        write!(buf, "{}1;{}{}", CSI, 1 + encode_modifiers(mods), c)?;
      } else {
        write!(buf, "{}{}", csi_or_ss3, c)?;
      }
    }

    PageUp | PageDown | Insert | Delete => {
      let c = match code {
        Insert => 2,
        Delete => 3,
        PageUp => 5,
        PageDown => 6,
        _ => unreachable!(),
      };

      if mods.contains(KeyModifiers::ALT)
        || mods.contains(KeyModifiers::SHIFT)
        || mods.contains(KeyModifiers::CONTROL)
      {
        write!(buf, "\x1b[{};{}~", c, 1 + encode_modifiers(mods))?;
      } else {
        write!(buf, "\x1b[{}~", c)?;
      }
    }

    F(n) => {
      if mods.is_empty() && n < 5 {
        // F1-F4 are encoded using SS3 if there are no modifiers
        write!(
          buf,
          "{}",
          match n {
            1 => "\x1bOP",
            2 => "\x1bOQ",
            3 => "\x1bOR",
            4 => "\x1bOS",
            _ => unreachable!("wat?"),
          }
        )?;
      } else {
        // Higher numbered F-keys plus modified F-keys are encoded
        // using CSI instead of SS3.
        let intro = match n {
          1 => "\x1b[11",
          2 => "\x1b[12",
          3 => "\x1b[13",
          4 => "\x1b[14",
          5 => "\x1b[15",
          6 => "\x1b[17",
          7 => "\x1b[18",
          8 => "\x1b[19",
          9 => "\x1b[20",
          10 => "\x1b[21",
          11 => "\x1b[23",
          12 => "\x1b[24",
          _ => panic!("unhandled fkey number {}", n),
        };
        let encoded_mods = encode_modifiers(mods);
        if encoded_mods == 0 {
          // If no modifiers are held, don't send the modifier
          // sequence, as the modifier encoding is a CSI-u extension.
          write!(buf, "{}~", intro)?;
        } else {
          write!(buf, "{};{}~", intro, 1 + encoded_mods)?;
        }
      }
    }

    BackTab | Null => todo!(),
  };

  Ok(buf)
}

fn encode_modifiers(mods: KeyModifiers) -> u8 {
  let mut number = 0;
  if mods.contains(KeyModifiers::SHIFT) {
    number |= 1;
  }
  if mods.contains(KeyModifiers::ALT) {
    number |= 2;
  }
  if mods.contains(KeyModifiers::CONTROL) {
    number |= 4;
  }
  number
}

/// characters that when masked for CTRL could be an ascii control character
/// or could be a key that a user legitimately wants to process in their
/// terminal application
fn is_ambiguous_ascii_ctrl(c: char) -> bool {
  match c {
    'i' | 'I' | 'm' | 'M' | '[' | '{' | '@' => true,
    _ => false,
  }
}

/// Map c to its Ctrl equivalent.
/// In theory, this mapping is simply translating alpha characters
/// to upper case and then masking them by 0x1f, but xterm inherits
/// some built-in translation from legacy X11 so that are some
/// aliased mappings and a couple that might be technically tied
/// to US keyboard layout (particularly the punctuation characters
/// produced in combination with SHIFT) that may not be 100%
/// the right thing to do here for users with non-US layouts.
fn ctrl_mapping(c: char) -> Option<char> {
  Some(match c {
    '@' | '`' | ' ' | '2' => '\x00',
    'A' | 'a' => '\x01',
    'B' | 'b' => '\x02',
    'C' | 'c' => '\x03',
    'D' | 'd' => '\x04',
    'E' | 'e' => '\x05',
    'F' | 'f' => '\x06',
    'G' | 'g' => '\x07',
    'H' | 'h' => '\x08',
    'I' | 'i' => '\x09',
    'J' | 'j' => '\x0a',
    'K' | 'k' => '\x0b',
    'L' | 'l' => '\x0c',
    'M' | 'm' => '\x0d',
    'N' | 'n' => '\x0e',
    'O' | 'o' => '\x0f',
    'P' | 'p' => '\x10',
    'Q' | 'q' => '\x11',
    'R' | 'r' => '\x12',
    'S' | 's' => '\x13',
    'T' | 't' => '\x14',
    'U' | 'u' => '\x15',
    'V' | 'v' => '\x16',
    'W' | 'w' => '\x17',
    'X' | 'x' => '\x18',
    'Y' | 'y' => '\x19',
    'Z' | 'z' => '\x1a',
    '[' | '3' | '{' => '\x1b',
    '\\' | '4' | '|' => '\x1c',
    ']' | '5' | '}' => '\x1d',
    '^' | '6' | '~' => '\x1e',
    '_' | '7' | '/' => '\x1f',
    '8' | '?' => '\x7f', // `Delete`
    _ => return None,
  })
}

fn csi_u_encode(
  buf: &mut String,
  c: char,
  mods: KeyModifiers,
  enable_csi_u_key_encoding: bool,
) -> Result<()> {
  if enable_csi_u_key_encoding {
    write!(buf, "\x1b[{};{}u", c as u32, 1 + encode_modifiers(mods))?;
  } else {
    let c = if mods.contains(KeyModifiers::CONTROL) && ctrl_mapping(c).is_some()
    {
      ctrl_mapping(c).unwrap()
    } else {
      c
    };
    if mods.contains(KeyModifiers::ALT) {
      buf.push(0x1b as char);
    }
    write!(buf, "{}", c)?;
  }
  Ok(())
}

/// if SHIFT is held and we have KeyCode::Char('c') we want to normalize
/// that keycode to KeyCode::Char('C'); that is what this function does.
/// In theory we should give the same treatment to keys like `[` -> `{`
/// but that assumes something about the keyboard layout and is probably
/// better done in the gui frontend rather than this layer.
/// In fact, this function might be better off if it lived elsewhere.
pub fn normalize_shift_to_upper_case(
  code: KeyCode,
  modifiers: &KeyModifiers,
) -> KeyCode {
  if modifiers.contains(KeyModifiers::SHIFT) {
    match code {
      KeyCode::Char(c) if c.is_ascii_lowercase() => KeyCode::Char(c),
      _ => code,
    }
  } else {
    code
  }
}

/// <https://github.com/microsoft/terminal/blob/main/doc/specs/%234999%20-%20Improved%20keyboard%20handling%20in%20Conpty.md>
#[cfg(windows)]
pub fn encode_key_win32(
  key: &Key,
  _modes: KeyCodeEncodeModes,
) -> Option<String> {
  // <https://docs.microsoft.com/en-us/windows/console/key-event-record-str>
  // defines the dwControlKeyState values
  let mut control_key_state = 0;

  if key.mods().contains(KeyModifiers::SHIFT) {
    control_key_state |= winapi::um::wincon::SHIFT_PRESSED;
  }
  if key.mods().contains(KeyModifiers::ALT) {
    control_key_state |= winapi::um::wincon::LEFT_ALT_PRESSED;
  }
  if key.mods().contains(KeyModifiers::CONTROL) {
    control_key_state |= winapi::um::wincon::LEFT_CTRL_PRESSED;
  }

  let vkey = virtual_key_code(key.code())?;
  let uni = match key.code() {
    KeyCode::Char(c) => {
      let c = *c;
      let c = match c {
        // Delete key is transmitted as 0x0
        '\x7f' => '\x00',
        // Backspace key is transmitted as 0x8, 0x7f or 0x0
        '\x08' => {
          if key.mods().contains(KeyModifiers::CONTROL) {
            if key.mods().contains(KeyModifiers::ALT)
              || key.mods().contains(KeyModifiers::SHIFT)
            {
              '\x00'
            } else {
              '\x7f'
            }
          } else {
            '\x08'
          }
        }
        _ => c,
      };

      let c = if key.mods().contains(KeyModifiers::CONTROL) {
        // Ensure that we rewrite the unicode value to the ASCII CTRL
        // equivalent value.
        // <https://github.com/microsoft/terminal/issues/13134>
        ctrl_mapping(c).unwrap_or(c)
      } else {
        c
      };
      c as u32
    }
    KeyCode::Backspace => 0x8,
    KeyCode::Enter => 0xd,
    KeyCode::Left => 0,
    KeyCode::Right => 0,
    KeyCode::Up => 0,
    KeyCode::Down => 0,
    KeyCode::Home => 0,
    KeyCode::End => 0,
    KeyCode::PageUp => 0,
    KeyCode::PageDown => 0,
    KeyCode::Tab => 0x9,
    KeyCode::BackTab => 0,
    KeyCode::Delete => 0x7f,
    KeyCode::Insert => 0,
    KeyCode::F(_) => 0,
    KeyCode::Null => 0,
    KeyCode::Esc => 0,
  };

  let scan_code = 0;
  let key_down = 1;
  let repeat_count = 1;
  Some(format!(
    "\u{1b}[{};{};{};{};{};{}_",
    vkey, scan_code, uni, key_down, control_key_state, repeat_count
  ))
}

/// <https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes>
#[cfg(windows)]
fn virtual_key_code(code: &KeyCode) -> Option<i32> {
  let code = match code {
    KeyCode::Char(c) => match c {
      '0'..='9' => *c as i32,
      'a'..='z' => c.to_ascii_uppercase() as i32,
      ' ' => winapi::um::winuser::VK_SPACE,
      '*' => winapi::um::winuser::VK_MULTIPLY,
      '+' => winapi::um::winuser::VK_ADD,
      ',' => winapi::um::winuser::VK_SEPARATOR,
      '-' => winapi::um::winuser::VK_SUBTRACT,
      '.' => winapi::um::winuser::VK_DECIMAL,
      '/' => winapi::um::winuser::VK_DIVIDE,
      _ => return None,
    },
    KeyCode::Backspace => winapi::um::winuser::VK_BACK,
    KeyCode::Enter => winapi::um::winuser::VK_RETURN,
    KeyCode::Left => winapi::um::winuser::VK_LEFT,
    KeyCode::Right => winapi::um::winuser::VK_RIGHT,
    KeyCode::Up => winapi::um::winuser::VK_UP,
    KeyCode::Down => winapi::um::winuser::VK_DOWN,
    KeyCode::Home => winapi::um::winuser::VK_HOME,
    KeyCode::End => winapi::um::winuser::VK_END,
    KeyCode::PageUp => winapi::um::winuser::VK_PRIOR,
    KeyCode::PageDown => winapi::um::winuser::VK_NEXT,
    KeyCode::Tab => winapi::um::winuser::VK_TAB,
    KeyCode::BackTab => return None,
    KeyCode::Delete => winapi::um::winuser::VK_DELETE,
    KeyCode::Insert => winapi::um::winuser::VK_INSERT,
    KeyCode::F(n) => match n {
      1..=24 => winapi::um::winuser::VK_F1 - 1 + *n as i32,
      _ => return None,
    },
    KeyCode::Null => 0,
    KeyCode::Esc => winapi::um::winuser::VK_ESCAPE,
  };

  Some(code)
}

pub fn print_key(key: &Key) -> String {
  let mut buf = String::new();

  if key.mods().contains(KeyModifiers::CONTROL) {
    buf.push_str("C-");
  }
  if key.mods().contains(KeyModifiers::SHIFT) {
    buf.push_str("S-");
  }
  if key.mods().contains(KeyModifiers::ALT) {
    buf.push_str("M-");
  }

  match key.code() {
    KeyCode::Backspace => buf.push_str("Backspace"),
    KeyCode::Enter => buf.push_str("Enter"),
    KeyCode::Left => buf.push_str("Left"),
    KeyCode::Right => buf.push_str("Right"),
    KeyCode::Up => buf.push_str("Up"),
    KeyCode::Down => buf.push_str("Down"),
    KeyCode::Home => buf.push_str("Home"),
    KeyCode::End => buf.push_str("End"),
    KeyCode::PageUp => buf.push_str("PgUp"),
    KeyCode::PageDown => buf.push_str("PgDn"),
    KeyCode::Tab => buf.push_str("Tab"),
    KeyCode::BackTab => buf.push_str("BackTab"),
    KeyCode::Delete => buf.push_str("Del"),
    KeyCode::Insert => buf.push_str("Ins"),
    KeyCode::F(n) => buf.push_str(&format!("F{}", n)),
    KeyCode::Char(ch) => buf.push(*ch),
    KeyCode::Null => buf.push_str("Null"),
    KeyCode::Esc => buf.push_str("Esc"),
  }

  return buf;
}

/*
 * Mouse
 */

pub fn encode_mouse_event(mev: MouseEvent) -> String {
  let mut buf = String::new();
  buf.push_str("\x1b[<");

  match mev.kind {
    MouseEventKind::Down(btn) | MouseEventKind::Up(btn) => match btn {
      MouseButton::Left => buf.push('0'),
      MouseButton::Right => buf.push('1'),
      MouseButton::Middle => buf.push('2'),
    },
    MouseEventKind::Drag(btn) => match btn {
      MouseButton::Left => buf.push_str("32"),
      MouseButton::Right => buf.push_str("33"),
      MouseButton::Middle => buf.push_str("34"),
    },
    MouseEventKind::Moved => {
      // TODO
      return "".to_string();
    }
    MouseEventKind::ScrollDown => buf.push_str("65"),
    MouseEventKind::ScrollUp => buf.push_str("64"),
  }
  buf.push(';');
  buf.push_str((mev.column + 1).to_string().as_str());
  buf.push(';');
  buf.push_str((mev.row + 1).to_string().as_str());

  buf.push(match mev.kind {
    MouseEventKind::Down(_) => 'M',
    MouseEventKind::Up(_) => 'm',
    MouseEventKind::Drag(_) => 'M',
    MouseEventKind::Moved => todo!(),
    MouseEventKind::ScrollDown => 'M',
    MouseEventKind::ScrollUp => 'M',
  });

  buf
}