retch-sysinfo 0.1.73

System information gathering library for retch
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
// SPDX-FileCopyrightText: 2026 Ken Tobias
// SPDX-License-Identifier: GPL-3.0-or-later

//! Graphics and compute API versions: Vulkan, OpenGL and OpenCL.
//!
//! The last user-visible gap against fastfetch (NOTES.md §6). Each API is reached by
//! `dlopen`ing its loader at runtime rather than linking it, for three reasons:
//!
//! 1. **Linking would make the libraries hard requirements.** A machine without Vulkan
//!    must still run retch; a `#[link]` on `libvulkan` would refuse to start.
//! 2. **They are genuinely optional.** Absence is a normal answer ("no Vulkan here"),
//!    not an error, so the field is simply omitted.
//! 3. It keeps the crate free of new dependencies, matching the hand-written FFI house
//!    style used for the Windows and macOS probes.
//!
//! # These probes never modify the process environment
//!
//! Mesa's **rusticl** OpenCL driver is opt-in via `RUSTICL_ENABLE`: without it the ICD
//! still registers a platform advertising OpenCL 3.0 while exposing **zero devices**.
//! It is tempting to set that variable in-process before loading the ICD so the field
//! looks better. This module deliberately does not, for two reasons:
//!
//! - **It would be a data race.** Fields are collected inside a `std::thread::scope`, and
//!   mutating the environment while sibling threads read it is unsound. `std::env::set_var`
//!   became `unsafe` in Rust 2024 precisely for this; this crate is on edition 2021, where
//!   it still compiles silently — a trap rather than a compile error.
//! - **It would report something false.** A device visible only because retch enabled it
//!   for itself is not a device the user's own programs can use.
//!
//! So the OpenCL field reports the device count it actually observes, and says when that
//! count is zero. fastfetch prints a bare `OpenCL: 3.0` in both states — i.e. it reports a
//! working stack when nothing can run on it. Under-reporting beats asserting something
//! false, the same call as the `Users: 0` suppression (v0.6.1) and the v0.7.0 input
//! classification.

#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::ffi::c_int;
#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
use std::ffi::{c_char, c_void, CStr};

/// Versions reported by each graphics/compute API present on the system.
///
/// A `None` means the loader is absent or answered nothing usable — both are normal.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct GpuApis {
    /// Vulkan: device `apiVersion`, driver name and driver info, e.g.
    /// `1.4.354 - radv [Mesa 26.1.8]`.
    pub vulkan: Option<String>,
    /// OpenGL: the `GL_VERSION` string of a headless context, e.g.
    /// `4.6 (Compatibility Profile) Mesa 26.1.8`.
    pub opengl: Option<String>,
    /// OpenCL: platform version, provider, and what device (if any) is actually exposed.
    pub opencl: Option<String>,
}

/// Decode a packed Vulkan version into `major.minor.patch`.
///
/// Vulkan packs the version as `variant:3 | major:7 | minor:10 | patch:12`. The variant
/// field is deliberately ignored: it is non-zero only for non-Khronos derivatives, and
/// including it would print a leading number no user recognises.
pub fn format_vulkan_version(packed: u32) -> String {
    let major = (packed >> 22) & 0x7F;
    let minor = (packed >> 12) & 0x3FF;
    let patch = packed & 0xFFF;
    format!("{major}.{minor}.{patch}")
}

/// Rank a Vulkan `VkPhysicalDeviceType` so the most capable real device wins.
///
/// Lower is better. The ordering is load-bearing rather than cosmetic: a machine with a
/// real GPU almost always *also* exposes Mesa's `llvmpipe` software rasteriser as a
/// `CPU` device, so picking the first enumerated device would report software rendering
/// on a box with a perfectly good GPU. Observed on this hardware: the AMD 780M enumerates
/// as `INTEGRATED_GPU` (1) alongside `llvmpipe` as `CPU` (4).
pub fn device_type_rank(device_type: u32) -> u8 {
    match device_type {
        2 => 0, // DISCRETE_GPU
        1 => 1, // INTEGRATED_GPU
        3 => 2, // VIRTUAL_GPU
        4 => 4, // CPU (software rasteriser — a last resort, never a preference)
        _ => 3, // OTHER
    }
}

/// Render the Vulkan field from its parts.
///
/// `driver_name`/`driver_info` are empty when the driver did not fill the
/// `VkPhysicalDeviceDriverProperties` chain, which happens on any instance created below
/// Vulkan 1.2 — silently, with no error. The version alone is still worth printing.
pub fn format_vulkan(version: &str, driver_name: &str, driver_info: &str) -> String {
    match (driver_name.trim(), driver_info.trim()) {
        ("", _) => version.to_string(),
        (name, "") => format!("{version} - {name}"),
        (name, info) => format!("{version} - {name} [{info}]"),
    }
}

/// Render the OpenCL field, distinguishing "usable" from "present but inert".
///
/// A platform that advertises a version while exposing no device cannot run anything, so
/// saying so is the whole point of the field. See the module docs for why this does not
/// simply enable rusticl for itself and report the better-looking answer.
pub fn format_opencl(version: &str, platform: &str, device: Option<&str>) -> String {
    // CL_PLATFORM_VERSION is specified to start with "OpenCL <major>.<minor>", so the raw
    // string would render as "OpenCL: OpenCL 3.0" under the field's own label.
    let version = version
        .trim()
        .strip_prefix("OpenCL ")
        .unwrap_or(version.trim())
        .trim();
    let platform = platform.trim();
    match device {
        Some(d) if !d.trim().is_empty() => {
            if platform.is_empty() {
                format!("{version} ({})", d.trim())
            } else {
                format!("{version} - {platform} ({})", d.trim())
            }
        }
        _ => {
            if platform.is_empty() {
                format!("{version} (no device enabled)")
            } else {
                format!("{version} - {platform} (no device enabled)")
            }
        }
    }
}

/// Shorten a driver-reported device name to the part a human recognises.
///
/// Mesa reports OpenCL and GL device names with a full driver descriptor appended, e.g.
/// `AMD Radeon 780M Graphics (radeonsi, phoenix, ACO, DRM 3.64, 7.1.13-200.fc44.x86_64)`.
/// That is 80+ characters of kernel and driver detail that pushes the line into wrapping
/// and tells the reader nothing the `GPU` field does not already say, so everything from
/// the first parenthesised descriptor on is dropped.
pub fn shorten_device_name(name: &str) -> String {
    match name.find(" (") {
        Some(i) => name[..i].trim().to_string(),
        None => name.trim().to_string(),
    }
}

/// Trim a NUL-terminated fixed-size C string field into a `String`.
///
/// Reads up to the first NUL and ignores the rest of the buffer. Returns an empty string
/// when the field was never written, which is how an unfilled `pNext` chain presents.
pub fn cstr_field(buf: &[u8]) -> String {
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8_lossy(&buf[..end]).into_owned()
}

// ---------------------------------------------------------------------------
// Runtime loader — one interface, two backends
// ---------------------------------------------------------------------------

/// Runtime library loading, presenting the same `open`/`sym`/`close` interface on every
/// platform so the probes above it need no `cfg` of their own.
///
/// The probes are the same code on Linux and Windows — the Vulkan and OpenCL APIs are
/// identical, and only the loader's *name* differs — so the platform split lives here
/// rather than being duplicated per API. A second copy of the
/// `VkPhysicalDeviceProperties2` offset arithmetic is exactly the drift that the shared
/// `win_setupapi` and `win_iftable` modules exist to prevent.
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod dl {
    use super::*;

    extern "C" {
        pub fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void;
        pub fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
        pub fn dlclose(handle: *mut c_void) -> c_int;
    }
    pub const RTLD_NOW: c_int = 2;
    pub const RTLD_LOCAL: c_int = 0;

    /// Open a shared library by soname, or `None` if it is not installed.
    ///
    /// `RTLD_LOCAL` keeps the symbols out of the global namespace so loading, say, a
    /// software OpenCL ICD cannot shadow symbols another probe resolves later.
    pub fn open(soname: &CStr) -> Option<*mut c_void> {
        // SAFETY: `soname` is a valid NUL-terminated C string for the duration of the
        // call. A null return is the documented "not found" answer and is handled.
        let h = unsafe { dlopen(soname.as_ptr(), RTLD_NOW | RTLD_LOCAL) };
        (!h.is_null()).then_some(h)
    }

    /// Resolve a symbol, or `None` if the library does not export it.
    pub fn sym(handle: *mut c_void, name: &CStr) -> Option<*mut c_void> {
        // SAFETY: `handle` came from `open` above and has not been closed; `name` is a
        // valid NUL-terminated C string.
        let p = unsafe { dlsym(handle, name.as_ptr()) };
        (!p.is_null()).then_some(p)
    }

    /// Close a handle opened by [`open`].
    pub fn close(handle: *mut c_void) {
        // SAFETY: `handle` came from `open` and is not used afterwards.
        unsafe {
            dlclose(handle);
        }
    }
}

/// Windows backend for the loader interface above.
///
/// `LoadLibraryA` rather than `LoadLibraryW`: the names are ASCII DLL filenames resolved
/// through the standard search order, so widening them would buy nothing and would mean
/// converting a `CStr` the callers already hold. `media.rs`'s `combase.dll` bootstrap is
/// the precedent for loading a system DLL at runtime rather than linking it.
///
/// There is no `RTLD_LOCAL` equivalent to worry about — Windows does not have the global
/// symbol namespace that flag exists to avoid polluting.
#[cfg(target_os = "windows")]
mod dl {
    use super::*;

    #[link(name = "kernel32")]
    extern "system" {
        fn LoadLibraryA(lp_lib_file_name: *const c_char) -> *mut c_void;
        fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const c_char) -> *mut c_void;
        fn FreeLibrary(h_module: *mut c_void) -> i32;
    }

    /// Open a DLL by name, or `None` if it is not installed.
    ///
    /// A missing loader is the normal answer on a machine without that API — a headless
    /// server, or one with no GPU driver — not an error.
    pub fn open(name: &CStr) -> Option<*mut c_void> {
        // SAFETY: `name` is a valid NUL-terminated C string for the duration of the call.
        // A null return is the documented "not found" answer and is handled.
        let h = unsafe { LoadLibraryA(name.as_ptr()) };
        (!h.is_null()).then_some(h)
    }

    /// Resolve an exported symbol, or `None` if the DLL does not export it.
    pub fn sym(handle: *mut c_void, name: &CStr) -> Option<*mut c_void> {
        // SAFETY: `handle` came from `open` above and has not been freed; `name` is a
        // valid NUL-terminated C string.
        let p = unsafe { GetProcAddress(handle, name.as_ptr()) };
        (!p.is_null()).then_some(p)
    }

    /// Release a handle opened by [`open`].
    pub fn close(handle: *mut c_void) {
        // SAFETY: `handle` came from `open` and is not used afterwards.
        unsafe {
            FreeLibrary(handle);
        }
    }
}

/// The Vulkan loader's filename on this platform.
#[cfg(target_os = "linux")]
const VULKAN_LIB: &CStr = c"libvulkan.so.1";
/// `vulkan-1.dll` is the Khronos loader's fixed name on Windows, installed by every
/// conformant driver into `System32`.
#[cfg(target_os = "windows")]
const VULKAN_LIB: &CStr = c"vulkan-1.dll";
/// macOS has **no Vulkan at all** out of the box — there is no system loader and no
/// driver. Vulkan exists only through MoltenVK, a Vulkan-to-Metal translation layer, and
/// only once a user installs it (the LunarG SDK, or Homebrew).
///
/// This names the **Khronos loader**, `libvulkan.1.dylib`, which the SDK installs into
/// `/usr/local/lib` — a directory `dlopen` searches by default. Naming the loader rather
/// than `libMoltenVK.dylib` is deliberate: the loader is the entry point a portable Vulkan
/// application actually uses, so its presence is what "this machine has Vulkan" means. A
/// bare MoltenVK with no loader is reported as absent, which under-reports rather than
/// claiming an API that ordinary Vulkan software could not reach — the v0.11.6 rule.
///
/// On a stock Mac this simply fails to open and the field is absent, which is correct:
/// fastfetch prints no Vulkan line here either.
#[cfg(target_os = "macos")]
const VULKAN_LIB: &CStr = c"libvulkan.1.dylib";

/// The OpenCL ICD loader's filename on this platform.
#[cfg(target_os = "linux")]
const OPENCL_LIB: &CStr = c"libOpenCL.so.1";
/// `OpenCL.dll` is the Khronos ICD loader on Windows; vendor drivers register themselves
/// with it rather than being opened directly.
#[cfg(target_os = "windows")]
const OPENCL_LIB: &CStr = c"OpenCL.dll";
/// macOS ships OpenCL as a **framework**, and the full path is required.
///
/// **A bare `dlopen("OpenCL")` fails**, as does `libOpenCL.dylib` — verified on macOS 26.
/// System frameworks live in the dyld shared cache rather than on disk, so the file does
/// not exist to `stat` but the framework path still resolves through `dlopen`. Apple has
/// deprecated OpenCL in favour of Metal, but it is still present and still functional.
#[cfg(target_os = "macos")]
const OPENCL_LIB: &CStr = c"/System/Library/Frameworks/OpenCL.framework/OpenCL";

#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
mod vulkan {
    use super::dl;
    use super::*;

    const VK_STRUCTURE_TYPE_APPLICATION_INFO: u32 = 0;
    const VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO: u32 = 1;
    const VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2: u32 = 1000059001;
    const VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES: u32 = 1000196000;

    /// `VkPhysicalDeviceProperties2` places `properties` after `sType` + padding + `pNext`.
    const PROPS2_BODY: usize = 16;
    /// Offsets within `VkPhysicalDeviceProperties`.
    const OFF_API_VERSION: usize = 0;
    const OFF_DEVICE_TYPE: usize = 16;
    const OFF_DEVICE_NAME: usize = 20;
    /// Comfortably larger than `sizeof(VkPhysicalDeviceProperties)` (~824 bytes). The
    /// struct embeds `VkPhysicalDeviceLimits` (100+ fields) that this probe never reads,
    /// so it is handled as a sized byte buffer with documented offsets — the same approach
    /// `memory.rs` uses for SMBIOS type-17 and `win_iftable.rs` for `MIB_IF_ROW2`.
    const PROPS_BUF: usize = 1024;

    /// Offsets within `VkPhysicalDeviceDriverProperties`.
    const OFF_DRIVER_NAME: usize = 20;
    const OFF_DRIVER_INFO: usize = 276;
    const DRIVER_BUF: usize = 560;
    const VK_MAX_NAME: usize = 256;

    #[repr(C)]
    struct AppInfo {
        s_type: u32,
        p_next: *const c_void,
        app_name: *const c_char,
        app_version: u32,
        engine_name: *const c_char,
        engine_version: u32,
        api_version: u32,
    }

    #[repr(C)]
    struct InstanceCreateInfo {
        s_type: u32,
        p_next: *const c_void,
        flags: u32,
        app_info: *const AppInfo,
        layer_count: u32,
        layer_names: *const *const c_char,
        ext_count: u32,
        ext_names: *const *const c_char,
    }

    type VkCreateInstance =
        unsafe extern "C" fn(*const InstanceCreateInfo, *const c_void, *mut *mut c_void) -> i32;
    type VkDestroyInstance = unsafe extern "C" fn(*mut c_void, *const c_void);
    type VkEnumeratePhysicalDevices =
        unsafe extern "C" fn(*mut c_void, *mut u32, *mut *mut c_void) -> i32;
    type VkGetPhysicalDeviceProperties2 = unsafe extern "C" fn(*mut c_void, *mut c_void);
    type VkGetInstanceProcAddr = unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void;

    /// Query the best physical device's API version and driver identity.
    ///
    /// Returns `None` when Vulkan is absent, no instance can be created, or no device is
    /// present — all normal on a headless or GPU-less machine.
    pub fn detect() -> Option<String> {
        let lib = dl::open(VULKAN_LIB)?;
        let result = detect_with(lib);
        dl::close(lib);
        result
    }

    fn detect_with(lib: *mut c_void) -> Option<String> {
        let create = dl::sym(lib, c"vkCreateInstance")?;
        let gipa = dl::sym(lib, c"vkGetInstanceProcAddr")?;

        // SAFETY: every pointer below is either freshly resolved from the Vulkan loader or
        // a local we own. Buffers passed to the driver are sized at or above the structs
        // the API writes, and every returned code is checked before the result is read.
        unsafe {
            let create: VkCreateInstance = std::mem::transmute(create);
            let gipa: VkGetInstanceProcAddr = std::mem::transmute(gipa);

            let app = AppInfo {
                s_type: VK_STRUCTURE_TYPE_APPLICATION_INFO,
                p_next: std::ptr::null(),
                app_name: c"retch".as_ptr(),
                app_version: 0,
                engine_name: std::ptr::null(),
                engine_version: 0,
                // Must be >= 1.2. With a 1.0 or 1.1 instance the driver SILENTLY IGNORES
                // the `VkPhysicalDeviceDriverProperties` chain below and the driver name
                // and info come back as empty strings with no error anywhere — verified
                // against a 1.0 instance, which returned the right version and blank
                // driver fields.
                api_version: (1 << 22) | (2 << 12),
            };
            let ci = InstanceCreateInfo {
                s_type: VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
                p_next: std::ptr::null(),
                flags: 0,
                app_info: &app,
                layer_count: 0,
                layer_names: std::ptr::null(),
                ext_count: 0,
                ext_names: std::ptr::null(),
            };

            let mut instance: *mut c_void = std::ptr::null_mut();
            if create(&ci, std::ptr::null(), &mut instance) != 0 || instance.is_null() {
                return None;
            }

            let out = read_best_device(instance, gipa);

            if let Some(p) = dl::sym(lib, c"vkDestroyInstance") {
                let destroy: VkDestroyInstance = std::mem::transmute(p);
                destroy(instance, std::ptr::null());
            }
            out
        }
    }

    /// SAFETY: caller guarantees `instance` is a live `VkInstance` and `gipa` is the
    /// loader's `vkGetInstanceProcAddr`.
    unsafe fn read_best_device(
        instance: *mut c_void,
        gipa: VkGetInstanceProcAddr,
    ) -> Option<String> {
        let enum_ptr = gipa(instance, c"vkEnumeratePhysicalDevices".as_ptr());
        let props_ptr = gipa(instance, c"vkGetPhysicalDeviceProperties2".as_ptr());
        if enum_ptr.is_null() || props_ptr.is_null() {
            return None;
        }
        let enumerate: VkEnumeratePhysicalDevices = std::mem::transmute(enum_ptr);
        let get_props2: VkGetPhysicalDeviceProperties2 = std::mem::transmute(props_ptr);

        let mut count: u32 = 0;
        if enumerate(instance, &mut count, std::ptr::null_mut()) != 0 || count == 0 {
            return None;
        }
        let mut devices = vec![std::ptr::null_mut::<c_void>(); count as usize];
        if enumerate(instance, &mut count, devices.as_mut_ptr()) != 0 {
            return None;
        }

        let mut best: Option<(u8, String)> = None;
        for device in devices.iter().take(count as usize) {
            let mut driver = vec![0u8; DRIVER_BUF];
            driver[0..4].copy_from_slice(
                &VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES.to_ne_bytes(),
            );
            let mut props = vec![0u8; PROPS2_BODY + PROPS_BUF];
            props[0..4]
                .copy_from_slice(&VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2.to_ne_bytes());
            let chain = driver.as_mut_ptr() as usize;
            props[8..16].copy_from_slice(&chain.to_ne_bytes());

            get_props2(*device, props.as_mut_ptr() as *mut c_void);

            let at = |off: usize| -> u32 {
                let s = PROPS2_BODY + off;
                u32::from_ne_bytes(props[s..s + 4].try_into().unwrap_or([0; 4]))
            };
            let api = at(OFF_API_VERSION);
            let dtype = at(OFF_DEVICE_TYPE);
            let name_start = PROPS2_BODY + OFF_DEVICE_NAME;
            let _device_name = cstr_field(&props[name_start..name_start + VK_MAX_NAME]);

            let driver_name = cstr_field(&driver[OFF_DRIVER_NAME..OFF_DRIVER_NAME + VK_MAX_NAME]);
            let driver_info = cstr_field(&driver[OFF_DRIVER_INFO..OFF_DRIVER_INFO + VK_MAX_NAME]);

            let rank = device_type_rank(dtype);
            let rendered = format_vulkan(&format_vulkan_version(api), &driver_name, &driver_info);
            if best.as_ref().is_none_or(|(r, _)| rank < *r) {
                best = Some((rank, rendered));
            }
        }
        best.map(|(_, s)| s)
    }
}

#[cfg(target_os = "linux")]
mod opengl {
    use super::dl;
    use super::*;

    const EGL_OPENGL_API: u32 = 0x30A2;
    const EGL_NONE: i32 = 0x3038;
    const EGL_SURFACE_TYPE: i32 = 0x3033;
    const EGL_PBUFFER_BIT: i32 = 0x0001;
    const EGL_RENDERABLE_TYPE: i32 = 0x3040;
    const EGL_OPENGL_BIT: i32 = 0x0008;
    const GL_VERSION: u32 = 0x1F02;

    type EglGetDisplay = unsafe extern "C" fn(*mut c_void) -> *mut c_void;
    type EglInitialize = unsafe extern "C" fn(*mut c_void, *mut i32, *mut i32) -> u32;
    type EglBindApi = unsafe extern "C" fn(u32) -> u32;
    type EglChooseConfig =
        unsafe extern "C" fn(*mut c_void, *const i32, *mut *mut c_void, i32, *mut i32) -> u32;
    type EglCreateContext =
        unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, *const i32) -> *mut c_void;
    type EglMakeCurrent =
        unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, *mut c_void) -> u32;
    type EglGetProcAddress = unsafe extern "C" fn(*const c_char) -> *mut c_void;
    type EglTerminate = unsafe extern "C" fn(*mut c_void) -> u32;
    type GlGetString = unsafe extern "C" fn(u32) -> *const c_char;

    /// Read `GL_VERSION` from a headless EGL context.
    ///
    /// Deliberately uses EGL with `EGL_DEFAULT_DISPLAY` and a surfaceless
    /// `eglMakeCurrent`, so this works with no X or Wayland connection and without
    /// touching the environment. GLX would require a display server.
    ///
    /// **The context choice decides the number printed.** Passing no attribute list asks
    /// for the driver's default, which is the highest *compatibility* profile — matching
    /// what fastfetch reports. Requesting a core profile instead reports a different
    /// string for the same machine (`glxinfo -B` says `4.6 (Core Profile)` here where this
    /// returns `4.6 (Compatibility Profile)`), so the choice is deliberate, not incidental.
    pub fn detect() -> Option<String> {
        let lib = dl::open(c"libEGL.so.1")?;
        let out = detect_with(lib);
        dl::close(lib);
        out
    }

    fn detect_with(lib: *mut c_void) -> Option<String> {
        let get_display = dl::sym(lib, c"eglGetDisplay")?;
        let initialize = dl::sym(lib, c"eglInitialize")?;
        let bind_api = dl::sym(lib, c"eglBindAPI")?;
        let choose = dl::sym(lib, c"eglChooseConfig")?;
        let create_context = dl::sym(lib, c"eglCreateContext")?;
        let make_current = dl::sym(lib, c"eglMakeCurrent")?;
        let get_proc = dl::sym(lib, c"eglGetProcAddress")?;

        // SAFETY: all pointers are freshly resolved from libEGL or locals we own. Every
        // EGL call's status is checked before its output is used, and the display is
        // terminated on the success path.
        unsafe {
            let get_display: EglGetDisplay = std::mem::transmute(get_display);
            let initialize: EglInitialize = std::mem::transmute(initialize);
            let bind_api: EglBindApi = std::mem::transmute(bind_api);
            let choose: EglChooseConfig = std::mem::transmute(choose);
            let create_context: EglCreateContext = std::mem::transmute(create_context);
            let make_current: EglMakeCurrent = std::mem::transmute(make_current);
            let get_proc: EglGetProcAddress = std::mem::transmute(get_proc);

            // EGL_DEFAULT_DISPLAY is a null handle.
            let display = get_display(std::ptr::null_mut());
            if display.is_null() {
                return None;
            }
            let (mut major, mut minor) = (0i32, 0i32);
            if initialize(display, &mut major, &mut minor) == 0 {
                return None;
            }
            // Desktop GL specifically; an ES-only stack answers 0 here and is reported as
            // "no OpenGL" rather than being silently downgraded to an ES version string.
            if bind_api(EGL_OPENGL_API) == 0 {
                terminate(lib, display);
                return None;
            }

            let attrs = [
                EGL_SURFACE_TYPE,
                EGL_PBUFFER_BIT,
                EGL_RENDERABLE_TYPE,
                EGL_OPENGL_BIT,
                EGL_NONE,
            ];
            let mut config: *mut c_void = std::ptr::null_mut();
            let mut configs = 0i32;
            if choose(display, attrs.as_ptr(), &mut config, 1, &mut configs) == 0 || configs == 0 {
                terminate(lib, display);
                return None;
            }
            let context = create_context(display, config, std::ptr::null_mut(), std::ptr::null());
            if context.is_null() {
                terminate(lib, display);
                return None;
            }
            if make_current(display, std::ptr::null_mut(), std::ptr::null_mut(), context) == 0 {
                terminate(lib, display);
                return None;
            }
            let gl_get_string = get_proc(c"glGetString".as_ptr());
            let version = if gl_get_string.is_null() {
                None
            } else {
                let gl_get_string: GlGetString = std::mem::transmute(gl_get_string);
                let p = gl_get_string(GL_VERSION);
                if p.is_null() {
                    None
                } else {
                    Some(CStr::from_ptr(p).to_string_lossy().into_owned())
                }
            };
            terminate(lib, display);
            version.filter(|v| !v.trim().is_empty())
        }
    }

    /// Best-effort `eglTerminate`; failure to release is not worth reporting to the user.
    ///
    /// SAFETY: `display` is a live EGL display obtained from `eglGetDisplay`.
    unsafe fn terminate(lib: *mut c_void, display: *mut c_void) {
        if let Some(p) = dl::sym(lib, c"eglTerminate") {
            let terminate: EglTerminate = std::mem::transmute(p);
            terminate(display);
        }
    }
}

/// Windows OpenGL, via WGL against a hidden window.
///
/// **Why this is a separate module rather than a wider `cfg` on the EGL one.** Vulkan and
/// OpenCL are the same code on both platforms because those APIs are identical and only the
/// loader's filename differs. OpenGL is not: the Linux path gets a context from EGL with no
/// window and no display server, and **stock Windows ships no `libEGL.dll`** — verified on a
/// Windows 11 box carrying `vulkan-1.dll`, `opengl32.dll` and `OpenCL.dll` in `System32`
/// with no EGL at all. Windows has no headless equivalent in the base OS: WGL requires a
/// device context, a device context requires a window, and a window requires a window class.
/// So this is a genuinely different mechanism reaching the same `glGetString(GL_VERSION)`.
///
/// **The window is never shown.** It is created without `WS_VISIBLE` and `ShowWindow` is
/// never called, so nothing appears on screen — a fetch tool that flashed a window on every
/// run would be broken. This is asserted rather than assumed: see the visibility check
/// recorded in NOTES for v0.13.0, which enumerates top-level windows during a run.
///
/// `user32` and `gdi32` are linked rather than loaded at runtime, unlike the graphics
/// loaders: they are core OS libraries always present on any Windows that can run the
/// binary at all, and `display.rs` already links `user32` on the same grounds. `opengl32`
/// *is* loaded at runtime, because a machine with no OpenGL ICD is a real case and must
/// yield an absent field rather than a failure.
#[cfg(target_os = "windows")]
mod opengl {
    use super::dl;
    use super::*;

    const GL_VERSION: u32 = 0x1F02;

    // PIXELFORMATDESCRIPTOR.dwFlags
    const PFD_DOUBLEBUFFER: u32 = 0x0000_0001;
    const PFD_DRAW_TO_WINDOW: u32 = 0x0000_0004;
    const PFD_SUPPORT_OPENGL: u32 = 0x0000_0020;
    /// `PFD_TYPE_RGBA`.
    const PFD_TYPE_RGBA: u8 = 0;
    /// `PFD_MAIN_PLANE`.
    const PFD_MAIN_PLANE: u8 = 0;

    /// `WS_OVERLAPPED` is literally zero — the absence of `WS_VISIBLE` is what keeps the
    /// window off screen, so it is spelled out rather than left implicit.
    const WS_OVERLAPPED: u32 = 0x0000_0000;

    /// `PIXELFORMATDESCRIPTOR`, 40 bytes. Only a handful of fields are set; the rest must
    /// be zero, which is what `ChoosePixelFormat` expects for "don't care".
    #[repr(C)]
    #[derive(Default)]
    struct PixelFormatDescriptor {
        n_size: u16,
        n_version: u16,
        dw_flags: u32,
        i_pixel_type: u8,
        c_color_bits: u8,
        c_red_bits: u8,
        c_red_shift: u8,
        c_green_bits: u8,
        c_green_shift: u8,
        c_blue_bits: u8,
        c_blue_shift: u8,
        c_alpha_bits: u8,
        c_alpha_shift: u8,
        c_accum_bits: u8,
        c_accum_red_bits: u8,
        c_accum_green_bits: u8,
        c_accum_blue_bits: u8,
        c_accum_alpha_bits: u8,
        c_depth_bits: u8,
        c_stencil_bits: u8,
        c_aux_buffers: u8,
        i_layer_type: u8,
        b_reserved: u8,
        dw_layer_mask: u32,
        dw_visible_mask: u32,
        dw_damage_mask: u32,
    }

    /// `WNDCLASSW`, 72 bytes on x64. `lpfnWndProc` points at `DefWindowProcW`: the window
    /// never receives messages we care about, but a class still needs a procedure.
    #[repr(C)]
    struct WndClassW {
        style: u32,
        lpfn_wnd_proc: *const c_void,
        cb_cls_extra: i32,
        cb_wnd_extra: i32,
        h_instance: *mut c_void,
        h_icon: *mut c_void,
        h_cursor: *mut c_void,
        hbr_background: *mut c_void,
        lpsz_menu_name: *const u16,
        lpsz_class_name: *const u16,
    }

    #[link(name = "user32")]
    extern "system" {
        fn RegisterClassW(lp_wnd_class: *const WndClassW) -> u16;
        fn UnregisterClassW(lp_class_name: *const u16, h_instance: *mut c_void) -> i32;
        fn CreateWindowExW(
            dw_ex_style: u32,
            lp_class_name: *const u16,
            lp_window_name: *const u16,
            dw_style: u32,
            x: i32,
            y: i32,
            n_width: i32,
            n_height: i32,
            h_wnd_parent: *mut c_void,
            h_menu: *mut c_void,
            h_instance: *mut c_void,
            lp_param: *mut c_void,
        ) -> *mut c_void;
        fn DestroyWindow(h_wnd: *mut c_void) -> i32;
        fn GetDC(h_wnd: *mut c_void) -> *mut c_void;
        fn ReleaseDC(h_wnd: *mut c_void, h_dc: *mut c_void) -> i32;
        fn DefWindowProcW(h_wnd: *mut c_void, msg: u32, w_param: usize, l_param: isize) -> isize;
    }

    #[link(name = "gdi32")]
    extern "system" {
        fn ChoosePixelFormat(h_dc: *mut c_void, ppfd: *const PixelFormatDescriptor) -> i32;
        fn SetPixelFormat(
            h_dc: *mut c_void,
            format: i32,
            ppfd: *const PixelFormatDescriptor,
        ) -> i32;
    }

    type WglCreateContext = unsafe extern "system" fn(*mut c_void) -> *mut c_void;
    type WglMakeCurrent = unsafe extern "system" fn(*mut c_void, *mut c_void) -> i32;
    type WglDeleteContext = unsafe extern "system" fn(*mut c_void) -> i32;
    type GlGetString = unsafe extern "system" fn(u32) -> *const c_char;

    /// A hidden window plus its class, unregistered and destroyed on drop.
    ///
    /// Kept as a guard type so every early return unwinds the OS objects in the right
    /// order. Doing it by hand at each `?` is how a window or class leaks — and a leaked
    /// class makes a *second* run in the same process fail to register.
    struct HiddenWindow {
        class_name: Vec<u16>,
        hwnd: *mut c_void,
        hdc: *mut c_void,
    }

    impl HiddenWindow {
        fn new() -> Option<Self> {
            // A distinctive class name: it is unregistered on drop, so a collision would
            // only matter if two probes ran concurrently in one process, which they do not.
            let class_name: Vec<u16> = "retch_gl_probe\0".encode_utf16().collect();

            let wc = WndClassW {
                style: 0,
                lpfn_wnd_proc: DefWindowProcW as *const c_void,
                cb_cls_extra: 0,
                cb_wnd_extra: 0,
                h_instance: std::ptr::null_mut(),
                h_icon: std::ptr::null_mut(),
                h_cursor: std::ptr::null_mut(),
                hbr_background: std::ptr::null_mut(),
                lpsz_menu_name: std::ptr::null(),
                lpsz_class_name: class_name.as_ptr(),
            };

            // SAFETY: `wc` is a fully initialised WNDCLASSW whose string pointer outlives
            // the call, and every handle below is checked before use.
            unsafe {
                if RegisterClassW(&wc) == 0 {
                    return None;
                }
                // No WS_VISIBLE and no ShowWindow: the window exists only to own a device
                // context, and must never appear on screen. 1x1 at the origin.
                let hwnd = CreateWindowExW(
                    0,
                    class_name.as_ptr(),
                    std::ptr::null(),
                    WS_OVERLAPPED,
                    0,
                    0,
                    1,
                    1,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                );
                if hwnd.is_null() {
                    UnregisterClassW(class_name.as_ptr(), std::ptr::null_mut());
                    return None;
                }
                let hdc = GetDC(hwnd);
                if hdc.is_null() {
                    DestroyWindow(hwnd);
                    UnregisterClassW(class_name.as_ptr(), std::ptr::null_mut());
                    return None;
                }
                Some(Self {
                    class_name,
                    hwnd,
                    hdc,
                })
            }
        }
    }

    impl Drop for HiddenWindow {
        fn drop(&mut self) {
            // SAFETY: all three handles came from `new` and are released exactly once, in
            // the reverse of the order they were acquired.
            unsafe {
                ReleaseDC(self.hwnd, self.hdc);
                DestroyWindow(self.hwnd);
                UnregisterClassW(self.class_name.as_ptr(), std::ptr::null_mut());
            }
        }
    }

    /// Read `GL_VERSION` from a WGL context on a hidden window.
    ///
    /// **The pixel format is what makes the context creatable**, and it must be set before
    /// `wglCreateContext`: a device context with no pixel format cannot back a GL context,
    /// and the failure is a null handle rather than an error code that says so.
    ///
    /// Like the Linux path, this asks for the driver's **default** context rather than a
    /// core profile. `wglCreateContext` yields the highest compatibility profile the driver
    /// offers, which is what fastfetch reports — measured here as
    /// `4.6.0 Compatibility Profile Context 25.20.32.06.251214`. Requesting a core profile
    /// would need `wglCreateContextAttribsARB` and would print a different string for the
    /// same machine, so this is deliberate rather than the path of least resistance.
    pub fn detect() -> Option<String> {
        let lib = dl::open(c"opengl32.dll")?;
        let out = detect_with(lib);
        dl::close(lib);
        out
    }

    fn detect_with(lib: *mut c_void) -> Option<String> {
        let create_ctx = dl::sym(lib, c"wglCreateContext")?;
        let make_current = dl::sym(lib, c"wglMakeCurrent")?;
        let delete_ctx = dl::sym(lib, c"wglDeleteContext")?;
        let get_string = dl::sym(lib, c"glGetString")?;

        let window = HiddenWindow::new()?;

        // SAFETY: every function pointer is freshly resolved from opengl32; `window.hdc` is
        // a live device context owned by the guard above; the context is made non-current
        // and deleted before returning on every path.
        unsafe {
            let create_ctx: WglCreateContext = std::mem::transmute(create_ctx);
            let make_current: WglMakeCurrent = std::mem::transmute(make_current);
            let delete_ctx: WglDeleteContext = std::mem::transmute(delete_ctx);
            let get_string: GlGetString = std::mem::transmute(get_string);

            let pfd = PixelFormatDescriptor {
                n_size: std::mem::size_of::<PixelFormatDescriptor>() as u16,
                n_version: 1,
                dw_flags: PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
                i_pixel_type: PFD_TYPE_RGBA,
                c_color_bits: 32,
                c_depth_bits: 24,
                c_stencil_bits: 8,
                i_layer_type: PFD_MAIN_PLANE,
                ..Default::default()
            };
            let format = ChoosePixelFormat(window.hdc, &pfd);
            if format == 0 || SetPixelFormat(window.hdc, format, &pfd) == 0 {
                return None;
            }

            let ctx = create_ctx(window.hdc);
            if ctx.is_null() {
                return None;
            }
            let version = if make_current(window.hdc, ctx) != 0 {
                let p = get_string(GL_VERSION);
                let s = (!p.is_null()).then(|| CStr::from_ptr(p).to_string_lossy().into_owned());
                // Unbind before deleting: deleting the context that is current to this
                // thread is documented as failing, which would leak it.
                make_current(std::ptr::null_mut(), std::ptr::null_mut());
                s
            } else {
                None
            };
            delete_ctx(ctx);

            version
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        }
    }

    #[cfg(test)]
    mod layout {
        use std::mem::{offset_of, size_of};

        // Both structs are passed to the OS by pointer and read by fixed offset, and
        // `PIXELFORMATDESCRIPTOR.nSize` is set from `size_of` — so a layout change would
        // silently hand `ChoosePixelFormat` a wrong size rather than fail to compile.
        #[test]
        fn ffi_struct_layout() {
            assert_eq!(size_of::<super::PixelFormatDescriptor>(), 40);
            assert_eq!(offset_of!(super::PixelFormatDescriptor, dw_flags), 4);
            assert_eq!(offset_of!(super::PixelFormatDescriptor, i_pixel_type), 8);
            assert_eq!(offset_of!(super::PixelFormatDescriptor, c_color_bits), 9);
            assert_eq!(offset_of!(super::PixelFormatDescriptor, c_depth_bits), 23);
            assert_eq!(offset_of!(super::PixelFormatDescriptor, i_layer_type), 26);

            assert_eq!(size_of::<super::WndClassW>(), 72);
            assert_eq!(offset_of!(super::WndClassW, lpfn_wnd_proc), 8);
            assert_eq!(offset_of!(super::WndClassW, h_instance), 24);
            assert_eq!(offset_of!(super::WndClassW, lpsz_class_name), 64);
        }
    }
}

/// macOS: `GL_VERSION` from a headless CGL context.
///
/// **A third mechanism, which is why this is a third module rather than a wider `cfg`.**
/// Linux takes a context from EGL, Windows needs WGL against a hidden window, and macOS
/// has neither: it has CGL, which creates a context with **no window and no surface at
/// all**. That makes the macOS path the simplest of the three — there is no window class
/// to register and nothing that could flash on screen, so the visibility check the Windows
/// arm needs (v0.13.0) has no analogue here.
///
/// **THE DECISION THAT SETS THE NUMBER: the pixel format's profile attribute.** Measured
/// on this machine, all four variants in one run:
///
/// | requested profile | `GL_VERSION` |
/// |---|---|
/// | no profile attribute | `2.1 Metal - 90.5` |
/// | `kCGLOGLPVersion_Legacy` | `2.1 Metal - 90.5` |
/// | `kCGLOGLPVersion_3_2_Core` | `4.1 Metal - 90.5` |
/// | `kCGLOGLPVersion_GL4_Core` | `4.1 Metal - 90.5` |
///
/// So the default — no attribute — reports **2.1**, less than half the version the machine
/// actually supports, and fastfetch reports `4.1 Metal - 90.5`. Apple caps OpenGL at 4.1
/// and only exposes it through a core profile; the legacy profile is frozen at 2.1. This
/// requests `GL4_Core` deliberately, and the table is recorded here because the same
/// choice on Linux (v0.11.6) and Windows (v0.13.0) changed only the profile *label*, while
/// here it changes the version itself.
#[cfg(target_os = "macos")]
mod opengl {
    use super::dl;
    use super::*;

    /// Framework path — a bare `dlopen("OpenGL")` does not resolve. See [`OPENCL_LIB`] for
    /// why the full path is required for system frameworks.
    const OPENGL_FRAMEWORK: &CStr = c"/System/Library/Frameworks/OpenGL.framework/OpenGL";

    /// `kCGLPFAAccelerated` — require a hardware renderer rather than the software one.
    pub(super) const KCGLPFA_ACCELERATED: u32 = 73;
    /// `kCGLPFAOpenGLProfile` — the attribute whose value decides the reported version.
    pub(super) const KCGLPFA_OPENGL_PROFILE: u32 = 99;
    /// `kCGLOGLPVersion_GL4_Core` — the highest profile Apple offers (OpenGL 4.1).
    pub(super) const KCGL_OGLP_VERSION_GL4_CORE: u32 = 0x4100;
    /// `GL_VERSION`.
    const GL_VERSION: u32 = 0x1F02;

    type CGLChoosePixelFormat = unsafe extern "C" fn(*const u32, *mut *mut c_void, *mut i32) -> i32;
    type CGLCreateContext = unsafe extern "C" fn(*mut c_void, *mut c_void, *mut *mut c_void) -> i32;
    type CGLSetCurrentContext = unsafe extern "C" fn(*mut c_void) -> i32;
    type CGLDestroyContext = unsafe extern "C" fn(*mut c_void) -> i32;
    type CGLDestroyPixelFormat = unsafe extern "C" fn(*mut c_void) -> i32;
    type GlGetString = unsafe extern "C" fn(u32) -> *const c_char;

    /// Unwinds the CGL objects in reverse order of acquisition, on every exit path.
    ///
    /// Releasing by hand at each `?` is how a context or a pixel format leaks, and a leaked
    /// *current* context would keep the GPU objects alive for the rest of the process — the
    /// same reasoning as the Windows arm's window/class guard, minus the window.
    struct CglGuard {
        set_current: CGLSetCurrentContext,
        destroy_context: CGLDestroyContext,
        destroy_pixel_format: CGLDestroyPixelFormat,
        context: *mut c_void,
        pixel_format: *mut c_void,
    }

    impl Drop for CglGuard {
        fn drop(&mut self) {
            // SAFETY: each pointer was produced by the matching CGL create call and is
            // destroyed exactly once. Clearing the current context before destroying it is
            // required — destroying a context that is current to the calling thread is
            // documented to fail, which would leak it.
            unsafe {
                if !self.context.is_null() {
                    (self.set_current)(std::ptr::null_mut());
                    (self.destroy_context)(self.context);
                }
                if !self.pixel_format.is_null() {
                    (self.destroy_pixel_format)(self.pixel_format);
                }
            }
        }
    }

    /// Read `GL_VERSION`, or `None` when OpenGL is unavailable.
    pub fn detect() -> Option<String> {
        let lib = dl::open(OPENGL_FRAMEWORK)?;
        let result = probe(lib);
        dl::close(lib);
        result
    }

    fn probe(lib: *mut c_void) -> Option<String> {
        // SAFETY: every symbol is resolved from the OpenGL framework and transmuted to the
        // signature Apple documents for it; a missing symbol yields None and aborts here.
        unsafe {
            let choose: CGLChoosePixelFormat =
                std::mem::transmute(dl::sym(lib, c"CGLChoosePixelFormat")?);
            let create: CGLCreateContext = std::mem::transmute(dl::sym(lib, c"CGLCreateContext")?);
            let set_current: CGLSetCurrentContext =
                std::mem::transmute(dl::sym(lib, c"CGLSetCurrentContext")?);
            let destroy_context: CGLDestroyContext =
                std::mem::transmute(dl::sym(lib, c"CGLDestroyContext")?);
            let destroy_pixel_format: CGLDestroyPixelFormat =
                std::mem::transmute(dl::sym(lib, c"CGLDestroyPixelFormat")?);
            let gl_get_string: GlGetString = std::mem::transmute(dl::sym(lib, c"glGetString")?);

            // NUL-terminated attribute list, as CGL expects.
            let attrs: [u32; 4] = [
                KCGLPFA_ACCELERATED,
                KCGLPFA_OPENGL_PROFILE,
                KCGL_OGLP_VERSION_GL4_CORE,
                0,
            ];
            let mut pixel_format: *mut c_void = std::ptr::null_mut();
            let mut count: i32 = 0;
            if choose(attrs.as_ptr(), &mut pixel_format, &mut count) != 0
                || pixel_format.is_null()
                || count == 0
            {
                return None;
            }

            let mut context: *mut c_void = std::ptr::null_mut();
            let err = create(pixel_format, std::ptr::null_mut(), &mut context);

            // Guard is armed with whatever succeeded, so an early return still unwinds.
            let guard = CglGuard {
                set_current,
                destroy_context,
                destroy_pixel_format,
                context: if err == 0 {
                    context
                } else {
                    std::ptr::null_mut()
                },
                pixel_format,
            };

            if err != 0 || context.is_null() {
                return None;
            }
            if set_current(context) != 0 {
                return None;
            }
            let raw = gl_get_string(GL_VERSION);
            let version = (!raw.is_null())
                .then(|| CStr::from_ptr(raw).to_string_lossy().trim().to_string())
                .filter(|s| !s.is_empty());
            drop(guard);
            version
        }
    }
}

#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
mod opencl {
    use super::dl;
    use super::*;

    const CL_PLATFORM_VERSION: u32 = 0x0901;
    const CL_PLATFORM_NAME: u32 = 0x0902;
    const CL_DEVICE_TYPE_ALL: u64 = 0xFFFF_FFFF;
    const CL_DEVICE_NAME: u32 = 0x102B;

    type ClGetPlatformIDs = unsafe extern "C" fn(u32, *mut *mut c_void, *mut u32) -> i32;
    type ClGetPlatformInfo =
        unsafe extern "C" fn(*mut c_void, u32, usize, *mut c_void, *mut usize) -> i32;
    type ClGetDeviceIDs =
        unsafe extern "C" fn(*mut c_void, u64, u32, *mut *mut c_void, *mut u32) -> i32;
    type ClGetDeviceInfo =
        unsafe extern "C" fn(*mut c_void, u32, usize, *mut c_void, *mut usize) -> i32;

    #[cfg(target_os = "linux")]
    extern "C" {
        fn dup(oldfd: c_int) -> c_int;
        fn dup2(oldfd: c_int, newfd: c_int) -> c_int;
        fn close(fd: c_int) -> c_int;
        fn open(path: *const c_char, flags: c_int) -> c_int;
    }
    #[cfg(target_os = "linux")]
    const STDERR_FILENO: c_int = 2;
    #[cfg(target_os = "linux")]
    const O_WRONLY: c_int = 1;

    /// Silences `stderr` for its lifetime, restoring the original on drop.
    ///
    /// **Why this exists:** initialising an OpenCL driver can make it print to `stderr`
    /// over which retch has no control. Mesa's rusticl emits a 247-byte "Patched Mesa
    /// libclc not detected" warning on every enumeration once `RUSTICL_ENABLE` is set, and
    /// a fetch tool that sprays a driver's diagnostics into the terminal is broken. This
    /// was caught by `test_cli_full_mode`, which asserts retch writes nothing to `stderr`;
    /// fastfetch has the same leak and simply lets it through.
    ///
    /// **The caveat, stated rather than hidden:** file descriptors are process-wide, so
    /// this suppresses `stderr` for *every* thread while it is alive, and could in
    /// principle swallow a concurrent probe's error message. It is therefore scoped as
    /// tightly as possible — only around the OpenCL calls, ~20 ms — rather than around the
    /// collection scope. Moving the probe out of the concurrent scope would make the
    /// suppression provably safe, but costs ~100 ms serially and pushes `--full` past
    /// `fastfetch -c all` (1.02 s here), which NOTES.md §3 treats as blocking.
    #[cfg(target_os = "linux")]
    struct SuppressStderr {
        saved: c_int,
    }

    #[cfg(target_os = "linux")]
    impl SuppressStderr {
        fn new() -> Option<Self> {
            // SAFETY: plain fd manipulation. Every call's result is checked, and the
            // original descriptor is retained for restoration in `drop`.
            unsafe {
                let saved = dup(STDERR_FILENO);
                if saved < 0 {
                    return None;
                }
                let devnull = open(c"/dev/null".as_ptr(), O_WRONLY);
                if devnull < 0 {
                    close(saved);
                    return None;
                }
                dup2(devnull, STDERR_FILENO);
                close(devnull);
                Some(Self { saved })
            }
        }
    }

    #[cfg(target_os = "linux")]
    impl Drop for SuppressStderr {
        fn drop(&mut self) {
            // SAFETY: `self.saved` is a live descriptor duplicated from stderr in `new`.
            unsafe {
                dup2(self.saved, STDERR_FILENO);
                close(self.saved);
            }
        }
    }

    /// Report the OpenCL platform version, its provider, and whether a device exists.
    ///
    /// The device count is the point: see the module docs for why a platform advertising a
    /// version while exposing no device is reported as such rather than as a bare version.
    /// No-op stand-in on Windows and macOS.
    ///
    /// The Linux suppression exists for one specific driver: Mesa's rusticl prints a
    /// "Patched Mesa libclc not detected" warning to stderr on every enumeration. That
    /// driver does not exist on Windows, where the ICD loader dispatches to vendor DLLs
    /// instead, nor on macOS, where Apple's own framework is the only implementation.
    /// **Rather than assume those stacks are equally quiet, both were checked** — a probe
    /// running the full platform *and* device enumeration wrote **0 bytes** to stderr on
    /// each, and `test_cli_full_mode` asserts retch writes nothing to stderr and runs on
    /// both CI legs, so a future leak fails loudly instead of silently spraying a driver's
    /// diagnostics into the terminal. Adding suppression pre-emptively would mean
    /// reimplementing the `dup2` dance to solve a problem no observation has shown to
    /// exist, while silencing every other thread's diagnostics for the duration.
    #[cfg(any(target_os = "windows", target_os = "macos"))]
    struct SuppressStderr;

    #[cfg(any(target_os = "windows", target_os = "macos"))]
    impl SuppressStderr {
        fn new() -> Option<Self> {
            None
        }
    }

    pub fn detect() -> Option<String> {
        // Held across the whole probe: the driver can write to stderr at dlopen, at
        // platform enumeration, or at device enumeration, and rusticl does so at the last.
        let _quiet = SuppressStderr::new();
        let lib = dl::open(OPENCL_LIB)?;
        let out = detect_with(lib);
        dl::close(lib);
        out
    }

    fn detect_with(lib: *mut c_void) -> Option<String> {
        let get_platform_ids = dl::sym(lib, c"clGetPlatformIDs")?;
        let get_platform_info = dl::sym(lib, c"clGetPlatformInfo")?;

        // SAFETY: pointers are resolved from the ICD loader; every call's return code is
        // checked, and every buffer is sized by a preceding size query.
        unsafe {
            let get_platform_ids: ClGetPlatformIDs = std::mem::transmute(get_platform_ids);
            let get_platform_info: ClGetPlatformInfo = std::mem::transmute(get_platform_info);

            let mut count: u32 = 0;
            if get_platform_ids(0, std::ptr::null_mut(), &mut count) != 0 || count == 0 {
                return None;
            }
            let mut platforms = vec![std::ptr::null_mut::<c_void>(); count as usize];
            if get_platform_ids(count, platforms.as_mut_ptr(), std::ptr::null_mut()) != 0 {
                return None;
            }
            let platform = *platforms.first()?;

            let version = query(get_platform_info, platform, CL_PLATFORM_VERSION)?;
            let name = query(get_platform_info, platform, CL_PLATFORM_NAME).unwrap_or_default();

            let device = dl::sym(lib, c"clGetDeviceIDs")
                .zip(dl::sym(lib, c"clGetDeviceInfo"))
                .and_then(|(ids, info)| first_device_name(platform, ids, info))
                .map(|n| shorten_device_name(&n));

            Some(format_opencl(&version, &name, device.as_deref()))
        }
    }

    /// Two-call size-then-read query against a platform.
    ///
    /// SAFETY: `f` is `clGetPlatformInfo` and `obj` a valid platform id.
    unsafe fn query(f: ClGetPlatformInfo, obj: *mut c_void, param: u32) -> Option<String> {
        let mut size: usize = 0;
        if f(obj, param, 0, std::ptr::null_mut(), &mut size) != 0 || size == 0 {
            return None;
        }
        let mut buf = vec![0u8; size];
        if f(
            obj,
            param,
            size,
            buf.as_mut_ptr() as *mut c_void,
            std::ptr::null_mut(),
        ) != 0
        {
            return None;
        }
        let s = cstr_field(&buf);
        (!s.trim().is_empty()).then(|| s.trim().to_string())
    }

    /// Name of the first device on a platform, or `None` when it exposes none.
    ///
    /// SAFETY: `ids`/`info` are the corresponding OpenCL entry points and `platform` is a
    /// valid platform id.
    unsafe fn first_device_name(
        platform: *mut c_void,
        ids: *mut c_void,
        info: *mut c_void,
    ) -> Option<String> {
        let get_device_ids: ClGetDeviceIDs = std::mem::transmute(ids);
        let get_device_info: ClGetDeviceInfo = std::mem::transmute(info);

        let mut count: u32 = 0;
        // A platform with no usable device answers CL_DEVICE_NOT_FOUND (-1) here. That is
        // the rusticl-without-RUSTICL_ENABLE state, and it is a real answer, not an error.
        if get_device_ids(
            platform,
            CL_DEVICE_TYPE_ALL,
            0,
            std::ptr::null_mut(),
            &mut count,
        ) != 0
            || count == 0
        {
            return None;
        }
        let mut devices = vec![std::ptr::null_mut::<c_void>(); count as usize];
        if get_device_ids(
            platform,
            CL_DEVICE_TYPE_ALL,
            count,
            devices.as_mut_ptr(),
            std::ptr::null_mut(),
        ) != 0
        {
            return None;
        }
        let device = *devices.first()?;
        let mut size: usize = 0;
        if get_device_info(device, CL_DEVICE_NAME, 0, std::ptr::null_mut(), &mut size) != 0
            || size == 0
        {
            return None;
        }
        let mut buf = vec![0u8; size];
        if get_device_info(
            device,
            CL_DEVICE_NAME,
            size,
            buf.as_mut_ptr() as *mut c_void,
            std::ptr::null_mut(),
        ) != 0
        {
            return None;
        }
        let s = cstr_field(&buf);
        (!s.trim().is_empty()).then(|| s.trim().to_string())
    }
}

/// Detect Vulkan, OpenGL and OpenCL versions.
#[cfg(target_os = "linux")]
pub fn detect_gpu_apis() -> GpuApis {
    GpuApis {
        vulkan: vulkan::detect(),
        opengl: opengl::detect(),
        opencl: opencl::detect(),
    }
}

/// Windows: Vulkan and OpenCL, but not OpenGL.
///
/// The Vulkan and OpenCL probes are the *same code* as Linux — those APIs are identical
/// across platforms and only the loader filename differs, which is why the split lives in
/// [`dl`] and the two `*_LIB` constants rather than in duplicated probes.
///
/// **OpenGL is absent here deliberately, not by oversight.** The Linux path gets a headless
/// context through EGL (`EGL_DEFAULT_DISPLAY` plus a surfaceless `eglMakeCurrent`), and
/// **stock Windows ships no `libEGL.dll`** — checked on a Windows 11 box that has
/// `vulkan-1.dll`, `opengl32.dll` and `OpenCL.dll` in `System32` but no EGL at all. A
/// Windows OpenGL version therefore needs WGL against a hidden window, which is a different
/// mechanism rather than a different library name, so it is tracked as separate work
/// (NOTES.md §6a) instead of being half-done here.
#[cfg(target_os = "windows")]
pub fn detect_gpu_apis() -> GpuApis {
    GpuApis {
        vulkan: vulkan::detect(),
        opengl: opengl::detect(),
        opencl: opencl::detect(),
    }
}

/// macOS: all three, with Vulkan normally absent.
///
/// The Vulkan and OpenCL probes are the *same code* as Linux and Windows — those APIs are
/// identical across platforms and only the loader's filename differs, which is why the
/// split lives in [`dl`] and the two `*_LIB` constants. **OpenGL is a genuinely different
/// mechanism** and has its own module: CGL, which yields a context with no window and no
/// surface, where Linux uses EGL and Windows needs WGL against a hidden window.
///
/// **Vulkan will report nothing on a stock Mac, and that is correct.** macOS has no system
/// Vulkan; it exists only via MoltenVK once a user installs it. fastfetch prints no Vulkan
/// line here either. The probe is still wired up so that a machine *with* the SDK reports
/// accurately, and a failed `dlopen` of a missing library is the cheapest possible answer.
///
/// **OpenGL and OpenCL are both deprecated by Apple in favour of Metal** but are still
/// shipped and still functional. Reporting the version they actually return is the honest
/// answer; retch does not editorialise about deprecation in the field value.
#[cfg(target_os = "macos")]
pub fn detect_gpu_apis() -> GpuApis {
    GpuApis {
        vulkan: vulkan::detect(),
        opengl: opengl::detect(),
        opencl: opencl::detect(),
    }
}

/// Other platforms: reports nothing rather than guessing.
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
pub fn detect_gpu_apis() -> GpuApis {
    GpuApis::default()
}

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

    /// The loader filenames are the one part of the Windows arm with no runtime guard: a
    /// typo does not fail, it makes the probe report "not installed", which is
    /// indistinguishable from a machine that genuinely has no Vulkan. Pin them.
    ///
    /// `vulkan-1.dll` and `OpenCL.dll` are the Khronos loaders' fixed names on Windows —
    /// not vendor DLLs, which register themselves behind these. Confirmed present in
    /// `System32` on the machine this was developed against.
    #[cfg(target_os = "windows")]
    #[test]
    fn test_windows_loader_names_are_the_khronos_loaders() {
        assert_eq!(VULKAN_LIB.to_str().unwrap(), "vulkan-1.dll");
        assert_eq!(OPENCL_LIB.to_str().unwrap(), "OpenCL.dll");
    }

    /// The Linux sonames, pinned for the same reason and to keep the two arms visibly
    /// paired — a change to one should prompt a look at the other.
    #[cfg(target_os = "linux")]
    #[test]
    fn test_linux_loader_sonames() {
        assert_eq!(VULKAN_LIB.to_str().unwrap(), "libvulkan.so.1");
        assert_eq!(OPENCL_LIB.to_str().unwrap(), "libOpenCL.so.1");
    }

    /// The AMD platform string this machine reports, run through the same formatter the
    /// Linux Mesa strings go through.
    ///
    /// Windows drivers phrase `CL_PLATFORM_VERSION` differently from Mesa — AMD's carries
    /// a build number in parentheses — so this pins that the `OpenCL ` prefix strip still
    /// does the right thing on a non-Mesa string, and that the parenthesised build number
    /// is **not** mistaken for the device descriptor `shorten_device_name` strips.
    #[test]
    fn test_format_opencl_handles_a_windows_vendor_platform_string() {
        assert_eq!(
            format_opencl(
                "OpenCL 2.1 AMD-APP (3661.0)",
                "AMD Accelerated Parallel Processing",
                Some("gfx1151"),
            ),
            "2.1 AMD-APP (3661.0) - AMD Accelerated Parallel Processing (gfx1151)"
        );
    }

    /// A device name with no parenthesised driver descriptor must survive intact.
    ///
    /// The Linux fixtures all have one (Mesa appends `(radeonsi, phoenix, ACO, …)`), so
    /// nothing pinned the other branch until Windows produced a bare `gfx1151`.
    #[test]
    fn test_shorten_device_name_leaves_a_bare_name_alone() {
        assert_eq!(shorten_device_name("gfx1151"), "gfx1151");
        assert_eq!(shorten_device_name("  gfx1151  "), "gfx1151");
    }

    #[test]
    fn test_format_vulkan_version_decodes_packed_fields() {
        // 0x00404155 is what this machine's loader reports: 1.4.341.
        assert_eq!(format_vulkan_version(0x0040_4155), "1.4.341");
        // major/minor/patch boundaries
        assert_eq!(format_vulkan_version(1 << 22), "1.0.0");
        assert_eq!(format_vulkan_version((1 << 22) | (2 << 12)), "1.2.0");
        assert_eq!(
            format_vulkan_version((1 << 22) | (3 << 12) | 290),
            "1.3.290"
        );
    }

    #[test]
    fn test_format_vulkan_version_ignores_variant_bits() {
        // The top 3 bits are the variant; a non-Khronos variant must not leak into the
        // printed version or users see a leading number that means nothing to them.
        let with_variant = (1u32 << 29) | (1 << 22) | (4 << 12) | 354;
        assert_eq!(format_vulkan_version(with_variant), "1.4.354");
    }

    #[test]
    fn test_device_type_rank_prefers_real_gpu_over_software() {
        // The case that matters: a real GPU (integrated=1) must outrank llvmpipe (CPU=4),
        // which is enumerated alongside it on any Mesa system.
        assert!(device_type_rank(1) < device_type_rank(4));
        assert!(device_type_rank(2) < device_type_rank(1)); // discrete beats integrated
        assert!(device_type_rank(3) < device_type_rank(4)); // virtual beats CPU
        assert!(device_type_rank(0) < device_type_rank(4)); // even "other" beats CPU
    }

    #[test]
    fn test_format_vulkan_handles_unfilled_driver_chain() {
        // An instance below Vulkan 1.2 leaves these empty with no error, so the version
        // alone must still render.
        assert_eq!(format_vulkan("1.4.354", "", ""), "1.4.354");
        assert_eq!(format_vulkan("1.4.354", "radv", ""), "1.4.354 - radv");
        assert_eq!(
            format_vulkan("1.4.354", "radv", "Mesa 26.1.8"),
            "1.4.354 - radv [Mesa 26.1.8]"
        );
    }

    #[test]
    fn test_format_opencl_distinguishes_inert_platform_from_working_one() {
        // The whole point of the field: rusticl without RUSTICL_ENABLE advertises 3.0 and
        // exposes nothing. fastfetch prints "3.0" for both of these.
        assert_eq!(
            format_opencl("OpenCL 3.0", "rusticl", None),
            "3.0 - rusticl (no device enabled)"
        );
        assert_eq!(
            format_opencl("OpenCL 3.0", "rusticl", Some("AMD Radeon 780M Graphics")),
            "3.0 - rusticl (AMD Radeon 780M Graphics)"
        );
        // A device string that is only whitespace is not a device.
        assert_eq!(
            format_opencl("OpenCL 3.0", "rusticl", Some("   ")),
            "3.0 - rusticl (no device enabled)"
        );
    }

    #[test]
    fn test_format_opencl_without_platform_name() {
        assert_eq!(
            format_opencl("OpenCL 1.2", "", None),
            "1.2 (no device enabled)"
        );
        assert_eq!(format_opencl("OpenCL 1.2", "", Some("GPU")), "1.2 (GPU)");
        // A platform that does not carry the spec-mandated prefix is left alone rather
        // than having its first word eaten.
        assert_eq!(format_opencl("3.0", "x", Some("GPU")), "3.0 - x (GPU)");
    }

    #[test]
    fn test_shorten_device_name_drops_the_driver_descriptor() {
        // The real string this machine returns, otherwise 80+ characters of driver detail.
        assert_eq!(
            shorten_device_name(
                "AMD Radeon 780M Graphics (radeonsi, phoenix, ACO, DRM 3.64, 7.1.13-200.fc44.x86_64)"
            ),
            "AMD Radeon 780M Graphics"
        );
        // A name with no descriptor is returned intact rather than truncated.
        assert_eq!(
            shorten_device_name("NVIDIA GeForce RTX 4090"),
            "NVIDIA GeForce RTX 4090"
        );
        // Only " (" splits, so a parenthesis inside a model name survives.
        assert_eq!(
            shorten_device_name("Intel(R) Arc(TM) A770"),
            "Intel(R) Arc(TM) A770"
        );
    }

    #[test]
    fn test_cstr_field_stops_at_nul() {
        let mut buf = [0u8; 16];
        buf[..4].copy_from_slice(b"radv");
        assert_eq!(cstr_field(&buf), "radv");
        // An unwritten field is empty, not garbage — this is how an ignored pNext presents.
        assert_eq!(cstr_field(&[0u8; 16]), "");
        // No NUL at all: use the whole buffer rather than reading past it.
        assert_eq!(cstr_field(b"abcd"), "abcd");
    }

    /// macOS loader names, pinned for the same reason as the Windows ones: a typo here
    /// does not fail, it makes the probe report "not installed" — indistinguishable from a
    /// machine that genuinely lacks the API.
    ///
    /// **The framework paths must be absolute.** A bare `dlopen("OpenCL")` does *not*
    /// resolve on macOS — verified on macOS 26 — because system frameworks live in the
    /// dyld shared cache rather than on disk. Shortening either of these to a bare name
    /// would silently disable the field on every Mac.
    #[cfg(target_os = "macos")]
    #[test]
    fn test_macos_loader_names() {
        assert_eq!(VULKAN_LIB.to_str().unwrap(), "libvulkan.1.dylib");
        assert_eq!(
            OPENCL_LIB.to_str().unwrap(),
            "/System/Library/Frameworks/OpenCL.framework/OpenCL"
        );
        // The framework path is absolute precisely because the short name does not work.
        assert!(OPENCL_LIB.to_str().unwrap().starts_with('/'));
    }

    /// The CGL profile attribute is the single value that decides the OpenGL version
    /// reported on macOS, so it is pinned.
    ///
    /// Measured on an M3 Pro, all four variants in one run: no attribute and
    /// `kCGLOGLPVersion_Legacy` both yield **`2.1 Metal - 90.5`**, while
    /// `kCGLOGLPVersion_3_2_Core` and `kCGLOGLPVersion_GL4_Core` yield
    /// **`4.1 Metal - 90.5`** — which is what fastfetch reports. Dropping this attribute
    /// would silently halve the reported version on every Mac while still producing a
    /// perfectly plausible-looking string, which is exactly the failure mode this repo
    /// keeps recording.
    #[cfg(target_os = "macos")]
    #[test]
    fn test_macos_cgl_requests_a_core_profile() {
        // 0x4100 is kCGLOGLPVersion_GL4_Core; 0x1000 is kCGLOGLPVersion_Legacy, which
        // caps at OpenGL 2.1 and must not be what we ask for.
        assert_eq!(opengl::KCGL_OGLP_VERSION_GL4_CORE, 0x4100);
        assert_ne!(opengl::KCGL_OGLP_VERSION_GL4_CORE, 0x1000);
        assert_eq!(opengl::KCGLPFA_OPENGL_PROFILE, 99);
        assert_eq!(opengl::KCGLPFA_ACCELERATED, 73);
    }
}