rgpui 1.2.1

GUI UI framework
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
#[cfg(not(target_family = "wasm"))]
pub mod archive;
pub mod collections;
#[cfg(not(target_family = "wasm"))]
pub mod command;
pub mod debounce;
pub mod disambiguate;
#[cfg(not(target_family = "wasm"))]
pub mod fs;
pub mod markdown;
pub mod path_list;
pub mod paths;
#[cfg(not(target_family = "wasm"))]
pub mod process;
pub mod redact;
pub mod rel_path;
pub mod result_ext;
pub mod scheduler;
pub mod schemars;
pub mod serde;
pub mod shell;
#[cfg(not(target_family = "wasm"))]
pub mod shell_builder;
#[cfg(not(target_family = "wasm"))]
pub mod shell_env;
pub mod size;
pub mod sum_tree;
#[cfg(any(test, feature = "test-support"))]
pub mod test;
pub mod time;

pub use result_ext::ResultExt;

use anyhow::Result;
use itertools::Either;
use regex::Regex;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::{
    borrow::Cow,
    cmp::{self, Ordering},
    ops::{Range, RangeInclusive},
};
use unicase::UniCase;

#[cfg(any(test, feature = "test-support"))]
pub use rgpui_macros::{line_endings, path, uri};
pub use take_until::*;

pub use self::shell::{
    get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
};

#[inline]
pub const fn is_utf8_char_boundary(u8: u8) -> bool {
    // This is bit magic equivalent to: b < 128 || b >= 192
    (u8 as i8) >= -0x40
}

pub fn truncate(s: &str, max_chars: usize) -> &str {
    match s.char_indices().nth(max_chars) {
        None => s,
        Some((idx, _)) => &s[..idx],
    }
}

/// 如果字符串长度大于 `max_chars`,则从字符串末尾移除字符,
/// 并在字符串末尾附加 "..."。如果字符串长度小于 max_chars,则返回不变的字符串。
pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
    debug_assert!(max_chars >= 5);

    // If the string's byte length is <= max_chars, walking the string can be skipped since the
    // number of chars is <= the number of bytes.
    if s.len() <= max_chars {
        return s.to_string();
    }
    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
    match truncation_ix {
        Some(index) => s[..index].to_string() + "",
        _ => s.to_string(),
    }
}

/// 如果字符串长度大于 `max_chars`,则从字符串开头移除字符,
/// 并在字符串开头添加 "..."。如果字符串长度小于 max_chars,则返回不变的字符串。
pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
    debug_assert!(max_chars >= 5);

    // If the string's byte length is <= max_chars, walking the string can be skipped since the
    // number of chars is <= the number of bytes.
    if s.len() <= max_chars {
        return s.to_string();
    }
    let suffix_char_length = max_chars.saturating_sub(1);
    let truncation_ix = s
        .char_indices()
        .map(|(i, _)| i)
        .nth_back(suffix_char_length);
    match truncation_ix {
        Some(index) if index > 0 => "".to_string() + &s[index..],
        _ => s.to_string(),
    }
}

/// 仅从字符串中获取 `max_lines` 行,如果超过 `max_lines-1` 行,
/// 则在字符串末尾附加换行符和 "...",以便返回 `max_lines` 行。
/// 如果字符串长度小于 max_lines,则返回不变的字符串。
pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
    if lines.len() > max_lines - 1 {
        lines.pop();
        lines.join("\n") + "\n"
    } else {
        lines.join("\n")
    }
}

/// 在字符边界处截断字符串,使结果长度小于 `max_bytes`。
pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str {
    if s.len() < max_bytes {
        return s;
    }

    for i in (0..max_bytes).rev() {
        if s.is_char_boundary(i) {
            return &s[..i];
        }
    }

    ""
}

/// 获取适合字节限制的完整行前缀。如果第一行长于
/// 限制,则在字符边界处截断。
pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str {
    if s.len() < max_bytes {
        return s;
    }

    for i in (0..max_bytes).rev() {
        if s.is_char_boundary(i) && s.as_bytes()[i] == b'\n' {
            // Since the i-th character is \n, valid to slice at i + 1.
            return &s[..i + 1];
        }
    }

    truncate_to_byte_limit(s, max_bytes)
}

/// 安全切片扩展:统一收敛“坐标位置取子串”逻辑,杜绝中文多字节 panic。
///
/// 背景:`&s[a..b]` 按字节下标切片,`a/b` 落在中文/emoji 中间即 panic。
/// 后续新增代码禁止直接 `&s[a..b]`,一律经此 trait(`get` + 边界吸附)。
pub trait SafeStrSlice {
    /// 按字节范围安全切片:越界或非边界返回 `None`(`str::get` 语义)。
    fn safe_get(&self, range: Range<usize>) -> Option<&str>;
    /// 按字节范围切片并吸附到最近字符边界,永不 panic。
    /// `start` 向下取整,`end` 向下取整后钳制到 `len`。
    fn safe_slice_floor(&self, start: usize, end: usize) -> &str;
    /// `self[start..]` 的安全版:`start` 非边界时向下吸附。
    fn safe_suffix_from(&self, start: usize) -> &str;
    /// `self[..end]` 的安全版:`end` 非边界时向下吸附。
    fn safe_prefix_until(&self, end: usize) -> &str;
    /// 按起止字节偏移掐头去尾:返回 `(head, tail)`,中间段丢弃,永不 panic。
    /// `start` 向下吸附,`end` 向下吸附后钳制到 `>= start`。
    /// 典型用于输入法替换:`head + new_text + tail`,且 `head.len()` 即吸附后的
    /// `start`(可直接用于光标跟随,无需另算下标)。
    fn safe_head_tail(&self, start: usize, end: usize) -> (&str, &str);
}

impl SafeStrSlice for str {
    fn safe_get(&self, range: Range<usize>) -> Option<&str> {
        self.get(range)
    }

    fn safe_slice_floor(&self, start: usize, end: usize) -> &str {
        let start = self.floor_char_boundary(start.min(self.len()));
        let end = self.floor_char_boundary(end.min(self.len())).max(start);
        // `floor` 保证边界,`get` 理论必中;兜底空串避免任何 panic。
        self.get(start..end).unwrap_or("")
    }

    fn safe_suffix_from(&self, start: usize) -> &str {
        let start = self.floor_char_boundary(start.min(self.len()));
        self.get(start..).unwrap_or("")
    }

    fn safe_prefix_until(&self, end: usize) -> &str {
        let end = self.floor_char_boundary(end.min(self.len()));
        self.get(..end).unwrap_or("")
    }

    fn safe_head_tail(&self, start: usize, end: usize) -> (&str, &str) {
        let start = self.floor_char_boundary(start.min(self.len()));
        let end = self.floor_char_boundary(end.min(self.len())).max(start);
        (
            self.get(..start).unwrap_or(""),
            self.get(end..).unwrap_or(""),
        )
    }
}

#[test]
fn test_truncate_lines_to_byte_limit() {
    let text = "Line 1\nLine 2\nLine 3\nLine 4";

    // Limit that includes all lines
    assert_eq!(truncate_lines_to_byte_limit(text, 100), text);

    // Exactly the first line
    assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");

    // Limit between lines
    assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
    assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");

    // Limit before first newline
    assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");

    // Test with non-ASCII characters
    let text_utf8 = "Line 1\nLíne 2\nLine 3";
    assert_eq!(
        truncate_lines_to_byte_limit(text_utf8, 15),
        "Line 1\nLíne 2\n"
    );
}

/// 安全切片永不 panic:中文(3 字节)/emoji(4 字节)中间下标向下吸附,
/// 越界钳制到 `len`,`end < start` 时吞空。
#[test]
fn test_safe_str_slice_never_panics_on_cjk() {
    let s = "a运b👨c";
    // `运` 占 bytes 1..4,`👨` 占 bytes 5..9。
    assert!(s.get(..2).is_none());
    assert_eq!(s.safe_prefix_until(2), "a");
    assert_eq!(s.safe_prefix_until(4), "a运");
    assert_eq!(s.safe_suffix_from(2), "运b👨c");
    assert_eq!(s.safe_slice_floor(2, 6), "运b");
    assert_eq!(s.safe_slice_floor(6, 2), "");
    assert_eq!(s.safe_slice_floor(0, 100), s);
    assert_eq!(s.safe_head_tail(2, 6), ("a", "👨c"));
    // 掐掉的正是完整的字符:head.len() 即吸附后的 start。
    let (head, tail) = s.safe_head_tail(2, 6);
    assert_eq!(head.len(), 1);
    assert_eq!(format!("{head}X{tail}"), "aX👨c");
}

/// 用已排序的项序列扩展已排序的向量,维护向量的排序顺序并
/// 强制最大长度。这还会对项进行去重。根据给定的回调对项进行排序。调用此函数之前,
/// `vec` 和 `new_items` 都应已根据 `cmp` 比较器排序。
pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
where
    I: IntoIterator<Item = T>,
    F: FnMut(&T, &T) -> Ordering,
{
    let mut start_index = 0;
    for new_item in new_items {
        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
            let index = start_index + i;
            if vec.len() < limit {
                vec.insert(index, new_item);
            } else if index < vec.len() {
                vec.pop();
                vec.insert(index, new_item);
            }
            start_index = index;
        }
    }
}

pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
where
    F: Fn(&T, &T) -> Ordering,
{
    if limit == 0 {
        items.clear();
    }
    if items.len() <= limit {
        items.sort_by(compare);
        return;
    }
    // When limit is near to items.len() it may be more efficient to sort the whole list and
    // truncate, rather than always doing selection first as is done below. It's hard to analyze
    // where the threshold for this should be since the quickselect style algorithm used by
    // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
    // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
    // unsorted input.
    items.select_nth_unstable_by(limit, compare);
    items.truncate(limit);
    items.sort_by(compare);
}

/// 防止在 Unix 系统上以 root 权限执行应用程序。
///
/// 此函数检查当前进程是否以 root 权限运行,
/// 除非通过 `RGPUI_ALLOW_ROOT` 环境变量明确允许,否则将终止程序并显示错误消息。
#[cfg(unix)]
pub fn prevent_root_execution() {
    let is_root = nix::unistd::geteuid().is_root();
    let allow_root = std::env::var("RGPUI_ALLOW_ROOT").is_ok_and(|val| val == "true");

    if is_root && !allow_root {
        eprintln!(
            "\
Error: Running rgpui as root or via sudo is unsupported.
       Doing so (even once) may subtly break things for all subsequent non-root usage of rgpui.
       It is untested and not recommended, don't complain when things break.
       If you wish to proceed anyways, set `RGPUI_ALLOW_ROOT=true` in your environment."
        );
        std::process::exit(1);
    }
}

#[cfg(unix)]
fn load_shell_from_passwd() -> Result<()> {
    let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
        n if n < 0 => 1024,
        n => n as usize,
    };
    let mut buffer = Vec::with_capacity(buflen);

    let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
    let mut result: *mut libc::passwd = std::ptr::null_mut();

    let uid = unsafe { libc::getuid() };
    let status = unsafe {
        libc::getpwuid_r(
            uid,
            pwd.as_mut_ptr(),
            buffer.as_mut_ptr() as *mut libc::c_char,
            buflen,
            &mut result,
        )
    };
    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);

    // SAFETY: If `getpwuid_r` doesn't error, we have the entry here.
    let entry = unsafe { pwd.assume_init() };

    anyhow::ensure!(
        status == 0,
        "call to getpwuid_r failed. uid: {}, status: {}",
        uid,
        status
    );
    anyhow::ensure!(
        entry.pw_uid == uid,
        "passwd entry has different uid ({}) than getuid ({}) returned",
        entry.pw_uid,
        uid,
    );

    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
    let should_set_shell = std::env::var("SHELL").map_or(true, |shell_env| {
        shell_env != shell && !std::path::Path::new(&shell_env).exists()
    });

    if should_set_shell {
        log::info!(
            "updating SHELL environment variable to value from passwd entry: {:?}",
            shell,
        );
        unsafe { std::env::set_var("SHELL", shell) };
    }

    Ok(())
}

/// 返回当前 rgpui 可执行文件的 shell 转义路径
#[cfg(not(target_family = "wasm"))]
pub fn get_shell_safe_rgpui_path(shell_kind: shell::ShellKind) -> anyhow::Result<String> {
    use anyhow::Context as _;
    use paths::PathExt;
    let mut rgpui_path =
        std::env::current_exe().context("Failed to determine current rgpui executable path.")?;
    if cfg!(target_os = "linux")
        && !rgpui_path.is_file()
        && let Some(truncated) = rgpui_path
            .clone()
            .file_name()
            .and_then(|s| s.to_str())
            .and_then(|n| n.strip_suffix(" (deleted)"))
    {
        // Might have been deleted during update; let's use the new binary if there is one.
        rgpui_path.set_file_name(truncated);
    }

    rgpui_path
        .try_shell_safe(shell_kind)
        .context("Failed to shell-escape rgpui executable path.")
}

/// 返回 rgpui cli 可执行文件的路径,此函数
/// 应从 rgpui 可执行文件调用,而不是 rgpui-cli。
pub fn get_rgpui_cli_path() -> Result<PathBuf> {
    use anyhow::Context as _;
    let rgpui_path =
        std::env::current_exe().context("Failed to determine current rgpui executable path.")?;
    let parent = rgpui_path
        .parent()
        .context("Failed to determine parent directory of rgpui executable path.")?;

    let possible_locations: &[&str] = if cfg!(target_os = "macos") {
        // On macOS, the rgpui executable and rgpui-cli are inside the app bundle,
        // so here ./cli is for both installed and development builds.
        &["./cli"]
    } else if cfg!(target_os = "windows") {
        // bin/rgpui.exe is for installed builds, ./cli.exe is for development builds.
        &["bin/rgpui.exe", "./cli.exe"]
    } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
        // bin is the standard, ./cli is for the target directory in development builds.
        &["../bin/rgpui", "./cli"]
    } else {
        anyhow::bail!("unsupported platform for determining rgpui-cli path");
    };

    possible_locations
        .iter()
        .find_map(|p| {
            parent
                .join(p)
                .canonicalize()
                .ok()
                .filter(|p| p != &rgpui_path)
        })
        .with_context(|| {
            format!(
                "could not find rgpui-cli from any of: {}",
                possible_locations.join(", ")
            )
        })
}

#[cfg(unix)]
pub async fn load_login_shell_environment() -> Result<()> {
    use anyhow::Context as _;

    load_shell_from_passwd().log_err();

    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
    // into shell's `cd` command (and hooks) to manipulate env.
    // We do this so that we get the env a user would have when spawning a shell
    // in home directory.
    for (name, value) in shell_env::capture(get_system_shell(), &[], paths::home_dir())
        .await
        .with_context(|| format!("capturing environment with {:?}", get_system_shell()))?
    {
        // Skip SHLVL to prevent it from polluting rgpui's process environment.
        // The login shell used for env capture increments SHLVL, and if we propagate it,
        // terminals spawned by rgpui will inherit it and increment again, causing SHLVL
        // to start at 2 instead of 1 (and increase by 2 on each reload).
        if name == "SHLVL" {
            continue;
        }
        unsafe { std::env::set_var(&name, &value) };
    }

    log::info!(
        "set environment variables from shell:{}, path:{}",
        std::env::var("SHELL").unwrap_or_default(),
        std::env::var("PATH").unwrap_or_default(),
    );

    Ok(())
}

/// 配置进程以启动新会话,防止交互式 shell 控制终端。
///
/// 详情请参阅:<https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell>
pub fn set_pre_exec_to_start_new_session(
    command: &mut std::process::Command,
) -> &mut std::process::Command {
    // safety: code in pre_exec should be signal safe.
    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
    #[cfg(unix)]
    unsafe {
        use std::os::unix::process::CommandExt;
        command.pre_exec(|| {
            libc::setsid();
            Ok(())
        });
    };
    command
}

pub fn merge_json_lenient_value_into(
    source: serde_json_lenient::Value,
    target: &mut serde_json_lenient::Value,
) {
    match (source, target) {
        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
            for (key, value) in source {
                if let Some(target) = target.get_mut(&key) {
                    merge_json_lenient_value_into(value, target);
                } else {
                    target.insert(key, value);
                }
            }
        }

        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
            for value in source {
                target.push(value);
            }
        }

        (source, target) => *target = source,
    }
}

pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
    use serde_json::Value;

    match (source, target) {
        (Value::Object(source), Value::Object(target)) => {
            for (key, value) in source {
                if let Some(target) = target.get_mut(&key) {
                    merge_json_value_into(value, target);
                } else {
                    target.insert(key, value);
                }
            }
        }

        (Value::Array(source), Value::Array(target)) => {
            for value in source {
                target.push(value);
            }
        }

        (source, target) => *target = source,
    }
}

pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
    use serde_json::Value;
    if let Value::Object(source_object) = source {
        let target_object = if let Value::Object(target) = target {
            target
        } else {
            *target = Value::Object(Default::default());
            target.as_object_mut().unwrap()
        };
        for (key, value) in source_object {
            if let Some(target) = target_object.get_mut(&key) {
                merge_non_null_json_value_into(value, target);
            } else if !value.is_null() {
                target_object.insert(key, value);
            }
        }
    } else if !source.is_null() {
        *target = source
    }
}

pub fn expanded_and_wrapped_usize_range(
    range: Range<usize>,
    additional_before: usize,
    additional_after: usize,
    wrap_length: usize,
) -> impl Iterator<Item = usize> {
    let start_wraps = range.start < additional_before;
    let end_wraps = wrap_length < range.end + additional_after;
    if start_wraps && end_wraps {
        Either::Left(0..wrap_length)
    } else if start_wraps {
        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
        if wrapped_start <= range.end {
            Either::Left(0..wrap_length)
        } else {
            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
        }
    } else if end_wraps {
        let wrapped_end = range.end + additional_after - wrap_length;
        if range.start <= wrapped_end {
            Either::Left(0..wrap_length)
        } else {
            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
        }
    } else {
        Either::Left((range.start - additional_before)..(range.end + additional_after))
    }
}

/// 生成 `[i, i + 1, i - 1, i + 2, ..]`,每个值对 `wrap_length` 取模,
/// 并受 `additional_before` 和 `additional_after` 限制。如果换行导致重叠,则不
/// 发出重复项。如果 wrap_length 为 0,则不生成任何内容。
pub fn wrapped_usize_outward_from(
    start: usize,
    additional_before: usize,
    additional_after: usize,
    wrap_length: usize,
) -> impl Iterator<Item = usize> {
    let mut count = 0;
    let mut after_offset = 1;
    let mut before_offset = 1;

    std::iter::from_fn(move || {
        count += 1;
        if count > wrap_length {
            None
        } else if count == 1 {
            Some(start % wrap_length)
        } else if after_offset <= additional_after && after_offset <= before_offset {
            let value = (start + after_offset) % wrap_length;
            after_offset += 1;
            Some(value)
        } else if before_offset <= additional_before {
            let value = (start + wrap_length - before_offset) % wrap_length;
            before_offset += 1;
            Some(value)
        } else if after_offset <= additional_after {
            let value = (start + after_offset) % wrap_length;
            after_offset += 1;
            Some(value)
        } else {
            None
        }
    })
}

#[cfg(any(test, feature = "test-support"))]
mod rng {
    use rand::prelude::*;

    pub struct RandomCharIter<T: Rng> {
        rng: T,
        simple_text: bool,
    }

    impl<T: Rng> RandomCharIter<T> {
        pub fn new(rng: T) -> Self {
            Self {
                rng,
                simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
            }
        }

        pub fn with_simple_text(mut self) -> Self {
            self.simple_text = true;
            self
        }
    }

    impl<T: Rng> Iterator for RandomCharIter<T> {
        type Item = char;

        fn next(&mut self) -> Option<Self::Item> {
            if self.simple_text {
                return if self.rng.random_range(0..100) < 5 {
                    Some('\n')
                } else {
                    Some(self.rng.random_range(b'a'..b'z' + 1).into())
                };
            }

            match self.rng.random_range(0..100) {
                // whitespace
                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
                // two-byte greek letters
                20..=32 => char::from_u32(self.rng.random_range(('α' as u32)..('ω' as u32 + 1))),
                // // three-byte characters
                33..=45 => ['', '', '', '', '']
                    .choose(&mut self.rng)
                    .copied(),
                // // four-byte characters
                46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
                // ascii letters
                _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
            }
        }
    }
}
#[cfg(any(test, feature = "test-support"))]
pub use rng::RandomCharIter;

/// 以字符串形式获取嵌入文件。
pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
    match A::get(path).expect(path).data {
        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
    }
}

pub trait RangeExt<T> {
    fn sorted(&self) -> Self;
    fn to_inclusive(&self) -> RangeInclusive<T>;
    fn overlaps(&self, other: &Range<T>) -> bool;
    fn contains_inclusive(&self, other: &Range<T>) -> bool;
}

impl<T: Ord + Clone> RangeExt<T> for Range<T> {
    fn sorted(&self) -> Self {
        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
    }

    fn to_inclusive(&self) -> RangeInclusive<T> {
        self.start.clone()..=self.end.clone()
    }

    fn overlaps(&self, other: &Range<T>) -> bool {
        self.start < other.end && other.start < self.end
    }

    fn contains_inclusive(&self, other: &Range<T>) -> bool {
        self.start <= other.start && other.end <= self.end
    }
}

impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
    fn sorted(&self) -> Self {
        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
    }

    fn to_inclusive(&self) -> RangeInclusive<T> {
        self.clone()
    }

    fn overlaps(&self, other: &Range<T>) -> bool {
        self.start() < &other.end && &other.start <= self.end()
    }

    fn contains_inclusive(&self, other: &Range<T>) -> bool {
        self.start() <= &other.start && &other.end <= self.end()
    }
}

/// 一种按数字排序以数字开头的字符串的方法,回退到不区分大小写的字母数字排序。
///
/// 这对于将常规字母数字排序的序列(如 `1-abc, 10, 11-def, .., 2, 21-abc`)
/// 转换为 `1-abc, 2, 10, 11-def, .., 21-abc` 很有用
#[derive(Debug, PartialEq, Eq)]
pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);

impl<'a> NumericPrefixWithSuffix<'a> {
    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
        let (prefix, remainder) = str.split_at(i);

        let prefix = prefix.parse().ok();
        Self(prefix, remainder)
    }
}

/// 在处理相等性时,我们需要考虑字符串的大小写以实现严格相等性,
/// 以处理 "a" < "A" 而不是 "a" == "A" 的情况。
impl Ord for NumericPrefixWithSuffix<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self.0, other.0) {
            (None, None) => UniCase::new(self.1)
                .cmp(&UniCase::new(other.1))
                .then_with(|| self.1.cmp(other.1).reverse()),
            (None, Some(_)) => Ordering::Greater,
            (Some(_), None) => Ordering::Less,
            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
                UniCase::new(self.1)
                    .cmp(&UniCase::new(other.1))
                    .then_with(|| self.1.cmp(other.1).reverse())
            }),
        }
    }
}

impl PartialOrd for NumericPrefixWithSuffix<'_> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn emoji_regex() -> &'static Regex {
    static EMOJI_REGEX: LazyLock<Regex> =
        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
    &EMOJI_REGEX
}

/// 如果给定字符串仅由表情符号组成则返回 true。
/// 例如 "👨‍👩‍👧‍👧👋" 将返回 true,但 "👋!" 将返回 false。
pub fn word_consists_of_emojis(s: &str) -> bool {
    let mut prev_end = 0;
    for capture in emoji_regex().find_iter(s) {
        if capture.start() != prev_end {
            return false;
        }
        prev_end = capture.end();
    }
    prev_end == s.len()
}

/// 类似于 `str::split`,但还提供结果的字节偏移范围。与
/// `str::split` 不同,这不对模式类型进行泛型化,也不返回 `Iterator`。
pub fn split_str_with_ranges<'s>(
    s: &'s str,
    pat: &dyn Fn(char) -> bool,
) -> Vec<(Range<usize>, &'s str)> {
    let mut result = Vec::new();
    let mut start = 0;

    for (i, ch) in s.char_indices() {
        if pat(ch) {
            if i > start {
                result.push((start..i, &s[start..i]));
            }
            start = i + ch.len_utf8();
        }
    }

    if s.len() > start {
        result.push((start..s.len(), &s[start..s.len()]));
    }

    result
}

pub fn default<D: Default>() -> D {
    Default::default()
}

#[derive(Debug)]
pub enum ConnectionResult<O> {
    Timeout,
    ConnectionReset,
    Result(anyhow::Result<O>),
}

impl<O> ConnectionResult<O> {
    pub fn into_response(self) -> anyhow::Result<O> {
        match self {
            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
            ConnectionResult::Result(r) => r,
        }
    }
}

impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
    fn from(result: anyhow::Result<O>) -> Self {
        ConnectionResult::Result(result)
    }
}

/// 通过解析 `.` 和 `..` 组件来规范化路径,无需
/// 路径存在于磁盘上(与 `canonicalize` 不同)。
pub fn normalize_path(path: &Path) -> PathBuf {
    use std::path::Component;
    let mut components = path.components().peekable();
    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
        components.next();
        PathBuf::from(c.as_os_str())
    } else {
        PathBuf::new()
    };

    for component in components {
        match component {
            Component::Prefix(..) => unreachable!(),
            Component::RootDir => {
                ret.push(component.as_os_str());
            }
            Component::CurDir => {}
            Component::ParentDir => {
                ret.pop();
            }
            Component::Normal(c) => {
                ret.push(c);
            }
        }
    }
    ret
}

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

    #[test]
    fn test_extend_sorted() {
        let mut vec = vec![];

        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
        assert_eq!(vec, &[21, 17, 13, 8, 1]);

        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);

        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
    }

    #[test]
    fn test_truncate_to_bottom_n_sorted_by() {
        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
        assert_eq!(vec, &[1, 2, 3, 4, 5]);

        vec = vec![5, 2, 3, 4, 1];
        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
        assert_eq!(vec, &[1, 2, 3, 4, 5]);

        vec = vec![5, 2, 3, 4, 1];
        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
        assert_eq!(vec, &[1, 2, 3, 4]);

        vec = vec![5, 2, 3, 4, 1];
        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
        assert_eq!(vec, &[1]);

        vec = vec![5, 2, 3, 4, 1];
        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
        assert!(vec.is_empty());
    }

    #[test]
    fn test_iife() {
        fn option_returning_function() -> Option<()> {
            None
        }

        let foo = maybe!({
            option_returning_function()?;
            Some(())
        });

        assert_eq!(foo, None);
    }

    #[test]
    fn test_truncate_and_trailoff() {
        assert_eq!(truncate_and_trailoff("", 5), "");
        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
    }

    #[test]
    fn test_truncate_and_remove_front() {
        assert_eq!(truncate_and_remove_front("", 5), "");
        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
    }

    #[test]
    fn test_numeric_prefix_str_method() {
        let target = "1a";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(1), "a")
        );

        let target = "12ab";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(12), "ab")
        );

        let target = "12_ab";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(12), "_ab")
        );

        let target = "1_2ab";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(1), "_2ab")
        );

        let target = "1.2";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(1), ".2")
        );

        let target = "1.2_a";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(1), ".2_a")
        );

        let target = "12.2_a";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(12), ".2_a")
        );

        let target = "12a.2_a";
        assert_eq!(
            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
            NumericPrefixWithSuffix(Some(12), "a.2_a")
        );
    }

    #[test]
    fn test_numeric_prefix_with_suffix() {
        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);

        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
            assert_eq!(
                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
                NumericPrefixWithSuffix(None, numeric_prefix_less),
                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
            )
        }
    }

    #[test]
    fn test_word_consists_of_emojis() {
        let words_to_test = vec![
            ("👨‍👩‍👧‍👧👋🥒", true),
            ("👋", true),
            ("!👋", false),
            ("👋!", false),
            ("👋 ", false),
            (" 👋", false),
            ("Test", false),
        ];

        for (text, expected_result) in words_to_test {
            assert_eq!(word_consists_of_emojis(text), expected_result);
        }
    }

    #[test]
    fn test_truncate_lines_and_trailoff() {
        let text = r#"Line 1
Line 2
Line 3"#;

        assert_eq!(
            truncate_lines_and_trailoff(text, 2),
            r#"Line 1
…"#
        );

        assert_eq!(
            truncate_lines_and_trailoff(text, 3),
            r#"Line 1
Line 2
…"#
        );

        assert_eq!(
            truncate_lines_and_trailoff(text, 4),
            r#"Line 1
Line 2
Line 3"#
        );
    }

    #[test]
    fn test_expanded_and_wrapped_usize_range() {
        // Neither wrap
        assert_eq!(
            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
            (1..5).collect::<Vec<usize>>()
        );
        // Start wraps
        assert_eq!(
            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
            ((0..5).chain(7..8)).collect::<Vec<usize>>()
        );
        // Start wraps all the way around
        assert_eq!(
            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
            (0..8).collect::<Vec<usize>>()
        );
        // Start wraps all the way around and past 0
        assert_eq!(
            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
            (0..8).collect::<Vec<usize>>()
        );
        // End wraps
        assert_eq!(
            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
            (0..1).chain(2..8).collect::<Vec<usize>>()
        );
        // End wraps all the way around
        assert_eq!(
            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
            (0..8).collect::<Vec<usize>>()
        );
        // End wraps all the way around and past the end
        assert_eq!(
            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
            (0..8).collect::<Vec<usize>>()
        );
        // Both start and end wrap
        assert_eq!(
            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
            (0..8).collect::<Vec<usize>>()
        );
    }

    #[test]
    fn test_wrapped_usize_outward_from() {
        // No wrapping
        assert_eq!(
            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
            vec![4, 5, 3, 6, 2]
        );
        // Wrapping at end
        assert_eq!(
            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
            vec![8, 9, 7, 0, 6, 1]
        );
        // Wrapping at start
        assert_eq!(
            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
            vec![1, 2, 0, 3, 9, 8]
        );
        // All values wrap around
        assert_eq!(
            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
            vec![5, 6, 4, 7, 3, 0, 2, 1]
        );
        // None before / after
        assert_eq!(
            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
            vec![3]
        );
        // Starting point already wrapped
        assert_eq!(
            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
            vec![5, 6, 4, 7, 3]
        );
        // wrap_length of 0
        assert_eq!(
            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
            Vec::<usize>::new()
        );
    }

    #[test]
    fn test_split_with_ranges() {
        let input = "hi";
        let result = split_str_with_ranges(input, &|c| c == ' ');

        assert_eq!(result.len(), 1);
        assert_eq!(result[0], (0..2, "hi"));

        let input = "héllo🦀world";
        let result = split_str_with_ranges(input, &|c| c == '🦀');

        assert_eq!(result.len(), 2);
        assert_eq!(result[0], (0..6, "héllo")); // 'é' is 2 bytes
        assert_eq!(result[1], (10..15, "world")); // '🦀' is 4 bytes
    }

    #[test]
    fn test_round_half_toward_zero() {
        // Midpoint ties go toward zero
        assert_eq!(round_half_toward_zero(0.5), 0.0);
        assert_eq!(round_half_toward_zero(1.5), 1.0);
        assert_eq!(round_half_toward_zero(2.5), 2.0);
        assert_eq!(round_half_toward_zero(-0.5), 0.0);
        assert_eq!(round_half_toward_zero(-1.5), -1.0);
        assert_eq!(round_half_toward_zero(-2.5), -2.0);

        // Non-midpoint values round to nearest
        assert_eq!(round_half_toward_zero(1.5001), 2.0);
        assert_eq!(round_half_toward_zero(1.4999), 1.0);
        assert_eq!(round_half_toward_zero(-1.5001), -2.0);
        assert_eq!(round_half_toward_zero(-1.4999), -1.0);

        // Integers are unchanged
        assert_eq!(round_half_toward_zero(0.0), 0.0);
        assert_eq!(round_half_toward_zero(3.0), 3.0);
        assert_eq!(round_half_toward_zero(-3.0), -3.0);
    }

    #[test]
    fn test_device_pixel_helpers() {
        // Snap uses half-toward-zero: 1.0 * 1.5 = 1.5 ties toward 1.0.
        assert_eq!(round_to_device_pixel(1.0, 1.5), 1.0);
        // Below the tie rounds down, above rounds up.
        assert_eq!(round_to_device_pixel(0.3, 2.0), 1.0);
        assert_eq!(round_to_device_pixel(1.4, 1.0), 1.0);
        assert_eq!(round_to_device_pixel(1.6, 1.0), 2.0);

        // Stroke uses snap, but clamps non-zero input up to at least 1dp.
        assert_eq!(round_stroke_to_device_pixel(0.0, 1.0), 0.0);
        assert_eq!(round_stroke_to_device_pixel(0.4, 1.0), 1.0);
        assert_eq!(round_stroke_to_device_pixel(0.5, 1.0), 1.0);
        assert_eq!(round_stroke_to_device_pixel(1.0, 1.5), 1.0);
        assert_eq!(round_stroke_to_device_pixel(1.6, 1.0), 2.0);

        // Cover's near edge floors, far edge ceils. Together they form a strict superset.
        assert_eq!(floor_to_device_pixel(0.3, 2.0), 0.0);
        assert_eq!(ceil_to_device_pixel(0.3, 2.0), 1.0);
        assert_eq!(floor_to_device_pixel(2.1, 1.0), 2.0);
        assert_eq!(ceil_to_device_pixel(2.1, 1.0), 3.0);

        // Integer device-pixel inputs are stable under all three.
        assert_eq!(round_to_device_pixel(2.0, 2.0), 4.0);
        assert_eq!(floor_to_device_pixel(2.0, 2.0), 4.0);
        assert_eq!(ceil_to_device_pixel(2.0, 2.0), 4.0);
    }

    #[test]
    fn test_round_half_toward_zero_f64() {
        assert_eq!(round_half_toward_zero_f64(0.5), 0.0);
        assert_eq!(round_half_toward_zero_f64(-0.5), 0.0);
        assert_eq!(round_half_toward_zero_f64(1.5), 1.0);
        assert_eq!(round_half_toward_zero_f64(-1.5), -1.0);
        assert_eq!(round_half_toward_zero_f64(2.5001), 3.0);
    }

    #[rgpui::test]
    async fn test_with_timeout(cx: &mut TestAppContext) {
        Task::ready(())
            .with_timeout(Duration::from_secs(1), &cx.executor())
            .await
            .expect("Timeout should be noop");

        let long_duration = Duration::from_secs(6000);
        let short_duration = Duration::from_secs(1);
        cx.executor()
            .timer(long_duration)
            .with_timeout(short_duration, &cx.executor())
            .await
            .expect_err("timeout should have triggered");

        let fut = cx
            .executor()
            .timer(long_duration)
            .with_timeout(short_duration, &cx.executor());
        cx.executor().advance_clock(short_duration * 2);
        futures::FutureExt::now_or_never(fut)
            .unwrap_or_else(|| panic!("timeout should have triggered"))
            .expect_err("timeout");
    }
}
use super::{BackgroundExecutor, Task};
use std::{
    future::Future,
    pin::Pin,
    sync::atomic::{AtomicUsize, Ordering::SeqCst},
    task,
    time::Duration,
};

/// 一个用于在流式风格中通过命令式条件构建复杂对象的辅助 trait。
pub trait FluentBuilder {
    /// 使用给定的闭包以命令式方式修改自身。
    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
    where
        Self: Sized,
    {
        f(self)
    }

    /// 使用给定的闭包有条件地修改自身。
    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
    where
        Self: Sized,
    {
        self.map(|this| if condition { then(this) } else { this })
    }

    /// 使用给定的闭包有条件地修改自身。
    fn when_else(
        self,
        condition: bool,
        then: impl FnOnce(Self) -> Self,
        else_fn: impl FnOnce(Self) -> Self,
    ) -> Self
    where
        Self: Sized,
    {
        self.map(|this| if condition { then(this) } else { else_fn(this) })
    }

    /// 如果给定的选项是 Some,则有条件地解包并使用给定的闭包修改自身。
    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
    where
        Self: Sized,
    {
        self.map(|this| {
            if let Some(value) = option {
                then(this, value)
            } else {
                this
            }
        })
    }
    /// 如果给定的选项是 None,则有条件地解包并使用给定的闭包修改自身。
    fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
    where
        Self: Sized,
    {
        self.map(|this| if option.is_some() { this } else { then(this) })
    }
}

/// Future 类型的扩展,提供额外的组合器和实用程序。
pub trait FutureExt {
    /// 要求 Future 在指定持续时间过去之前完成。
    /// 类似于 tokio::timeout。
    fn with_timeout(self, timeout: Duration, executor: &BackgroundExecutor) -> WithTimeout<Self>
    where
        Self: Sized;
}

impl<T: Future> FutureExt for T {
    fn with_timeout(self, timeout: Duration, executor: &BackgroundExecutor) -> WithTimeout<Self>
    where
        Self: Sized,
    {
        WithTimeout {
            future: self,
            timer: executor.timer(timeout),
        }
    }
}

#[pin_project::pin_project]
pub struct WithTimeout<T> {
    #[pin]
    future: T,
    #[pin]
    timer: Task<()>,
}

#[derive(Debug, thiserror::Error)]
#[error("Timed out before future resolved")]
/// 当超时持续时间在 future 解决之前过去时,with_timeout 返回的错误
pub struct Timeout;

impl<T: Future> Future for WithTimeout<T> {
    type Output = Result<T::Output, Timeout>;

    fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> task::Poll<Self::Output> {
        let this = self.project();

        if let task::Poll::Ready(output) = this.future.poll(cx) {
            task::Poll::Ready(Ok(output))
        } else if this.timer.poll(cx).is_ready() {
            task::Poll::Ready(Err(Timeout))
        } else {
            task::Poll::Pending
        }
    }
}

/// 如果给定的原子计数器不为零,则递增它。
/// 返回计数器的新值。
pub(crate) fn atomic_incr_if_not_zero(counter: &AtomicUsize) -> usize {
    let mut loaded = counter.load(SeqCst);
    loop {
        if loaded == 0 {
            return 0;
        }
        match counter.compare_exchange_weak(loaded, loaded + 1, SeqCst, SeqCst) {
            Ok(x) => return x + 1,
            Err(actual) => loaded = actual,
        }
    }
}

/// 将 0.5 舍入到最接近的整数,向零方向舍入。
#[inline]
pub(crate) fn round_half_toward_zero(value: f32) -> f32 {
    (value.abs() - 0.5).ceil().copysign(value)
}

#[inline]
pub(crate) fn round_half_toward_zero_f64(value: f64) -> f64 {
    (value.abs() - 0.5).ceil().copysign(value)
}

#[inline]
pub(crate) fn round_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
    round_half_toward_zero(logical * scale_factor)
}

#[inline]
pub(crate) fn round_stroke_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
    if logical == 0.0 {
        0.0
    } else {
        round_to_device_pixel(logical.max(0.0), scale_factor).max(1.0)
    }
}

#[inline]
pub(crate) fn floor_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
    (logical * scale_factor).floor()
}

#[inline]
pub(crate) fn ceil_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
    (logical * scale_factor).ceil()
}