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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
//! Provides an interface to terminal devices

use std::fmt;
use std::io;
use std::sync::{LockResult, TryLockResult};
use std::time::Duration;

use crate::priv_util::{map_lock_result, map_try_lock_result};
use crate::signal::{Signal, SignalSet};
use crate::sys;

/// Represents a color attribute applied to text foreground or background.
///
/// # Notes
///
/// Names here correspond to possible default values for some systems.
/// Because users may reconfigure the set of colors available in their terminal,
/// these color values may correspond to different user-configured display colors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Color {
    /// Black
    Black,
    /// Blue
    Blue,
    /// Cyan
    Cyan,
    /// Green
    Green,
    /// Magenta
    Magenta,
    /// Red
    Red,
    /// White
    White,
    /// Yellow
    Yellow,
}

bitflags!{
    /// Represents a set of style attributes applied to text.
    ///
    /// Some styles may not be supported on all systems.
    #[derive(Default)]
    pub struct Style: u8 {
        /// Bold
        const BOLD      = 1 << 0;
        /// Italic
        const ITALIC    = 1 << 1;
        /// Reverse; foreground and background color swapped
        const REVERSE   = 1 << 2;
        /// Underline
        const UNDERLINE = 1 << 3;
    }
}

/// Represents a terminal output theme.
///
/// A theme consists of a foreground and background color as well as a style.
#[derive(Copy, Clone, Debug, Default)]
pub struct Theme {
    /// Foreground color
    pub fg: Option<Color>,
    /// Background color
    pub bg: Option<Color>,
    /// Style
    pub style: Style,
}

impl Theme {
    /// Creates a new theme with given values.
    ///
    /// # Note
    ///
    /// In order to create a Theme using default values you might want to use
    /// `Theme::default()` instead.
    pub fn new<F,B,S>(fg: F, bg: B, style: S) -> Theme
            where
                F: Into<Option<Color>>,
                B: Into<Option<Color>>,
                S: Into<Option<Style>> {
        Theme {
            fg: fg.into(),
            bg: bg.into(),
            style: style.into().unwrap_or_default(),
        }
    }

    /// Sets the foreground color on the given Theme and returns the new.
    pub fn fg<F>(mut self, fg: F) -> Theme
            where F: Into<Option<Color>> {
        self.fg = fg.into();
        self
    }

    /// Sets the background color on the given Theme and returns the new.
    pub fn bg<B>(mut self, bg: B) -> Theme
            where B: Into<Option<Color>> {
        self.bg = bg.into();
        self
    }

    /// Sets the style on the given Theme and returns the new.
    pub fn style<S>(mut self, style: S) -> Theme
            where S: Into<Option<Style>> {
        self.style = style.into().unwrap_or_default();
        self
    }
}

/// Represents the cursor position in a terminal device
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Cursor {
    /// Index of line in terminal, beginning at `0`.
    pub line: usize,
    /// Index of column in terminal, beginning at `0`.
    pub column: usize,
}

impl Cursor {
    /// Returns the position of the next cell within a terminal of the given size.
    ///
    /// Returns `None` if this cursor position represents the last cell.
    #[inline]
    pub fn next(&self, size: Size) -> Option<Cursor> {
        let mut line = self.line;
        let mut column = self.column + 1;

        if column >= size.columns {
            column = 0;
            line += 1;
        }

        if line >= size.lines {
            None
        } else {
            Some(Cursor{line, column})
        }
    }

    /// Returns the position of the previous cell within a terminal of the given size.
    ///
    /// Returns `None` if this cursor position represents the first cell.
    #[inline]
    pub fn previous(&self, size: Size) -> Option<Cursor> {
        if self.column == 0 {
            if self.line == 0 {
                None
            } else {
                Some(Cursor{line: self.line - 1, column: size.columns - 1})
            }
        } else {
            Some(Cursor{line: self.line, column: self.column - 1})
        }
    }

    /// Returns a `Cursor` pointing to the first cell, i.e. `(0, 0)`.
    #[inline]
    pub fn first() -> Cursor {
        Cursor{
            line: 0,
            column: 0,
        }
    }

    /// Returns a `Cursor` pointing to the last cell of a screen of the given size.
    #[inline]
    pub fn last(size: Size) -> Cursor {
        Cursor{
            line: size.lines - 1,
            column: size.columns - 1,
        }
    }

    /// Returns whether the cursor is out of bounds of the given size.
    #[inline]
    pub fn is_out_of_bounds(&self, size: Size) -> bool {
        self.line >= size.lines || self.column >= size.columns
    }

    /// Returns the index of the cursor position within a one-dimensional array
    /// of the given size.
    pub(crate) fn as_index(&self, size: Size) -> usize {
        self.line * size.columns + self.column
    }
}

impl From<(usize, usize)> for Cursor {
    /// Returns a `Cursor` value from a `(line, column)` or `(y, x)` tuple.
    fn from((line, column): (usize, usize)) -> Cursor {
        Cursor{line, column}
    }
}

/// Represents the visual appearance of the cursor in the terminal
///
/// Some cursor states may not be available on all systems.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum CursorMode {
    /// Normal mode
    Normal,
    /// Invisible mode
    Invisible,
    /// Overwrite mode
    Overwrite,
}

/// Represents an event generated from a terminal interface
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Event {
    /// Keyboard event
    Key(Key),
    /// Mouse event
    Mouse(MouseEvent),
    /// Raw data read
    ///
    /// A value of this variant can only be returned when using the
    /// platform-dependent extension trait, `TerminalExt`.
    ///
    /// On Unix, this trait is [`mortal::unix::TerminalExt`].
    ///
    /// On Windows, this trait is [`mortal::windows::TerminalExt`].
    ///
    /// [`mortal::unix::TerminalExt`]: ../unix/trait.TerminalExt.html
    /// [`mortal::windows::TerminalExt`]: ../windows/trait.TerminalExt.html
    Raw(usize),
    /// Terminal window size changed; contained value is the new size.
    Resize(Size),
    /// Terminal signal received
    Signal(Signal),
    /// No event
    ///
    /// Returned when a low-level terminal event does not correspond
    /// to a reported event type.
    NoEvent,
}

/// Represents a keyboard key press event
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Key {
    /// Backspace
    Backspace,
    /// Enter
    Enter,
    /// Escape
    Escape,
    /// Tab
    Tab,
    /// Up arrow
    Up,
    /// Down arrow
    Down,
    /// Left arrow
    Left,
    /// Right arrow
    Right,
    /// Delete
    Delete,
    /// Insert
    Insert,
    /// Home
    Home,
    /// End
    End,
    /// PageUp
    PageUp,
    /// PageDown
    PageDown,
    /// Character key
    Char(char),
    /// Control character
    ///
    /// # Notes
    ///
    /// The contained `char` value must always be lowercase;
    /// e.g. `Ctrl('a')` and **not** `Ctrl('A')`.
    ///
    /// On Unix, certain special `Key` values are represented as control
    /// characters; therefore, the following combinations will not generate a
    /// `Ctrl(_)` value:
    ///
    /// * Ctrl-I instead generates `Tab`
    /// * Ctrl-J and Ctrl-M instead generate `Enter`
    Ctrl(char),
    /// Function `n` key; e.g. F1, F2, ...
    F(u32),
}

impl From<char> for Key {
    fn from(ch: char) -> Key {
        use crate::util::{is_ctrl, unctrl_lower};

        match ch {
            '\x1b' => Key::Escape,
            '\x7f' => Key::Backspace,
            '\r' | '\n' => Key::Enter,
            '\t' => Key::Tab,
            _ if is_ctrl(ch) => Key::Ctrl(unctrl_lower(ch)),
            _ => Key::Char(ch),
        }
    }
}

/// Represents a mouse event
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MouseEvent {
    /// The position of the mouse within the terminal when the event occurred
    pub position: Cursor,
    /// The input event that occurred
    pub input: MouseInput,
    /// Modifier keys held when the input event occurred
    ///
    /// # Notes
    ///
    /// On some systems, certain combinations of mouse button and modifier may
    /// be interpreted by the system and not reported as terminal events.
    pub modifiers: ModifierState,
}

/// Represents the type of mouse input event
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum MouseInput {
    /// The mouse cursor was moved
    Motion,
    /// A mouse button was pressed
    ButtonPressed(MouseButton),
    /// A mouse button was released
    ButtonReleased(MouseButton),
    /// The mouse wheel was scrolled up
    WheelUp,
    /// The mouse wheel was scrolled down
    WheelDown,
}

/// Represents a button on a mouse device
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum MouseButton {
    /// Left mouse button
    Left,
    /// Right mouse button
    Right,
    /// Middle mouse button
    Middle,
    /// Other mouse button
    Other(u32),
}

bitflags!{
    /// Represents a set of modifier keys
    pub struct ModifierState: u8 {
        /// Alt key
        const ALT   = 1 << 0;
        /// Ctrl key
        const CTRL  = 1 << 1;
        /// Shift key
        const SHIFT = 1 << 2;
    }
}

/// Configures a [`Terminal`] or [`Screen`] instance to read special input.
///
/// This struct implements the [`Default`] trait, providing default
/// values for all options.
///
/// To override only some options while using the remaining default values,
/// one may use the following construct:
///
/// ```no_run
/// # use std::io;
/// # fn example() -> io::Result<()> {
/// use mortal::{Terminal, PrepareConfig};
///
/// let term = Terminal::new()?;
///
/// let state = term.prepare(PrepareConfig{
///     enable_keypad: false,
///     enable_mouse: true,
///     .. PrepareConfig::default()
/// })?;
///
/// // ...
///
/// term.restore(state)?;
/// # Ok(())
/// # }
/// ```
///
/// [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
/// [`Terminal`]: struct.Terminal.html
/// [`Screen`]: ../screen/struct.Screen.html
#[derive(Copy, Clone, Debug)]
pub struct PrepareConfig {
    /// Whether to block signals that result from user input.
    ///
    /// If `true`, e.g. when the user presses Ctrl-C,
    /// `Key(Ctrl('c'))` will be read instead of `Signal(Interrupt)`.
    ///
    /// The default is `true`.
    pub block_signals: bool,
    /// Whether to enable control flow characters.
    ///
    /// The default is `false`.
    ///
    /// # Notes
    ///
    /// On Unix, when this setting is enabled, Ctrl-S and Ctrl-Q
    /// will stop and start, respectively, terminal input from being processed.
    ///
    /// On Windows, this setting has no effect.
    pub enable_control_flow: bool,
    /// If `true`, the terminal will be configured to generate events from
    /// function keys.
    ///
    /// The default is `true`.
    ///
    /// # Notes
    ///
    /// On Unix, this may be required to receive events for arrow keys.
    ///
    /// On Windows, this setting has no effect.
    pub enable_keypad: bool,
    /// If `true`, the terminal will be configured to generate events for
    /// mouse input, if supported, and `read_event` may return `Event::Mouse(_)`.
    ///
    /// The default is `false`.
    ///
    /// # Notes
    ///
    /// This setting may not be supported on all systems.
    pub enable_mouse: bool,
    /// If `true`, mouse motion events will always be reported.
    /// If `false`, such events will only be reported while at least one mouse
    /// button is pressed.
    ///
    /// Mouse events are only reported if `enable_mouse` is `true`.
    ///
    /// The default is `false`.
    pub always_track_motion: bool,
    /// For each signal in the set, a signal handler will intercept the signal
    /// and report it by returning an `Event::Signal(_)` value.
    ///
    /// `block_signals` must be `false` for any of these signals to be received.
    ///
    /// By default, no signals are reported.
    pub report_signals: SignalSet,
}

impl Default for PrepareConfig {
    fn default() -> PrepareConfig {
        PrepareConfig{
            block_signals: true,
            enable_control_flow: false,
            enable_keypad: true,
            enable_mouse: false,
            always_track_motion: false,
            report_signals: SignalSet::new(),
        }
    }
}

/// Represents a previous device state of a [`Terminal`].
///
/// A value of this type is returned by [`Terminal::prepare`].
///
/// Required to revert terminal state using [`Terminal::restore`].
///
/// [`Terminal`]: struct.Terminal.html
/// [`Terminal::prepare`]: struct.Terminal.html#method.prepare
/// [`Terminal::restore`]: struct.Terminal.html#method.restore
#[must_use = "the result of `terminal.prepare()` should be passed to \
    `terminal.restore()` to restore terminal to its original state"]
pub struct PrepareState(sys::PrepareState);

/// Represents the size of a terminal window
///
/// A valid size must not have zero lines or zero columns.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Size {
    /// Number of lines in the terminal
    pub lines: usize,
    /// Number of columns in the terminal
    pub columns: usize,
}

impl Size {
    /// Returns the total number of cells in a terminal of the given size.
    ///
    /// # Panics
    ///
    /// If `lines * columns` would overflow.
    #[inline]
    pub fn area(&self) -> usize {
        self.checked_area().unwrap_or_else(
            || panic!("overflow in Size::area {:?}", self))
    }

    /// Returns the total number of cells in a terminal of the given size.
    ///
    /// Returns `None` in case of overflow.
    #[inline]
    pub fn checked_area(&self) -> Option<usize> {
        self.lines.checked_mul(self.columns)
    }
}

/// Provides concurrent read and write access to a terminal device
///
/// # Concurrency
///
/// Access to read and write operations is controlled by two internal locks:
/// One for [reading] and one for [writing]. Each lock may be held independently
/// of the other.
///
/// If any one thread wishes to hold both locks, the read lock
/// must be acquired first, in order to prevent deadlocks.
///
/// [reading]: struct.TerminalReadGuard.html
/// [writing]: struct.TerminalWriteGuard.html
pub struct Terminal(pub(crate) sys::Terminal);

/// Holds an exclusive lock for read operations on a `Terminal`
///
/// See [`Terminal`] documentation for details on locking.
///
/// [`Terminal`]: struct.Terminal.html
pub struct TerminalReadGuard<'a>(sys::TerminalReadGuard<'a>);

/// Holds an exclusive lock for write operations on a `Terminal`
///
/// See [`Terminal`] documentation for details on locking.
///
/// [`Terminal`]: struct.Terminal.html
pub struct TerminalWriteGuard<'a>(sys::TerminalWriteGuard<'a>);

impl Terminal {
    /// Opens a new interface to the terminal on `stdout`.
    pub fn new() -> io::Result<Terminal> {
        Ok(Terminal(sys::Terminal::stdout()?))
    }

    /// Opens a new interface to the terminal on `stderr`.
    pub fn stderr() -> io::Result<Terminal> {
        Ok(Terminal(sys::Terminal::stderr()?))
    }

    /// Returns the name of the terminal.
    ///
    /// # Notes
    ///
    /// On Unix, this method returns the contents of the `TERM` environment variable.
    ///
    /// On Windows, this method always returns the string `"windows-console"`.
    #[inline]
    pub fn name(&self) -> &str {
        self.0.name()
    }

    /// Attempts to acquire an exclusive lock on terminal read operations.
    ///
    /// The current thread will block until the lock can be acquired.
    #[inline]
    pub fn lock_read(&self) -> LockResult<TerminalReadGuard> {
        map_lock_result(self.0.lock_read(), TerminalReadGuard)
    }

    /// Attempts to acquire an exclusive lock on terminal write operations.
    ///
    /// The current thread will block until the lock can be acquired.
    #[inline]
    pub fn lock_write(&self) -> LockResult<TerminalWriteGuard> {
        map_lock_result(self.0.lock_write(), TerminalWriteGuard)
    }

    /// Attempts to acquire an exclusive lock on terminal read operations.
    ///
    /// If the lock cannot be acquired immediately, `Err(_)` is returned.
    #[inline]
    pub fn try_lock_read(&self) -> TryLockResult<TerminalReadGuard> {
        map_try_lock_result(self.0.try_lock_read(), TerminalReadGuard)
    }

    /// Attempts to acquire an exclusive lock on terminal write operations.
    ///
    /// If the lock cannot be acquired immediately, `Err(_)` is returned.
    #[inline]
    pub fn try_lock_write(&self) -> TryLockResult<TerminalWriteGuard> {
        map_try_lock_result(self.0.try_lock_write(), TerminalWriteGuard)
    }
}

/// # Locking
///
/// The following methods internally acquire both the read and write locks.
///
/// The locks are released before the method returns.
///
/// These methods are also implemented on [`TerminalReadGuard`],
/// which holds the `Terminal` read lock until the value is dropped.
///
/// [`TerminalReadGuard`]: struct.TerminalReadGuard.html
impl Terminal {
    /// Prepares the terminal to read input.
    ///
    /// When reading operations have concluded, [`restore`] should be called
    /// with the resulting `PrepareState` value to restore the terminal to
    /// its previous state.
    ///
    /// This method may be called more than once before a corresponding
    /// `restore` call. However, each `restore` call must receive the most
    /// recently created `PrepareState` value.
    ///
    /// See [`PrepareConfig`] for details.
    ///
    /// [`PrepareConfig`]: struct.PrepareConfig.html
    /// [`restore`]: #method.restore
    pub fn prepare(&self, config: PrepareConfig) -> io::Result<PrepareState> {
        self.0.prepare(config).map(PrepareState)
    }

    /// Restores the terminal to its previous state.
    pub fn restore(&self, state: PrepareState) -> io::Result<()> {
        self.0.restore(state.0)
    }
}

/// # Locking
///
/// The following methods internally acquire the read lock.
///
/// The lock is released before the method returns.
///
/// These methods are also implemented on [`TerminalReadGuard`],
/// which holds the `Terminal` read lock until the value is dropped.
///
/// [`TerminalReadGuard`]: struct.TerminalReadGuard.html
impl Terminal {
    /// Waits for an event from the terminal.
    ///
    /// Returns `Ok(false)` if `timeout` elapses without an event occurring.
    ///
    /// If `timeout` is `None`, this method will wait indefinitely.
    pub fn wait_event(&self, timeout: Option<Duration>) -> io::Result<bool> {
        self.0.wait_event(timeout)
    }

    /// Waits for input and reads an event from the terminal.
    ///
    /// Returns `Ok(None)` if `timeout` elapses without an event occurring.
    ///
    /// If `timeout` is `None`, this method will wait indefinitely.
    pub fn read_event(&self, timeout: Option<Duration>) -> io::Result<Option<Event>>  {
        self.0.read_event(timeout)
    }
}

/// # Locking
///
/// The following methods internally acquire the write lock.
///
/// The lock is released before the method returns.
///
/// These methods are also implemented on [`TerminalWriteGuard`],
/// which holds the `Terminal` write lock until the value is dropped.
///
/// [`TerminalWriteGuard`]: struct.TerminalWriteGuard.html
impl Terminal {
    /// Returns the size of the terminal.
    #[inline]
    pub fn size(&self) -> io::Result<Size> {
        self.0.size()
    }

    /// Clears the terminal screen, placing the cursor at the first line and column.
    ///
    /// If the terminal contains a scrolling window over a buffer, the window
    /// will be scrolled downward, preserving as much of the existing buffer
    /// as possible.
    pub fn clear_screen(&self) -> io::Result<()> {
        self.0.clear_screen()
    }

    /// Clears the current line, starting at cursor position.
    pub fn clear_to_line_end(&self) -> io::Result<()> {
        self.0.clear_to_line_end()
    }

    /// Clears the screen, starting at cursor position.
    pub fn clear_to_screen_end(&self) -> io::Result<()> {
        self.0.clear_to_screen_end()
    }

    /// Moves the cursor up `n` lines.
    pub fn move_up(&self, n: usize) -> io::Result<()> {
        self.0.move_up(n)
    }

    /// Moves the cursor down `n` lines.
    pub fn move_down(&self, n: usize) -> io::Result<()> {
        self.0.move_down(n)
    }

    /// Moves the cursor left `n` columns.
    pub fn move_left(&self, n: usize) -> io::Result<()> {
        self.0.move_left(n)
    }

    /// Moves the cursor right `n` columns.
    pub fn move_right(&self, n: usize) -> io::Result<()> {
        self.0.move_right(n)
    }

    /// Moves the cursor to the first column of the current line
    pub fn move_to_first_column(&self) -> io::Result<()> {
        self.0.move_to_first_column()
    }

    /// Set the current cursor mode.
    ///
    /// This setting is a visible hint to the user.
    /// It produces no change in behavior.
    ///
    /// # Notes
    ///
    /// On some systems, this setting may have no effect.
    pub fn set_cursor_mode(&self, mode: CursorMode) -> io::Result<()> {
        self.0.set_cursor_mode(mode)
    }

    /// Adds a set of `Style` flags to the current style setting.
    pub fn add_style(&self, style: Style) -> io::Result<()> {
        self.0.add_style(style)
    }

    /// Removes a set of `Style` flags from the current style setting.
    pub fn remove_style(&self, style: Style) -> io::Result<()> {
        self.0.remove_style(style)
    }

    /// Sets the current style to the given set of flags.
    pub fn set_style<S>(&self, style: S) -> io::Result<()>
            where S: Into<Option<Style>> {
        self.0.set_style(style.into().unwrap_or_default())
    }

    /// Sets all attributes for the terminal.
    pub fn set_theme(&self, theme: Theme) -> io::Result<()> {
        self.0.set_theme(theme)
    }

    /// Sets the foreground text color.
    pub fn set_fg<C: Into<Option<Color>>>(&self, fg: C) -> io::Result<()> {
        self.0.set_fg(fg.into())
    }

    /// Sets the background text color.
    pub fn set_bg<C: Into<Option<Color>>>(&self, bg: C) -> io::Result<()> {
        self.0.set_bg(bg.into())
    }

    /// Removes color and style attributes.
    pub fn clear_attributes(&self) -> io::Result<()> {
        self.0.clear_attributes()
    }

    /// Adds bold to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::BOLD)`.
    pub fn bold(&self) -> io::Result<()> {
        self.add_style(Style::BOLD)
    }

    /// Adds italic to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::ITALIC)`.
    pub fn italic(&self) -> io::Result<()> {
        self.add_style(Style::ITALIC)
    }

    /// Adds underline to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::UNDERLINE)`.
    pub fn underline(&self) -> io::Result<()> {
        self.add_style(Style::UNDERLINE)
    }

    /// Adds reverse to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::REVERSE)`.
    pub fn reverse(&self) -> io::Result<()> {
        self.add_style(Style::REVERSE)
    }

    /// Writes output to the terminal with the given color and style.
    ///
    /// All attributes are removed after the given text is written.
    pub fn write_styled<F, B, S>(&self, fg: F, bg: B, style: S, s: &str)
            -> io::Result<()> where
            F: Into<Option<Color>>,
            B: Into<Option<Color>>,
            S: Into<Option<Style>>,
            {
        self.0.write_styled(fg.into(), bg.into(), style.into().unwrap_or_default(), s)
    }

    /// Writes a single character to the terminal
    /// using the current style and color settings.
    pub fn write_char(&self, ch: char) -> io::Result<()> {
        self.0.write_char(ch)
    }

    /// Writes a string to the terminal
    /// using the current style and color settings.
    pub fn write_str(&self, s: &str) -> io::Result<()> {
        self.0.write_str(s)
    }

    /// Writes formatted text to the terminal
    /// using the current style and color settings.
    ///
    /// This method enables `Terminal` to be used as the receiver to
    /// the [`write!`] and [`writeln!`] macros.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use std::io;
    /// # use mortal::Terminal;
    /// # fn example() -> io::Result<()> {
    /// let term = Terminal::new()?;
    ///
    /// writeln!(term, "Hello, world!")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`write!`]: https://doc.rust-lang.org/std/macro.write.html
    /// [`writeln!`]: https://doc.rust-lang.org/std/macro.writeln.html
    pub fn write_fmt(&self, args: fmt::Arguments) -> io::Result<()> {
        let s = args.to_string();
        self.write_str(&s)
    }

    #[doc(hidden)]
    pub fn borrow_term_write_guard(&self) -> TerminalWriteGuard {
        self.lock_write().unwrap()
    }
}

impl<'a> TerminalReadGuard<'a> {
    /// Prepares the terminal to read input.
    ///
    /// When reading operations have concluded, [`restore`]
    /// should be called with the resulting `PrepareState` value to restore
    /// the terminal to its previous state.
    ///
    /// This method may be called more than once before a corresponding
    /// `restore` call. However, each `restore` call must receive the most recently
    /// created `PrepareState` value.
    ///
    /// See [`PrepareConfig`] for details.
    ///
    /// [`PrepareConfig`]: struct.PrepareConfig.html
    /// [`restore`]: #method.restore
    ///
    /// ## Locking
    ///
    /// This method internally acquires the [`Terminal`] write lock.
    ///
    /// If the write lock is already held by the current thread,
    /// call [`prepare_with_lock`], in order to prevent deadlocks.
    ///
    /// [`Terminal`]: struct.Terminal.html
    /// [`prepare_with_lock`]: #method.prepare_with_lock
    pub fn prepare(&mut self, config: PrepareConfig) -> io::Result<PrepareState> {
        self.0.prepare(config).map(PrepareState)
    }

    /// Performs terminal preparation using both [`Terminal`] locks.
    ///
    /// [`Terminal`]: struct.Terminal.html
    pub fn prepare_with_lock(&mut self, writer: &mut TerminalWriteGuard,
            config: PrepareConfig) -> io::Result<PrepareState> {
        self.0.prepare_with_lock(&mut writer.0, config).map(PrepareState)
    }

    /// Restores the terminal to its previous state.
    ///
    /// ## Locking
    ///
    /// This method internally acquires the [`Terminal`] write lock.
    ///
    /// If the write lock is already held by the current thread,
    /// call [`restore_with_lock`], in order to prevent deadlocks.
    ///
    /// [`Terminal`]: struct.Terminal.html
    /// [`restore_with_lock`]: #method.restore_with_lock
    pub fn restore(&mut self, state: PrepareState) -> io::Result<()> {
        self.0.restore(state.0)
    }

    /// Performs terminal state restoration using both [`Terminal`] locks.
    ///
    /// [`Terminal`]: struct.Terminal.html
    pub fn restore_with_lock(&mut self, writer: &mut TerminalWriteGuard,
            state: PrepareState) -> io::Result<()> {
        self.0.restore_with_lock(&mut writer.0, state.0)
    }

    /// Waits for an event from the terminal.
    ///
    /// Returns `Ok(false)` if `timeout` elapses without an event occurring.
    ///
    /// If `timeout` is `None`, this method will wait indefinitely.
    pub fn wait_event(&mut self, timeout: Option<Duration>) -> io::Result<bool> {
        self.0.wait_event(timeout)
    }

    /// Waits for input and reads an event from the terminal.
    ///
    /// Returns `Ok(None)` if `timeout` elapses without an event occurring.
    ///
    /// If `timeout` is `None`, this method will wait indefinitely.
    pub fn read_event(&mut self, timeout: Option<Duration>) -> io::Result<Option<Event>>  {
        self.0.read_event(timeout)
    }
}

impl<'a> TerminalWriteGuard<'a> {
    /// Flush all output to the terminal device.
    ///
    /// This is called automatically when the `TerminalWriteGuard` is dropped.
    pub fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }

    /// Returns the size of the terminal.
    #[inline]
    pub fn size(&self) -> io::Result<Size> {
        self.0.size()
    }

    /// Clears the terminal screen, placing the cursor at the first line and column.
    ///
    /// If the terminal contains a scrolling window over a buffer, the window
    /// will be scrolled downward, preserving as much of the existing buffer
    /// as possible.
    pub fn clear_screen(&mut self) -> io::Result<()> {
        self.0.clear_screen()
    }

    /// Clears the current line, starting at cursor position.
    pub fn clear_to_line_end(&mut self) -> io::Result<()> {
        self.0.clear_to_line_end()
    }

    /// Clears the screen, starting at cursor position.
    pub fn clear_to_screen_end(&mut self) -> io::Result<()> {
        self.0.clear_to_screen_end()
    }

    /// Moves the cursor up `n` lines.
    pub fn move_up(&mut self, n: usize) -> io::Result<()> {
        self.0.move_up(n)
    }

    /// Moves the cursor down `n` lines.
    pub fn move_down(&mut self, n: usize) -> io::Result<()> {
        self.0.move_down(n)
    }

    /// Moves the cursor left `n` columns.
    pub fn move_left(&mut self, n: usize) -> io::Result<()> {
        self.0.move_left(n)
    }

    /// Moves the cursor right `n` columns.
    pub fn move_right(&mut self, n: usize) -> io::Result<()> {
        self.0.move_right(n)
    }

    /// Moves the cursor to the first column of the current line
    pub fn move_to_first_column(&mut self) -> io::Result<()> {
        self.0.move_to_first_column()
    }

    /// Set the current cursor mode.
    ///
    /// This setting is a visible hint to the user.
    /// It produces no change in behavior.
    ///
    /// # Notes
    ///
    /// On some systems, this setting may have no effect.
    pub fn set_cursor_mode(&mut self, mode: CursorMode) -> io::Result<()> {
        self.0.set_cursor_mode(mode)
    }

    /// Adds a set of `Style` flags to the current style setting.
    pub fn add_style(&mut self, style: Style) -> io::Result<()> {
        self.0.add_style(style)
    }

    /// Removes a set of `Style` flags from the current style setting.
    pub fn remove_style(&mut self, style: Style) -> io::Result<()> {
        self.0.remove_style(style)
    }

    /// Sets the current style to the given set of flags.
    pub fn set_style<S>(&mut self, style: S) -> io::Result<()>
            where S: Into<Option<Style>> {
        self.0.set_style(style.into().unwrap_or_default())
    }

    /// Sets all attributes for the terminal.
    pub fn set_theme(&mut self, theme: Theme) -> io::Result<()> {
        self.0.set_theme(theme)
    }

    /// Sets the background text color.
    pub fn set_fg<C: Into<Option<Color>>>(&mut self, fg: C) -> io::Result<()> {
        self.0.set_fg(fg.into())
    }

    /// Removes color and style attributes.
    pub fn set_bg<C: Into<Option<Color>>>(&mut self, bg: C) -> io::Result<()> {
        self.0.set_bg(bg.into())
    }

    /// Adds bold to the current style setting.
    pub fn clear_attributes(&mut self) -> io::Result<()> {
        self.0.clear_attributes()
    }

    /// Adds bold to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::BOLD)`.
    pub fn bold(&mut self) -> io::Result<()> {
        self.add_style(Style::BOLD)
    }

    /// Adds italic to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::ITALIC)`.
    pub fn italic(&mut self) -> io::Result<()> {
        self.add_style(Style::ITALIC)
    }

    /// Adds underline to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::UNDERLINE)`.
    pub fn underline(&mut self) -> io::Result<()> {
        self.add_style(Style::UNDERLINE)
    }

    /// Adds reverse to the current style setting.
    ///
    /// This is equivalent to `self.add_style(Style::REVERSE)`.
    pub fn reverse(&mut self) -> io::Result<()> {
        self.add_style(Style::REVERSE)
    }

    /// Writes output to the terminal with the given color and style added.
    ///
    /// All attributes are removed after the given text is written.
    pub fn write_styled<F, B, S>(&mut self, fg: F, bg: B, style: S, s: &str)
            -> io::Result<()> where
            F: Into<Option<Color>>,
            B: Into<Option<Color>>,
            S: Into<Option<Style>>,
            {
        self.0.write_styled(fg.into(), bg.into(), style.into().unwrap_or_default(), s)
    }

    /// Writes a single character to the terminal
    /// using the current style and color settings.
    pub fn write_char(&mut self, ch: char) -> io::Result<()> {
        self.0.write_char(ch)
    }

    /// Writes a string to the terminal
    /// using the current style and color settings.
    pub fn write_str(&mut self, s: &str) -> io::Result<()> {
        self.0.write_str(s)
    }

    /// Writes formatted text to the terminal
    /// using the current style and color settings.
    ///
    /// This method enables `TerminalWriteGuard` to be used as the receiver to
    /// the [`write!`] and [`writeln!`] macros.
    ///
    /// [`write!`]: https://doc.rust-lang.org/std/macro.write.html
    /// [`writeln!`]: https://doc.rust-lang.org/std/macro.writeln.html
    pub fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
        let s = args.to_string();
        self.write_str(&s)
    }

    #[doc(hidden)]
    pub fn borrow_term_write_guard(&mut self) -> &mut Self {
        self
    }
}

#[cfg(unix)]
use std::path::Path;

#[cfg(unix)]
impl crate::unix::OpenTerminalExt for Terminal {
    fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        sys::Terminal::open(path).map(Terminal)
    }
}

#[cfg(unix)]
impl crate::unix::TerminalExt for Terminal {
    fn read_raw(&mut self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<Option<Event>> {
        self.0.read_raw(buf, timeout)
    }
}

#[cfg(unix)]
impl<'a> crate::unix::TerminalExt for TerminalReadGuard<'a> {
    fn read_raw(&mut self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<Option<Event>> {
        self.0.read_raw(buf, timeout)
    }
}

#[cfg(windows)]
impl crate::windows::TerminalExt for Terminal {
    fn read_raw(&mut self, buf: &mut [u16], timeout: Option<Duration>) -> io::Result<Option<Event>> {
        self.0.read_raw(buf, timeout)
    }

    fn read_raw_event(&mut self, events: &mut [::winapi::um::wincon::INPUT_RECORD],
            timeout: Option<Duration>) -> io::Result<Option<Event>> {
        self.0.read_raw_event(events, timeout)
    }
}

#[cfg(windows)]
impl<'a> crate::windows::TerminalExt for TerminalReadGuard<'a> {
    fn read_raw(&mut self, buf: &mut [u16], timeout: Option<Duration>) -> io::Result<Option<Event>> {
        self.0.read_raw(buf, timeout)
    }

    fn read_raw_event(&mut self, events: &mut [::winapi::um::wincon::INPUT_RECORD],
            timeout: Option<Duration>) -> io::Result<Option<Event>> {
        self.0.read_raw_event(events, timeout)
    }
}