workflow-terminal 0.19.0

Terminal abstraction layer over Xterm.js and termion crates for creating terminal applications that function uniformly in native (console) and in browser (WASM32) environments.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use super::bindings::*;
use super::{LinkMatcherHandlerFn, Modifiers};
use crate::Result;
use crate::keys::Key;
use crate::terminal::Event;
use crate::terminal::EventHandlerFn;
use crate::terminal::Options;
use crate::terminal::TargetElement;
use crate::terminal::Terminal;
use std::cell::{RefCell, RefMut};
use std::fmt::Debug;
use std::rc::Rc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsValue;
use web_sys::Element;
use workflow_core::channel::{Receiver, Sender, unbounded};
use workflow_core::runtime::{self, Platform, platform};
use workflow_dom::clipboard;
use workflow_dom::inject::*;
use workflow_dom::utils::body;
use workflow_dom::utils::*;
use workflow_log::*;
use workflow_wasm::jserror::*;
use workflow_wasm::prelude::*;
use workflow_wasm::utils::*;

/// Color theme for the terminal, with each element given as an optional CSS
/// color string. Unset fields leave the corresponding color unchanged.
#[derive(Default)]
pub struct Theme {
    /// Background color, as a CSS color string.
    pub background: Option<String>,
    /// Foreground (text) color, as a CSS color string.
    pub foreground: Option<String>,
    /// Selection highlight color, as a CSS color string.
    pub selection: Option<String>,
    /// Cursor color, as a CSS color string.
    pub cursor: Option<String>,
}

/// Identifies an individual themeable terminal color.
pub enum ThemeOption {
    /// The terminal background color.
    Background,
    /// The terminal foreground (text) color.
    Foreground,
    /// The selection highlight color.
    Selection,
    /// The cursor color.
    Cursor,
}
impl ThemeOption {
    /// Returns all theme options as a vector.
    pub fn list() -> Vec<Self> {
        Vec::from([
            Self::Background,
            Self::Foreground,
            Self::Selection,
            Self::Cursor,
        ])
    }
}

impl std::fmt::Display for ThemeOption {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Background => write!(f, "Background"),
            Self::Foreground => write!(f, "Foreground"),
            Self::Selection => write!(f, "Selection"),
            Self::Cursor => write!(f, "Cursor"),
        }
    }
}

impl Theme {
    /// Creates a new theme with all colors unset.
    pub fn new() -> Self {
        Self {
            ..Default::default()
        }
    }
    /// Returns the color string for the given theme option, if set.
    pub fn get(&self, key: &ThemeOption) -> Option<String> {
        match key {
            ThemeOption::Background => self.background.clone(),
            ThemeOption::Foreground => self.foreground.clone(),
            ThemeOption::Selection => self.selection.clone(),
            ThemeOption::Cursor => self.cursor.clone(),
        }
    }
    /// Sets the color for the given theme option.
    pub fn set(&mut self, key: ThemeOption, value: Option<String>) {
        match key {
            ThemeOption::Background => {
                self.background = value;
            }
            ThemeOption::Foreground => {
                self.foreground = value;
            }
            ThemeOption::Selection => {
                self.selection = value;
            }
            ThemeOption::Cursor => {
                self.cursor = value;
            }
        }
    }
}

enum Ctl {
    SinkEvent(SinkEvent),
    Copy(Option<String>),
    Paste(Option<String>),
    Close,
}

/// A keyboard event captured from xterm.js and forwarded through the input
/// sink, carrying both the resolved key and modifier state.
#[derive(Debug)]
pub struct SinkEvent {
    key: String,
    term_key: String,
    ctrl_key: bool,
    alt_key: bool,
    meta_key: bool,
}

impl SinkEvent {
    fn new(key: String, term_key: String, ctrl_key: bool, alt_key: bool, meta_key: bool) -> Self {
        Self {
            key,
            term_key,
            ctrl_key,
            alt_key,
            meta_key,
        }
    }
}

/// Channel pair used to forward terminal control events (key input, copy,
/// paste and close) from the DOM callbacks to the intake loop.
#[derive(Clone)]
pub struct Sink {
    receiver: Receiver<Ctl>,
    sender: Sender<Ctl>,
}

impl Default for Sink {
    fn default() -> Self {
        let (sender, receiver) = unbounded();
        Sink { receiver, sender }
    }
}

/// Holds a [`ResizeObserver`] together with its callback to keep both alive
/// for the lifetime of the terminal.
pub struct ResizeObserverInfo {
    #[allow(dead_code)]
    observer: ResizeObserver,
    #[allow(dead_code)]
    callback: Callback<CallbackClosure<JsValue>>,
}

impl ResizeObserverInfo {
    /// Creates a new `ResizeObserverInfo`, retaining the observer and its callback.
    pub fn new(observer: ResizeObserver, callback: Callback<CallbackClosure<JsValue>>) -> Self {
        Self { observer, callback }
    }
}

/// Subset of terminal options applied when initializing the xterm.js instance.
pub struct XtermOptions {
    /// Font family name, or `None` to use the platform default.
    pub font_family: Option<String>,
    /// Font size in pixels.
    pub font_size: Option<f64>,
    /// Number of scrollback lines to retain.
    pub scrollback: Option<u32>,
}

///
/// # Xterm
///
/// Wrapper around XtermJS - <https://github.com/xtermjs/xterm.js>
///
/// TODO enhance API to match <https://github.com/xtermjs/xterm.js/blob/4.14.1/typings/xterm.d.ts>
///
///
pub struct Xterm {
    /// The DOM element that hosts the terminal.
    pub element: Element,
    xterm: Rc<RefCell<Option<XtermImpl>>>,
    terminal: Arc<Mutex<Option<Arc<Terminal>>>>,
    listener: Arc<Mutex<Option<Callback<CallbackClosure<XtermEvent>>>>>,
    sink: Arc<Sink>,
    resize: Rc<RefCell<Option<ResizeObserverInfo>>>,
    fit: Rc<RefCell<Option<FitAddon>>>,
    _web_links: Rc<RefCell<Option<WebLinksAddon>>>,
    terminate: Arc<AtomicBool>,
    disable_clipboard_handling: bool,
    callbacks: CallbackMap,
    defaults: XtermOptions,
    event_handler: Rc<RefCell<Option<EventHandlerFn>>>,
}

unsafe impl Send for Xterm {}
unsafe impl Sync for Xterm {}

impl Xterm {
    /// Creates a new terminal using default [`Options`].
    pub fn try_new() -> Result<Self> {
        Self::try_new_with_options(&Options::default())
    }

    /// Creates a new terminal using the given options, resolving the target
    /// parent element from [`Options::element`].
    pub fn try_new_with_options(options: &Options) -> Result<Self> {
        let el = match &options.element {
            TargetElement::Body => body().expect("Unable to get 'body' element"),
            TargetElement::Element(el) => el.clone(),
            TargetElement::TagName(tag) => document()
                .get_elements_by_tag_name(tag)
                .item(0)
                .ok_or("Unable to locate parent element for terminal")?,
            TargetElement::Id(id) => document()
                .get_element_by_id(id)
                .ok_or("Unable to locate parent element for terminal")?,
        };
        Self::try_new_with_element(&el, options)
    }

    /// Creates a new terminal rendered as a child `div` of the given parent element.
    pub fn try_new_with_element(parent: &Element, options: &Options) -> Result<Self> {
        let element = document().create_element("div")?;
        element.set_attribute("class", "terminal")?;
        parent.append_child(&element)?;
        let defaults = XtermOptions {
            font_size: options.font_size,
            font_family: options.font_family.clone(),
            scrollback: options.scrollback,
        };
        let terminal = Xterm {
            element,
            listener: Arc::new(Mutex::new(None)),
            xterm: Rc::new(RefCell::new(None)),
            terminal: Arc::new(Mutex::new(None)),
            sink: Arc::new(Sink::default()),
            resize: Rc::new(RefCell::new(None)),
            // addons: Arc::new(Mutex::new(Vec::new())),
            fit: Rc::new(RefCell::new(None)),
            _web_links: Rc::new(RefCell::new(None)),
            terminate: Arc::new(AtomicBool::new(false)),
            disable_clipboard_handling: options.disable_clipboard_handling,
            callbacks: CallbackMap::default(),
            event_handler: Rc::new(RefCell::new(None)),
            defaults,
        };
        Ok(terminal)
    }

    fn init_xterm(defaults: &XtermOptions) -> Result<XtermImpl> {
        let theme = js_sys::Object::new();
        let theme_opts = Vec::from([
            ("background", JsValue::from("rgba(255,255,255,1)")),
            ("foreground", JsValue::from("#000")),
            ("selection", JsValue::from("rgba(0,0,0,0.25)")),
            // ("background", JsValue::from("rgba(0,0,0,1)")),
            // ("foreground", JsValue::from("#FFF")),
            ("cursor", JsValue::from("#000")),
        ]);
        for (k, v) in theme_opts {
            js_sys::Reflect::set(&theme, &k.into(), &v)?;
        }

        let font = match platform() {
            Platform::MacOS | Platform::IOS => "Menlo",
            Platform::Windows => "Consolas",
            Platform::Linux => "Ubuntu Mono",
            _ => "monospace",
        };

        let options = js_sys::Object::new();
        let opts = Vec::from([
            ("allowTransparency", JsValue::from(true)),
            ("fontFamily", JsValue::from(font)),
            (
                "fontSize",
                JsValue::from(defaults.font_size.unwrap_or(20.0)),
            ),
            ("cursorBlink", JsValue::from(true)),
            ("theme", JsValue::from(theme)),
        ]);
        for (k, v) in opts {
            js_sys::Reflect::set(&options, &k.into(), &v)?;
        }
        if let Some(scrollback) = defaults.scrollback {
            js_sys::Reflect::set(&options, &"scrollback".into(), &JsValue::from(scrollback))?;
        }

        let term = XtermImpl::new(options);

        Ok(term)
    }

    // pub fn xterm(&self) -> MutexGuard<Option<XtermImpl>> {
    /// Returns a mutable borrow of the underlying xterm.js instance, if initialized.
    pub fn xterm(&self) -> RefMut<'_, Option<XtermImpl>> {
        //MutexGuard<Option<XtermImpl>> {
        // self.xterm.lock().unwrap()
        self.xterm.borrow_mut()
    }

    /// Updates the terminal theme from the host element's computed CSS custom
    /// properties (`--workflow-terminal-*`).
    pub fn update_theme(&self) -> Result<()> {
        let el = self
            .xterm
            .borrow_mut()
            // .unwrap()
            .as_ref()
            .expect("xterm is missing")
            .get_element();
        let css = window().get_computed_style(&el)?;
        //log_trace!("css: {:?}", css);
        if let Some(css) = css {
            let keys = Vec::from([
                ("background", "--workflow-terminal-background"),
                ("foreground", "--workflow-terminal-foreground"),
                ("cursor", "--workflow-terminal-cursor"),
                ("selection", "--workflow-terminal-selection"),
            ]);
            let theme_obj = js_sys::Object::new();
            for (key, css_var) in keys {
                if let Ok(value) = css.get_property_value(css_var) {
                    // log_trace!("workflow-terminal: `{}`: {:?}", key, value);
                    js_sys::Reflect::set(
                        &theme_obj,
                        &JsValue::from(key),
                        &JsValue::from(value.trim()),
                    )?;
                }
            }

            let term = self.xterm.borrow_mut();
            let term = term.as_ref().expect("xterm is missing");
            term.set_theme(theme_obj);
        }

        Ok(())
    }
    /// Applies the given [`Theme`] to the terminal, setting only the colors
    /// that are present.
    pub fn set_theme(&self, theme: Theme) -> Result<()> {
        let theme_obj = js_sys::Object::new();
        let properties = ThemeOption::list();

        for key in properties {
            if let Some(v) = theme.get(&key) {
                js_sys::Reflect::set(
                    &theme_obj,
                    &JsValue::from(key.to_string().to_lowercase()),
                    &JsValue::from(v),
                )?;
            }
        }

        let term = self.xterm.borrow_mut();
        let term = term.as_ref().expect("xterm is missing");
        term.set_theme(theme_obj);
        Ok(())
    }

    fn init_addons(&self, xterm: &XtermImpl) -> Result<()> {
        let fit = FitAddon::new();
        xterm.load_addon(fit.clone());
        *self.fit.borrow_mut() = Some(fit);
        Ok(())
    }

    /// Loads xterm.js, constructs the underlying terminal, attaches addons and
    /// keyboard/resize/clipboard listeners, and binds it to the given
    /// [`Terminal`].
    pub async fn init(self: &Arc<Self>, terminal: &Arc<Terminal>) -> Result<()> {
        load_scripts().await?;

        let xterm = Self::init_xterm(&self.defaults)?;

        self.init_addons(&xterm)?;

        xterm.open(&self.element);
        xterm.focus();

        self.init_kbd_listener(&xterm)?;
        self.init_resize_observer()?;
        if runtime::is_macos() && !self.disable_clipboard_handling {
            self.init_clipboard_listener_for_macos(&xterm)?;
        }

        *self.xterm.borrow_mut() = Some(xterm);
        *self.terminal.lock().unwrap() = Some(terminal.clone());

        Ok(())
    }

    /// Sets the named xterm.js option to the given value.
    pub fn set_option(&self, name: &str, option: JsValue) -> Result<()> {
        let xterm = self.xterm();
        let xterm = xterm.as_ref().expect("unable to get xterm");
        xterm.set_option(name, option);
        Ok(())
    }

    /// Returns the value of the named xterm.js option.
    pub fn get_option(&self, name: &str) -> Result<JsValue> {
        let xterm = self.xterm();
        let xterm = xterm.as_ref().expect("unable to get xterm");
        Ok(xterm.get_option(name))
    }

    /// Redraws the terminal rows in the inclusive range `start..=stop`.
    pub fn refresh(&self, start: u32, stop: u32) {
        let xterm = self.xterm();
        let xterm = xterm.as_ref().expect("unable to get xterm");
        xterm.refresh(start, stop);
    }

    fn event_handler(&self) -> Option<EventHandlerFn> {
        self.event_handler.borrow().clone()
    }

    #[allow(dead_code)]
    pub(super) fn register_event_handler(self: &Arc<Self>, handler: EventHandlerFn) -> Result<()> {
        self.event_handler.borrow_mut().replace(handler);
        Ok(())
    }

    #[allow(dead_code)]
    pub(super) fn register_link_matcher(
        self: &Arc<Self>,
        regexp: &js_sys::RegExp,
        handler: LinkMatcherHandlerFn,
    ) -> Result<()> {
        let xterm = self.xterm();
        let xterm = xterm.as_ref().expect("unable to get xterm");

        #[rustfmt::skip]
        let callback = callback!(
            move |e: web_sys::MouseEvent, link: String| -> std::result::Result<(), JsValue> {
                let modifiers = Modifiers {
                    shift: e.shift_key(),
                    ctrl: e.ctrl_key(),
                    alt: e.alt_key(),
                    meta: e.meta_key(),
                };
                handler(modifiers, link.as_str());
                Ok(())
            }
        );
        xterm.register_link_matcher(regexp, callback.as_ref());
        self.callbacks.retain(callback)?;

        Ok(())
    }

    /// Queues a paste of the given text, or of the clipboard contents when `None`.
    pub fn paste(&self, text: Option<String>) -> Result<()> {
        self.sink
            .sender
            .try_send(Ctl::Paste(text))
            .map_err(|_| "Unable to send paste Ctl")?;
        Ok(())
    }

    fn init_resize_observer(self: &Arc<Self>) -> Result<()> {
        let this = self.clone();
        let resize_callback = callback!(move |_| -> std::result::Result<(), JsValue> {
            if let Err(err) = this.resize() {
                log_error!("terminal resize error: {:?}", err);
            }
            Ok(())
        });
        let resize_observer = ResizeObserver::new(resize_callback.as_ref())?;
        resize_observer.observe(&self.element);
        *self.resize.borrow_mut() = Some(ResizeObserverInfo::new(resize_observer, resize_callback));

        Ok(())
    }

    fn init_clipboard_listener_for_macos(self: &Arc<Self>, xterm: &XtermImpl) -> Result<()> {
        let this = self.clone();
        let clipboard_callback = callback!(
            move |e: web_sys::KeyboardEvent| -> std::result::Result<(), JsValue> {
                // log_trace!("xterm: key:{}, ctrl_key:{}, meta_key:{},  {:?}", e.key(), e.ctrl_key(), e.meta_key(), e);
                if e.key() == "v" && (e.ctrl_key() || e.meta_key()) {
                    this.sink
                        .sender
                        .try_send(Ctl::Paste(None))
                        .expect("Unable to send paste Ctl");
                }
                if e.key() == "c" && (e.ctrl_key() || e.meta_key()) {
                    let text = this.xterm().as_ref().unwrap().get_selection();
                    this.sink
                        .sender
                        .try_send(Ctl::Copy(Some(text)))
                        .expect("Unable to send copy Ctl");
                }
                Ok(())
            }
        );

        xterm
            .get_element()
            .add_event_listener_with_callback("keydown", clipboard_callback.as_ref())?;
        self.callbacks.retain(clipboard_callback)?;

        Ok(())
    }

    fn init_kbd_listener(self: &Arc<Self>, xterm: &XtermImpl) -> Result<()> {
        let this = self.clone();
        let callback = callback!(move |e: XtermEvent| -> std::result::Result<(), JsValue> {
            //let term_key = try_get_string(&e, "key")?;
            let term_key = e.get_key();
            let dom_event = e.get_dom_event();
            let key = dom_event.key();
            let ctrl_key = dom_event.ctrl_key();
            let alt_key = dom_event.alt_key();
            let meta_key = dom_event.meta_key();

            // log_info!("key: {key}, ctrl: {ctrl_key}, alt: {alt_key}, meta: {meta_key}");

            if !runtime::is_macos() && !this.disable_clipboard_handling {
                if (key == "v" || key == "V") && (ctrl_key || meta_key) {
                    this.sink
                        .sender
                        .try_send(Ctl::Paste(None))
                        .expect("Unable to send paste Ctl");
                    return Ok(());
                } else if (key == "c" || key == "C") && (ctrl_key || meta_key) {
                    let text = this.xterm().as_ref().unwrap().get_selection();
                    this.sink
                        .sender
                        .try_send(Ctl::Copy(Some(text)))
                        .expect("Unable to send copy Ctl");
                    return Ok(());
                }
            }

            this.sink
                .sender
                .try_send(Ctl::SinkEvent(SinkEvent::new(
                    key, term_key, ctrl_key, alt_key, meta_key,
                )))
                .unwrap();

            Ok(())
        });

        xterm.on_key(callback.as_ref());
        *self.listener.lock().unwrap() = Some(callback);

        Ok(())
    }

    /// Returns the [`Terminal`] this xterm instance is bound to.
    pub fn terminal(&self) -> Arc<Terminal> {
        self.terminal.lock().unwrap().as_ref().unwrap().clone()
    }

    /// Runs the terminal input intake loop until the terminal exits.
    pub async fn run(self: &Arc<Self>) -> Result<()> {
        self.intake(&self.terminate).await?;
        Ok(())
    }

    /// Processes queued key, copy, paste and close events, dispatching them to
    /// the bound terminal and clipboard, until `terminate` is set or a close
    /// event is received.
    pub async fn intake(self: &Arc<Self>, terminate: &Arc<AtomicBool>) -> Result<()> {
        loop {
            if terminate.load(Ordering::SeqCst) {
                break;
            }

            let event = self.sink.receiver.recv().await?;
            match event {
                Ctl::SinkEvent(event) => {
                    self.sink(event).await?;
                }
                Ctl::Copy(text) => {
                    let text =
                        text.unwrap_or_else(|| self.xterm().as_ref().unwrap().get_selection());
                    if runtime::is_nw() {
                        let clipboard = nw_sys::clipboard::get();
                        clipboard.set(&text);
                    } else {
                        if let Err(err) = clipboard::write_text(&text).await {
                            log_error!("{}", JsErrorData::from(err));
                        }
                    }

                    if let Some(handler) = self.event_handler() {
                        handler(Event::Copy);
                    }
                }
                Ctl::Paste(text) => {
                    if let Some(text) = text {
                        self.terminal().inject(text)?;
                    } else if runtime::is_nw() {
                        let clipboard = nw_sys::clipboard::get();
                        let text = clipboard.get();
                        if !text.is_empty() {
                            self.terminal().inject(text)?;
                        }
                    } else {
                        let data_js_value = clipboard::read_text().await;
                        if let Some(text) = data_js_value.as_string() {
                            self.terminal().inject(text)?;
                        }
                    }

                    if let Some(handler) = self.event_handler() {
                        handler(Event::Copy);
                    }
                }
                Ctl::Close => {
                    break;
                }
            }
        }

        Ok(())
    }

    /// Signals the input intake loop to terminate.
    pub fn exit(&self) {
        self.terminate.store(true, Ordering::SeqCst);
        self.sink
            .sender
            .try_send(Ctl::Close)
            .expect("Unable to send exit Ctl");
    }

    async fn sink(&self, e: SinkEvent) -> Result<()> {
        let key = match e.key.as_str() {
            "Backspace" => Key::Backspace,
            "ArrowUp" => Key::ArrowUp,
            "ArrowDown" => Key::ArrowDown,
            "ArrowLeft" => Key::ArrowLeft,
            "ArrowRight" => Key::ArrowRight,
            "Escape" => Key::Esc,
            "Delete" => Key::Delete,
            "Tab" => {
                // TODO implement completion handler
                return Ok(());
            }
            "Enter" => Key::Enter,
            _ => {
                let printable = !e.meta_key; // ! (e.ctrl_key || e.alt_key || e.meta_key);
                if !printable {
                    return Ok(());
                }
                //log_trace!("e:{:?}", e);
                if let Some(c) = e.key.chars().next() {
                    if e.ctrl_key {
                        Key::Ctrl(c)
                    } else if e.alt_key {
                        Key::Alt(c)
                    } else {
                        Key::Char(c)
                    }
                } else {
                    return Ok(());
                }
            }
        };

        self.terminal().ingest(key, e.term_key).await?;

        Ok(())
    }

    /// Writes the given text to the terminal display.
    pub fn write<S>(&self, s: S)
    where
        S: ToString,
    {
        self.xterm
            .borrow_mut()
            .as_ref()
            .expect("Xterm is not initialized")
            .write(s);
    }

    /// Forces xterm.js to recompute character dimensions when its cached size
    /// is invalid (e.g. after the terminal becomes visible).
    pub fn measure(&self) -> Result<()> {
        let xterm = self.xterm.borrow_mut();
        let xterm = xterm.as_ref().unwrap();
        let core = try_get_js_value_prop(xterm, "_core").expect("Unable to get xterm core");
        let char_size_service = try_get_js_value_prop(&core, "_charSizeService")
            .expect("Unable to get xterm charSizeService");
        let has_valid_size = try_get_js_value_prop(&char_size_service, "hasValidSize")
            .expect("Unable to get xterm charSizeService::hasValidSize");
        if has_valid_size.is_falsy() {
            apply_with_args0(&char_size_service, "measure")?;
        }

        Ok(())
    }

    /// Refits the terminal to the current size of its container element.
    pub fn resize(&self) -> Result<()> {
        //self.measure()?;
        if let Some(xterm) = self.xterm.borrow_mut().as_ref() {
            let el = xterm.get_element();
            let height = el.client_height();
            if height < 1 {
                return Ok(());
            }
        } else {
            return Ok(());
        }

        let fit = self.fit.borrow();
        let fit = fit.as_ref().unwrap();
        // TODO review if this is correct
        //fit.propose_dimensions();
        // TODO review if this is correct
        fit.fit();

        Ok(())
    }

    /// Returns the current terminal font size in pixels, if available.
    pub fn get_font_size(&self) -> Result<Option<f64>> {
        let font_size = self.get_option("fontSize")?;
        Ok(font_size.as_f64())
    }

    /// Sets the terminal font size, in pixels.
    pub fn set_font_size(&self, font_size: f64) -> Result<()> {
        self.set_option("fontSize", JsValue::from_f64(font_size))
    }

    /// Returns the number of terminal columns, or `None` if not yet initialized.
    pub fn cols(&self) -> Option<usize> {
        self.xterm().as_ref().map(|xterm| xterm.cols() as usize)
    }

    /// Returns the number of terminal rows, or `None` if not yet initialized.
    pub fn rows(&self) -> Option<usize> {
        self.xterm().as_ref().map(|xterm| xterm.rows() as usize)
    }

    fn adjust_font_size(&self, delta: f64) -> Result<Option<f64>> {
        let font_size = self.get_option("fontSize")?;
        let mut font_size = font_size.as_f64().ok_or("Unable to get font size")?;
        font_size += delta;
        if font_size < 4.0 {
            font_size = 4.0;
        }

        self.set_option("fontSize", JsValue::from_f64(font_size))?;
        self.resize()?;
        Ok(Some(font_size))
    }

    /// Increases the terminal font size by one pixel, returning the new size.
    pub fn increase_font_size(&self) -> Result<Option<f64>> {
        self.adjust_font_size(1.0)
    }

    /// Decreases the terminal font size by one pixel, returning the new size.
    pub fn decrease_font_size(&self) -> Result<Option<f64>> {
        self.adjust_font_size(-1.0)
    }

    /// Copies the terminal's current selection to the clipboard.
    pub fn clipboard_copy(&self) -> Result<()> {
        let text = self.xterm().as_ref().unwrap().get_selection();
        self.sink
            .sender
            .try_send(Ctl::Copy(Some(text)))
            .expect("Unable to send copy Ctl");
        if let Some(handler) = self.event_handler() {
            handler(Event::Copy);
        }

        Ok(())
    }

    /// Pastes the current clipboard contents into the terminal.
    pub fn clipboard_paste(&self) -> Result<()> {
        self.sink
            .sender
            .try_send(Ctl::Paste(None))
            .expect("Unable to send paste Ctl");
        if let Some(handler) = self.event_handler() {
            handler(Event::Paste);
        }

        Ok(())
    }
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

static mut XTERM_LOADED: bool = false;

/// Injects the bundled xterm.js scripts, its fit and web-links addons, and
/// stylesheet into the document. Subsequent calls are a no-op once loaded.
pub async fn load_scripts() -> Result<()> {
    if unsafe { XTERM_LOADED } {
        return Ok(());
    }

    let xterm_js = include_bytes!("../../extern/resources/xterm.js");
    inject_blob(Content::Script(None, xterm_js)).await?;
    let xterm_addon_fit_js = include_bytes!("../../extern/resources/xterm-addon-fit.js");
    inject_blob(Content::Script(None, xterm_addon_fit_js)).await?;
    let xterm_addon_web_links_js =
        include_bytes!("../../extern/resources/xterm-addon-web-links.js");
    inject_blob(Content::Script(None, xterm_addon_web_links_js)).await?;
    let xterm_css = include_bytes!("../../extern/resources/xterm.css");
    inject_blob(Content::Style(None, xterm_css)).await?;

    unsafe { XTERM_LOADED = true };

    Ok(())
}