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
#![cfg(feature = "wincon")]

//! Stuff for interacting with the console.
//!
//! The [`consoleapi`] module adds more to what you find here. They're meant to
//! be used together really.

use super::*;

use winapi::um::wincon::{
  AddConsoleAliasW, AttachConsole, CreateConsoleScreenBuffer,
  FillConsoleOutputAttribute, FillConsoleOutputCharacterW, FlushConsoleInputBuffer,
  FreeConsole, GenerateConsoleCtrlEvent, GetConsoleAliasW, GetConsoleAliasesLengthW,
  GetConsoleAliasesW, GetConsoleCursorInfo, GetConsoleDisplayMode,
  GetConsoleFontSize, GetConsoleHistoryInfo, GetConsoleOriginalTitleW,
  GetConsoleProcessList, GetConsoleScreenBufferInfo, GetConsoleScreenBufferInfoEx,
  GetConsoleSelectionInfo, GetConsoleTitleW, GetConsoleWindow,
  GetCurrentConsoleFont, GetCurrentConsoleFontEx, GetLargestConsoleWindowSize,
  GetNumberOfConsoleMouseButtons, PeekConsoleInputW, ReadConsoleOutputAttribute,
  ReadConsoleOutputCharacterW, ReadConsoleOutputW, ScrollConsoleScreenBufferW,
  SetConsoleActiveScreenBuffer, SetConsoleCP, SetConsoleCursorInfo,
  SetConsoleCursorPosition, SetConsoleDisplayMode, SetConsoleHistoryInfo,
  SetConsoleOutputCP, SetConsoleScreenBufferInfoEx, SetConsoleScreenBufferSize,
  SetConsoleTextAttribute, SetConsoleTitleW, SetConsoleWindowInfo,
  SetCurrentConsoleFontEx, WriteConsoleInputW, WriteConsoleOutputAttribute,
  WriteConsoleOutputCharacterW, WriteConsoleOutputW, CONSOLE_TEXTMODE_BUFFER,
};

pub use winapi::um::wincon::{
  ATTACH_PARENT_PROCESS, CONSOLE_CURSOR_INFO, CONSOLE_FONT_INFOEX,
  CONSOLE_HISTORY_INFO, CONSOLE_READCONSOLE_CONTROL, CONSOLE_SCREEN_BUFFER_INFO,
  CONSOLE_SCREEN_BUFFER_INFOEX, CONSOLE_SELECTION_INFO, DISABLE_NEWLINE_AUTO_RETURN,
  ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS, ENABLE_INSERT_MODE, ENABLE_LINE_INPUT,
  ENABLE_LVB_GRID_WORLDWIDE, ENABLE_MOUSE_INPUT, ENABLE_PROCESSED_INPUT,
  ENABLE_PROCESSED_OUTPUT, ENABLE_QUICK_EDIT_MODE, ENABLE_VIRTUAL_TERMINAL_INPUT,
  ENABLE_VIRTUAL_TERMINAL_PROCESSING, ENABLE_WINDOW_INPUT,
  ENABLE_WRAP_AT_EOL_OUTPUT,
};

/// A ConsoleScreenBuffer is _similar to_ a "surface" or "backbuffer" for a
/// console.
///
/// You can edit the content of a ConsoleScreenBuffer at any time, and you can
/// have more than one ConsoleScreenBuffer, and exactly one ConsoleScreenBuffer
/// can be the active screen buffer of your console (that's the one that
/// actually gets displayed).
#[derive(Debug)]
#[repr(transparent)]
pub struct ConsoleScreenBuffer {
  nn_handle: NonNull<winapi::ctypes::c_void>,
}
#[cfg(all(feature = "processenv", feature = "processthreadsapi"))]
impl core::clone::Clone for ConsoleScreenBuffer {
  /// Duplicates the `ConsoleScreenBuffer` by duplicating the inner handle.
  /// ## Panics
  /// This will panic if the duplication fails.
  fn clone(&self) -> Self {
    let mut dup: HANDLE = null_mut();
    let b = unsafe {
      DuplicateHandle(
        GetCurrentProcess(),
        self.nn_handle.as_ptr(),
        GetCurrentProcess(),
        &mut dup,
        0,
        TRUE,
        DUPLICATE_SAME_ACCESS,
      )
    };
    if b != 0 {
      match NonNull::new(dup) {
        Some(nn_handle) => ConsoleScreenBuffer { nn_handle },
        None => panic!("Duplicated handle returned as null."),
      }
    } else {
      panic!("Could not duplicate the handle.")
    }
  }
}
impl Drop for ConsoleScreenBuffer {
  #[allow(clippy::if_same_then_else)]
  fn drop(&mut self) {
    if unsafe { CloseHandle(self.nn_handle.as_ptr()) } != 0 {
      // success
    } else if cfg!(debug_assertions) {
      // TODO: print an error message if debug assertions are on. We should never
      // fail to close a handle, but I guess it could happen, and in that case
      // you'd probably want to know.
    }
  }
}
impl ConsoleScreenBuffer {
  /// Creates a new ConsoleScreenBuffer.
  // TODO: better document the failure cases.
  pub fn new() -> Result<Self, ErrorCode> {
    // Note(Lokathor): No security descriptor specified makes us default to the
    // access token of the calling process.
    let security_attributes = SECURITY_ATTRIBUTES {
      nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
      lpSecurityDescriptor: null_mut(),
      bInheritHandle: TRUE,
    };
    let handle = unsafe {
      CreateConsoleScreenBuffer(
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        &security_attributes,
        CONSOLE_TEXTMODE_BUFFER,
        null_mut(),
      )
    };
    if handle != INVALID_HANDLE_VALUE {
      Ok(Self {
        nn_handle: NonNull::new(handle).unwrap(),
      })
    } else {
      Err(get_last_error())
    }
  }

  /// Makes a `ConsoleScreenBuffer` using stdout.
  ///
  /// The resulting `ConsoleScreenBuffer` is _not_ exclusively controlled by
  /// you. Any other bit of code can still get the stdout handle and then do
  /// output (eg: `println!`). You could even call this more than once and have
  /// more than one `ConsoleScreenBuffer` all pointing at stdout.
  ///
  /// The internal handle of the `ConsoleScreenBuffer` will be a _duplicate_ of
  /// stdout, which means that if you just let it drop normally then your stdout
  /// won't actually be closed.
  ///
  /// ## Failure
  ///
  /// * If the stdout handle can't be obtained you get an OS error.
  /// * If the stdout handle can't be duplicated you get an OS error.
  /// * If stdout is obtained but an invalid handle you get application error 0.
  /// * If stdout is duplicated but null you get application error 1.
  #[cfg(all(feature = "processenv", feature = "processthreadsapi"))]
  pub fn from_stdout() -> Result<Self, ErrorCode> {
    get_std_handle(StdHandle::Output).and_then(|std_handle| {
      if std_handle != INVALID_HANDLE_VALUE && !std_handle.is_null() {
        let mut std_dup: HANDLE = null_mut();
        let b = unsafe {
          DuplicateHandle(
            GetCurrentProcess(),
            std_handle,
            GetCurrentProcess(),
            &mut std_dup,
            0,
            TRUE,
            DUPLICATE_SAME_ACCESS,
          )
        };
        if b != 0 {
          match NonNull::new(std_dup) {
            Some(nn_handle) => Ok(ConsoleScreenBuffer { nn_handle }),
            None => Err(ErrorCode(ErrorCode::APPLICATION_ERROR_BIT | 1)),
          }
        } else {
          Err(get_last_error())
        }
      } else {
        Err(ErrorCode(ErrorCode::APPLICATION_ERROR_BIT))
      }
    })
  }
}

/// Defines a new console alias.
///
/// Source is the input text, target is the text to map it to (use `None` to
/// _remove_ an existing mapping), and exe is the executable that the mapping
/// should apply for.
///
/// See
/// [`AddConsoleAlias`](https://docs.microsoft.com/en-us/windows/console/AddConsoleAlias)
/// (uses the `W` version)
#[inline]
pub fn add_console_alias(
  source: &str,
  opt_target: Option<&str>,
  exe: &str,
) -> Result<(), ErrorCode> {
  let mut source_w = wide_null(source);
  let mut exe_w = wide_null(exe);
  let mut opt_target_w = opt_target.map(wide_null);
  if unsafe {
    AddConsoleAliasW(
      source_w.as_mut_ptr(),
      opt_target_w
        .as_mut()
        .map(|v| v.as_mut_ptr())
        .unwrap_or(null_mut()),
      exe_w.as_mut_ptr(),
    )
  } != 0
  {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// Attaches your process to the console of the process you specify.
///
/// You can use the `ATTACH_PARENT_PROCESS` constant to pick your parent process
/// without knowing its exact value.
///
/// A process can only be connected to one console at a time.
///
/// See
/// [`AttachConsole`](https://docs.microsoft.com/en-us/windows/console/AttachConsole),
/// [`alloc_console`], and [`free_console`].
#[inline]
pub fn attach_console(process_id: u32) -> Result<(), ErrorCode> {
  if unsafe { AttachConsole(process_id) } == 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`CreateConsoleScreenBuffer`](https://docs.microsoft.com/en-us/windows/console/CreateConsoleScreenBuffer)
#[inline]
pub unsafe fn create_console_screen_buffer(
  desired_access: u32,
  share_mode: u32,
  security_attributes: Option<&SECURITY_ATTRIBUTES>,
) -> Result<HANDLE, ErrorCode> {
  let handle = CreateConsoleScreenBuffer(
    desired_access,
    share_mode,
    opt_to_ptr(security_attributes),
    CONSOLE_TEXTMODE_BUFFER,
    null_mut(),
  );
  if handle != INVALID_HANDLE_VALUE {
    Ok(handle)
  } else {
    Err(get_last_error())
  }
}

/// See [`FillConsoleOutputAttribute`](https://docs.rs/winapi/0.3.8/winapi/um/wincon/fn.FillConsoleOutputAttribute.html)
#[inline]
pub unsafe fn fill_console_output_attribute(
  console_output: HANDLE,
  attribute: u16,
  length: u32,
  write_coord: COORD,
) -> Result<u32, ErrorCode> {
  let mut out: u32 = 0;
  let s = FillConsoleOutputAttribute(
    console_output,
    attribute,
    length,
    write_coord,
    &mut out,
  );
  if s != 0 {
    Ok(out)
  } else {
    Err(get_last_error())
  }
}

/// See [`FillConsoleOutputCharacter`](https://docs.microsoft.com/en-us/windows/console/FillConsoleOutputCharacter) (uses the `W` version)
#[inline]
pub unsafe fn fill_console_output_character(
  console_output: HANDLE,
  ch: u16,
  length: u32,
  write_coord: COORD,
) -> Result<u32, ErrorCode> {
  let mut out: u32 = 0;
  let s =
    FillConsoleOutputCharacterW(console_output, ch, length, write_coord, &mut out);
  if s != 0 {
    Ok(out)
  } else {
    Err(get_last_error())
  }
}

/// See [`FlushConsoleInputBuffer`](https://docs.microsoft.com/en-us/windows/console/FlushConsoleInputBuffer)
#[inline]
pub unsafe fn flush_console_input_buffer(
  console_input: HANDLE,
) -> Result<(), ErrorCode> {
  if FlushConsoleInputBuffer(console_input) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// Detaches the calling process from its console.
///
/// Each process has at most 1 console, so this doesn't need any input. Note
/// that this doesn't _actually_ free the console itself unless you were the
/// last process connected to that console.
///
/// See
/// [`FreeConsole`](https://docs.microsoft.com/en-us/windows/console/FreeConsole)
#[inline]
pub fn free_console() -> Result<(), ErrorCode> {
  if unsafe { FreeConsole() } != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`GenerateConsoleCtrlEvent`](https://docs.microsoft.com/en-us/windows/console/GenerateConsoleCtrlEvent)
#[inline]
pub unsafe fn generate_console_ctrl_event(
  event: u32,
  process_group_id: u32,
) -> Result<(), ErrorCode> {
  if GenerateConsoleCtrlEvent(event, process_group_id) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`GetConsoleAlias`](https://docs.microsoft.com/en-us/windows/console/GetConsoleAlias)
#[inline]
pub unsafe fn get_console_alias(
  source: &str,
  exe: &str,
) -> Result<String, ErrorCode> {
  // Note(Lokathor): This function doesn't tell us how many characters it wrote
  // into the buffer like winapi functions normally do, so we have to do it
  // differently than we usually do.
  let mut source_w = wide_null(source);
  let mut exe_w = wide_null(exe);
  let mut buffer: Vec<u16> = vec![0; 4096];
  if GetConsoleAliasW(
    source_w.as_mut_ptr(),
    buffer.as_mut_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    exe_w.as_mut_ptr(),
  ) != 0
  {
    let null_position = buffer.iter().copied().position(|u| u == 0).unwrap();
    buffer.set_len(null_position);
    Ok(String::from_utf16_lossy(&buffer))
  } else {
    Err(get_last_error())
  }
}

/// Gets all console aliases associated with the specified executable.
///
/// The data format is "source=target\0source=target\0..." for however many
/// aliases are defined.
///
/// See
/// [`GetConsoleAliases`](https://docs.microsoft.com/en-us/windows/console/GetConsoleAliases)
/// (uses the `W` version)
#[inline]
pub fn get_console_aliases(exe: &str) -> Result<String, ErrorCode> {
  let mut exe_w = wide_null(exe);
  // Note(Lokathor): This return value is in _bytes_ so we're technically
  // over-allocating with the Vec in the next step, but that's fine because it's
  // just temporary.
  let needed_capacity =
    unsafe { GetConsoleAliasesLengthW(exe_w.as_mut_ptr()) as usize };
  let mut buffer: Vec<u16> = vec![0; needed_capacity];
  if unsafe {
    GetConsoleAliasesW(buffer.as_mut_ptr(), buffer.len() as u32, exe_w.as_mut_ptr())
  } != 0
  {
    Ok(String::from_utf16_lossy(&buffer))
  } else {
    Err(get_last_error())
  }
}

/// The number of bytes required to store all console aliases of the executable.
///
/// There's not much point to using this, [`get_console_aliases`] does it for
/// you, but it's here if you want I guess.
///
/// See
/// [`GetConsoleAliasesLength`](https://docs.microsoft.com/en-us/windows/console/GetConsoleAliasesLength)
/// (uses the `W` version)
#[inline]
pub fn get_console_aliases_length(exe: &str) -> usize {
  let mut exe_w = wide_null(exe);
  unsafe { GetConsoleAliasesLengthW(exe_w.as_mut_ptr()) as usize }
}

/// See [`GetConsoleCursorInfo`](https://docs.microsoft.com/en-us/windows/console/GetConsoleCursorInfo)
#[inline]
pub unsafe fn get_console_cursor_info(
  console_output: HANDLE,
) -> Result<CONSOLE_CURSOR_INFO, ErrorCode> {
  let mut info = CONSOLE_CURSOR_INFO::default();
  if GetConsoleCursorInfo(console_output, &mut info) != 0 {
    Ok(info)
  } else {
    Err(get_last_error())
  }
}

/// Gets the display mode of the current console.
///
/// Output will generally be one of:
/// * 0: Windowed.
/// * 1: `CONSOLE_FULLSCREEN`, the console is maximized, but transition to
///   full-screen mode can still fail.
/// * 2: `CONSOLE_FULLSCREEN_HARDWARE`, the console is maximized and directly
///   using the video hardware.
///
/// See
/// [`GetConsoleDisplayMode`](https://docs.microsoft.com/en-us/windows/console/GetConsoleDisplayMode)
#[inline]
pub fn get_console_display_mode() -> Result<u32, ErrorCode> {
  let mut out: u32 = 0;
  if unsafe { GetConsoleDisplayMode(&mut out) } != 0 {
    Ok(out)
  } else {
    Err(get_last_error())
  }
}

/// See [`GetConsoleFontSize`](https://docs.microsoft.com/en-us/windows/console/GetConsoleFontSize)
#[inline]
pub unsafe fn get_console_font_size(
  console_output: HANDLE,
  font: u32,
) -> Result<COORD, ErrorCode> {
  let c = GetConsoleFontSize(console_output, font);
  if c.X != 0 && c.Y != 0 {
    Ok(c)
  } else {
    Err(get_last_error())
  }
}

/// Obtains history info about this process's console.
///
/// Naturally, this fails if this process has no console.
///
/// See [`GetConsoleHistoryInfo`](https://docs.microsoft.com/en-us/windows/console/GetConsoleHistoryInfo)
#[inline]
pub fn get_console_history_info() -> Result<CONSOLE_HISTORY_INFO, ErrorCode> {
  let mut out = CONSOLE_HISTORY_INFO::default();
  out.cbSize = size_of::<CONSOLE_HISTORY_INFO>() as u32;
  if unsafe { GetConsoleHistoryInfo(&mut out) } != 0 {
    Ok(out)
  } else {
    Err(get_last_error())
  }
}

/// Gets the original title of the console.
///
/// This might not be the current title, for that use [`get_console_title`].
///
/// See [`GetConsoleOriginalTitle`](https://docs.microsoft.com/en-us/windows/console/GetConsoleOriginalTitle) (uses the `W` version).
pub fn get_console_original_title() -> Result<String, ErrorCode> {
  // Note(Lokathor): A huge temporary buffer helps avoid running out of space
  // during the copy, and the final data goes into a separately allocated
  // String, so it's fine if this is way large than you'd ever normally need.
  let mut buffer: Vec<u16> = Vec::with_capacity(1024);
  loop {
    let str_len_copied: u32 = unsafe {
      GetConsoleOriginalTitleW(buffer.as_mut_ptr(), buffer.capacity() as u32)
    };
    if str_len_copied > 0 {
      // if the byte count written is non-zero there was success. Also, this
      // unwrap can't ever panic because you'd have to have written a number of
      // buffer units that doesn't fit into `usize`, which can't happen.
      unsafe { buffer.set_len(usize::try_from(str_len_copied).unwrap()) };
      return Ok(String::from_utf16_lossy(&buffer));
    } else {
      let e = get_last_error();
      if e.0 == ERROR_SUCCESS {
        // if we "failed" but the last error is ERROR_SUCCESS we need more
        // buffer space, so reserve more and try again. If we'd be somehow
        // forced to reserve more than u32::MAX worth of bytes (the maximum
        // buffer size you can pass to `GetConsoleOriginalTitleW`) then we'll
        // actually give up, but that seems like an unlikely problem.
        let new_cap_target = buffer.capacity() * 2;
        if new_cap_target > core::u32::MAX as usize {
          return Err(e);
        } else {
          buffer.reserve(new_cap_target);
          continue;
        }
      } else {
        // otherwise we really have some other error, and we return that.
        return Err(e);
      }
    }
  }
}

/// Gets the list of process ID values connected to the current console.
///
/// See
/// [`GetConsoleProcessList`](https://docs.microsoft.com/en-us/windows/console/GetConsoleProcessList)
#[inline]
pub fn get_console_process_list() -> Result<Vec<u32>, ErrorCode> {
  let mut buffer: Vec<u32> = Vec::with_capacity(10);
  loop {
    let out = unsafe {
      GetConsoleProcessList(buffer.as_mut_ptr(), buffer.capacity() as u32)
    };
    if out == 0 {
      return Err(get_last_error());
    }
    if out <= buffer.capacity() as u32 {
      unsafe { buffer.set_len(out as usize) };
      return Ok(buffer);
    } else {
      buffer.reserve(out as usize);
      continue;
    }
  }
}

/// See [`GetConsoleScreenBufferInfo`](https://docs.microsoft.com/en-us/windows/console/GetConsoleScreenBufferInfo)
#[inline]
pub unsafe fn get_console_screenbuffer_info(
  console_output: HANDLE,
) -> Result<CONSOLE_SCREEN_BUFFER_INFO, ErrorCode> {
  let mut info = CONSOLE_SCREEN_BUFFER_INFO::default();
  if GetConsoleScreenBufferInfo(console_output, &mut info) != 0 {
    Ok(info)
  } else {
    Err(get_last_error())
  }
}

/// See [`GetConsoleScreenBufferInfoEx`](https://docs.microsoft.com/en-us/windows/console/GetConsoleScreenBufferInfoEx)
#[inline]
pub unsafe fn get_console_screenbuffer_info_ex(
  console_output: HANDLE,
) -> Result<CONSOLE_SCREEN_BUFFER_INFOEX, ErrorCode> {
  let mut info = CONSOLE_SCREEN_BUFFER_INFOEX::default();
  info.cbSize = size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as u32;
  if GetConsoleScreenBufferInfoEx(console_output, &mut info) != 0 {
    Ok(info)
  } else {
    Err(get_last_error())
  }
}

/// Gets information about the currently selected area of the console.
///
/// See [`GetConsoleSelectionInfo`](https://docs.microsoft.com/en-us/windows/console/GetConsoleSelectionInfo)
#[inline]
pub fn get_console_selection_info() -> Result<CONSOLE_SELECTION_INFO, ErrorCode> {
  let mut info = CONSOLE_SELECTION_INFO::default();
  if unsafe { GetConsoleSelectionInfo(&mut info) } != 0 {
    Ok(info)
  } else {
    Err(get_last_error())
  }
}

/// Get the current title of the console.
///
/// See [`GetConsoleTitle`](https://docs.microsoft.com/en-us/windows/console/GetConsoleTitle) (uses the `W` version)
#[inline]
pub fn get_console_title() -> Result<String, ErrorCode> {
  // Note(Lokathor): As with a few other functions in this module, we just need
  // a "large" temporary buffer and then the final String returned will use a
  // separate allocation. If this fails we don't get any info about how much
  // space we'd need to try again, so we'll just hope that the title is
  // generally less than 4k code units.
  let mut buffer: Vec<u16> = Vec::with_capacity(4096);
  let out =
    unsafe { GetConsoleTitleW(buffer.as_mut_ptr(), buffer.capacity() as u32) };
  if out != 0 {
    unsafe { buffer.set_len(out as usize - 1) };
    Ok(String::from_utf16_lossy(&buffer))
  } else {
    Err(get_last_error())
  }
}

/// Obtains the `HWND` value of the console's window.
///
/// See [`GetConsoleWindow`](https://docs.microsoft.com/en-us/windows/console/GetConsoleWindow)
#[inline]
pub unsafe fn get_console_window() -> HWND {
  GetConsoleWindow()
}

/// See [`GetCurrentConsoleFont`](https://docs.microsoft.com/en-us/windows/console/GetCurrentConsoleFont)
#[inline]
pub unsafe fn get_current_console_font(
  console_output: HANDLE,
  max_window: bool,
) -> Result<CONSOLE_FONT_INFO, ErrorCode> {
  let mut info = CONSOLE_FONT_INFO::default();
  if GetCurrentConsoleFont(console_output, max_window as i32, &mut info) != 0 {
    Ok(info)
  } else {
    Err(get_last_error())
  }
}

/// See [`GetCurrentConsoleFontEx`](https://docs.microsoft.com/en-us/windows/console/GetCurrentConsoleFontEx)
#[inline]
pub unsafe fn get_current_console_font_ex(
  console_output: HANDLE,
  max_window: bool,
) -> Result<CONSOLE_FONT_INFOEX, ErrorCode> {
  let mut info = CONSOLE_FONT_INFOEX::default();
  info.cbSize = size_of::<CONSOLE_FONT_INFOEX>() as u32;
  if GetCurrentConsoleFontEx(console_output, max_window as i32, &mut info) != 0 {
    Ok(info)
  } else {
    Err(get_last_error())
  }
}

/// See [`GetLargestConsoleWindowSize`](https://docs.microsoft.com/en-us/windows/console/GetLargestConsoleWindowSize)
#[inline]
pub unsafe fn get_largest_console_window_size(
  console_output: HANDLE,
) -> Result<COORD, ErrorCode> {
  let coord = GetLargestConsoleWindowSize(console_output);
  if coord.X != 0 && coord.Y != 0 {
    Ok(coord)
  } else {
    Err(get_last_error())
  }
}

/// Gets the number of buttons on the mouse associated with the console.
///
/// Use this to determine the number of mouse button bits that are important to
/// check when reading `MOUSE_EVENT_RECORD` values.
///
/// See
/// [`GetNumberOfConsoleMouseButtons`](https://docs.microsoft.com/en-us/windows/console/GetNumberOfConsoleMouseButtons)
#[inline]
pub fn get_number_of_console_mouse_buttons() -> Result<u32, ErrorCode> {
  let mut out: u32 = 0;
  if unsafe { GetNumberOfConsoleMouseButtons(&mut out) } != 0 {
    Ok(out)
  } else {
    Err(get_last_error())
  }
}

/// See [`PeekConsoleInput`](https://docs.microsoft.com/en-us/windows/console/PeekConsoleInput) (uses the `W` version)
#[inline]
pub unsafe fn peek_console_input(
  console_input: HANDLE,
  buffer: &mut [INPUT_RECORD],
) -> Result<usize, ErrorCode> {
  let mut num_read: u32 = 0;
  if PeekConsoleInputW(
    console_input,
    buffer.as_mut_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    &mut num_read,
  ) != 0
  {
    Ok(num_read as usize)
  } else {
    Err(get_last_error())
  }
}

/// See [`ReadConsoleOutput`](https://docs.microsoft.com/en-us/windows/console/ReadConsoleOutput) (uses the `W` version)
#[inline]
pub unsafe fn read_console_output(
  console_output: HANDLE,
  buffer: &mut [CHAR_INFO],
  buffer_size: COORD,
  buffer_target_coord: COORD,
  mut read_region: SMALL_RECT,
) -> Result<SMALL_RECT, ErrorCode> {
  if ReadConsoleOutputW(
    console_output,
    buffer.as_mut_ptr(),
    buffer_size,
    buffer_target_coord,
    &mut read_region,
  ) != 0
  {
    Ok(read_region)
  } else {
    Err(get_last_error())
  }
}

/// See [`ReadConsoleOutputAttribute`](https://docs.microsoft.com/en-us/windows/console/ReadConsoleOutputAttribute)
#[inline]
pub unsafe fn read_console_output_attribute(
  console_output: HANDLE,
  buffer: &mut [u16],
  read_coord: COORD,
) -> Result<usize, ErrorCode> {
  let mut num_read: u32 = 0;
  if ReadConsoleOutputAttribute(
    console_output,
    buffer.as_mut_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    read_coord,
    &mut num_read,
  ) != 0
  {
    Ok(num_read as usize)
  } else {
    Err(get_last_error())
  }
}

/// See [`ReadConsoleOutputCharacter`](https://docs.microsoft.com/en-us/windows/console/ReadConsoleOutputCharacter) (uses the `W` version)
#[inline]
pub unsafe fn read_console_output_character(
  console_output: HANDLE,
  buffer: &mut [u16],
  read_coord: COORD,
) -> Result<usize, ErrorCode> {
  let mut num_read: u32 = 0;
  if ReadConsoleOutputCharacterW(
    console_output,
    buffer.as_mut_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    read_coord,
    &mut num_read,
  ) != 0
  {
    Ok(num_read as usize)
  } else {
    Err(get_last_error())
  }
}

/// See [`ScrollConsoleScreenBuffer`](https://docs.microsoft.com/en-us/windows/console/ScrollConsoleScreenBuffer) (uses the `W` version)
pub unsafe fn scroll_console_screen_buffer(
  console_output: HANDLE,
  scroll_rectangle: SMALL_RECT,
  clip_rect: Option<SMALL_RECT>,
  destination_origin: COORD,
  fill: CHAR_INFO,
) -> Result<(), ErrorCode> {
  if ScrollConsoleScreenBufferW(
    console_output,
    &scroll_rectangle,
    opt_to_ptr(clip_rect.as_ref()),
    destination_origin,
    &fill,
  ) != 0
  {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleActiveScreenBuffer`](https://docs.microsoft.com/en-us/windows/console/SetConsoleActiveScreenBuffer)
#[inline]
pub unsafe fn set_console_active_screen_buffer(
  console_output: HANDLE,
) -> Result<(), ErrorCode> {
  if SetConsoleActiveScreenBuffer(console_output) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// Sets the console's input code page.
///
/// You can check the console's input code page with [`get_console_cp`].
///
/// Note that the _output_ code page is controlled separately with
/// [`get_console_output_cp`] and [`set_console_output_cp`].
///
/// See [`SetConsoleCP`](https://docs.microsoft.com/en-us/windows/console/SetConsoleCP)
#[inline]
pub fn set_console_cp(code_page: u32) -> Result<(), ErrorCode> {
  if unsafe { SetConsoleCP(code_page) } != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// [`SetConsoleCursorInfo`](https://docs.microsoft.com/en-us/windows/console/SetConsoleCursorInfo)
#[inline]
pub unsafe fn set_console_cursor_info(
  console_output: HANDLE,
  info: CONSOLE_CURSOR_INFO,
) -> Result<(), ErrorCode> {
  if SetConsoleCursorInfo(console_output, &info) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleCursorPosition`](https://docs.microsoft.com/en-us/windows/console/SetConsoleCursorPosition)
pub unsafe fn set_console_cursor_position(
  console_output: HANDLE,
  position: COORD,
) -> Result<(), ErrorCode> {
  if SetConsoleCursorPosition(console_output, position) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleDisplayMode`](https://docs.microsoft.com/en-us/windows/console/SetConsoleDisplayMode)
#[inline]
pub unsafe fn set_console_display_mode(
  console_output: HANDLE,
  flags: u32,
) -> Result<COORD, ErrorCode> {
  let mut out = COORD::default();
  if SetConsoleDisplayMode(console_output, flags, &mut out) != 0 {
    Ok(out)
  } else {
    Err(get_last_error())
  }
}

/// Sets the history settings for the console.
///
/// See [`SetConsoleHistoryInfo`](https://docs.microsoft.com/en-us/windows/console/SetConsoleHistoryInfo)
#[inline]
pub fn set_console_history_info(
  mut info: CONSOLE_HISTORY_INFO,
) -> Result<(), ErrorCode> {
  info.cbSize = size_of::<CONSOLE_HISTORY_INFO>() as u32;
  if unsafe { SetConsoleHistoryInfo(&mut info) } != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// Sets the console's output code page.
///
/// You can check the current output code page with [`get_console_output_cp`].
///
/// Note that the _input_ code page is controlled separately with
/// [`get_console_cp`] and [`set_console_cp`].
///
/// See [`SetConsoleOutputCP`](https://docs.microsoft.com/en-us/windows/console/SetConsoleOutputCP)
#[inline]
pub fn set_console_output_cp(code_page: u32) -> Result<(), ErrorCode> {
  if unsafe { SetConsoleOutputCP(code_page) } != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleScreenBufferInfoEx`](https://docs.microsoft.com/en-us/windows/console/SetConsoleScreenBufferInfoEx)
#[inline]
pub unsafe fn set_console_screen_buffer_info_ex(
  console_output: HANDLE,
  mut info: CONSOLE_SCREEN_BUFFER_INFOEX,
) -> Result<(), ErrorCode> {
  info.cbSize = size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as u32;
  if SetConsoleScreenBufferInfoEx(console_output, &mut info) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleScreenBufferSize`](https://docs.microsoft.com/en-us/windows/console/SetConsoleScreenBufferSize)
#[inline]
pub unsafe fn set_console_screen_buffer_size(
  console_output: HANDLE,
  size: COORD,
) -> Result<(), ErrorCode> {
  if SetConsoleScreenBufferSize(console_output, size) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleTextAttribute`](https://docs.microsoft.com/en-us/windows/console/SetConsoleTextAttribute)
#[inline]
pub unsafe fn set_console_text_attribute(
  console_output: HANDLE,
  attribute: u16,
) -> Result<(), ErrorCode> {
  if SetConsoleTextAttribute(console_output, attribute) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// Assigns a new title to the console.
///
/// See [`SetConsoleTitle`](https://docs.microsoft.com/en-us/windows/console/SetConsoleTitle) (uses the `W` version)
#[inline]
pub fn set_console_title(title: &str) -> Result<(), ErrorCode> {
  let wide = wide_null(title);
  if unsafe { SetConsoleTitleW(wide.as_ptr()) } != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetConsoleWindowInfo`](https://docs.microsoft.com/en-us/windows/console/SetConsoleWindowInfo)
#[inline]
pub unsafe fn set_console_window_info(
  console_output: HANDLE,
  absolute: bool,
  window: SMALL_RECT,
) -> Result<(), ErrorCode> {
  if SetConsoleWindowInfo(console_output, absolute as i32, &window) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`SetCurrentConsoleFontEx`](https://docs.microsoft.com/en-us/windows/console/SetCurrentConsoleFontEx)
#[inline]
pub unsafe fn set_current_console_font_ex(
  console_output: HANDLE,
  maximum: bool,
  mut info: CONSOLE_FONT_INFOEX,
) -> Result<(), ErrorCode> {
  info.cbSize = size_of::<CONSOLE_FONT_INFOEX>() as u32;
  if SetCurrentConsoleFontEx(console_output, maximum as i32, &mut info) != 0 {
    Ok(())
  } else {
    Err(get_last_error())
  }
}

/// See [`WriteConsoleInput`](https://docs.microsoft.com/en-us/windows/console/WriteConsoleInput) (uses the `W` version)
#[inline]
pub unsafe fn write_console_input(
  console_input: HANDLE,
  buffer: &[INPUT_RECORD],
) -> Result<usize, ErrorCode> {
  let mut events_written: u32 = 0;
  if WriteConsoleInputW(
    console_input,
    buffer.as_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    &mut events_written,
  ) != 0
  {
    Ok(events_written as usize)
  } else {
    Err(get_last_error())
  }
}

/// See [`WriteConsoleOutput`](https://docs.microsoft.com/en-us/windows/console/WriteConsoleOutput)
#[inline]
pub unsafe fn write_console_output(
  console_output: HANDLE,
  buffer: &[CHAR_INFO],
  buffer_size: COORD,
  buffer_coord: COORD,
  mut write_region: SMALL_RECT,
) -> Result<SMALL_RECT, ErrorCode> {
  if WriteConsoleOutputW(
    console_output,
    buffer.as_ptr(),
    buffer_size,
    buffer_coord,
    &mut write_region,
  ) != 0
  {
    Ok(write_region)
  } else {
    Err(get_last_error())
  }
}

/// See [`WriteConsoleOutputAttribute`](https://docs.microsoft.com/en-us/windows/console/WriteConsoleOutputAttribute)
#[inline]
pub unsafe fn write_console_output_attribute(
  console_output: HANDLE,
  buffer: &[u16],
  position: COORD,
) -> Result<usize, ErrorCode> {
  let mut num_written: u32 = 0;
  if WriteConsoleOutputAttribute(
    console_output,
    buffer.as_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    position,
    &mut num_written,
  ) != 0
  {
    Ok(num_written as usize)
  } else {
    Err(get_last_error())
  }
}

/// See [`WriteConsoleOutputCharacter`](https://docs.microsoft.com/en-us/windows/console/WriteConsoleOutputCharacter)
#[inline]
pub unsafe fn write_console_output_character(
  console_output: HANDLE,
  buffer: &[u16],
  position: COORD,
) -> Result<usize, ErrorCode> {
  let mut num_written: u32 = 0;
  if WriteConsoleOutputCharacterW(
    console_output,
    buffer.as_ptr(),
    buffer.len().min(core::u32::MAX as usize) as u32,
    position,
    &mut num_written,
  ) != 0
  {
    Ok(num_written as usize)
  } else {
    Err(get_last_error())
  }
}