tinsel 1.0.0

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
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
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
//! The terminal itself: its size, its modes, its background colour, and putting everything
//! back on Ctrl-C. Calls libc directly and shells out to `stty`, to stay dependency-free.

use std::io::{self, IsTerminal, Read, Write};
use std::time::{Duration, Instant};

/// The width tinsel lays text out in: the terminal's, capped at 76 columns so lines stay
/// readable. What [`markdown`](fn@crate::markdown), cards and messages wrap to.
pub fn content_width() -> usize {
    width().min(76)
}

/// Columns in the terminal tinsel draws on (stdout, or the [`Target`](crate::Target)), falling
/// back to `$COLUMNS`, then 80. For the width of a piece of text, see
/// [`text::width`](crate::text::width).
pub fn width() -> usize {
    measured_or(ioctl_size().map(|(cols, _)| cols), "COLUMNS", 80)
}

/// Rows in the terminal tinsel draws on, falling back to `$LINES`, then 24.
/// Whether a switch like `TINSEL_NO_FOCUS` is on: set to anything, as long as it isn't
/// empty, the way `NO_COLOR` is read.
pub(crate) fn env_flag(name: &str) -> bool {
    std::env::var_os(name).is_some_and(|v| !v.is_empty())
}

pub(crate) fn height() -> usize {
    measured_or(ioctl_size().map(|(_, rows)| rows), "LINES", 24)
}

/// What the terminal measured, or else what the environment variable `var` says, or else
/// `default`.
fn measured_or(measured: Option<usize>, var: &str, default: usize) -> usize {
    measured
        .or_else(|| std::env::var(var).ok()?.parse().ok())
        .filter(|&n| n > 0)
        .unwrap_or(default)
}

/// Whether both ends are a terminal: stdout to draw a full-screen app on, and someone typing.
pub(crate) fn interactive() -> bool {
    if let Some(terminal) = crate::output::pretended_terminal() {
        return terminal;
    }
    io::stdin().is_terminal() && io::stdout().is_terminal()
}

/// Whether the stream tinsel draws on (stdout, or the [`Target`](crate::Target)) and stdin
/// are both a terminal, so the terminal can be asked something and answer.
fn can_ask() -> bool {
    if let Some(terminal) = crate::output::pretended_terminal() {
        return terminal;
    }
    io::stdin().is_terminal() && crate::output::is_terminal()
}

/// Run `stty` against the terminal on stdin. `stty` is used rather than termios structs
/// because their layout differs between operating systems.
#[cfg(not(windows))]
pub(crate) fn stty(args: &[&str]) -> io::Result<String> {
    use std::process::{Command, Stdio};
    let out = Command::new("stty")
        .args(args)
        .stdin(Stdio::inherit())
        .stderr(Stdio::null())
        .output()?;
    if !out.status.success() {
        return Err(io::Error::other("stty couldn't configure the terminal"));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Character-at-a-time input with no echo, read with [`read_some`], for listening to the
/// terminal while something's drawn. Unlike [`RawMode`], Ctrl-C still interrupts. Several can
/// be held at once, by overlapping displays: the first changes the terminal and the last to be
/// dropped puts it back as it was before the first, whichever order they end in.
pub(crate) struct Cbreak(());

/// The terminal's settings before cbreak, for whichever [`Cbreak`] is dropped last.
#[cfg(not(windows))]
static CBREAK: Holders<Option<String>> = Holders::new(None);
#[cfg(windows)]
static CBREAK: Holders<Option<win::Saved>> = Holders::new(None);

impl Cbreak {
    pub(crate) fn enter() -> io::Result<Cbreak> {
        CBREAK.try_hold(|saved| {
            #[cfg(not(windows))]
            {
                let before = stty(&["-g"])?;
                stty(&["-icanon", "-echo", "min", "0", "time", "1"])?;
                *saved = Some(before);
            }
            #[cfg(windows)]
            {
                *saved = Some(win::enter(false)?);
            }
            Ok(())
        })?;
        Ok(Cbreak(()))
    }
}

impl Drop for Cbreak {
    fn drop(&mut self) {
        CBREAK.let_go(|saved| {
            let Some(saved) = saved.take() else { return };
            #[cfg(not(windows))]
            let _ = stty(&[&saved]);
            #[cfg(windows)]
            win::leave_raw(&saved);
        });
    }
}

/// Something process-wide that overlapping displays share, such as the terminal's settings or
/// the Ctrl-C handler: set up by the first to hold it and undone by the last to let go, in
/// whatever order they finish.
pub(crate) struct Holders<T> {
    held: std::sync::Mutex<(usize, T)>,
}

impl<T> Holders<T> {
    pub(crate) const fn new(state: T) -> Holders<T> {
        Holders {
            held: std::sync::Mutex::new((0, state)),
        }
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, (usize, T)> {
        self.held.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Hold it, running `first` if no one else does yet.
    pub(crate) fn hold(&self, first: impl FnOnce(&mut T)) {
        let _ = self.try_hold(|state| {
            first(state);
            Ok(())
        });
    }

    /// [`hold`](Holders::hold), unless `first` fails, which leaves it unheld.
    pub(crate) fn try_hold(&self, first: impl FnOnce(&mut T) -> io::Result<()>) -> io::Result<()> {
        let mut held = self.lock();
        if held.0 == 0 {
            first(&mut held.1)?;
        }
        held.0 += 1;
        Ok(())
    }

    /// Let go of it, running `last` if no one else holds it now. Letting go of what isn't held
    /// does nothing.
    pub(crate) fn let_go(&self, last: impl FnOnce(&mut T)) {
        let mut held = self.lock();
        if held.0 == 0 {
            return;
        }
        held.0 -= 1;
        if held.0 == 0 {
            last(&mut held.1);
        }
    }
}

/// Whatever's been typed, up to `buf`'s length, waiting at most 0.1s for it: 0 if nothing
/// came. For use in [`Cbreak`] or [`RawMode`].
pub(crate) fn read_some(buf: &mut [u8]) -> io::Result<usize> {
    #[cfg(windows)]
    if !win::key_waiting(100) {
        return Ok(0);
    }
    io::stdin().lock().read(buf)
}

/// [`read_some`], telling a terminal that's quiet from one that's gone. A quiet one gives
/// nothing after waiting 0.1s; one that's hung up (its window closed) gives nothing at once,
/// every time, which read on regardless would spin a core.
#[derive(Default)]
pub(crate) struct Keyboard {
    instant_nothings: u32,
}

impl Keyboard {
    pub(crate) fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let asked = Instant::now();
        let n = match read_some(buf) {
            // a signal (the window resizing, say) cut the wait short
            Err(e) if e.kind() == io::ErrorKind::Interrupted => return Ok(0),
            read => read?,
        };
        self.saw(n, asked.elapsed())?;
        Ok(n)
    }

    fn saw(&mut self, n: usize, took: Duration) -> io::Result<()> {
        // only Unix reads wait; on Windows nothing can come back at once, from mouse events
        let instant = n == 0 && took < Duration::from_millis(20) && cfg!(unix);
        self.instant_nothings = if instant { self.instant_nothings + 1 } else { 0 };
        if self.instant_nothings >= 10 {
            return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the terminal closed"));
        }
        Ok(())
    }
}

/// Stdin read through [`read_some`], so reads give up after 0.1s everywhere.
pub(crate) struct TimedStdin;

impl Read for TimedStdin {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        read_some(buf)
    }
}

/// Whether the terminal answers questions and reports focus (OSC 11, mode 1004). On Unix,
/// most do, and the rest are waited for briefly. On Windows only Windows Terminal does, and
/// the console it replaced would make every program wait for answers that never come.
pub(crate) fn answers_queries() -> bool {
    !cfg!(windows) || std::env::var_os("WT_SESSION").is_some()
}

/// Single keypresses for prompts: no echo, no line buffering, Ctrl-C delivered as a byte (so
/// the terminal is always put back before leaving), and reads that give up after 0.1s so a
/// lone Esc can be told apart from the start of an arrow key. Undone when dropped.
pub(crate) struct RawMode {
    #[cfg(not(windows))]
    saved: String,
    #[cfg(windows)]
    saved: win::Saved,
}

/// The `stty` settings for [`RawMode`]. Beyond echo, line buffering and signals, flow
/// control (`ixon`: Ctrl-S and Ctrl-Q) and the extended keys (`iexten`: Ctrl-V and Ctrl-O) are
/// turned off, so those keys arrive too and Ctrl-S can't freeze the screen. `icrnl` goes as
/// well, so Return comes as the `\r` it is (both `\r` and `\n` read as Enter).
#[cfg(not(windows))]
const RAW: &[&str] = &[
    "-icanon", "-echo", "-isig", "-ixon", "-iexten", "-icrnl", "min", "0", "time", "1",
];

impl RawMode {
    pub(crate) fn enter() -> io::Result<RawMode> {
        #[cfg(not(windows))]
        {
            let saved = stty(&["-g"])?;
            stty(RAW)?;
            Ok(RawMode { saved })
        }
        #[cfg(windows)]
        {
            Ok(RawMode {
                saved: win::enter(true)?,
            })
        }
    }
}

impl Drop for RawMode {
    fn drop(&mut self) {
        #[cfg(not(windows))]
        let _ = stty(&[&self.saved]);
        #[cfg(windows)]
        win::leave_raw(&self.saved);
    }
}

/// Set when the window changes size, until [`resized`] is asked.
static RESIZED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Note each change of window size (SIGWINCH), for [`resized`] to report, rather than
/// waiting for the next look at the size. Returns the previous handler, to put back with
/// [`unwatch_resize`]. A handler someone else set is left in place, and then nothing is noted.
#[cfg(unix)]
pub(crate) fn watch_resize() -> Option<usize> {
    // SAFETY: on_resize only stores to an atomic, which is async-signal-safe
    let prev = unsafe { take_signal(SIGWINCH, on_resize, |prev| prev != SIG_DFL && prev != SIG_IGN) }?;
    Some(prev.handler())
}

#[cfg(unix)]
pub(crate) fn unwatch_resize(prev: Option<usize>) {
    if let Some(prev) = prev {
        // SAFETY: prev came from signal() itself, so it is a valid handler value
        unsafe { signal(SIGWINCH, prev) };
    }
}

#[cfg(unix)]
extern "C" fn on_resize(_: i32) {
    RESIZED.store(true, std::sync::atomic::Ordering::SeqCst);
}

/// Windows has no signal for it, so the size is only ever looked at.
#[cfg(not(unix))]
pub(crate) fn watch_resize() -> Option<usize> {
    None
}

#[cfg(not(unix))]
pub(crate) fn unwatch_resize(_: Option<usize>) {}

/// Whether the window has changed size since this was last asked.
pub(crate) fn resized() -> bool {
    RESIZED.swap(false, std::sync::atomic::Ordering::SeqCst)
}

/// One byte from the keyboard while in [`RawMode`], or `None` if nothing came within 0.1s.
pub(crate) fn read_byte() -> io::Result<Option<u8>> {
    let mut b = [0u8; 1];
    Ok((read_some(&mut b)? == 1).then_some(b[0]))
}

/// Ask the terminal for its background colour (OSC 11). Most modern terminals answer within
/// a few milliseconds; ones that don't are given 150ms.
pub(crate) fn query_background() -> Option<(u8, u8, u8)> {
    if !can_ask() || !answers_queries() {
        return None;
    }
    let cbreak = Cbreak::enter().ok()?;
    // asked on the stream tinsel draws on: with TINSEL_TARGET=stderr, stdout may be a pipe
    let mut out = crate::output::writer();
    let _ = out.write_all(b"\x1b]11;?\x1b\\");
    let _ = out.flush();
    let deadline = Instant::now() + Duration::from_millis(150);
    let mut reply = Vec::new();
    while Instant::now() < deadline {
        let mut b = [0u8; 64];
        let n = read_some(&mut b).unwrap_or(0);
        reply.extend_from_slice(&b[..n]);
        // the reply ends with BEL or ST (ESC \)
        if reply.ends_with(b"\x07") || reply.ends_with(b"\x1b\\") {
            break;
        }
    }
    drop(cbreak);
    parse_osc_color(&String::from_utf8_lossy(&reply))
}

/// `rgb:RRRR/GGGG/BBBB` (1-4 hex digits a channel) out of an OSC colour reply.
fn parse_osc_color(reply: &str) -> Option<(u8, u8, u8)> {
    let rgb = &reply[reply.find("rgb:")? + 4..];
    let mut channels = rgb.split('/').map(|c| {
        let hex: String = c.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
        // more than four digits isn't a colour any terminal sends, and would overflow
        if hex.len() > 4 {
            return None;
        }
        let v = u64::from_str_radix(&hex, 16).ok()?;
        let max = (1u64 << (4 * hex.len())) - 1;
        Some((v * 255 / max) as u8)
    });
    Some((channels.next()??, channels.next()??, channels.next()??))
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
unsafe extern "C" {
    fn ioctl(fd: i32, request: std::ffi::c_ulong, ...) -> i32;
}

/// The terminal's columns and rows, if it could be asked: for [`doctor`](crate::doctor).
pub(crate) fn measured_size() -> Option<(usize, usize)> {
    ioctl_size()
}

/// Columns and rows of the terminal on stderr, where questions are drawn, which may be a
/// terminal while stdout is a pipe. Falls back as [`width`] and [`height`] do.
pub(crate) fn stderr_size() -> (usize, usize) {
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    let measured = ioctl_size_on(2).or_else(ioctl_size);
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    let measured = ioctl_size();
    (
        measured_or(measured.map(|(cols, _)| cols), "COLUMNS", 80),
        measured_or(measured.map(|(_, rows)| rows), "LINES", 24),
    )
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn ioctl_size() -> Option<(usize, usize)> {
    ioctl_size_on(crate::output::fd())
}

/// The size of the terminal open as `fd`.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn ioctl_size_on(fd: i32) -> Option<(usize, usize)> {
    #[repr(C)]
    #[allow(dead_code)]
    struct WinSize {
        rows: u16,
        cols: u16,
        xpixel: u16,
        ypixel: u16,
    }

    #[cfg(target_os = "macos")]
    const TIOCGWINSZ: std::ffi::c_ulong = 0x4008_7468;
    #[cfg(target_os = "linux")]
    const TIOCGWINSZ: std::ffi::c_ulong = 0x5413;

    let mut ws = WinSize {
        rows: 0,
        cols: 0,
        xpixel: 0,
        ypixel: 0,
    };
    // SAFETY: TIOCGWINSZ writes exactly one winsize struct through the pointer.
    let ok = unsafe { ioctl(fd, TIOCGWINSZ, &mut ws as *mut WinSize) } == 0;
    (ok && ws.cols > 0).then_some((ws.cols as usize, ws.rows as usize))
}

#[cfg(windows)]
fn ioctl_size() -> Option<(usize, usize)> {
    win::size()
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
fn ioctl_size() -> Option<(usize, usize)> {
    None
}

/// How far local time is ahead of UTC at `secs` since the epoch, in seconds, from the C
/// library's idea of the time zone. 0 where that can't be found.
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) fn utc_offset_secs(secs: i64) -> i64 {
    #[repr(C)]
    struct Tm {
        fields: [i32; 9],
        gmtoff: std::ffi::c_long,
        zone: *const std::ffi::c_char,
    }
    unsafe extern "C" {
        fn localtime_r(time: *const i64, out: *mut Tm) -> *mut Tm;
    }
    let mut tm = Tm {
        fields: [0; 9],
        gmtoff: 0,
        zone: std::ptr::null(),
    };
    // SAFETY: localtime_r fills one struct tm, whose leading fields have this layout on both
    // platforms; it returns null on failure, leaving gmtoff at 0.
    unsafe { localtime_r(&secs, &mut tm) };
    // c_long is 32 bits on some targets
    #[allow(clippy::unnecessary_cast)]
    let offset = tm.gmtoff as i64;
    offset
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub(crate) fn utc_offset_secs(_: i64) -> i64 {
    0
}

/// Turn on escape-code handling for output in older Windows consoles. Elsewhere, and in
/// Windows Terminal, it's always on.
pub(crate) fn enable_escapes() {
    #[cfg(windows)]
    win::enable_escapes();
}

/// The Windows console API, for what Unix does with `stty` and `ioctl`.
#[cfg(windows)]
mod win {
    use std::ffi::c_void;
    use std::io;

    type Handle = *mut c_void;

    const STD_INPUT_HANDLE: u32 = -10i32 as u32;
    const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
    const STD_ERROR_HANDLE: u32 = -12i32 as u32;
    const ENABLE_PROCESSED_INPUT: u32 = 0x0001;
    const ENABLE_LINE_INPUT: u32 = 0x0002;
    const ENABLE_ECHO_INPUT: u32 = 0x0004;
    const ENABLE_VIRTUAL_TERMINAL_INPUT: u32 = 0x0200;
    const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
    const WAIT_OBJECT_0: u32 = 0;
    const KEY_EVENT: u16 = 1;
    const CTRL_BREAK_EVENT: u32 = 1;
    const UTF8: u32 = 65001;

    #[repr(C)]
    #[derive(Default)]
    struct Coord {
        x: i16,
        y: i16,
    }

    #[repr(C)]
    #[derive(Default)]
    struct ScreenBufferInfo {
        size: Coord,
        cursor: Coord,
        attributes: u16,
        left: i16,
        top: i16,
        right: i16,
        bottom: i16,
        max_size: Coord,
    }

    /// INPUT_RECORD, with its union read as a KEY_EVENT_RECORD (the largest member, 16 bytes).
    #[repr(C)]
    #[derive(Default, Clone, Copy)]
    struct InputRecord {
        kind: u16,
        _pad: u16,
        key_down: i32,
        repeat: u16,
        virtual_key: u16,
        scan_code: u16,
        ch: u16,
        control_state: u32,
    }

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetStdHandle(which: u32) -> Handle;
        fn GetConsoleMode(h: Handle, mode: *mut u32) -> i32;
        fn SetConsoleMode(h: Handle, mode: u32) -> i32;
        fn GetConsoleCP() -> u32;
        fn SetConsoleCP(cp: u32) -> i32;
        fn WaitForSingleObject(h: Handle, ms: u32) -> u32;
        fn PeekConsoleInputW(h: Handle, buf: *mut InputRecord, len: u32, read: *mut u32) -> i32;
        fn ReadConsoleInputW(h: Handle, buf: *mut InputRecord, len: u32, read: *mut u32) -> i32;
        fn GetConsoleScreenBufferInfo(h: Handle, info: *mut ScreenBufferInfo) -> i32;
        fn WriteConsoleInputW(h: Handle, buf: *const InputRecord, len: u32, written: *mut u32) -> i32;
        fn WriteFile(h: Handle, buf: *const u8, len: u32, written: *mut u32, overlapped: *mut c_void) -> i32;
        fn SetConsoleCtrlHandler(handler: Option<unsafe extern "system" fn(u32) -> i32>, add: i32) -> i32;
    }

    pub(super) struct Saved {
        input: u32,
        error: u32,
        code_page: u32,
    }

    fn mode(h: Handle) -> io::Result<u32> {
        let mut m = 0;
        // SAFETY: GetConsoleMode writes one u32 through the pointer.
        if unsafe { GetConsoleMode(h, &mut m) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(m)
    }

    /// Keys a character at a time, unechoed, as escape sequences. `raw` also turns Ctrl-C
    /// into a key rather than an interruption.
    pub(super) fn enter(raw: bool) -> io::Result<Saved> {
        let mut off = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;
        if raw {
            off |= ENABLE_PROCESSED_INPUT;
        }
        // SAFETY: these calls only read and set console flags on standard handles.
        unsafe {
            let (input, error) = (GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
            let saved = Saved {
                input: mode(input)?,
                error: mode(error).unwrap_or(0),
                code_page: GetConsoleCP(),
            };
            let raw = (saved.input & !off) | ENABLE_VIRTUAL_TERMINAL_INPUT;
            if SetConsoleMode(input, raw) == 0 {
                return Err(io::Error::last_os_error());
            }
            SetConsoleMode(error, saved.error | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
            SetConsoleCP(UTF8);
            Ok(saved)
        }
    }

    pub(super) fn leave_raw(saved: &Saved) {
        // SAFETY: as above, restoring values read earlier.
        unsafe {
            SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), saved.input);
            SetConsoleMode(GetStdHandle(STD_ERROR_HANDLE), saved.error);
            SetConsoleCP(saved.code_page);
        }
    }

    /// Wait up to `ms` for a keypress that will produce a character, throwing away events that
    /// won't (key releases, focus and mouse events), which would otherwise leave a read blocked.
    pub(super) fn key_waiting(ms: u32) -> bool {
        // SAFETY: the record buffer is one element long, matching the length passed.
        unsafe {
            let input = GetStdHandle(STD_INPUT_HANDLE);
            if WaitForSingleObject(input, ms) != WAIT_OBJECT_0 {
                return false;
            }
            loop {
                let mut rec = InputRecord::default();
                let mut n = 0;
                if PeekConsoleInputW(input, &mut rec, 1, &mut n) == 0 || n == 0 {
                    return false;
                }
                if rec.kind == KEY_EVENT && rec.key_down != 0 && rec.ch != 0 {
                    return true;
                }
                ReadConsoleInputW(input, &mut rec, 1, &mut n);
            }
        }
    }

    pub(super) fn size() -> Option<(usize, usize)> {
        let mut info = ScreenBufferInfo::default();
        let which = if crate::output::fd() == 2 {
            STD_ERROR_HANDLE
        } else {
            STD_OUTPUT_HANDLE
        };
        // SAFETY: GetConsoleScreenBufferInfo fills one struct through the pointer.
        let ok = unsafe { GetConsoleScreenBufferInfo(GetStdHandle(which), &mut info) } != 0;
        let w = (info.right - info.left + 1) as usize;
        let h = (info.bottom - info.top + 1) as usize;
        (ok && w > 0).then_some((w, h))
    }

    /// The console's input mode, to put back after a Ctrl-C.
    pub(super) fn input_mode() -> Option<u32> {
        // SAFETY: as above.
        mode(unsafe { GetStdHandle(STD_INPUT_HANDLE) }).ok()
    }

    pub(super) fn set_input_mode(m: u32) {
        // SAFETY: as above, with a mode read earlier.
        unsafe { SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), m) };
    }

    /// Write straight to stdout (`fd` 1) or stderr (2), past std's lock on them, which a
    /// thread drawing a frame may be holding when Ctrl-C comes.
    pub(super) fn write_raw(fd: i32, bytes: &[u8]) {
        let which = if fd == 2 { STD_ERROR_HANDLE } else { STD_OUTPUT_HANDLE };
        let mut n = 0;
        // SAFETY: WriteFile reads `bytes.len()` bytes from the pointer and writes one u32.
        unsafe {
            WriteFile(
                GetStdHandle(which),
                bytes.as_ptr(),
                bytes.len() as u32,
                &mut n,
                std::ptr::null_mut(),
            )
        };
    }

    /// Called on a thread of its own when Ctrl-C or Ctrl-Break is pressed. Anything else
    /// (the window closing, logging off) is left to the next handler.
    pub(super) unsafe extern "system" fn on_ctrl(kind: u32) -> i32 {
        if kind > CTRL_BREAK_EVENT {
            return 0;
        }
        super::interrupted()
    }

    /// Start or stop handling Ctrl-C. Handlers stack, so each start is undone by one stop.
    pub(super) fn handle_ctrl_c(on: bool) -> bool {
        // SAFETY: on_ctrl has the signature the console calls handlers with.
        unsafe { SetConsoleCtrlHandler(Some(on_ctrl), i32::from(on)) != 0 }
    }

    /// Type `text` into the console's input, as key presses. Escape sequences are left out:
    /// the shell reads keys, not sequences, and would take their Esc as a press of Esc.
    pub(super) fn push_back(text: &str) {
        let text = crate::text::strip_ansi(text);
        let records: Vec<InputRecord> = text
            .chars()
            .filter(|&c| c == '\r' || !c.is_control())
            .collect::<String>()
            .encode_utf16()
            .map(|ch| InputRecord {
                kind: KEY_EVENT,
                key_down: 1,
                repeat: 1,
                ch,
                ..InputRecord::default()
            })
            .collect();
        if records.is_empty() {
            return;
        }
        let mut n = 0;
        // SAFETY: WriteConsoleInputW reads `records.len()` records and writes one u32.
        unsafe {
            WriteConsoleInputW(
                GetStdHandle(STD_INPUT_HANDLE),
                records.as_ptr(),
                records.len() as u32,
                &mut n,
            )
        };
    }

    pub(super) fn enable_escapes() {
        for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
            // SAFETY: as above.
            unsafe {
                let h = GetStdHandle(which);
                if let Ok(m) = mode(h) {
                    SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
                }
            }
        }
    }
}

/// Put bytes back into the terminal's input queue, so keys typed while tinsel was reading
/// stdin reach the shell afterwards. Best effort: Linux 6.2 and later refuse TIOCSTI unless
/// `dev.tty.legacy_tiocsti` is set, and then the keys are lost; nothing else can put them back.
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) fn push_back_input(bytes: &[u8]) {
    push_back_to(0, bytes);
}

/// [`push_back_input`], to the terminal open as `fd`.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn push_back_to(fd: i32, bytes: &[u8]) {
    #[cfg(target_os = "macos")]
    const TIOCSTI: std::ffi::c_ulong = 0x8001_7472;
    #[cfg(target_os = "linux")]
    const TIOCSTI: std::ffi::c_ulong = 0x5412;
    for b in bytes {
        // SAFETY: TIOCSTI reads one byte through the pointer.
        if unsafe { ioctl(fd, TIOCSTI, b as *const u8) } != 0 {
            return;
        }
    }
}

#[cfg(windows)]
pub(crate) fn push_back_input(bytes: &[u8]) {
    win::push_back(&String::from_utf8_lossy(bytes));
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
pub(crate) fn push_back_input(_: &[u8]) {}

// MARK: - Ctrl-C

/// What Ctrl-C does while tinsel draws something live: a spinner, progress bar, steps, a
/// [`Region`](crate::Region) or the help pager. Set with [`set_ctrl_c`].
///
/// On Unix, a Ctrl-C handler the program set before the drawing started (with the `ctrlc`
/// crate or `tokio::signal`, say) is left in place, whatever this says, as is a Ctrl-C the
/// program ignores; tinsel only steps in where Ctrl-C would otherwise end the program.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CtrlC {
    /// Put the terminal back and end the program as Ctrl-C would have: on Unix by the signal
    /// itself, so a shell sees it was interrupted (status 130) and stops a loop running it,
    /// and on Windows with exit code 130. The default.
    Exit,
    /// The same, printing this line on the way out, so the program can say what was stopped.
    ExitWith(String),
    /// Leave Ctrl-C to the program's own handler, so it can stop its work its own way. The
    /// terminal is put back when the drawing ends, as usual.
    Leave,
}

static LEAVE_CTRL_C: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The line to print on the way out, leaked so the signal handler only ever reads it.
static CTRL_C_LINE: std::sync::atomic::AtomicPtr<Vec<u8>> = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());

/// Choose what Ctrl-C does while tinsel draws something live. Call it early in `main`.
///
/// ```
/// tinsel::set_ctrl_c(tinsel::CtrlC::ExitWith("stopped: nothing was changed".into()));
/// ```
pub fn set_ctrl_c(how: CtrlC) {
    use std::sync::atomic::Ordering::SeqCst;
    LEAVE_CTRL_C.store(how == CtrlC::Leave, SeqCst);
    let line = match how {
        CtrlC::ExitWith(line) => Box::into_raw(Box::new(format!("{line}\n").into_bytes())),
        CtrlC::Exit | CtrlC::Leave => std::ptr::null_mut(),
    };
    // the old line is left alone: the handler may be reading it right now
    CTRL_C_LINE.store(line, SeqCst);
}

/// While tinsel has the cursor hidden or the terminal in a special mode, Ctrl-C would leave
/// the user's shell that way. Overlapping displays share one handler: the first sets it and
/// the last to finish puts back what was there before. A handler the program set itself, or
/// a Ctrl-C it ignores, is left alone. Returns something when this display holds the guard,
/// for [`restore_interrupt`] to let go of.
#[cfg(unix)]
pub(crate) fn guard_interrupt() -> Option<usize> {
    if LEAVE_CTRL_C.load(std::sync::atomic::Ordering::SeqCst) {
        return None;
    }
    INTERRUPT.hold(|prev| {
        // SAFETY: on_interrupt only calls async-signal-safe functions
        *prev = unsafe { take_signal(SIGINT, on_interrupt, |prev| prev != SIG_DFL) };
    });
    Some(0)
}

#[cfg(unix)]
pub(crate) fn restore_interrupt(held: Option<usize>) {
    if held.is_none() {
        return;
    }
    INTERRUPT.let_go(|prev| {
        if let Some(prev) = prev.take() {
            // SAFETY: prev is what sigaction (or signal) gave back, so it is a valid handler
            unsafe { put_back_signal(SIGINT, &prev) };
        }
    });
}

/// What SIGINT did before tinsel's handler, while any display holds it.
#[cfg(unix)]
static INTERRUPT: Holders<Option<Disposition>> = Holders::new(None);

/// Snapshot the terminal's settings so the Ctrl-C handler can restore them. The snapshot is
/// kept as opaque bytes: tcsetattr is safe to call from a signal handler, `stty` isn't, and
/// handing back exactly what tcgetattr gave means never needing to know the struct's layout.
/// Overlapping displays share it: the first takes it, so a later one doesn't mistake an
/// earlier one's raw mode for how the terminal was, and it's kept until the last lets go.
pub(crate) fn remember_terminal() {
    restore_at_exit();
    TERMINAL.hold(|()| save_terminal());
}

pub(crate) fn forget_terminal() {
    TERMINAL.let_go(|()| HAVE_SAVED.store(false, std::sync::atomic::Ordering::SeqCst));
}

/// Who holds the saved terminal settings.
static TERMINAL: Holders<()> = Holders::new(());

#[cfg(unix)]
fn save_terminal() {
    // SAFETY: the buffer is larger than any platform's termios struct, and HAVE_SAVED is
    // false while no one holds it, so no handler is reading it
    let ok = unsafe { tcgetattr(0, (&raw mut SAVED_TERMIOS).cast()) } == 0;
    HAVE_SAVED.store(ok, std::sync::atomic::Ordering::SeqCst);
}

/// Put back the settings [`remember_terminal`] saved, if any, and stop focus reports.
#[cfg(unix)]
pub(crate) fn restore_saved_terminal() {
    if HAVE_SAVED.swap(false, std::sync::atomic::Ordering::SeqCst) {
        // SAFETY: SAVED_TERMIOS holds exactly what tcgetattr wrote.
        unsafe { tcsetattr(0, TCSANOW, (&raw const SAVED_TERMIOS).cast()) };
    }
    crate::output::write(std::str::from_utf8(RESTORE).unwrap_or_default());
}

#[cfg(unix)]
const SIGINT: i32 = 2;
#[cfg(unix)]
const SIGHUP: i32 = 1;
#[cfg(unix)]
const SIGTERM: i32 = 15;
#[cfg(unix)]
const SIG_DFL: usize = 0;
#[cfg(unix)]
const SIG_IGN: usize = 1;
/// 28 on Linux, macOS and the BSDs, but for Linux on MIPS.
#[cfg(all(unix, not(any(target_arch = "mips", target_arch = "mips64"))))]
const SIGWINCH: i32 = 28;
#[cfg(all(unix, any(target_arch = "mips", target_arch = "mips64")))]
const SIGWINCH: i32 = 20;
#[cfg(unix)]
const TCSANOW: i32 = 0;
/// 1 on Linux, but for MIPS and SPARC; 2 on macOS and the BSDs.
#[cfg(all(
    target_os = "linux",
    not(any(
        target_arch = "mips",
        target_arch = "mips64",
        target_arch = "sparc",
        target_arch = "sparc64"
    ))
))]
const SIG_UNBLOCK: i32 = 1;
#[cfg(all(
    unix,
    not(all(
        target_os = "linux",
        not(any(
            target_arch = "mips",
            target_arch = "mips64",
            target_arch = "sparc",
            target_arch = "sparc64"
        ))
    ))
))]
const SIG_UNBLOCK: i32 = 2;

/// A sigset_t, as big as any platform's (Linux's 1024 bits; macOS uses the first 32), a
/// signal's bit at `sig - 1` counting from the low bit of the first word.
#[cfg(unix)]
type SigSet = [usize; 1024 / usize::BITS as usize];

#[cfg(unix)]
static mut SAVED_TERMIOS: [u8; 256] = [0; 256];
static HAVE_SAVED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The console's input mode, saved for Ctrl-C to put back.
#[cfg(windows)]
static SAVED_MODE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
/// What Ctrl-C writes on its way out: focus reports off, the cursor back, line wrapping on,
/// and bracketed paste off, which a prompt may have turned on (harmless if it hadn't).
const RESTORE: &[u8] = b"\x1b[?1004l\x1b[?25h\x1b[?7h\x1b[?2004l";

#[cfg(unix)]
unsafe extern "C" {
    fn signal(sig: i32, handler: usize) -> usize;
    fn write(fd: i32, buf: *const std::ffi::c_void, count: usize) -> isize;
    fn _exit(code: i32) -> !;
    fn raise(sig: i32) -> i32;
    fn pthread_sigmask(how: i32, set: *const SigSet, old: *mut SigSet) -> i32;
    fn tcgetattr(fd: i32, termios: *mut u8) -> i32;
    fn tcsetattr(fd: i32, action: i32, termios: *const u8) -> i32;
    fn atexit(f: extern "C" fn()) -> i32;
}

// MARK: - Signal handlers, kept whole

/// struct sigaction as the C library takes it, where its layout is known: handler, mask and
/// flags, so a handler can be put back exactly as it was. Elsewhere only `signal` is used,
/// which keeps the handler but not its flags.
#[cfg(target_vendor = "apple")]
#[repr(C)]
#[derive(Clone, Copy)]
struct SigAction {
    handler: usize,
    mask: u32,
    flags: i32,
}

/// Linux's generic layout, which glibc and musl share on these architectures (MIPS, SPARC and
/// s390x order theirs differently).
#[cfg(all(
    target_os = "linux",
    any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "arm",
        target_arch = "aarch64",
        target_arch = "riscv64",
        target_arch = "powerpc",
        target_arch = "powerpc64",
        target_arch = "loongarch64"
    )
))]
#[repr(C)]
#[derive(Clone, Copy)]
struct SigAction {
    handler: usize,
    mask: SigSet,
    flags: i32,
    restorer: usize,
}

#[cfg(target_vendor = "apple")]
const SA_RESTART: i32 = 0x0002;
#[cfg(target_os = "linux")]
const SA_RESTART: i32 = 0x1000_0000;

#[cfg(any(
    target_vendor = "apple",
    all(
        target_os = "linux",
        any(
            target_arch = "x86",
            target_arch = "x86_64",
            target_arch = "arm",
            target_arch = "aarch64",
            target_arch = "riscv64",
            target_arch = "powerpc",
            target_arch = "powerpc64",
            target_arch = "loongarch64"
        )
    )
))]
mod disposition {
    use super::{SA_RESTART, SigAction};

    unsafe extern "C" {
        fn sigaction(sig: i32, act: *const SigAction, old: *mut SigAction) -> i32;
    }

    /// What a signal does: its handler, mask and flags.
    pub(super) type Disposition = SigAction;

    impl SigAction {
        pub(super) fn handler(&self) -> usize {
            self.handler
        }
    }

    /// See [`super::take_signal`].
    pub(super) unsafe fn take(sig: i32, handler: usize, keep: impl Fn(usize) -> bool) -> Option<SigAction> {
        // SAFETY: zeroed is a valid sigaction (SIG_DFL, nothing masked, no flags)
        let mut prev: SigAction = unsafe { std::mem::zeroed() };
        // looked at before anything's set, so the program's own handler is never displaced,
        // even for a moment
        // SAFETY: sigaction writes one struct sigaction through the pointer
        if unsafe { sigaction(sig, std::ptr::null(), &mut prev) } != 0 || keep(prev.handler) {
            return None;
        }
        let ours = SigAction {
            handler,
            flags: SA_RESTART,
            // SAFETY: as above
            ..unsafe { std::mem::zeroed() }
        };
        // SAFETY: the caller vouches for the handler
        (unsafe { sigaction(sig, &ours, std::ptr::null_mut()) } == 0).then_some(prev)
    }

    pub(super) unsafe fn put_back(sig: i32, prev: &SigAction) {
        // SAFETY: prev came from sigaction itself, so it is a valid disposition
        unsafe { sigaction(sig, prev, std::ptr::null_mut()) };
    }

    /// What `sig` does now, for tests to look at.
    #[cfg(test)]
    pub(super) fn now(sig: i32) -> SigAction {
        // SAFETY: zeroed is a valid sigaction, and sigaction writes one through the pointer
        unsafe {
            let mut now: SigAction = std::mem::zeroed();
            sigaction(sig, std::ptr::null(), &mut now);
            now
        }
    }

    /// Set `sig`'s handler and flags, for tests.
    #[cfg(test)]
    pub(super) unsafe fn set(sig: i32, handler: usize, flags: i32) {
        // SAFETY: zeroed is a valid sigaction; the caller vouches for the handler
        unsafe {
            let act = SigAction {
                handler,
                flags,
                ..std::mem::zeroed()
            };
            sigaction(sig, &act, std::ptr::null_mut());
        }
    }
}

#[cfg(all(
    unix,
    not(any(
        target_vendor = "apple",
        all(
            target_os = "linux",
            any(
                target_arch = "x86",
                target_arch = "x86_64",
                target_arch = "arm",
                target_arch = "aarch64",
                target_arch = "riscv64",
                target_arch = "powerpc",
                target_arch = "powerpc64",
                target_arch = "loongarch64"
            )
        )
    ))
))]
mod disposition {
    use super::signal;

    const SIG_ERR: usize = usize::MAX;

    /// What a signal does: only its handler, here.
    #[derive(Clone, Copy)]
    pub(super) struct Disposition(usize);

    impl Disposition {
        pub(super) fn handler(&self) -> usize {
            self.0
        }
    }

    pub(super) unsafe fn take(sig: i32, handler: usize, keep: impl Fn(usize) -> bool) -> Option<Disposition> {
        // SAFETY: the caller vouches for the handler
        let prev = unsafe { signal(sig, handler) };
        if prev == SIG_ERR {
            return None;
        }
        if keep(prev) {
            // SAFETY: prev came from signal() itself, so it is a valid handler value
            unsafe { signal(sig, prev) };
            return None;
        }
        Some(Disposition(prev))
    }

    pub(super) unsafe fn put_back(sig: i32, prev: &Disposition) {
        // SAFETY: prev came from signal() itself, so it is a valid handler value
        unsafe { signal(sig, prev.0) };
    }
}

#[cfg(unix)]
use disposition::Disposition;

/// Set `handler` for `sig`, unless `keep` says the handler already there (or SIG_DFL or
/// SIG_IGN) should stay, and then it does, flags and all. Returns what was there, if replaced,
/// for [`put_back_signal`].
///
/// # Safety
/// `handler` may only call async-signal-safe functions.
#[cfg(unix)]
unsafe fn take_signal(sig: i32, handler: extern "C" fn(i32), keep: impl Fn(usize) -> bool) -> Option<Disposition> {
    // SAFETY: passed on from the caller
    unsafe { disposition::take(sig, handler as usize, keep) }
}

/// # Safety
/// `prev` must have come from [`take_signal`] for the same signal.
#[cfg(unix)]
unsafe fn put_back_signal(sig: i32, prev: &Disposition) {
    // SAFETY: passed on from the caller
    unsafe { disposition::put_back(sig, prev) }
}

/// Put the terminal back if the program ends with [`std::process::exit`] while something is
/// drawn: that skips every destructor, so a display would leave focus reports on, echo off
/// and the cursor hidden. Registered with `atexit` the first time it's needed; it does
/// nothing at an exit with nothing drawn.
#[cfg(unix)]
pub(crate) fn restore_at_exit() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    // SAFETY: on_exit takes no arguments and returns nothing, as atexit expects.
    ONCE.call_once(|| unsafe {
        atexit(on_exit);
    });
}

#[cfg(not(unix))]
pub(crate) fn restore_at_exit() {}

#[cfg(unix)]
extern "C" fn on_exit() {
    let saved = HAVE_SAVED.swap(false, std::sync::atomic::Ordering::SeqCst);
    if !saved && !crate::display::any_active() {
        return;
    }
    // SAFETY: SAVED_TERMIOS holds exactly what tcgetattr wrote, as for on_interrupt.
    unsafe {
        if saved {
            tcsetattr(0, TCSANOW, (&raw const SAVED_TERMIOS).cast());
        }
        write(crate::output::fd_now(), RESTORE.as_ptr().cast(), RESTORE.len());
    }
}

/// What a full-screen app writes on its way out, for [`on_terminate`] to write too.
#[cfg(unix)]
static LEAVING: std::sync::atomic::AtomicPtr<u8> = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
#[cfg(unix)]
static LEAVING_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Hangups (the window closed) and kills (SIGTERM) end the program at once, which would leave
/// the terminal in raw mode on the alternate screen. While guarded, they put the terminal
/// back and write `leave` first, then end the program as they would have. Only signals with
/// no handler of their own are guarded. Overlapping holders (a question asked inside an app,
/// say) share the guard: the first sets it, and its `leave` is the one written, and the last
/// to finish puts the handlers back. Returns a token for [`unguard_termination`].
#[cfg(unix)]
pub(crate) fn guard_termination(leave: &'static str) -> [Option<usize>; 2] {
    use std::sync::atomic::Ordering::SeqCst;
    TERMINATION.hold(|prev| {
        LEAVING_LEN.store(leave.len(), SeqCst);
        LEAVING.store(leave.as_ptr().cast_mut(), SeqCst);
        *prev = [SIGHUP, SIGTERM].map(|sig| {
            // ignored, or the program's own: either way, it stays
            // SAFETY: on_terminate only calls async-signal-safe functions
            unsafe { take_signal(sig, on_terminate, |prev| prev != SIG_DFL) }
        });
    });
    [Some(SIG_DFL), None]
}

#[cfg(unix)]
pub(crate) fn unguard_termination(held: [Option<usize>; 2]) {
    if held == [None, None] {
        return;
    }
    TERMINATION.let_go(|prev| {
        for (sig, prev) in [SIGHUP, SIGTERM].into_iter().zip(std::mem::take(prev)) {
            if let Some(prev) = prev {
                // SAFETY: prev is what take_signal gave back for this signal
                unsafe { put_back_signal(sig, &prev) };
            }
        }
        LEAVING.store(std::ptr::null_mut(), std::sync::atomic::Ordering::SeqCst);
    });
}

/// What SIGHUP and SIGTERM did before tinsel's handler, while anyone holds the guard.
#[cfg(unix)]
static TERMINATION: Holders<[Option<Disposition>; 2]> = Holders::new([None, None]);

#[cfg(unix)]
extern "C" fn on_terminate(sig: i32) {
    use std::sync::atomic::Ordering::SeqCst;
    // SAFETY: tcsetattr, write, signal and raise are all async-signal-safe; SAVED_TERMIOS is
    // only written before HAVE_SAVED is set, and LEAVING points at a &'static str
    unsafe {
        if HAVE_SAVED.load(SeqCst) {
            tcsetattr(0, TCSANOW, (&raw const SAVED_TERMIOS).cast());
        }
        let leave = LEAVING.load(SeqCst);
        if !leave.is_null() {
            write(1, leave.cast(), LEAVING_LEN.load(SeqCst));
        }
        // the signal waits until this handler returns, then ends the program as it would have
        signal(sig, SIG_DFL);
        raise(sig);
    }
}

#[cfg(not(unix))]
pub(crate) fn guard_termination(_: &'static str) -> [Option<usize>; 2] {
    [None, None]
}

#[cfg(not(unix))]
pub(crate) fn unguard_termination(_: [Option<usize>; 2]) {}

#[cfg(unix)]
extern "C" fn on_interrupt(_: i32) {
    // SAFETY: write, tcsetattr, signal, pthread_sigmask, raise and _exit are all
    // async-signal-safe, and SAVED_TERMIOS is only written before HAVE_SAVED is set.
    unsafe {
        if HAVE_SAVED.load(std::sync::atomic::Ordering::SeqCst) {
            tcsetattr(0, TCSANOW, (&raw const SAVED_TERMIOS).cast());
        }
        let fd = crate::output::fd_now();
        write(fd, RESTORE.as_ptr().cast(), RESTORE.len());
        write(fd, b"\n".as_ptr().cast(), 1);
        let line = CTRL_C_LINE.load(std::sync::atomic::Ordering::SeqCst);
        if !line.is_null() {
            write(fd, (*line).as_ptr().cast(), (*line).len());
        }
        // end by the signal itself, as Ctrl-C would have, so a shell running this in a loop
        // sees it was interrupted and stops. It's held back while this handler runs, so it's
        // let through at once; exiting with 130 is only for if that somehow didn't end it
        signal(SIGINT, SIG_DFL);
        raise(SIGINT);
        let mut only_sigint: SigSet = [0; 1024 / usize::BITS as usize];
        only_sigint[0] = 1 << (SIGINT - 1);
        pthread_sigmask(SIG_UNBLOCK, &only_sigint, std::ptr::null_mut());
        _exit(130)
    }
}

/// On Windows Ctrl-C is a call to a handler on a thread of its own, not a signal, so the
/// handler can do as it likes. Overlapping displays share it, as on Unix. Returns something
/// only so [`restore_interrupt`] knows to let go of it.
#[cfg(windows)]
pub(crate) fn guard_interrupt() -> Option<usize> {
    if LEAVE_CTRL_C.load(std::sync::atomic::Ordering::SeqCst) {
        return None;
    }
    INTERRUPT.hold(|set| *set = win::handle_ctrl_c(true));
    Some(0)
}

#[cfg(windows)]
pub(crate) fn restore_interrupt(held: Option<usize>) {
    if held.is_some() {
        INTERRUPT.let_go(|set| {
            if std::mem::take(set) {
                win::handle_ctrl_c(false);
            }
        });
    }
}

/// Whether tinsel's console handler is set, while any display holds it.
#[cfg(windows)]
static INTERRUPT: Holders<bool> = Holders::new(false);

#[cfg(windows)]
fn save_terminal() {
    if let Some(mode) = win::input_mode() {
        SAVED_MODE.store(mode, std::sync::atomic::Ordering::SeqCst);
        HAVE_SAVED.store(true, std::sync::atomic::Ordering::SeqCst);
    }
}

#[cfg(windows)]
pub(crate) fn restore_saved_terminal() {
    if HAVE_SAVED.swap(false, std::sync::atomic::Ordering::SeqCst) {
        win::set_input_mode(SAVED_MODE.load(std::sync::atomic::Ordering::SeqCst));
    }
    crate::output::write(std::str::from_utf8(RESTORE).unwrap_or_default());
}

/// Ctrl-C on Windows: the console put back as it was, the cursor shown, the program's line
/// said, and out with 130, as on Unix.
#[cfg(windows)]
fn interrupted() -> ! {
    use std::sync::atomic::Ordering::SeqCst;
    if HAVE_SAVED.swap(false, SeqCst) {
        win::set_input_mode(SAVED_MODE.load(SeqCst));
    }
    let fd = crate::output::fd_now();
    win::write_raw(fd, RESTORE);
    win::write_raw(fd, b"\n");
    let line = CTRL_C_LINE.load(SeqCst);
    if !line.is_null() {
        // SAFETY: lines are leaked when set and never freed, so this one is still there
        win::write_raw(fd, unsafe { &*line });
    }
    std::process::exit(130)
}

/// Ctrl-C, pressed by a test: a signal on Unix, and on Windows a call to the handler as the
/// console would make it (asking the console means interrupting the test runner too).
#[cfg(test)]
pub(crate) fn press_ctrl_c() {
    #[cfg(unix)]
    // SAFETY: raise only delivers a signal, to whichever handler is set
    unsafe {
        raise(SIGINT)
    };
    #[cfg(windows)]
    // SAFETY: as the console calls it, with Ctrl-C
    unsafe {
        win::on_ctrl(0);
    }
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn guard_interrupt() -> Option<usize> {
    None
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn restore_interrupt(_: Option<usize>) {}

#[cfg(not(any(unix, windows)))]
fn save_terminal() {}

#[cfg(not(any(unix, windows)))]
pub(crate) fn restore_saved_terminal() {
    crate::output::write(std::str::from_utf8(RESTORE).unwrap_or_default());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_osc_colour_replies() {
        assert_eq!(parse_osc_color("\x1b]11;rgb:ffff/ffff/ffff\x07"), Some((255, 255, 255)));
        assert_eq!(parse_osc_color("\x1b]11;rgb:1e1e/2020/2a2a\x1b\\"), Some((30, 32, 42)));
        assert_eq!(parse_osc_color("\x1b]11;rgb:ff/80/00\x07"), Some((255, 128, 0)));
        assert_eq!(parse_osc_color("garbage"), None);
        assert_eq!(parse_osc_color("\x1b]11;rgb:f/8/0\x07"), Some((255, 136, 0)));
        // too many digits, or none, is no colour rather than a panic
        assert_eq!(parse_osc_color("rgb:ffffffff/ffffffff/ffffffff"), None);
        assert_eq!(parse_osc_color("rgb:fffffff/0/0"), None);
        assert_eq!(parse_osc_color("rgb://"), None);
    }

    #[cfg(not(windows))]
    #[test]
    fn raw_mode_lets_every_control_key_through() {
        for flag in ["-isig", "-ixon", "-iexten"] {
            assert!(RAW.contains(&flag), "{flag}");
        }
        // stty accepts them all, where there's a terminal to try them on
        if io::stdin().is_terminal() {
            let saved = stty(&["-g"]).unwrap();
            assert!(stty(RAW).is_ok());
            stty(&[&saved]).unwrap();
        }
    }

    #[test]
    fn a_terminal_that_answers_nothing_at_once_has_gone() {
        let mut keyboard = Keyboard::default();
        let (now, waited) = (Duration::ZERO, Duration::from_millis(100));
        // quiet, then typing, then nothing at once a few times: all still there
        for (n, took) in [(0, waited), (3, now), (0, now), (0, now), (0, waited)] {
            assert!(keyboard.saw(n, took).is_ok());
        }
        let mut gone = Ok(());
        for _ in 0..10 {
            gone = keyboard.saw(0, now);
        }
        if cfg!(unix) {
            assert_eq!(gone.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
        } else {
            assert!(gone.is_ok());
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_resize_is_noted_while_watched() {
        let prev = watch_resize();
        assert!(prev.is_some());
        // SAFETY: raise only delivers a signal, to the handler just set
        unsafe { raise(SIGWINCH) };
        assert!(resized());
        assert!(!resized(), "noted once");
        unwatch_resize(prev);
    }

    #[test]
    fn whatever_is_shared_is_set_up_by_the_first_and_undone_by_the_last() {
        let shared = Holders::new(Vec::new());
        shared.hold(|log| log.push("set up"));
        shared.hold(|log| log.push("set up again"));
        // the first lets go before the second: nothing's undone yet
        shared.let_go(|log| log.push("undone"));
        assert_eq!(*shared.lock(), (1, vec!["set up"]));
        shared.let_go(|log| log.push("undone"));
        assert_eq!(*shared.lock(), (0, vec!["set up", "undone"]));
        // letting go of what isn't held does nothing
        shared.let_go(|log| log.push("undone again"));
        assert_eq!(shared.lock().1.len(), 2);
        // a set-up that fails leaves it unheld, to be tried again by the next
        assert!(shared.try_hold(|_| Err(io::Error::other("no"))).is_err());
        assert_eq!(shared.lock().0, 0);
        shared.hold(|log| log.push("set up"));
        assert_eq!(*shared.lock(), (1, vec!["set up", "undone", "set up"]));
    }

    #[cfg(any(
        target_vendor = "apple",
        all(target_os = "linux", any(target_arch = "x86_64", target_arch = "aarch64"))
    ))]
    const CHILD: &str = "TINSEL_TERM_CHILD";

    /// The child's half of [`ctrl_c_is_shared_kept_off_others_and_ends_by_the_signal`]: run
    /// on its own, so the handlers it sets can't touch other tests.
    #[cfg(any(
        target_vendor = "apple",
        all(target_os = "linux", any(target_arch = "x86_64", target_arch = "aarch64"))
    ))]
    #[test]
    #[ignore = "run by ctrl_c_is_shared_kept_off_others_and_ends_by_the_signal"]
    fn ctrl_c_child() {
        if std::env::var_os(CHILD).is_none() {
            return;
        }
        extern "C" fn own(_: i32) {}
        let own = own as extern "C" fn(i32) as usize;
        let ours = on_interrupt as extern "C" fn(i32) as usize;
        const SA_SIGINFO: i32 = if cfg!(target_vendor = "apple") { 0x40 } else { 4 };

        // the program's own handler stays, flags and all, and comes through untouched
        // SAFETY: `own` does nothing
        unsafe { disposition::set(SIGINT, own, SA_SIGINFO) };
        let held = guard_interrupt();
        assert!(held.is_some());
        let now = disposition::now(SIGINT);
        assert_eq!((now.handler, now.flags & SA_SIGINFO), (own, SA_SIGINFO));
        restore_interrupt(held);
        let now = disposition::now(SIGINT);
        assert_eq!((now.handler, now.flags & SA_SIGINFO), (own, SA_SIGINFO));

        // two displays ending out of order: the handler stays until the last has finished
        // SAFETY: back to the default
        unsafe { disposition::set(SIGINT, SIG_DFL, 0) };
        let (first, second) = (guard_interrupt(), guard_interrupt());
        assert_eq!(disposition::now(SIGINT).handler, ours);
        restore_interrupt(first);
        assert_eq!(disposition::now(SIGINT).handler, ours, "the second still draws");
        restore_interrupt(second);
        assert_eq!(disposition::now(SIGINT).handler, SIG_DFL);

        // the same for the terminal's settings: kept while anyone holds them
        remember_terminal();
        remember_terminal();
        HAVE_SAVED.store(true, std::sync::atomic::Ordering::SeqCst);
        forget_terminal();
        assert!(HAVE_SAVED.load(std::sync::atomic::Ordering::SeqCst));
        forget_terminal();
        assert!(!HAVE_SAVED.load(std::sync::atomic::Ordering::SeqCst));

        // hangups and kills: guarded only where the program has no handler of its own, and
        // the outermost holder's way out is the one written
        // SAFETY: `own` does nothing
        unsafe { disposition::set(SIGHUP, own, SA_SIGINFO) };
        let outer = guard_termination("outer");
        let inner = guard_termination("inner");
        let theirs = on_terminate as extern "C" fn(i32) as usize;
        assert_eq!(disposition::now(SIGHUP).handler, own, "the program's own handler stays");
        assert_eq!(disposition::now(SIGTERM).handler, theirs);
        assert_eq!(LEAVING_LEN.load(std::sync::atomic::Ordering::SeqCst), "outer".len());
        unguard_termination(outer);
        assert_eq!(
            disposition::now(SIGTERM).handler,
            theirs,
            "the inner one still holds it"
        );
        unguard_termination(inner);
        assert_eq!(disposition::now(SIGTERM).handler, SIG_DFL);
        assert_eq!(disposition::now(SIGHUP).flags & SA_SIGINFO, SA_SIGINFO);
        unguard_termination([None, None]);

        println!("[checked]");
        let _ = io::stdout().flush();
        let _held = guard_interrupt();
        press_ctrl_c();
        // the handler ends the process; carrying on fails the test
        std::thread::sleep(Duration::from_secs(20));
    }

    #[cfg(any(
        target_vendor = "apple",
        all(target_os = "linux", any(target_arch = "x86_64", target_arch = "aarch64"))
    ))]
    #[test]
    fn ctrl_c_is_shared_kept_off_others_and_ends_by_the_signal() {
        use std::os::unix::process::ExitStatusExt;
        let out = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["term::tests::ctrl_c_child", "--exact", "--ignored", "--nocapture"])
            .env(CHILD, "1")
            .stdin(std::process::Stdio::null())
            .output()
            .unwrap();
        let seen = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(seen.contains("[checked]"), "{seen}");
        // killed by SIGINT, which is what makes a shell stop a loop, rather than exiting 130
        assert_eq!(out.status.signal(), Some(SIGINT), "{} {seen}", out.status);
        assert!(seen.contains("\x1b[?25h"), "{seen}");
    }

    #[cfg(not(windows))]
    #[test]
    fn stty_says_when_it_couldnt() {
        assert!(stty(&["--no-such-setting"]).is_err());
    }

    #[test]
    fn nothing_is_asked_with_no_one_there() {
        let _ = (interactive(), can_ask());
        assert_eq!(crate::output::with_terminal(false, query_background), None);
    }

    #[test]
    fn the_terminal_is_put_back_as_it_was() {
        // remembered first, so on a real terminal it's put back exactly as it is
        remember_terminal();
        HAVE_SAVED.store(true, std::sync::atomic::Ordering::SeqCst);
        let out = crate::output::capture(restore_saved_terminal);
        assert!(out.contains("\x1b[?25h"));
        assert!(!HAVE_SAVED.load(std::sync::atomic::Ordering::SeqCst));
        // nothing saved now, so only the cursor and the rest come back
        assert!(crate::output::capture(restore_saved_terminal).contains("\x1b[?25h"));
        forget_terminal();
    }

    #[cfg(any(target_os = "macos", target_os = "linux"))]
    #[test]
    fn typed_keys_go_back_only_to_a_terminal() {
        use std::os::fd::AsRawFd;
        // a file isn't a terminal, so there's nowhere to put them
        let file = std::fs::File::open(std::env::current_exe().unwrap()).unwrap();
        push_back_to(file.as_raw_fd(), b"x");
    }

    #[test]
    fn sizes_fall_back_to_the_environment_then_a_default() {
        assert_eq!(measured_or(Some(120), "TINSEL_NO_SUCH_VARIABLE", 80), 120);
        assert_eq!(measured_or(None, "TINSEL_NO_SUCH_VARIABLE", 24), 24);
        assert_eq!(measured_or(Some(0), "TINSEL_NO_SUCH_VARIABLE", 80), 80);
    }
}