retch-sysinfo 0.1.41

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
// SPDX-FileCopyrightText: 2026 Ken Tobias
// SPDX-License-Identifier: GPL-3.0-or-later

//! macOS framework FFI helpers shared across detection modules.
//!
//! Wraps CoreFoundation, IOKit, CoreAudio, and CoreGraphics C APIs into safe
//! Rust functions. Mirrors the `win_reg` pattern: raw `extern "C"` blocks at
//! module level, followed by safe public wrappers.
//!
//! Memory rules:
//! - CF objects from "Create" / "Copy" functions are owned; drop via `CFRelease`.
//! - CF objects from "Get" functions are borrowed; do NOT release.
//! - IOKit service/iterator ports must be released with `IOObjectRelease`.
//! - `IOServiceGetMatchingServices` consumes the matching dict (do not CFRelease).

use std::ffi::{c_void, CString};
use std::ptr;

// ─── CoreFoundation types ────────────────────────────────────────────────────

pub type CFTypeRef = *const c_void;
pub type CFStringRef = *const c_void;
pub type CFMutableDictionaryRef = *mut c_void;
pub type CFDictionaryRef = *const c_void;
pub type CFAllocatorRef = *const c_void;
pub type CFDataRef = *const c_void;
pub type CFBooleanRef = *const c_void;
pub type CFNumberRef = *const c_void;
#[allow(non_upper_case_globals)]
pub const kCFNumberSInt32Type: i32 = 3;
#[allow(non_upper_case_globals)]
pub const kCFStringEncodingUTF8: u32 = 0x08000100;

#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
    pub static kCFAllocatorDefault: CFAllocatorRef;

    pub fn CFStringCreateWithCString(
        alloc: CFAllocatorRef,
        c_str: *const i8,
        encoding: u32,
    ) -> CFStringRef;
    pub fn CFStringGetCString(
        the_string: CFStringRef,
        buffer: *mut i8,
        buffer_size: isize,
        encoding: u32,
    ) -> bool;
    pub fn CFStringGetLength(the_string: CFStringRef) -> isize;
    pub fn CFDataGetBytePtr(the_data: CFDataRef) -> *const u8;
    pub fn CFDataGetLength(the_data: CFDataRef) -> isize;
    pub fn CFGetTypeID(cf: CFTypeRef) -> usize;
    pub fn CFStringGetTypeID() -> usize;
    pub fn CFDataGetTypeID() -> usize;
    pub fn CFBooleanGetTypeID() -> usize;
    pub fn CFNumberGetTypeID() -> usize;
    pub fn CFBooleanGetValue(boolean: CFBooleanRef) -> bool;
    pub fn CFNumberGetValue(number: CFNumberRef, the_type: i32, value_ptr: *mut c_void) -> bool;
    pub fn CFNumberCreate(
        alloc: CFAllocatorRef,
        the_type: i32,
        value_ptr: *const c_void,
    ) -> CFNumberRef;
    pub fn CFDictionarySetValue(the_dict: CFMutableDictionaryRef, key: CFTypeRef, value: CFTypeRef);
    pub fn CFRelease(cf: CFTypeRef);

    pub static kCFPreferencesAnyApplication: CFStringRef;
    pub static kCFPreferencesCurrentUser: CFStringRef;
    pub static kCFPreferencesAnyHost: CFStringRef;
    pub fn CFPreferencesCopyValue(
        key: CFStringRef,
        application_id: CFStringRef,
        user_name: CFStringRef,
        host_name: CFStringRef,
    ) -> CFTypeRef;
}

// ─── CoreFoundation safe helpers ─────────────────────────────────────────────

/// RAII wrapper for a CF object that must be released with `CFRelease`.
pub struct OwnedCF(pub CFTypeRef);
impl Drop for OwnedCF {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { CFRelease(self.0) };
        }
    }
}

/// Convert a `CFStringRef` to a Rust `String`. Does not release the ref.
pub unsafe fn cf_string_to_rust(s: CFStringRef) -> Option<String> {
    if s.is_null() {
        return None;
    }
    let len = CFStringGetLength(s);
    if len <= 0 {
        return None;
    }
    // Each UTF-8 char can be up to 4 bytes; add room for null terminator.
    let buf_size = (len * 4 + 1) as usize;
    let mut buf = vec![0i8; buf_size];
    let ok = CFStringGetCString(
        s,
        buf.as_mut_ptr(),
        buf_size as isize,
        kCFStringEncodingUTF8,
    );
    if !ok {
        return None;
    }
    let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
    let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, end) };
    String::from_utf8(bytes.to_vec()).ok()
}

/// Convert a `CFDataRef` of ASCII bytes to a Rust `String`. Does not release.
pub unsafe fn cf_data_to_string(d: CFDataRef) -> Option<String> {
    if d.is_null() {
        return None;
    }
    let len = CFDataGetLength(d) as usize;
    if len == 0 {
        return None;
    }
    let ptr = CFDataGetBytePtr(d);
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    // Strip null terminators and non-printable bytes
    let s = String::from_utf8_lossy(bytes);
    let trimmed = s.trim_matches(|c: char| c == '\0' || !c.is_ascii_graphic() && c != ' ');
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Create a temporary CFStringRef from a Rust &str, call `f`, then release it.
unsafe fn with_cfstring<F, R>(s: &str, f: F) -> R
where
    F: FnOnce(CFStringRef) -> R,
{
    let cs = CString::new(s).unwrap_or_default();
    let cf = CFStringCreateWithCString(kCFAllocatorDefault, cs.as_ptr(), kCFStringEncodingUTF8);
    let result = f(cf);
    if !cf.is_null() {
        CFRelease(cf as CFTypeRef);
    }
    result
}

// ─── IOKit types ─────────────────────────────────────────────────────────────

pub type IOService = u32;
pub type IOIterator = u32;
pub const MACH_PORT_NULL: u32 = 0;
// IOKIT_MAIN_PORT == kIOMasterPortDefault == 0 on all macOS versions.
// IOKIT_MAIN_PORT was introduced as an exported symbol in macOS 12; using the
// literal avoids a link error when the SDK deployment target is macOS 11.
const IOKIT_MAIN_PORT: u32 = 0;

#[link(name = "IOKit", kind = "framework")]
extern "C" {
    pub fn IOServiceMatching(name: *const i8) -> CFMutableDictionaryRef;
    pub fn IOServiceGetMatchingService(main_port: u32, matching: CFDictionaryRef) -> IOService;
    pub fn IOServiceGetMatchingServices(
        main_port: u32,
        matching: CFDictionaryRef,
        existing: *mut IOIterator,
    ) -> i32;
    pub fn IOIteratorNext(iter: IOIterator) -> IOService;
    pub fn IOObjectRelease(obj: u32) -> i32;
    pub fn IORegistryEntryCreateCFProperty(
        entry: IOService,
        key: CFStringRef,
        allocator: CFAllocatorRef,
        options: u32,
    ) -> CFTypeRef;
    pub fn IORegistryEntryFromPath(main_port: u32, path: *const i8) -> IOService;
    pub fn IORegistryEntryGetChildIterator(
        entry: IOService,
        plane: *const i8,
        iter: *mut IOIterator,
    ) -> i32;
}

/// Read an IOKit registry property as a Rust String (handles CFString and CFData).
pub unsafe fn iokit_property_as_string(entry: IOService, key: &str) -> Option<String> {
    if entry == MACH_PORT_NULL {
        return None;
    }
    let val = with_cfstring(key, |k| {
        IORegistryEntryCreateCFProperty(entry, k, kCFAllocatorDefault, 0)
    });
    if val.is_null() {
        return None;
    }
    let _owned = OwnedCF(val);
    let type_id = CFGetTypeID(val);
    if type_id == CFStringGetTypeID() {
        cf_string_to_rust(val as CFStringRef)
    } else if type_id == CFDataGetTypeID() {
        cf_data_to_string(val as CFDataRef)
    } else {
        None
    }
}

/// Read an IOKit registry property as a u64 (handles CFData bytes and CFNumber).
pub unsafe fn iokit_property_as_u64(entry: IOService, key: &str) -> Option<u64> {
    if entry == MACH_PORT_NULL {
        return None;
    }
    let val = with_cfstring(key, |k| {
        IORegistryEntryCreateCFProperty(entry, k, kCFAllocatorDefault, 0)
    });
    if val.is_null() {
        return None;
    }
    let _owned = OwnedCF(val);
    let type_id = CFGetTypeID(val);
    if type_id == CFDataGetTypeID() {
        let len = CFDataGetLength(val as CFDataRef) as usize;
        let ptr = CFDataGetBytePtr(val as CFDataRef);
        match len {
            8 => {
                let mut arr = [0u8; 8];
                ptr::copy_nonoverlapping(ptr, arr.as_mut_ptr(), 8);
                Some(u64::from_le_bytes(arr))
            }
            4 => {
                let mut arr = [0u8; 4];
                ptr::copy_nonoverlapping(ptr, arr.as_mut_ptr(), 4);
                Some(u32::from_le_bytes(arr) as u64)
            }
            _ => None,
        }
    } else if type_id == CFNumberGetTypeID() {
        let mut v: i64 = 0;
        CFNumberGetValue(
            val as CFNumberRef,
            4, /* kCFNumberSInt64Type */
            &mut v as *mut i64 as *mut c_void,
        );
        if v > 0 {
            Some(v as u64)
        } else {
            None
        }
    } else {
        None
    }
}

/// Read an IOKit registry property as bool (handles CFBoolean).
pub unsafe fn iokit_property_as_bool(entry: IOService, key: &str) -> Option<bool> {
    if entry == MACH_PORT_NULL {
        return None;
    }
    let val = with_cfstring(key, |k| {
        IORegistryEntryCreateCFProperty(entry, k, kCFAllocatorDefault, 0)
    });
    if val.is_null() {
        return None;
    }
    let _owned = OwnedCF(val);
    if CFGetTypeID(val) == CFBooleanGetTypeID() {
        Some(CFBooleanGetValue(val as CFBooleanRef))
    } else {
        None
    }
}

// ─── BIOS — IODeviceTree:/rom ─────────────────────────────────────────────────

/// Read the system firmware version from IODeviceTree:/rom.
pub fn get_firmware_version() -> Option<String> {
    unsafe {
        let path = b"IODeviceTree:/rom\0";
        let entry = IORegistryEntryFromPath(IOKIT_MAIN_PORT, path.as_ptr() as *const i8);
        if entry == MACH_PORT_NULL {
            return None;
        }
        let result = iokit_property_as_string(entry, "version");
        IOObjectRelease(entry);
        result
    }
}

// ─── GPU — IOPCIDevice + AGXAccelerator ──────────────────────────────────────

/// Enumerate GPUs. Returns `(name, vram_bytes)` pairs.
/// Covers discrete/Intel GPUs (IOPCIDevice, PCI class 0x03) and Apple Silicon (AGXAccelerator).
pub fn get_gpus() -> Vec<(String, Option<u64>)> {
    let mut gpus = Vec::new();
    unsafe {
        // Apple Silicon: AGXAccelerator services
        let agx_name = CString::new("AGXAccelerator").unwrap();
        let matching = IOServiceMatching(agx_name.as_ptr());
        if !matching.is_null() {
            let mut iter: IOIterator = MACH_PORT_NULL;
            if IOServiceGetMatchingServices(IOKIT_MAIN_PORT, matching as CFDictionaryRef, &mut iter)
                == 0
            {
                loop {
                    let service = IOIteratorNext(iter);
                    if service == MACH_PORT_NULL {
                        break;
                    }
                    if let Some(name) = iokit_property_as_string(service, "model") {
                        gpus.push((name, None)); // Unified memory; no discrete VRAM
                    }
                    IOObjectRelease(service);
                }
                IOObjectRelease(iter);
            }
        }

        // Discrete / Intel GPUs: IOPCIDevice with PCI class 0x03 (display controller)
        let pci_name = CString::new("IOPCIDevice").unwrap();
        let matching = IOServiceMatching(pci_name.as_ptr());
        if !matching.is_null() {
            let mut iter: IOIterator = MACH_PORT_NULL;
            if IOServiceGetMatchingServices(IOKIT_MAIN_PORT, matching as CFDictionaryRef, &mut iter)
                == 0
            {
                loop {
                    let service = IOIteratorNext(iter);
                    if service == MACH_PORT_NULL {
                        break;
                    }

                    // Check PCI class code: 4-byte big-endian; byte[0] == 0x03 → display
                    let is_display = with_cfstring("class-code", |k| {
                        let v = IORegistryEntryCreateCFProperty(service, k, kCFAllocatorDefault, 0);
                        if v.is_null() {
                            return false;
                        }
                        let _owned = OwnedCF(v);
                        if CFGetTypeID(v) != CFDataGetTypeID() {
                            return false;
                        }
                        let len = CFDataGetLength(v as CFDataRef);
                        if len < 1 {
                            return false;
                        }
                        let ptr = CFDataGetBytePtr(v as CFDataRef);
                        // PCI class stored little-endian: byte[3] is class
                        *ptr.add((len - 1) as usize) == 0x03
                    });

                    if is_display {
                        if let Some(name) = iokit_property_as_string(service, "model") {
                            // Try VRAM properties (discrete GPUs only)
                            let vram =
                                iokit_property_as_u64(service, "VRAM,totalsize").or_else(|| {
                                    iokit_property_as_u64(service, "VRAM,totalMB")
                                        .map(|mb| mb * 1024 * 1024)
                                });
                            gpus.push((name, vram));
                        }
                    }
                    IOObjectRelease(service);
                }
                IOObjectRelease(iter);
            }
        }
    }
    gpus
}

// ─── CoreAudio ───────────────────────────────────────────────────────────────

#[repr(C)]
struct AudioObjectPropertyAddress {
    selector: u32,
    scope: u32,
    element: u32,
}

// AudioObject constants (4-char codes as big-endian u32)
const K_AUDIO_OBJECT_SYSTEM_OBJECT: u32 = 1;
const K_AUDIO_HARDWARE_PROPERTY_DEVICES: u32 = 0x6465_7623; // 'dev#'
const K_AUDIO_OBJECT_PROPERTY_NAME: u32 = 0x6c6e_616d; // 'lnam'
const K_AUDIO_OBJECT_PROPERTY_SCOPE_GLOBAL: u32 = 0x676c_6f62; // 'glob'
const K_AUDIO_OBJECT_PROPERTY_ELEMENT_MAIN: u32 = 0;

#[link(name = "CoreAudio", kind = "framework")]
extern "C" {
    fn AudioObjectGetPropertyDataSize(
        object_id: u32,
        address: *const AudioObjectPropertyAddress,
        qualifier_data_size: u32,
        qualifier_data: *const c_void,
        out_data_size: *mut u32,
    ) -> i32;

    fn AudioObjectGetPropertyData(
        object_id: u32,
        address: *const AudioObjectPropertyAddress,
        qualifier_data_size: u32,
        qualifier_data: *const c_void,
        io_data_size: *mut u32,
        out_data: *mut c_void,
    ) -> i32;
}

/// Enumerate CoreAudio device names.
pub fn get_audio_device_names() -> Vec<String> {
    let mut names = Vec::new();
    unsafe {
        let devices_addr = AudioObjectPropertyAddress {
            selector: K_AUDIO_HARDWARE_PROPERTY_DEVICES,
            scope: K_AUDIO_OBJECT_PROPERTY_SCOPE_GLOBAL,
            element: K_AUDIO_OBJECT_PROPERTY_ELEMENT_MAIN,
        };

        let mut data_size: u32 = 0;
        if AudioObjectGetPropertyDataSize(
            K_AUDIO_OBJECT_SYSTEM_OBJECT,
            &devices_addr,
            0,
            ptr::null(),
            &mut data_size,
        ) != 0
            || data_size == 0
        {
            return names;
        }

        let count = (data_size / 4) as usize; // AudioDeviceID is u32
        let mut device_ids = vec![0u32; count];
        if AudioObjectGetPropertyData(
            K_AUDIO_OBJECT_SYSTEM_OBJECT,
            &devices_addr,
            0,
            ptr::null(),
            &mut data_size,
            device_ids.as_mut_ptr() as *mut c_void,
        ) != 0
        {
            return names;
        }

        let name_addr = AudioObjectPropertyAddress {
            selector: K_AUDIO_OBJECT_PROPERTY_NAME,
            scope: K_AUDIO_OBJECT_PROPERTY_SCOPE_GLOBAL,
            element: K_AUDIO_OBJECT_PROPERTY_ELEMENT_MAIN,
        };

        for &device_id in &device_ids {
            let mut name_ref: CFStringRef = ptr::null();
            let mut name_size = std::mem::size_of::<CFStringRef>() as u32;
            if AudioObjectGetPropertyData(
                device_id,
                &name_addr,
                0,
                ptr::null(),
                &mut name_size,
                &mut name_ref as *mut CFStringRef as *mut c_void,
            ) == 0
                && !name_ref.is_null()
            {
                if let Some(name) = cf_string_to_rust(name_ref) {
                    if !name.is_empty() && !names.contains(&name) {
                        names.push(name);
                    }
                }
                CFRelease(name_ref as CFTypeRef);
            }
        }
    }
    names
}

// ─── CoreGraphics — Displays ──────────────────────────────────────────────────

#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
    fn CGGetActiveDisplayList(
        max_displays: u32,
        active_displays: *mut u32,
        display_count: *mut u32,
    ) -> i32;
    fn CGDisplayPixelsWide(display: u32) -> usize;
    fn CGDisplayPixelsHigh(display: u32) -> usize;
    fn CGDisplayCopyDisplayMode(display: u32) -> *mut c_void;
    fn CGDisplayModeGetRefreshRate(mode: *mut c_void) -> f64;
    fn CGDisplayModeRelease(mode: *mut c_void);
    fn CGDisplayVendorNumber(display: u32) -> u32;
    fn CGDisplayModelNumber(display: u32) -> u32;
}

/// Return a list of active displays as `(width_px, height_px, refresh_hz, vendor, model)`.
fn get_active_displays() -> Vec<(usize, usize, f64, u32, u32)> {
    let mut displays = Vec::new();
    unsafe {
        let mut count: u32 = 0;
        if CGGetActiveDisplayList(0, ptr::null_mut(), &mut count) != 0 || count == 0 {
            return displays;
        }
        let mut ids = vec![0u32; count as usize];
        if CGGetActiveDisplayList(count, ids.as_mut_ptr(), &mut count) != 0 {
            return displays;
        }
        for id in ids {
            let w = CGDisplayPixelsWide(id);
            let h = CGDisplayPixelsHigh(id);
            let mode = CGDisplayCopyDisplayMode(id);
            let refresh = if mode.is_null() {
                0.0
            } else {
                let r = CGDisplayModeGetRefreshRate(mode);
                CGDisplayModeRelease(mode);
                r
            };
            let vendor = CGDisplayVendorNumber(id);
            let model = CGDisplayModelNumber(id);
            displays.push((w, h, refresh, vendor, model));
        }
    }
    displays
}

/// Try to find a display name via IODisplayConnect by matching vendor+model numbers.
unsafe fn iokit_display_name(vendor: u32, model: u32) -> Option<String> {
    let matching_name = CString::new("IODisplayConnect").unwrap();
    let matching = IOServiceMatching(matching_name.as_ptr());
    if matching.is_null() {
        return None;
    }
    let mut iter: IOIterator = MACH_PORT_NULL;
    if IOServiceGetMatchingServices(IOKIT_MAIN_PORT, matching as CFDictionaryRef, &mut iter) != 0 {
        return None;
    }
    let mut result = None;
    loop {
        let service = IOIteratorNext(iter);
        if service == MACH_PORT_NULL {
            break;
        }
        // Read DisplayVendorID and DisplayProductID
        let v = iokit_property_as_u64(service, "DisplayVendorID").unwrap_or(0) as u32;
        let m = iokit_property_as_u64(service, "DisplayProductID").unwrap_or(0) as u32;
        if v == vendor && m == model {
            // DisplayProductName may be a CFString directly (on some macOS versions)
            result = iokit_property_as_string(service, "DisplayProductName");
            IOObjectRelease(service);
            break;
        }
        IOObjectRelease(service);
    }
    IOObjectRelease(iter);
    result
}

/// Return human-readable display descriptions: `"Name (WxH @ RRHz)"` or `"Display N (WxH @ RRHz)"`.
pub fn get_displays() -> Vec<String> {
    let raw = get_active_displays();
    raw.into_iter()
        .enumerate()
        .map(|(i, (w, h, refresh, vendor, model))| {
            let name = unsafe { iokit_display_name(vendor, model) }
                .unwrap_or_else(|| format!("Display {}", i + 1));
            let res = format!("{}x{}", w, h);
            if refresh > 0.0 {
                let rr = crate::display::format_refresh_rate(refresh);
                format!("{} ({} @ {}Hz)", name, res, rr)
            } else {
                format!("{} ({})", name, res)
            }
        })
        .collect()
}

// ─── IOKit — USB Cameras ──────────────────────────────────────────────────────

const USB_VIDEO_CLASS: u64 = 0x0E; // bInterfaceClass for UVC webcams

/// Enumerate USB cameras by finding IOUSBDevice children with bInterfaceClass = 0x0E.
pub fn get_usb_cameras() -> Vec<String> {
    let mut cameras = Vec::new();
    unsafe {
        let usb_name = CString::new("IOUSBDevice").unwrap();
        let matching = IOServiceMatching(usb_name.as_ptr());
        if matching.is_null() {
            return cameras;
        }
        let mut iter: IOIterator = MACH_PORT_NULL;
        if IOServiceGetMatchingServices(IOKIT_MAIN_PORT, matching as CFDictionaryRef, &mut iter)
            != 0
        {
            return cameras;
        }
        loop {
            let service = IOIteratorNext(iter);
            if service == MACH_PORT_NULL {
                break;
            }

            // Check if any child interface has bInterfaceClass == 0x0E (Video)
            let has_video = has_video_interface(service);
            if has_video {
                // Prefer "USB Product Name", fall back to "idProduct" numeric
                if let Some(name) = iokit_property_as_string(service, "USB Product Name") {
                    if !name.is_empty() && !cameras.contains(&name) {
                        cameras.push(name);
                    }
                }
            }
            IOObjectRelease(service);
        }
        IOObjectRelease(iter);
    }
    cameras
}

unsafe fn has_video_interface(device: IOService) -> bool {
    let mut child_iter: IOIterator = MACH_PORT_NULL;
    let plane = b"IOService\0";
    if IORegistryEntryGetChildIterator(device, plane.as_ptr() as *const i8, &mut child_iter) != 0 {
        return false;
    }
    let mut found = false;
    loop {
        let child = IOIteratorNext(child_iter);
        if child == MACH_PORT_NULL {
            break;
        }
        if let Some(class) = iokit_property_as_u64(child, "bInterfaceClass") {
            if class == USB_VIDEO_CLASS {
                found = true;
                IOObjectRelease(child);
                break;
            }
        }
        IOObjectRelease(child);
    }
    IOObjectRelease(child_iter);
    found
}

// ─── IOKit — HID Gamepads ─────────────────────────────────────────────────────

/// Enumerate HID gamepads and joysticks (covers USB and Bluetooth).
/// Matches usage page 0x01 (Generic Desktop) with usages 0x04 (Joystick) and 0x05 (Gamepad).
pub fn get_hid_gamepads() -> Vec<String> {
    let mut gamepads = Vec::new();
    for usage in [0x04u32, 0x05u32] {
        // Enumerate separately for joystick and gamepad usages
        let mut found = unsafe { enumerate_hid_usage(0x01, usage) };
        for name in found.drain(..) {
            if !gamepads.contains(&name) {
                gamepads.push(name);
            }
        }
    }
    gamepads
}

unsafe fn enumerate_hid_usage(page: u32, usage: u32) -> Vec<String> {
    let mut results = Vec::new();

    let hid_name = CString::new("IOHIDDevice").unwrap();
    let matching = IOServiceMatching(hid_name.as_ptr());
    if matching.is_null() {
        return results;
    }

    // Add usage page and usage filters to the matching dict
    let page_key = CString::new("DeviceUsagePage").unwrap();
    let usage_key = CString::new("DeviceUsage").unwrap();
    let page_cf_key = CFStringCreateWithCString(
        kCFAllocatorDefault,
        page_key.as_ptr(),
        kCFStringEncodingUTF8,
    );
    let usage_cf_key = CFStringCreateWithCString(
        kCFAllocatorDefault,
        usage_key.as_ptr(),
        kCFStringEncodingUTF8,
    );
    let page_val = CFNumberCreate(
        kCFAllocatorDefault,
        kCFNumberSInt32Type,
        &(page as i32) as *const i32 as *const c_void,
    );
    let usage_val = CFNumberCreate(
        kCFAllocatorDefault,
        kCFNumberSInt32Type,
        &(usage as i32) as *const i32 as *const c_void,
    );

    CFDictionarySetValue(matching, page_cf_key as CFTypeRef, page_val as CFTypeRef);
    CFDictionarySetValue(matching, usage_cf_key as CFTypeRef, usage_val as CFTypeRef);

    // Release the key/value CF objects (dict has retained them)
    CFRelease(page_cf_key as CFTypeRef);
    CFRelease(usage_cf_key as CFTypeRef);
    CFRelease(page_val as CFTypeRef);
    CFRelease(usage_val as CFTypeRef);

    let mut iter: IOIterator = MACH_PORT_NULL;
    // matching dict is consumed by IOServiceGetMatchingServices
    if IOServiceGetMatchingServices(IOKIT_MAIN_PORT, matching as CFDictionaryRef, &mut iter) != 0 {
        return results;
    }

    loop {
        let service = IOIteratorNext(iter);
        if service == MACH_PORT_NULL {
            break;
        }
        if let Some(name) = iokit_property_as_string(service, "Product") {
            if !name.is_empty() {
                results.push(name);
            }
        }
        IOObjectRelease(service);
    }
    IOObjectRelease(iter);
    results
}

// ─── IOKit — Bluetooth state ──────────────────────────────────────────────────

/// Return `(power_on, chipset_name)` from the IOBluetoothHCIController IOKit service.
/// Connected device names are NOT available via pure-C IOKit (requires Obj-C IOBluetooth).
pub fn get_bluetooth_state() -> Option<(bool, Option<String>)> {
    unsafe {
        let svc_name = CString::new("IOBluetoothHCIController").unwrap();
        let matching = IOServiceMatching(svc_name.as_ptr());
        if matching.is_null() {
            return None;
        }
        let service = IOServiceGetMatchingService(IOKIT_MAIN_PORT, matching as CFDictionaryRef);
        if service == MACH_PORT_NULL {
            return None;
        }
        let power =
            iokit_property_as_bool(service, "BluetoothControllerPowerIsOn").unwrap_or(false);
        // Try several property names for chipset/product string
        let chipset = iokit_property_as_string(service, "HardwareTransportCurrentSetting")
            .or_else(|| iokit_property_as_string(service, "ProductName"))
            .or_else(|| iokit_property_as_string(service, "ChipsetString"));
        IOObjectRelease(service);
        Some((power, chipset))
    }
}

// ─── IOKit — Battery (AppleSmartBattery) ─────────────────────────────────────

/// Raw battery data read directly from the AppleSmartBattery IOKit service.
pub struct MacBatteryRaw {
    pub current_mah: Option<u64>,
    pub max_mah: Option<u64>,
    pub raw_max_mah: Option<u64>,
    pub design_mah: Option<u64>,
    pub is_charging: bool,
    pub fully_charged: bool,
    /// Minutes remaining; None if unknown (65535) or unavailable.
    pub time_remaining_mins: Option<u64>,
    pub vendor: Option<String>,
    pub model: Option<String>,
}

/// Read battery data from the AppleSmartBattery IOKit service.
pub fn get_battery_raw() -> Option<MacBatteryRaw> {
    unsafe {
        let svc_name = CString::new("AppleSmartBattery").unwrap();
        let matching = IOServiceMatching(svc_name.as_ptr());
        if matching.is_null() {
            return None;
        }
        let service = IOServiceGetMatchingService(IOKIT_MAIN_PORT, matching as CFDictionaryRef);
        if service == MACH_PORT_NULL {
            return None;
        }

        let current_mah = iokit_property_as_u64(service, "CurrentCapacity");
        let max_mah = iokit_property_as_u64(service, "MaxCapacity");
        let raw_max_mah = iokit_property_as_u64(service, "AppleRawMaxCapacity");
        let design_mah = iokit_property_as_u64(service, "DesignCapacity");
        let is_charging = iokit_property_as_bool(service, "IsCharging").unwrap_or(false);
        let fully_charged = iokit_property_as_bool(service, "FullyCharged").unwrap_or(false);
        // 65535 means unknown/unlimited (AC connected with no estimate); filter it out.
        let time_remaining_mins =
            iokit_property_as_u64(service, "TimeRemaining").filter(|&m| m < 65535);
        let vendor = iokit_property_as_string(service, "Manufacturer");
        let model = iokit_property_as_string(service, "DeviceName");

        IOObjectRelease(service);

        if current_mah.is_none() && max_mah.is_none() {
            return None;
        }

        Some(MacBatteryRaw {
            current_mah,
            max_mah,
            raw_max_mah,
            design_mah,
            is_charging,
            fully_charged,
            time_remaining_mins,
            vendor,
            model,
        })
    }
}

// ─── CoreFoundation — Preferences (theme) ────────────────────────────────────

/// Read the macOS appearance preference ("Dark" or nil for Light) from the global domain.
/// Equivalent to `defaults read -g AppleInterfaceStyle`.
pub fn get_macos_appearance() -> Option<String> {
    unsafe {
        with_cfstring("AppleInterfaceStyle", |key| {
            let val = CFPreferencesCopyValue(
                key,
                kCFPreferencesAnyApplication,
                kCFPreferencesCurrentUser,
                kCFPreferencesAnyHost,
            );
            if val.is_null() {
                return None;
            }
            let _owned = OwnedCF(val);
            if CFGetTypeID(val) == CFStringGetTypeID() {
                cf_string_to_rust(val as CFStringRef)
            } else {
                None
            }
        })
    }
}

// ─── CoreWLAN — Wi-Fi SSID and link rate ─────────────────────────────────────
//
// The SystemConfiguration dynamic store key `State:/Network/Interface/*/AirPort`
// is not populated on macOS 15 Sequoia, so we use CoreWLAN for both SSID and
// transmit rate. `NSString` is toll-free bridged with `CFStringRef`.

#[link(name = "CoreWLAN", kind = "framework")]
extern "C" {}

#[link(name = "objc")]
extern "C" {
    fn objc_getClass(name: *const i8) -> *mut c_void;
    fn sel_registerName(str: *const i8) -> *mut c_void;
    fn objc_msgSend(self_: *mut c_void, op: *mut c_void, ...) -> *mut c_void;
}

#[allow(clashing_extern_declarations)]
extern "C" {
    #[link_name = "objc_msgSend"]
    fn objc_msgSend_f64(self_: *mut c_void, op: *mut c_void) -> f64;
}

/// Return `(ssid, rate_mbps)` for the connected Wi-Fi network via CoreWLAN.
///
/// macOS 10.15+ restricts SSID access to processes with Location Services
/// authorization. `CWInterface.ssid` returns nil and `ipconfig getsummary`
/// returns the literal string `<redacted>` when authorization is absent.
/// When the SSID is genuinely unavailable but `transmitRate > 0` confirms an
/// active association, we return `"Connected"` as the display name so the
/// Wi-Fi line still appears with the rate.
pub fn get_wifi_info() -> Option<(String, Option<u64>)> {
    unsafe {
        let cls_name = CString::new("CWWiFiClient").unwrap();
        let cls = objc_getClass(cls_name.as_ptr());
        if cls.is_null() {
            return None;
        }
        let shared_sel = sel_registerName(CString::new("sharedWiFiClient").unwrap().as_ptr());
        let client = objc_msgSend(cls, shared_sel);
        if client.is_null() {
            return None;
        }
        let iface_sel = sel_registerName(CString::new("interface").unwrap().as_ptr());
        let iface = objc_msgSend(client, iface_sel);
        if iface.is_null() {
            return None;
        }

        // transmitRate does not require Location Services.
        let rate_sel = sel_registerName(CString::new("transmitRate").unwrap().as_ptr());
        let rate_f = objc_msgSend_f64(iface, rate_sel);
        let rate = if rate_f > 0.0 {
            Some(rate_f as u64)
        } else {
            None
        };

        // SSID: NSString is toll-free bridged with CFString.
        // Returns nil when Location Services is not granted.
        let ssid_sel = sel_registerName(CString::new("ssid").unwrap().as_ptr());
        let ssid_ns = objc_msgSend(iface, ssid_sel) as CFStringRef;
        if let Some(ssid) = cf_string_to_rust(ssid_ns) {
            return Some((ssid, rate));
        }

        // Fallback: read SSID from configd via ipconfig getsummary <iface>.
        // On macOS 10.15+ without Location Services, ipconfig returns the
        // literal string "<redacted>" — filter that out.
        let iface_name_sel = sel_registerName(CString::new("interfaceName").unwrap().as_ptr());
        let iface_name_ns = objc_msgSend(iface, iface_name_sel) as CFStringRef;
        let iface_bsd = cf_string_to_rust(iface_name_ns).unwrap_or_else(|| "en0".to_string());

        if let Ok(out) = std::process::Command::new("/usr/sbin/ipconfig")
            .args(["getsummary", &iface_bsd])
            .output()
        {
            let text = String::from_utf8_lossy(&out.stdout);
            if let Some(ssid) = parse_ipconfig_ssid(&text) {
                return Some((ssid, rate));
            }
        }

        // SSID unavailable (Location Services not granted). If the rate
        // confirms an active association, surface that rather than hiding
        // the Wi-Fi line entirely.
        rate.map(|r| ("Connected".to_string(), Some(r)))
    }
}

/// Parse the SSID from `ipconfig getsummary <iface>` output.
///
/// Returns `None` when the SSID line is absent, empty, or the literal string
/// `<redacted>` (which macOS substitutes when Location Services is not
/// granted to the calling process).
pub fn parse_ipconfig_ssid(output: &str) -> Option<String> {
    output
        .lines()
        .find_map(|l| {
            l.trim()
                .strip_prefix("SSID :")
                .map(|s| s.trim().to_string())
        })
        .filter(|s| !s.is_empty() && s != "<redacted>")
}

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

    #[test]
    fn test_parse_ipconfig_ssid() {
        let normal = "  SSID : MyNetwork\n  BSSID : aa:bb:cc:dd:ee:ff\n";
        assert_eq!(parse_ipconfig_ssid(normal), Some("MyNetwork".to_string()));

        // macOS 10.15+ redacts SSID when Location Services is not granted
        let redacted = "  BSSID : <redacted>\n  SSID : <redacted>\n";
        assert_eq!(parse_ipconfig_ssid(redacted), None);

        // SSID with spaces must be preserved
        let spaces = "  SSID : My Home Network\n";
        assert_eq!(
            parse_ipconfig_ssid(spaces),
            Some("My Home Network".to_string())
        );

        let empty_value = "  SSID : \n";
        assert_eq!(parse_ipconfig_ssid(empty_value), None);

        let no_ssid = "  BSSID : aa:bb:cc:dd:ee:ff\n  Channel : 149\n";
        assert_eq!(parse_ipconfig_ssid(no_ssid), None);
    }
}