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
//! `Nc*` methods and associated functions.

use core::ptr::{null, null_mut};

use crate::{
    c_api::{self, notcurses_init},
    cstring, error, error_ref_mut, rstring, rstring_free, Nc, NcAlign, NcBlitter, NcCapabilities,
    NcChannels, NcDim, NcError, NcFile, NcInput, NcLogLevel, NcMiceEvents, NcMiceEventsApi,
    NcOptions, NcPixelImpl, NcPlane, NcReceived, NcResult, NcRgb, NcScale, NcStats, NcStyle,
    NcStyleApi, NcTime, NcVGeom, NcVisual, NcVisualGeometry, NcVisualOptions,
};

/// # `NcOptions` Constructors
impl NcOptions {
    /// New `NcOptions`.
    pub const fn new() -> Self {
        Self::with_all_options(0, 0, 0, 0, 0, 0)
    }

    /// New `NcOptions`, with margins.
    pub const fn with_margins(top: NcDim, right: NcDim, bottom: NcDim, left: NcDim) -> Self {
        Self::with_all_options(0, top, right, bottom, left, 0)
    }

    /// New `NcOptions`, with flags.
    pub const fn with_flags(flags: u64) -> Self {
        Self::with_all_options(0, 0, 0, 0, 0, flags)
    }

    /// New `NcOptions`, with all the options.
    ///
    /// ## Arguments
    ///
    /// - loglevel
    ///
    ///   Progressively higher log levels result in more logging to stderr. By
    ///   default, nothing is printed to stderr once fullscreen service begins.
    ///
    /// - margin_t, margin_r, margin_b, margin_l
    ///
    ///   Desirable margins (top, right, bottom, left).
    ///
    ///   If all are 0 (default), we will render to the entirety of the screen.
    ///   If the screen is too small, we do what we can.
    ///   Absolute coordinates are relative to the rendering area
    ///   ((0, 0) is always the origin of the rendering area).
    ///
    /// - flags
    ///
    ///   General flags; This is expressed as a bitfield so that future options
    ///   can be added without reshaping the struct.
    ///   Undefined bits must be set to 0.
    pub const fn with_all_options(
        loglevel: NcLogLevel,
        margin_t: NcDim,
        margin_r: NcDim,
        margin_b: NcDim,
        margin_l: NcDim,
        flags: u64,
    ) -> Self {
        Self { termtype: null(), loglevel, margin_t, margin_r, margin_b, margin_l, flags }
    }
}

/// # `Nc` Constructors and destructors
//
// TODO: rethink constructors
impl Nc {
    /// New notcurses context (without banners).
    ///
    /// # Safety
    /// You must not create multiple `Nc` instances at the same time, on
    /// the same thread. You must [`stop`][Nc#method.stop] the current one
    /// before creating a new one.
    pub unsafe fn new<'a>() -> NcResult<&'a mut Nc> {
        Self::with_flags(NcOptions::SUPPRESS_BANNERS)
    }

    /// New notcurses context in CLI mode.
    ///
    /// It has the following flags:
    /// - [`NcOptions::SUPPRESS_BANNERS`][NcOptions#associatedconstant.SUPPRESS_BANNERS]
    /// - [`NcOptions::NO_ALTERNATE_SCREEN`][NcOptions#associatedconstant.NO_ALTERNATE_SCREEN]
    /// - [`NcOptions::NO_CLEAR_BITMAPS`][NcOptions#associatedconstant.NO_CLEAR_BITMAPS]
    /// - [`NcOptions::PRESERVE_CURSOR`][NcOptions#associatedconstant.PRESERVE_CURSOR]
    ///
    /// # Safety
    /// You must not create multiple `Nc` instances at the same time, on
    /// the same thread. You must [`stop`][Nc#method.stop] the current one
    /// before creating a new one.
    pub unsafe fn new_cli<'a>() -> NcResult<&'a mut Nc> {
        Self::with_flags(
            NcOptions::SUPPRESS_BANNERS
                | NcOptions::NO_ALTERNATE_SCREEN
                | NcOptions::NO_CLEAR_BITMAPS
                | NcOptions::PRESERVE_CURSOR,
        )
    }

    /// New notcurses context, with banners.
    ///
    /// This is the default in the C library.
    ///
    /// # Safety
    /// You must not create multiple `Nc` instances at the same time, on
    /// the same thread. You must [`stop`][Nc#method.stop] the current one
    /// before creating a new one.
    pub unsafe fn with_banners<'a>() -> NcResult<&'a mut Nc> {
        Self::with_flags(0)
    }

    /// New notcurses context, without an alternate screen (nor banners).
    ///
    #[deprecated]
    #[doc(hidden)]
    pub unsafe fn without_altscreen<'a>() -> NcResult<&'a mut Nc> {
        Self::with_flags(NcOptions::NO_ALTERNATE_SCREEN | NcOptions::SUPPRESS_BANNERS)
    }

    /// New notcurses context, expects `NcOptions::*` flags.
    ///
    /// # Safety
    /// You must not create multiple `Nc` instances at the same time, on
    /// the same thread. You must [`stop`][Nc#method.stop] the current one
    /// before creating a new one.
    pub unsafe fn with_flags<'a>(flags: u64) -> NcResult<&'a mut Nc> {
        Self::with_options(NcOptions::with_flags(flags))
    }

    /// New notcurses context, expects [NcOptions].
    ///
    /// # Safety
    /// You must not create multiple `Nc` instances at the same time, on
    /// the same thread. You must [`stop`][Nc#method.stop] the current one
    /// before creating a new one.
    pub unsafe fn with_options<'a>(options: NcOptions) -> NcResult<&'a mut Nc> {
        let res = notcurses_init(&options, null_mut());
        error_ref_mut![res, "Nc.with_options()"]
    }

    /// New notcurses context, expects [NcLogLevel] and flags.
    ///
    /// # Safety
    /// You must not create multiple `Nc` instances at the same time, on
    /// the same thread. You must [`stop`][Nc#method.stop] the current one
    /// before creating a new one.
    pub unsafe fn with_debug<'a>(loglevel: NcLogLevel, flags: u64) -> NcResult<&'a mut Nc> {
        Self::with_options(NcOptions::with_all_options(loglevel, 0, 0, 0, 0, flags))
    }

    /// Destroys the notcurses context.
    ///
    /// # Safety
    /// You must not call this method repeatedly on the same `Nc` instance.
    ///
    /// *C style function: [notcurses_stop()][c_api::notcurses_stop].*
    pub unsafe fn stop(&mut self) -> NcResult<()> {
        error![c_api::notcurses_stop(self)]
    }
}

/// # `Nc` methods
impl Nc {
    /// Returns the offset into `availcols` at which `cols` ought be output given
    /// the requirements of `align`.
    ///
    /// Returns `-`[NcIntResult::MAX][crate::NcIntResult::MAX] if
    /// [`NcAlign::Unaligned`].
    ///
    /// *C style function: [notcurses_align()][c_api::notcurses_align].*
    pub fn align(availcols: NcDim, align: NcAlign, cols: NcDim) -> NcResult<NcDim> {
        let res = c_api::notcurses_align(availcols, align, cols);
        error![
            res,
            &format!("NcPlane.valign({:?}, {})", align, cols),
            res as NcDim
        ]
    }

    /// Retrieves the current contents of the specified [`NcCell`][crate::NcCell]
    /// as last rendered, returning the `EGC` (or None on error) and writing
    /// out the [`NcStyle`] and the [`NcChannels`].
    ///
    /// *C style function: [notcurses_at_yx()][c_api::notcurses_at_yx].*
    pub fn at_yx(
        &mut self,
        y: NcDim,
        x: NcDim,
        stylemask: &mut NcStyle,
        channels: &mut NcChannels,
    ) -> Option<String> {
        let egc = unsafe { c_api::notcurses_at_yx(self, y, x, stylemask, channels) };
        if egc.is_null() {
            return None;
        }
        Some(rstring_free![egc])
    }

    /// Returns [`NcCapabilities`].
    ///
    /// *C style function: [notcurses_capabilities()][c_api::notcurses_capabilities].*
    pub fn capabilities(&self) -> NcCapabilities {
        unsafe { *c_api::notcurses_capabilities(self) }
    }

    /// Returns true if we can reliably use Unicode Braille.
    ///
    /// See also [`NcBlitter::Braille`].
    ///
    /// *C style function: [notcurses_canbraille()][c_api::notcurses_canbraille].*
    pub fn canbraille(&self) -> bool {
        c_api::notcurses_canbraille(self)
    }

    /// Returns true if it's possible to set the "hardware" palette.
    ///
    /// Requires the "ccc" terminfo capability.
    ///
    /// *C style function: [notcurses_canchangecolor()][c_api::notcurses_canchangecolor].*
    pub fn canchangecolor(&self) -> bool {
        c_api::notcurses_canchangecolor(self)
    }

    /// Returns true if fading is possible.
    ///
    /// Fading requires either the "rgb" or "ccc" terminfo capability.
    ///
    /// *C style function: [notcurses_canfade()][c_api::notcurses_canfade].*
    pub fn canfade(&self) -> bool {
        c_api::notcurses_canfade(self)
    }

    /// Returns true if we can reliably use Unicode half blocks.
    ///
    /// See also [`NcBlitter::Half`].
    ///
    /// *C style function: [notcurses_canhalfblock()][c_api::notcurses_canhalfblock].*
    pub fn canhalfblock(&self) -> bool {
        c_api::notcurses_canhalfblock(self)
    }

    /// Returns true if loading images is possible.
    ///
    /// This requires being built against FFmpeg/OIIO.
    ///
    /// *C style function: [notcurses_canopen_images()][c_api::notcurses_canopen_images].*
    pub fn canopen_images(&self) -> bool {
        unsafe { c_api::notcurses_canopen_images(self) }
    }

    /// Returns true if loading videos is possible.
    ///
    /// This requires being built against FFmpeg.
    ///
    /// *C style function: [notcurses_canopen_videos()][c_api::notcurses_canopen_videos].*
    pub fn canopen_videos(&self) -> bool {
        unsafe { c_api::notcurses_canopen_videos(self) }
    }

    /// Returns true if we can blit pixel-accurate bitmaps.
    ///
    /// See also [`check_pixel_support`][Nc#method.check_pixel_support].
    ///
    /// *C style function: [notcurses_canpixel()][c_api::notcurses_canpixel].*
    pub fn canpixel(&self) -> bool {
        c_api::notcurses_canpixel(self)
    }

    /// Returns true if we can reliably use Unicode quadrant blocks.
    ///
    /// See also [`NcBlitter::Quadrant`].
    ///
    /// *C style function: [notcurses_canquadrant()][c_api::notcurses_canquadrant].*
    pub fn canquadrant(&self) -> bool {
        c_api::notcurses_canquadrant(self)
    }

    /// Returns true if we can reliably use Unicode 13 sextants.
    ///
    /// See also [`NcBlitter::Sextant`].
    ///
    /// *C style function: [notcurses_cansextant()][c_api::notcurses_cansextant].*
    pub fn cansextant(&self) -> bool {
        c_api::notcurses_cansextant(self)
    }

    /// Returns true if it's possible to directly specify RGB values per cell,
    /// or false if it's only possible to use palettes.
    ///
    /// *C style function: [notcurses_cantruecolor()][c_api::notcurses_cantruecolor].*
    pub fn cantruecolor(&self) -> bool {
        c_api::notcurses_cantruecolor(self)
    }

    /// Returns true if the encoding is UTF-8.
    ///
    /// Requires `LANG` being set to a UTF-8 locale.
    ///
    /// *C style function: [notcurses_canutf8()][c_api::notcurses_canutf8].*
    pub fn canutf8(&self) -> bool {
        c_api::notcurses_canutf8(self)
    }

    /// Checks for pixel support.
    ///
    /// Returns [`NcPixelImpl`] with a non-zero constant corresponding to some
    /// pixel-blitting mechanism if bitmap support (via any mechanism) has been
    /// detected, or else 0 (NCPIXEL_NONE).
    ///
    /// *C style function: [notcurses_check_pixel_support()][c_api::notcurses_check-pixel_support].*
    #[allow(clippy::wildcard_in_or_patterns)]
    pub fn check_pixel_support(&self) -> NcPixelImpl {
        unsafe { c_api::notcurses_check_pixel_support(self) }
    }

    /// Returns the default foreground color, if it is known.
    pub fn default_forekground(&self) -> Option<NcRgb> {
        let mut fg: NcRgb = 0;
        let res = unsafe { c_api::notcurses_default_foreground(self, &mut fg) };
        if res == c_api::NCRESULT_ERR {
            None
        } else {
            Some(fg)
        }
    }

    /// Returns the default background color, if it is known.
    pub fn default_background(&self) -> Option<NcRgb> {
        let mut bg: NcRgb = 0;
        let res = unsafe { c_api::notcurses_default_background(self, &mut bg) };
        if res == c_api::NCRESULT_ERR {
            None
        } else {
            Some(bg)
        }
    }

    /// Disables the terminal's cursor, if supported.
    ///
    /// Immediate effect (no need for a call to notcurses_render()).
    ///
    /// *C style function: [notcurses_cursor_disable()][c_api::notcurses_cursor_disable].*
    pub fn cursor_disable(&mut self) -> NcResult<()> {
        error![unsafe { c_api::notcurses_cursor_disable(self) }]
    }

    /// Enables the terminal's cursor, if supported, placing it at `y`, `x`.
    ///
    /// Immediate effect (no need for a call to notcurses_render()).
    /// It is an error if `y`, `x` lies outside the standard plane.
    ///
    /// *C style function: [notcurses_cursor_enable()][c_api::notcurses_cursor_enable].*
    pub fn cursor_enable(&mut self, y: NcDim, x: NcDim) -> NcResult<()> {
        error![unsafe { c_api::notcurses_cursor_enable(self, y as i32, x as i32) }]
    }

    /// Shifts to the alternate screen, if available.
    ///
    /// If already using the alternate screen, this returns Ok(()) immediately.
    ///
    /// If the alternate screen is not available, returns an Error immediately.
    ///
    /// Entering the alternate screen turns off scrolling for the standard plane.
    ///
    /// *C style function:
    /// [notcurses_enter_alternate_screen()][c_api::notcurses_enter_alternate_screen].*
    pub fn enter_alternate_screen(&mut self) -> NcResult<()> {
        error![unsafe { c_api::notcurses_enter_alternate_screen(self) }]
    }

    /// Exits the alternate screen.
    ///
    /// Immediately returns Ok(()) if not currently using the alternate screen.
    ///
    /// *C style function:
    /// [notcurses_leave_alternate_screen()][c_api::notcurses_leave_alternate_screen].*
    pub fn leave_alternate_screen(&mut self) -> NcResult<()> {
        error![unsafe { c_api::notcurses_leave_alternate_screen(self) }]
    }

    /// Dumps notcurses state to the supplied `debugfp`.
    ///
    /// Output is freeform, and subject to change. It includes geometry of all
    /// planes, from all piles.
    ///
    /// *C style function: [notcurses_debug()][c_api::notcurses_debug].*
    pub fn debug(&mut self, debugfp: &mut NcFile) {
        unsafe {
            c_api::notcurses_debug(self, debugfp.as_nc_ptr());
        }
    }

    /// Returns the name of the user under which we are running.
    ///
    /// *C style function: [notcurses_accountname()][c_api::notcurses_accountname].*
    pub fn accountname() -> String {
        rstring_free![c_api::notcurses_accountname()]
    }

    /// Returns the name of the local hostname.
    ///
    /// *C style function: [notcurses_hostname()][c_api::notcurses_hostname].*
    pub fn hostname() -> String {
        rstring_free![c_api::notcurses_hostname()]
    }

    /// Returns the name of the detected terminal.
    ///
    /// *C style function: [notcurses_detected_terminal()][c_api::notcurses_detected_terminal].*
    pub fn detected_terminal(&self) -> String {
        rstring_free![c_api::notcurses_detected_terminal(self)]
    }

    /// Returns the name of the detected OS version.
    ///
    /// *C style function: [notcurses_osversion()][c_api::notcurses_osversion].*
    pub fn osversion(&self) -> String {
        rstring_free![c_api::notcurses_detected_terminal(self)]
    }

    /// Destroys all [`NcPlane`]s other than the stdplane.
    ///
    /// *C style function: [notcurses_drop_planes()][c_api::notcurses_drop_planes].*
    pub fn drop_planes(&mut self) {
        unsafe {
            c_api::notcurses_drop_planes(self);
        }
    }

    /// Gets an [`NcReceived`] from input.
    ///
    /// Provide `None` in `time` to block at length, and otherwise
    /// `Some(`[`NcTime`]`)` to bound blocking.
    ///
    /// `time` is an a delay bound against `CLOCK_MONOTONIC`
    /// (see [*pthread_cond_clockwait(3)*](https://linux.die.net/man/3/pthread_cond_wait)).
    ///
    /// *C style function: [notcurses_get()][c_api::notcurses_get].*
    pub fn get(
        &mut self,
        time: Option<NcTime>,
        input: Option<&mut NcInput>,
    ) -> NcResult<NcReceived> {
        let ntime;
        if let Some(time) = time {
            ntime = &time as *const _;
        } else {
            ntime = null();
        }

        let ninput;
        if let Some(input) = input {
            ninput = input as *mut _;
        } else {
            ninput = null_mut();
        }

        let res = unsafe { c_api::notcurses_get(self, ntime, ninput) };
        if res == c_api::NCRESULT_ERR as u32 {
            Err(NcError::new_msg(&format!["Nc.get({:?})", time]))
        } else {
            Ok(NcReceived::new(res))
        }
    }

    /// Reads input blocking until an event is processed or a signal is received.
    ///
    /// Will optionally write the event details in `input`.
    ///
    /// In the case of a valid read, a [`char`] is returned.
    ///
    /// *C style function: [notcurses_get_blocking()][c_api::notcurses_get_blocking].*
    pub fn get_blocking(&mut self, input: Option<&mut NcInput>) -> NcResult<NcReceived> {
        let res = c_api::notcurses_get_blocking(self, input);
        if res == c_api::NCRESULT_ERR {
            Err(NcError::new_msg("Nc.get_blocking()"))
        } else {
            Ok(NcReceived::new(res as u32))
        }
    }

    /// Reads input without blocking.
    ///
    /// In the case of a valid read, a [`char`] is returned.
    ///
    /// If no event is ready, returns 0.
    ///
    /// *C style function: [notcurses_get_nblock()][c_api::notcurses_get_nblock].*
    pub fn get_nblock(&mut self, input: Option<&mut NcInput>) -> NcResult<NcReceived> {
        let res = c_api::notcurses_get_nblock(self, input);
        if res == c_api::NCRESULT_ERR {
            Err(NcError::new_msg("Nc.get_nblock()"))
        } else {
            Ok(NcReceived::new(res as u32))
        }
    }

    /// Acquire up to 'vcount' [`NcInput`]s at the vector 'ni'.
    ///
    /// The number read will be returned, or 0 on timeout.
    ///
    /// *C style function: [notcurses_getvec()][c_api::notcurses_getvec].*
    pub fn getvec(
        &mut self,
        time: Option<NcTime>,
        ni: &mut Vec<NcInput>,
        vcount: u32,
    ) -> NcResult<u32> {
        let ntime;
        if let Some(time) = time {
            ntime = &time as *const _;
        } else {
            ntime = null();
        }
        let nivec = ni.as_mut_ptr() as *mut NcInput;

        let res = unsafe { c_api::notcurses_getvec(self, ntime, nivec, vcount as i32) };
        error![res, "", res as u32]
    }

    /// Gets a file descriptor suitable for input event poll()ing.
    ///
    /// When this descriptor becomes available, you can call
    /// [get_nblock()][Nc#method.get_nblock], and input ought be ready.
    ///
    /// This file descriptor is not necessarily the file descriptor associated
    /// with stdin (but it might be!).
    ///
    /// *C style function: [notcurses_inputready_fd()][c_api::notcurses_inputready_fd].*
    pub fn inputready_fd(&mut self) -> NcResult<()> {
        error![unsafe { c_api::notcurses_inputready_fd(self) }]
    }

    /// Returns an [`NcBlitter`] from a string representation.
    ///
    /// *C style function: [notcurses_lex_blitter()][c_api::notcurses_lex_blitter].*
    pub fn lex_blitter(blitter_str: &str) -> NcResult<NcBlitter> {
        let mut blitter = 0;
        error![
            unsafe { c_api::notcurses_lex_blitter(cstring![blitter_str], &mut blitter) },
            "Invalid blitter name",
            blitter.into()
        ]
    }

    /// Lexes a margin argument according to the standard notcurses definition.
    ///
    /// There can be either a single number, which will define all margins equally,
    /// or there can be four numbers separated by commas.
    ///
    /// *C style function: [notcurses_lex_margins()][c_api::notcurses_lex_margins].*
    pub fn lex_margins(margins_str: &str, options: &mut NcOptions) -> NcResult<()> {
        error![unsafe { c_api::notcurses_lex_margins(cstring![margins_str], options) }]
    }

    /// Returns an [`NcScale`] from a string representation.
    ///
    /// *C style function: [notcurses_lex_scalemode()][c_api::notcurses_lex_scalemode].*
    pub fn lex_scalemode(scale_str: &str) -> NcResult<NcScale> {
        let mut scale = 0;
        error![
            unsafe { c_api::notcurses_lex_scalemode(cstring![scale_str], &mut scale) },
            "",
            scale.into()
        ]
    }

    /// Returns an [`NcStyle`] from a string representation.
    ///
    /// It is case-insensitive, and supports multiple styles separated by
    /// spaces.
    ///
    /// The supported styles are: `italic`, `underline`, `undercurl`,
    /// `struck`, `bold`, and `none`.
    ///
    /// If a style is are not recognized returns an error.
    ///
    /// *(No equivalent C style function)*
    pub fn lex_styles(styles_str: &str) -> NcResult<NcStyle> {
        let mut style = NcStyle::NOSTYLE;
        let mut errstr = String::new();

        for s in styles_str.split(' ') {
            match s.to_lowercase().as_str() {
                "italic" => style.add(NcStyle::ITALIC),
                "underline" => style.add(NcStyle::UNDERLINE),
                "undercurl" => style.add(NcStyle::UNDERCURL),
                "struck" => style.add(NcStyle::STRUCK),
                "bold" => style.add(NcStyle::BOLD),
                "none" => (),
                _ => {
                    errstr.push_str(s);
                    errstr.push(' ');
                }
            }
        }
        if errstr.is_empty() {
            Ok(style)
        } else {
            let _ = errstr.pop();
            Err(NcError::new_msg(&format![
                "the following styles are not recognized: '{}'",
                errstr
            ]))
        }
    }

    /// Disables signals originating from the terminal's line discipline, i.e.
    /// SIGINT (^C), SIGQUIT (^), and SIGTSTP (^Z). They are enabled by default.
    ///
    /// *C style function: [notcurses_linesigs_disable()][c_api::notcurses_linesigs_disable].*
    pub fn linesigs_disable(&mut self) -> NcResult<()> {
        error![unsafe { c_api::notcurses_linesigs_disable(self) }]
    }

    /// Restores signals originating from the terminal's line discipline, i.e.
    /// SIGINT (^C), SIGQUIT (^), and SIGTSTP (^Z), if disabled.
    ///
    /// *C style function: [notcurses_linesigs_enable()][c_api::notcurses_linesigs_enable].*
    pub fn linesigs_enable(&mut self) -> NcResult<()> {
        error![unsafe { c_api::notcurses_linesigs_enable(self) }]
    }

    /// Disables mice events.
    ///
    /// *C style function: [notcurses_mice_disable()][c_api::notcurses_mice_disable].*
    pub fn mice_disable(&mut self) -> NcResult<()> {
        self.mice_enable(NcMiceEvents::NO_EVENTS)
    }

    /// Enables mice events according to `eventmask`.
    ///
    /// An eventmask of 0 will disable all mice tracking.
    ///
    /// On success mouse events will be published to `notcurses_get`.
    ///
    /// *C style function: [notcurses_mice_enable()][c_api::notcurses_mice_enable].*
    pub fn mice_enable(&mut self, eventmask: NcMiceEvents) -> NcResult<()> {
        error![
            unsafe { c_api::notcurses_mice_enable(self, eventmask) },
            "Nc.mice_enable()"
        ]
    }

    /// Returns the number of simultaneous colors claimed to be supported,
    /// if there is color support.
    ///
    /// Note that several terminal emulators advertise more colors than they
    /// actually support, downsampling internally.
    ///
    /// *C style function: [notcurses_palette_size()][c_api::notcurses_palette_size].*
    pub fn palette_size(&self) -> NcResult<u32> {
        let res = unsafe { c_api::notcurses_palette_size(self) };
        if res == 1 {
            return Err(NcError::with_msg(1, "No color support ← Nc.palette_size()"));
        }
        Ok(res)
    }

    /// Refreshes the physical screen to match what was last rendered (i.e.,
    /// without reflecting any changes since the last call to
    /// [`render`][crate::Nc#method.render]).
    ///
    /// Returns the current screen geometry (`y`, `x`).
    ///
    /// This is primarily useful if the screen is externally corrupted, or if an
    /// [NcKey::RESIZE][crate::NcKey#associatedconstant.RESIZE] event
    /// has been read and you're not yet ready to render.
    ///
    /// *C style function: [notcurses_refresh()][c_api::notcurses_refresh].*
    //
    pub fn refresh(&mut self) -> NcResult<(NcDim, NcDim)> {
        let (mut y, mut x) = (0, 0);
        error![
            unsafe { c_api::notcurses_refresh(self, &mut y, &mut x) },
            "",
            (y as NcDim, x as NcDim)
        ]
    }

    /// Renders and rasterizes the standard pile in one shot. Blocking call.
    ///
    /// *C style function: [notcurses_render()][c_api::notcurses_render].*
    pub fn render(&mut self) -> NcResult<()> {
        error![c_api::notcurses_render(self), "Nc.render()"]
    }

    /// Acquires an atomic snapshot of the notcurses object's stats.
    ///
    /// *C style function: [notcurses_stats()][c_api::notcurses_stats].*
    pub fn stats(&mut self, stats: &mut NcStats) {
        unsafe {
            c_api::notcurses_stats(self, stats);
        }
    }

    /// Allocates an [`NcStats`] object.
    ///
    /// Use this rather than allocating your own, since future versions of
    /// notcurses might enlarge this structure.
    ///
    /// *C style function: [notcurses_stats_alloc()][c_api::notcurses_stats_alloc].*
    pub fn stats_alloc(&mut self) -> &mut NcStats {
        unsafe { &mut *c_api::notcurses_stats_alloc(self) }
    }

    /// Resets all cumulative stats (immediate ones, such as fbbytes, are not reset).
    ///
    /// *C style function: [notcurses_stats_reset()][c_api::notcurses_stats_reset].*
    pub fn stats_reset(&mut self, stats: &mut NcStats) {
        unsafe {
            c_api::notcurses_stats_reset(self, stats);
        }
    }

    // TODO: decide what to do with these two:
    //
    // /// [notcurses_stdplane()][c_api::notcurses_stdplane], plus free bonus
    // /// dimensions written to non-NULL y/x!
    // ///
    // /// *C style function: [notcurses_stddim_yx()][c_api::notcurses_stddim_yx].*
    // #[inline]
    // pub fn stddim_yx<'a>(
    //     &'a mut self,
    //     y: &mut NcDim,
    //     x: &mut NcDim,
    // ) -> NcResult<&'a mut NcPlane> {
    //     c_api::notcurses_stddim_yx(self, y, x)
    // }

    // /// [stdplane_const()][Nc#method.stdplane_const], plus free
    // /// bonus dimensions written to non-NULL y/x!
    // ///
    // /// *C style function: [notcurses_stddim_yx()][c_api::notcurses_stddim_yx].*
    // #[inline]
    // pub fn stddim_yx_const<'a>(
    //     &'a self,
    //     y: &mut NcDim,
    //     x: &mut NcDim,
    // ) -> NcResult<&'a NcPlane> {
    //     c_api::notcurses_stddim_yx_const(self, y, x)
    // }

    /// Returns a mutable reference to the standard [`NcPlane`] for this terminal.
    ///
    /// The standard plane always exists, and its origin is always at the
    /// uppermost, leftmost cell.
    ///
    /// # Safety
    /// You must be careful not to end up with multiple exclusive references
    /// to the standard plane, or with one exclusive reference and one or more
    /// shared references.
    ///
    /// *C style function: [notcurses_stdplane()][c_api::notcurses_stdplane].*
    pub unsafe fn stdplane<'a>(&mut self) -> &'a mut NcPlane {
        &mut *c_api::notcurses_stdplane(self)
    }

    /// Returns a reference to the standard [`NcPlane`] for this terminal.
    ///
    /// The standard plane always exists, and its origin is always at the
    /// uppermost, leftmost cell.
    ///
    /// # Safety
    /// You must be careful not to end up with a mix of exclusive references
    /// and shared references to the standard plane.
    ///
    /// *C style function: [notcurses_stdplane_const()][c_api::notcurses_stdplane_const].*
    pub unsafe fn stdplane_const<'a>(&self) -> &'a NcPlane {
        &*c_api::notcurses_stdplane_const(self)
    }

    /// Gets the name of an [`NcBlitter`] blitter.
    ///
    /// *C style function: [notcurses_str_blitter()][c_api::notcurses_str_blitter].*
    pub fn str_blitter(blitter: NcBlitter) -> String {
        rstring![c_api::notcurses_str_blitter(blitter.into())].to_string()
    }

    /// Gets the name of an [`NcScale`] scaling mode.
    ///
    /// *C style function: [notcurses_str_scalemode()][c_api::notcurses_str_scalemode].*
    pub fn str_scalemode(scale: NcScale) -> String {
        rstring![c_api::notcurses_str_scalemode(scale.into())].to_string()
    }

    /// Gets the lowercase name (or names) of the styles included in an [`NcStyle`].
    ///
    /// *(No equivalent C style function)*
    pub fn str_styles(style: NcStyle) -> String {
        let mut string = String::new();
        for s in style.to_vec() {
            string.push_str(match s {
                NcStyle::ITALIC => "italic",
                NcStyle::UNDERLINE => "underline",
                NcStyle::UNDERCURL => "undercurl",
                NcStyle::STRUCK => "struck",
                NcStyle::BOLD => "bold",
                #[allow(unreachable_patterns)] // FIXME
                NcStyle::NOSTYLE => "none",
                _ => "none",
            });
            string.push(' ');
        }
        let _ = string.pop();
        string
    }

    /// Returns an [`NcStyle`] with the supported curses-style attributes.
    ///
    /// The attribute is only indicated as supported if the terminal can support
    /// it together with color.
    ///
    /// For more information, see the "ncv" capability in terminfo(5).
    ///
    /// *C style function: [notcurses_supported_styles()][c_api::notcurses_supported_styles].*
    pub fn supported_styles(&self) -> NcStyle {
        unsafe { c_api::notcurses_supported_styles(self) as NcStyle }
    }

    /// Returns our current idea of the terminal dimensions in rows and cols.
    ///
    /// *C style function: [notcurses_term_dim_yx()][c_api::notcurses_term_dim_yx].*
    pub fn term_dim_yx(&self) -> (NcDim, NcDim) {
        c_api::notcurses_term_dim_yx(self)
    }

    /// Returns the bottommost [`NcPlane`] on the standard pile,
    /// of which there is always at least one.
    ///
    /// *C style function: [notcurses_bottom()][c_api::notcurses_bottom].*
    pub fn bottom(&mut self) -> &mut NcPlane {
        c_api::notcurses_bottom(self)
    }

    /// Returns the topmost [`NcPlane`], of which there is always at least one.
    ///
    /// *C style function: [notcurses_top()][c_api::notcurses_top].*
    pub fn top(&mut self) -> &mut NcPlane {
        c_api::notcurses_top(self)
    }

    /// Returns a human-readable string describing the running notcurses version.
    ///
    /// *C style function: [notcurses_version()][c_api::notcurses_version].*
    pub fn version() -> String {
        rstring![c_api::notcurses_version()].to_string()
    }

    /// Returns the running notcurses version components
    /// (major, minor, patch, tweak).
    ///
    /// *C style function: [notcurses_version_components()][c_api::notcurses_version_components].*
    pub fn version_components() -> (u32, u32, u32, u32) {
        let (mut major, mut minor, mut patch, mut tweak) = (0, 0, 0, 0);
        unsafe {
            c_api::notcurses_version_components(&mut major, &mut minor, &mut patch, &mut tweak);
        }
        (major as u32, minor as u32, patch as u32, tweak as u32)
    }

    /// Returns [`NcVisualGeometry`].
    ///
    /// If an [`NcVisual`] is not provided, only the [`cdim_yx`], [`blitter`],
    /// [`scale_yx`], and [`maxpixel_yx`] fields will be filled in.
    ///
    /// If an [`NcVisualOptions`] is not provided, a default one will be used.
    ///
    /// Additionally `cdim_yx` and `maxpixel_yx` are only ever filled in if we
    /// know them, and `maxpixel_yx` is only defined for [`NcBlitter::Pixel`].
    ///
    /// # See also
    /// - [`NcVisual.geom`][NcVisual#method.geom]
    ///
    /// [`cdim_yx`]: NcVisualGeometry#structfield.cdim_yx
    /// [`blitter`]: NcVisualGeometry#structfield.blitter
    /// [`scale_yx`]: NcVisualGeometry#structfield.scale_yx
    /// [`maxpixel_yx`]: NcVisualGeometry#structfield.maxpixel_yx
    ///
    /// *C style function: [ncvisual_geom()][c_api::ncvisual_geom].*
    pub fn visual_geom(
        &self,
        visual: Option<&NcVisual>,
        vopts: Option<&NcVisualOptions>,
    ) -> NcResult<NcVisualGeometry> {
        let mut vg = NcVGeom::new();

        let v_ptr: *const NcVisual;
        if let Some(v) = visual {
            v_ptr = v;
        } else {
            v_ptr = null();
        }
        let vo_ptr: *const NcVisualOptions;
        if let Some(o) = vopts {
            vo_ptr = o;
        } else {
            let vo = NcVisualOptions::default();
            vo_ptr = &vo;
        }

        let res = unsafe { crate::c_api::ncvisual_geom(self, v_ptr, vo_ptr, &mut vg) };
        if res <= c_api::NCRESULT_ERR {
            return Err(NcError::with_msg(
                res,
                &format!["Nc.visual_geom({:?}, {:?})", visual, vopts],
            ));
        }

        let (pix_yx, cdim_yx, rpix_yx, rcell_yx, scale_yx, maxpixel_yx, beg_yx, len_yx);

        // if an `NcVisual` is not provided, only `maxpixel_yx`, `cdim_yx` and
        // `scale_yx` can be non-zero.
        if visual.is_none() {
            cdim_yx = Some((vg.cdimy as NcDim, vg.cdimx as NcDim));
            scale_yx = Some((vg.scaley as NcDim, vg.scalex as NcDim));

            // pixel blitter only is defined for Ncblitter::PIXEL
            if vg.blitter == NcBlitter::Pixel.into() {
                maxpixel_yx = Some((vg.maxpixely as NcDim, vg.maxpixelx as NcDim));
            } else {
                maxpixel_yx = None;
            }

            pix_yx = None;
            rpix_yx = None;
            rcell_yx = None;
            beg_yx = None;
            len_yx = None;
        } else {
            // `maxpixel_yx` only is defined for `Ncblitter`::PIXEL.
            if vg.blitter == NcBlitter::Pixel.into() {
                maxpixel_yx = Some((vg.maxpixely as NcDim, vg.maxpixelx as NcDim));
            } else {
                maxpixel_yx = None;
            }

            // `beg_yx` & `len_yx` can be safely ignored if they're all 0.
            if vg.begy | vg.begx | vg.leny | vg.lenx == 0 {
                beg_yx = None;
                len_yx = None;
            } else {
                beg_yx = Some((vg.begy as NcDim, vg.begx as NcDim));
                len_yx = Some((vg.leny as NcDim, vg.lenx as NcDim));
            }

            // valid values for the following fields can't be 0 either:
            if vg.pixy | vg.pixx == 0 {
                pix_yx = None;
            } else {
                pix_yx = Some((vg.pixy as NcDim, vg.pixx as NcDim));
            }
            if vg.cdimy | vg.cdimx == 0 {
                cdim_yx = None;
            } else {
                cdim_yx = Some((vg.cdimy as NcDim, vg.cdimx as NcDim));
            }
            if vg.scaley | vg.scalex == 0 {
                scale_yx = None;
            } else {
                scale_yx = Some((vg.scaley as NcDim, vg.scalex as NcDim));
            }
            if vg.rpixy | vg.rpixx == 0 {
                rpix_yx = None;
            } else {
                rpix_yx = Some((vg.rpixy as NcDim, vg.rpixx as NcDim));
            }
            if vg.rcelly | vg.rcellx == 0 {
                rcell_yx = None;
            } else {
                rcell_yx = Some((vg.rcelly as NcDim, vg.rcellx as NcDim));
            }
        }

        let vgeometry = NcVisualGeometry {
            pix_yx,
            cdim_yx,
            rpix_yx,
            rcell_yx,
            scale_yx,
            maxpixel_yx,
            beg_yx,
            len_yx,
            blitter: (vg.blitter as crate::c_api::NcBlitter_u32).into(),
        };
        Ok(vgeometry)
    }

    /// Like [`visual_geom`] but auto-fills the `NcVisualOptions` with
    /// `NcBlitter::Pixel` in order to get the maximum available resolution
    /// for `scale_yx`, which determines the minimum dot-size for an `NcVisual`.
    ///
    /// [`visual_geom`]: Nc#method.visual_geom
    pub fn visual_geom_with_pixel(&self, visual: Option<&NcVisual>) -> NcResult<NcVisualGeometry> {
        Self::visual_geom(
            self,
            visual,
            Some(&NcVisualOptions::builder().pixel().build()),
        )
    }
}