brlapi 0.4.1

Safe Rust bindings for the BrlAPI library
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
// SPDX-License-Identifier: LGPL-2.1

//! Key reading and input handling for BrlAPI
//!
//! This module provides functionality for reading key presses from braille keyboards,
//! managing key filtering, and handling key codes.

use crate::{BrlApiError, Result};
use std::time::Duration;

/// Type alias for BrlAPI key codes
pub type KeyCode = brlapi_sys::brlapi_keyCode_t;

/// Represents the result of a key reading operation
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyReadResult {
    /// A key was successfully read
    Key(KeyCode),
    /// No key was available (timeout or non-blocking read)
    NoKey,
    /// Operation was interrupted (signal, parameter change, etc.)
    Interrupted,
}

/// Types of key ranges for filtering operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RangeType {
    /// All keys
    All,
    /// All keys of a given type
    Type,
    /// All keys of a given command block
    Command,
    /// A given key with any flags
    Key,
    /// A given key code
    Code,
}

impl From<RangeType> for brlapi_sys::brlapi_rangeType_t::Type {
    fn from(range_type: RangeType) -> Self {
        match range_type {
            RangeType::All => brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_all,
            RangeType::Type => brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_type,
            RangeType::Command => brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_command,
            RangeType::Key => brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_key,
            RangeType::Code => brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_code,
        }
    }
}

/// A key range for filtering operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyRange {
    /// First key of the range (inclusive)
    pub first: KeyCode,
    /// Last key of the range (inclusive)
    pub last: KeyCode,
}

impl From<KeyRange> for brlapi_sys::brlapi_range_t {
    fn from(range: KeyRange) -> Self {
        brlapi_sys::brlapi_range_t {
            first: range.first,
            last: range.last,
        }
    }
}

impl KeyRange {
    /// Create a new key range
    pub fn new(first: KeyCode, last: KeyCode) -> Self {
        Self { first, last }
    }

    /// Create a key range for a single key
    pub fn single(key: KeyCode) -> Self {
        Self {
            first: key,
            last: key,
        }
    }
}

/// Key expansion result containing the decomposed parts of a key code
///
/// This structure breaks down a BrlAPI key code into its component parts:
/// type, command, argument, and flags. It's the result of calling the
/// `expand_key_code()` function.
///
/// # Example
/// ```no_run
/// use brlapi::{Connection, TtyMode};
/// use brlapi::keys::constants::*;
///
/// fn main() -> Result<(), brlapi::BrlApiError> {
///     let connection = Connection::open()?;
///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
///     let key_reader = tty_mode.key_reader();
///
///     // Expand a command key
///     let expansion = key_reader.expand_key_code(KEY_CMD_HOME)?;
///     println!("Type: {}, Command: {}, Argument: {}, Flags: {}",
///              expansion.key_type, expansion.command, expansion.argument, expansion.flags);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpandedKeyCode {
    /// The key type (command, keysym, etc.)
    pub key_type: u32,
    /// The command number (for braille commands)
    pub command: u32,
    /// The command argument (for commands that take arguments)
    pub argument: u32,
    /// Key modifier flags (shift, ctrl, alt, etc.)
    pub flags: u32,
}

impl From<brlapi_sys::brlapi_expandedKeyCode_t> for ExpandedKeyCode {
    fn from(expanded: brlapi_sys::brlapi_expandedKeyCode_t) -> Self {
        Self {
            key_type: expanded.type_,
            command: expanded.command,
            argument: expanded.argument,
            flags: expanded.flags,
        }
    }
}

/// Key description result containing human-readable descriptions of key components
///
/// This structure provides string descriptions for the various parts of a key code.
/// It's the result of calling the `describe_key_code()` function.
#[derive(Debug, Clone)]
pub struct DescribedKeyCode {
    /// Human-readable description of the key type
    pub key_type: Option<String>,
    /// Human-readable description of the command
    pub command: Option<String>,
    /// The command argument (numeric)
    pub argument: u32,
    /// Key modifier flags (numeric)
    pub flags: u32,
    /// Array of human-readable flag descriptions
    pub flag_descriptions: Vec<String>,
    /// The raw expanded values
    pub expanded: ExpandedKeyCode,
}

/// Key reader for handling braille keyboard input
///
/// This struct provides methods for reading keys from the braille keyboard,
/// managing key filtering, and analyzing key codes. It requires an active TTY mode
/// and borrows from the `TtyMode` to ensure TTY mode remains active during its lifetime.
///
/// # Safety
///
/// `KeyReader` can only be created from an active `TtyMode`, ensuring
/// that key operations are only performed when TTY mode is properly active.
/// This prevents runtime errors from attempting key operations without TTY mode.
///
/// # Example
/// ```no_run
/// use brlapi::{Connection, TtyMode};
/// use std::time::Duration;
///
/// fn main() -> Result<(), brlapi::BrlApiError> {
///     let connection = Connection::open()?;
///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
///     let key_reader = tty_mode.key_reader();
///
///     // Read a key with timeout
///     match key_reader.read_key_timeout(Duration::from_secs(5))? {
///         Some(key_code) => {
///             println!("Key pressed: {:016X}", key_code);
///             
///             // Expand and describe the key
///             let expansion = key_reader.expand_key_code(key_code)?;
///             let description = key_reader.describe_key_code(key_code)?;
///             
///             println!("Expansion: {:?}", expansion);
///             if let Some(cmd) = description.command {
///                 println!("Command: {}", cmd);
///             }
///         },
///         None => println!("No key pressed within timeout"),
///     }
///
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct KeyReader<'a> {
    tty_mode: &'a crate::TtyMode<'a>,
}

impl<'a> KeyReader<'a> {
    /// Create a new key reader from an active TTY mode
    ///
    /// This is the safe way to create a KeyReader, ensuring that TTY mode
    /// is active and will remain active for the lifetime of the KeyReader.
    ///
    /// # Safety
    ///
    /// This constructor ensures that key operations can only be performed
    /// when TTY mode is properly active, preventing runtime errors.
    pub fn from_tty_mode(tty_mode: &'a crate::TtyMode<'a>) -> Self {
        Self { tty_mode }
    }

    /// Internal constructor used by TtyMode - kept for compatibility
    ///
    /// This method is used internally by `TtyMode::key_reader()` and similar methods.
    /// It's not meant for direct public use - use `from_tty_mode()` instead.
    #[doc(hidden)]
    pub fn new(tty_mode: &'a crate::TtyMode<'a>) -> Self {
        Self::from_tty_mode(tty_mode)
    }

    /// Helper function to handle BrlAPI key read result patterns
    ///
    /// Converts the tri-state return values from BrlAPI key reading functions
    /// into proper Rust Result types.
    fn handle_key_read_result(result: i32, key_code: KeyCode) -> Result<Option<KeyCode>> {
        match result {
            -1 => Err(BrlApiError::from_brlapi_error()),
            0 => Ok(None),           // No key available/timeout
            1 => Ok(Some(key_code)), // Key read successfully
            _ => Err(BrlApiError::unexpected_return_value(result)), // Unexpected return value
        }
    }

    /// Read a key from the braille keyboard
    ///
    /// # Parameters
    /// - `wait`: If true, block until a key is pressed. If false, return immediately
    ///   if no key is available.
    ///
    /// # Returns
    /// - `Ok(Some(key_code))` if a key was pressed
    /// - `Ok(None)` if no key was available and `wait` was false
    /// - `Err(BrlApiError)` on error or interruption
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, TtyMode};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let key_reader = tty_mode.key_reader();
    ///
    ///     // Non-blocking read
    ///     if let Some(key_code) = key_reader.read_key(false)? {
    ///         println!("Key pressed: {:016X}", key_code);
    ///     } else {
    ///         println!("No key available");
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn read_key(&self, wait: bool) -> Result<Option<KeyCode>> {
        let mut key_code: KeyCode = 0;
        let wait_flag = if wait { 1 } else { 0 };
        // SAFETY: TTY mode connection handle is valid, wait_flag is valid boolean int,
        // key_code is properly initialized mutable reference for output
        let result = unsafe {
            brlapi_sys::brlapi__readKey(
                self.tty_mode.connection().handle_ptr(),
                wait_flag,
                &mut key_code,
            )
        };

        Self::handle_key_read_result(result, key_code)
    }

    /// Read a key from the braille keyboard with a timeout
    ///
    /// # Parameters
    /// - `timeout`: Maximum time to wait for a key press. Use `Duration::ZERO`
    ///   for non-blocking behavior.
    ///
    /// # Returns
    /// - `Ok(Some(key_code))` if a key was pressed
    /// - `Ok(None)` if the timeout expired without a key press
    /// - `Err(BrlApiError)` on error or interruption
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, TtyMode};
    /// use std::time::Duration;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let key_reader = tty_mode.key_reader();
    ///
    ///     // Wait up to 3 seconds for a key press
    ///     match key_reader.read_key_timeout(Duration::from_secs(3))? {
    ///         Some(key_code) => println!("Key pressed: {:016X}", key_code),
    ///         None => println!("Timeout - no key pressed"),
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn read_key_timeout(&self, timeout: Duration) -> Result<Option<KeyCode>> {
        let mut key_code: KeyCode = 0;
        let timeout_ms = if timeout.is_zero() {
            0
        } else if timeout >= Duration::from_millis(i32::MAX as u64) {
            -1 // Infinite timeout
        } else {
            timeout.as_millis() as i32
        };

        // SAFETY: timeout_ms is valid timeout value, key_code is properly initialized mutable reference
        let result = unsafe { brlapi_sys::brlapi_readKeyWithTimeout(timeout_ms, &mut key_code) };

        Self::handle_key_read_result(result, key_code)
    }

    /// Accept specific keys for the application
    ///
    /// This tells the server to send the specified keys to the application
    /// rather than passing them to BRLTTY.
    ///
    /// # Parameters
    /// - `range_type`: The type of key range to accept
    /// - `keys`: Array of key codes to accept
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, TtyMode, keys::RangeType};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let key_reader = tty_mode.key_reader();
    ///
    ///     // Accept specific key codes
    ///     let keys = [0x01, 0x02, 0x03];
    ///     key_reader.accept_keys(RangeType::Code, &keys)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn accept_keys(&self, range_type: RangeType, keys: &[KeyCode]) -> Result<()> {
        crate::brlapi_call!(unsafe {
            brlapi_sys::brlapi_acceptKeys(range_type.into(), keys.as_ptr(), keys.len() as u32)
        })?;
        Ok(())
    }

    /// Ignore specific keys for the application
    ///
    /// This tells the server to pass the specified keys to BRLTTY
    /// rather than sending them to the application.
    ///
    /// # Parameters
    /// - `range_type`: The type of key range to ignore
    /// - `keys`: Array of key codes to ignore
    pub fn ignore_keys(&self, range_type: RangeType, keys: &[KeyCode]) -> Result<()> {
        crate::brlapi_call!(unsafe {
            brlapi_sys::brlapi_ignoreKeys(range_type.into(), keys.as_ptr(), keys.len() as u32)
        })?;
        Ok(())
    }

    /// Accept key ranges for the application
    ///
    /// This tells the server to send keys in the specified ranges to the application.
    ///
    /// # Parameters
    /// - `ranges`: Array of key ranges to accept
    pub fn accept_key_ranges(&self, ranges: &[KeyRange]) -> Result<()> {
        let c_ranges: Vec<brlapi_sys::brlapi_range_t> = ranges.iter().map(|&r| r.into()).collect();
        crate::brlapi_call!(unsafe {
            brlapi_sys::brlapi_acceptKeyRanges(c_ranges.as_ptr(), ranges.len() as u32)
        })?;
        Ok(())
    }

    /// Ignore key ranges for the application
    ///
    /// This tells the server to pass keys in the specified ranges to BRLTTY.
    ///
    /// # Parameters
    /// - `ranges`: Array of key ranges to ignore
    pub fn ignore_key_ranges(&self, ranges: &[KeyRange]) -> Result<()> {
        let c_ranges: Vec<brlapi_sys::brlapi_range_t> = ranges.iter().map(|&r| r.into()).collect();
        crate::brlapi_call!(unsafe {
            brlapi_sys::brlapi_ignoreKeyRanges(c_ranges.as_ptr(), ranges.len() as u32)
        })?;
        Ok(())
    }

    /// Accept all keys for the application
    ///
    /// This tells the server to send all keys to the application.
    /// Warning: Make sure to ignore important system keys like virtual terminal switching.
    pub fn accept_all_keys(&self) -> Result<()> {
        crate::brlapi_call!(unsafe {
            brlapi_sys::brlapi__acceptAllKeys(self.tty_mode.connection().handle_ptr())
        })?;
        Ok(())
    }

    /// Ignore all keys for the application
    ///
    /// This tells the server to pass all keys to BRLTTY (default behavior).
    pub fn ignore_all_keys(&self) -> Result<()> {
        crate::brlapi_call!(unsafe { brlapi_sys::brlapi_ignoreAllKeys() })?;
        Ok(())
    }

    /// Get the TTY mode this key reader is associated with
    pub fn tty_mode(&self) -> &crate::TtyMode<'a> {
        self.tty_mode
    }

    /// Get the connection this key reader is associated with
    pub fn connection(&self) -> &crate::Connection {
        self.tty_mode.connection()
    }

    /// Expand a key code into its component parts
    ///
    /// This function breaks down a BrlAPI key code into its component parts:
    /// type, command, argument, and flags. This is useful for analyzing and
    /// understanding key presses in detail.
    ///
    /// # Parameters
    /// - `key_code`: The key code to expand
    ///
    /// # Returns
    /// - `Ok(ExpandedKeyCode)` containing the decomposed key parts
    /// - `Err(BrlApiError)` on error
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, TtyMode};
    /// use brlapi::keys::constants::*;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let key_reader = tty_mode.key_reader();
    ///
    ///     // Expand a command key
    ///     let expansion = key_reader.expand_key_code(KEY_CMD_HOME)?;
    ///     println!("Type: {}, Command: {}, Argument: {}, Flags: {}",
    ///              expansion.key_type, expansion.command, expansion.argument, expansion.flags);
    ///
    ///     // Expand a key with modifier flags
    ///     let key_with_ctrl = KEY_CMD_HOME | KEY_FLG_CONTROL;
    ///     let expansion = key_reader.expand_key_code(key_with_ctrl)?;
    ///     println!("Flags: {:#x}", expansion.flags);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn expand_key_code(&self, key_code: KeyCode) -> Result<ExpandedKeyCode> {
        let mut expansion: brlapi_sys::brlapi_expandedKeyCode_t = unsafe { std::mem::zeroed() };

        crate::brlapi_call!(unsafe { brlapi_sys::brlapi_expandKeyCode(key_code, &mut expansion) })?;

        Ok(ExpandedKeyCode::from(expansion))
    }

    /// Describe a key code with human-readable strings
    ///
    /// This function provides human-readable descriptions for the various parts
    /// of a key code, including string representations of the type, command,
    /// and individual flag names.
    ///
    /// # Parameters
    /// - `key_code`: The key code to describe
    ///
    /// # Returns
    /// - `Ok(DescribedKeyCode)` containing human-readable descriptions
    /// - `Err(BrlApiError)` on error
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, TtyMode};
    /// use brlapi::keys::constants::*;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let key_reader = tty_mode.key_reader();
    ///
    ///     // Describe a command key
    ///     let description = key_reader.describe_key_code(KEY_CMD_HOME)?;
    ///     if let Some(cmd) = &description.command {
    ///         println!("Command: {}", cmd);
    ///     }
    ///     
    ///     // Describe a key with flags
    ///     let key_with_flags = KEY_CMD_HOME | KEY_FLG_CONTROL | KEY_FLG_SHIFT;
    ///     let description = key_reader.describe_key_code(key_with_flags)?;
    ///     for flag_desc in &description.flag_descriptions {
    ///         println!("Flag: {}", flag_desc);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn describe_key_code(&self, key_code: KeyCode) -> Result<DescribedKeyCode> {
        let mut description: brlapi_sys::brlapi_describedKeyCode_t = unsafe { std::mem::zeroed() };

        crate::brlapi_call!(unsafe {
            brlapi_sys::brlapi_describeKeyCode(key_code, &mut description)
        })?;

        // Extract string descriptions
        let key_type = if description.type_.is_null() {
            None
        } else {
            let c_str = unsafe { std::ffi::CStr::from_ptr(description.type_) };
            c_str.to_str().ok().map(|s| s.to_owned())
        };

        let command = if description.command.is_null() {
            None
        } else {
            let c_str = unsafe { std::ffi::CStr::from_ptr(description.command) };
            c_str.to_str().ok().map(|s| s.to_owned())
        };

        // Extract flag descriptions
        let mut flag_descriptions = Vec::new();
        for i in 0..32 {
            if !description.flag[i].is_null() {
                let c_str = unsafe { std::ffi::CStr::from_ptr(description.flag[i]) };
                if let Ok(flag_str) = c_str.to_str() {
                    if !flag_str.is_empty() {
                        flag_descriptions.push(flag_str.to_owned());
                    }
                }
            }
        }

        Ok(DescribedKeyCode {
            key_type,
            command,
            argument: description.argument,
            flags: description.flags,
            flag_descriptions,
            expanded: ExpandedKeyCode::from(description.values),
        })
    }
}

/// Utility functions for key handling
pub mod util {
    use super::*;

    /// Read a single key with a timeout (convenience function)
    ///
    /// This is a convenience function that handles connection and TTY mode setup
    /// automatically for a single key read operation.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::keys::util;
    /// use std::time::Duration;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     match util::read_key_timeout(Duration::from_secs(5))? {
    ///         Some(key_code) => println!("Key pressed: {:016X}", key_code),
    ///         None => println!("No key pressed within timeout"),
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn read_key_timeout(timeout: Duration) -> Result<Option<KeyCode>> {
        use crate::{Connection, TtyMode};

        let connection = Connection::open()?;
        let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
        let key_reader = tty_mode.key_reader();

        key_reader.read_key_timeout(timeout)
    }

    /// Read a single key with blocking (convenience function)
    ///
    /// This is a convenience function that handles connection and TTY mode setup
    /// automatically for a single blocking key read operation.
    pub fn read_key_blocking() -> Result<KeyCode> {
        use crate::{Connection, TtyMode};

        let connection = Connection::open()?;
        let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
        let key_reader = tty_mode.key_reader();

        match key_reader.read_key(true)? {
            Some(key_code) => Ok(key_code),
            None => unreachable!("Blocking read should never return None"),
        }
    }

    /// Expand a key code into its component parts (convenience function)
    ///
    /// This is a convenience function that handles connection and TTY mode setup
    /// automatically for a single key expansion operation.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::keys::{util, constants::*};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let expansion = util::expand_key_code(KEY_CMD_HOME)?;
    ///     println!("Type: {}, Command: {}, Argument: {}, Flags: {}",
    ///              expansion.key_type, expansion.command, expansion.argument, expansion.flags);
    ///     Ok(())
    /// }
    /// ```
    pub fn expand_key_code(key_code: KeyCode) -> Result<ExpandedKeyCode> {
        use crate::{Connection, TtyMode};

        let connection = Connection::open()?;
        let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
        let key_reader = tty_mode.key_reader();

        key_reader.expand_key_code(key_code)
    }

    /// Describe a key code with human-readable strings (convenience function)
    ///
    /// This is a convenience function that handles connection and TTY mode setup
    /// automatically for a single key description operation.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::keys::{util, constants::*};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let description = util::describe_key_code(KEY_CMD_HOME)?;
    ///     if let Some(cmd) = &description.command {
    ///         println!("Command: {}", cmd);
    ///     }
    ///     for flag_desc in &description.flag_descriptions {
    ///         println!("Flag: {}", flag_desc);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn describe_key_code(key_code: KeyCode) -> Result<DescribedKeyCode> {
        use crate::{Connection, TtyMode};

        let connection = Connection::open()?;
        let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
        let key_reader = tty_mode.key_reader();

        key_reader.describe_key_code(key_code)
    }
}

/// Key code constants and utilities
///
/// This module provides constants for BrlAPI key codes, including:
/// - Braille command codes
/// - Standard X keysym constants  
/// - Key flags and modifiers
/// - Utility functions for working with key codes
pub mod constants {
    use super::KeyCode;

    // Key type masks and constants

    /// Mask for extracting key flags from a key code
    ///
    /// Key flags occupy the upper 32 bits of a 64-bit key code and include
    /// modifier keys like Shift, Ctrl, Alt, etc.
    pub const KEY_FLAGS_MASK: KeyCode = 0xFFFFFFFF00000000;

    /// Bit shift amount for key flags in a key code
    ///
    /// Corresponds to `BRLAPI_KEY_FLAGS_SHIFT` in BrlAPI.
    pub const KEY_FLAGS_SHIFT: u32 = brlapi_sys::BRLAPI_KEY_FLAGS_SHIFT;

    /// Mask for extracting key type from a key code
    ///
    /// Key type distinguishes between braille commands (KEY_TYPE_CMD) and
    /// X11 keysyms (KEY_TYPE_SYM).
    pub const KEY_TYPE_MASK: KeyCode = 0x00000000E0000000;

    /// Key type identifier for braille commands
    ///
    /// Commands are braille-specific operations like cursor movement,
    /// scrolling, and navigation.
    pub const KEY_TYPE_CMD: KeyCode = 0x0000000020000000;

    /// Key type identifier for X11 keysyms
    ///
    /// Keysyms represent standard keyboard keys and Unicode characters.
    pub const KEY_TYPE_SYM: KeyCode = 0x0000000000000000;

    /// Mask for extracting the base key code (without type or flags)
    pub const KEY_CODE_MASK: KeyCode = 0x000000001FFFFFFF;

    // Command-specific masks and constants

    /// Mask for extracting command block from a braille command key code
    ///
    /// Commands are organized into blocks, with each block containing
    /// related functionality (movement, editing, etc.).
    pub const KEY_CMD_BLK_MASK: KeyCode = 0x1FFF0000;

    /// Mask for extracting command argument from a braille command key code
    ///
    /// Some commands take arguments (e.g., cursor routing to specific cell).
    pub const KEY_CMD_ARG_MASK: KeyCode = 0x0000FFFF;

    // X11 modifier key flags

    /// Shift modifier key flag
    ///
    /// Corresponds to the Shift key being held during key press.
    /// Based on X11 ShiftMask.
    pub const KEY_FLG_SHIFT: KeyCode = 0x0000000100000000;

    /// Caps Lock modifier key flag
    ///
    /// Corresponds to Caps Lock state being active.
    /// Based on X11 LockMask.
    pub const KEY_FLG_LOCK: KeyCode = 0x0000000200000000;

    /// Control modifier key flag
    ///
    /// Corresponds to the Ctrl key being held during key press.
    /// Based on X11 ControlMask.
    pub const KEY_FLG_CONTROL: KeyCode = 0x0000000400000000;

    /// Alt/Meta modifier key flag
    ///
    /// Corresponds to the Alt or Meta key being held during key press.
    /// Based on X11 Mod1Mask.
    pub const KEY_FLG_MOD1: KeyCode = 0x0000000800000000;

    /// Num Lock modifier key flag
    ///
    /// Corresponds to Num Lock state being active.
    /// Based on X11 Mod2Mask.
    pub const KEY_FLG_MOD2: KeyCode = 0x0000001000000000;

    /// Modifier 3 key flag
    ///
    /// Additional modifier key, usage varies by system.
    /// Based on X11 Mod3Mask.
    pub const KEY_FLG_MOD3: KeyCode = 0x0000002000000000;

    /// Super/Windows modifier key flag
    ///
    /// Corresponds to the Super (Windows) key being held during key press.
    /// Based on X11 Mod4Mask.
    pub const KEY_FLG_MOD4: KeyCode = 0x0000004000000000;

    /// AltGr modifier key flag
    ///
    /// Corresponds to the AltGr key being held during key press.
    /// Based on X11 Mod5Mask.
    pub const KEY_FLG_MOD5: KeyCode = 0x0000008000000000;

    // Driver-specific key constants

    /// Driver key press indicator
    ///
    /// This flag indicates a driver-specific key press event.
    /// Used for hardware-specific keys that don't map to standard keysyms.
    pub const DRV_KEY_PRESS: KeyCode = 0x8000000000000000;

    // X11 keysyms for standard keyboard keys

    /// Backspace key
    ///
    /// Corresponds to X11 keysym XK_BackSpace (0xFF08).
    pub const KEY_SYM_BACKSPACE: KeyCode = 0x0000FF08;

    /// Tab key
    ///
    /// Corresponds to X11 keysym XK_Tab (0xFF09).
    pub const KEY_SYM_TAB: KeyCode = 0x0000FF09;

    /// Line feed key
    ///
    /// Corresponds to X11 keysym XK_Linefeed (0xFF0A).
    /// Note: The value here appears to be 0xFF0D which may be Return/Enter.
    pub const KEY_SYM_LINEFEED: KeyCode = 0x0000FF0D;

    /// Escape key
    ///
    /// Corresponds to X11 keysym XK_Escape (0xFF1B).
    pub const KEY_SYM_ESCAPE: KeyCode = 0x0000FF1B;

    /// Home key
    ///
    /// Corresponds to X11 keysym XK_Home (0xFF50).
    pub const KEY_SYM_HOME: KeyCode = 0x0000FF50;

    /// Left arrow key
    ///
    /// Corresponds to X11 keysym XK_Left (0xFF51).
    pub const KEY_SYM_LEFT: KeyCode = 0x0000FF51;

    /// Up arrow key
    ///
    /// Corresponds to X11 keysym XK_Up (0xFF52).
    pub const KEY_SYM_UP: KeyCode = 0x0000FF52;

    /// Right arrow key
    ///
    /// Corresponds to X11 keysym XK_Right (0xFF53).
    pub const KEY_SYM_RIGHT: KeyCode = 0x0000FF53;

    /// Down arrow key
    ///
    /// Corresponds to X11 keysym XK_Down (0xFF54).
    pub const KEY_SYM_DOWN: KeyCode = 0x0000FF54;

    /// Page Up key
    ///
    /// Corresponds to X11 keysym XK_Page_Up (0xFF55).
    pub const KEY_SYM_PAGE_UP: KeyCode = 0x0000FF55;

    /// Page Down key
    ///
    /// Corresponds to X11 keysym XK_Page_Down (0xFF56).
    pub const KEY_SYM_PAGE_DOWN: KeyCode = 0x0000FF56;

    /// End key
    ///
    /// Corresponds to X11 keysym XK_End (0xFF57).
    pub const KEY_SYM_END: KeyCode = 0x0000FF57;

    /// Insert key
    ///
    /// Corresponds to X11 keysym XK_Insert (0xFF63).
    pub const KEY_SYM_INSERT: KeyCode = 0x0000FF63;

    /// Delete key
    ///
    /// Corresponds to X11 keysym XK_Delete (0xFFFF).
    pub const KEY_SYM_DELETE: KeyCode = 0x0000FFFF;

    /// Unicode character indicator
    ///
    /// This flag in a keysym indicates that the lower bits contain
    /// a Unicode codepoint rather than an X11 keysym.
    pub const KEY_SYM_UNICODE: KeyCode = 0x01000000;

    // Braille-specific commands

    /// Base value for braille command key codes
    ///
    /// This corresponds to `BRLAPI_KEY_CMD(0)` in BrlAPI and serves as the
    /// foundation for calculating specific command codes.
    const KEY_CMD_BASE: KeyCode = KEY_TYPE_CMD;

    /// No operation command
    ///
    /// A null command that performs no action.
    /// Corresponds to BrlAPI command index 0.
    pub const KEY_CMD_NOOP: KeyCode = KEY_CMD_BASE;

    /// Move up one line
    ///
    /// Scrolls the braille display up by one line of text.
    /// Corresponds to BrlAPI command index 1.
    pub const KEY_CMD_LNUP: KeyCode = KEY_CMD_BASE + 1;

    /// Move down one line
    ///
    /// Scrolls the braille display down by one line of text.
    /// Corresponds to BrlAPI command index 2.
    pub const KEY_CMD_LNDN: KeyCode = KEY_CMD_BASE + 2;

    /// Move up one window
    ///
    /// Scrolls the braille display up by one full window (display height).
    /// Corresponds to BrlAPI command index 3.
    pub const KEY_CMD_WINUP: KeyCode = KEY_CMD_BASE + 3;

    /// Move down one window
    ///
    /// Scrolls the braille display down by one full window (display height).
    /// Corresponds to BrlAPI command index 4.
    pub const KEY_CMD_WINDN: KeyCode = KEY_CMD_BASE + 4;

    /// Move to top of document
    ///
    /// Jumps the braille display to the beginning of the document.
    /// Corresponds to BrlAPI command index 9.
    pub const KEY_CMD_TOP: KeyCode = KEY_CMD_BASE + 9;

    /// Move to bottom of document
    ///
    /// Jumps the braille display to the end of the document.
    /// Corresponds to BrlAPI command index 10.
    pub const KEY_CMD_BOT: KeyCode = KEY_CMD_BASE + 10;

    /// Move to cursor position
    ///
    /// Centers the braille display on the current cursor location.
    /// Corresponds to BrlAPI command index 29.
    pub const KEY_CMD_HOME: KeyCode = KEY_CMD_BASE + 29;

    /// Move back to previous position
    ///
    /// Returns to the previously viewed position on the braille display.
    /// Corresponds to BrlAPI command index 30.
    pub const KEY_CMD_BACK: KeyCode = KEY_CMD_BASE + 30;

    /// Confirm/activate current item
    ///
    /// Activates the currently focused element or confirms an action.
    /// Corresponds to BrlAPI command index 31.
    pub const KEY_CMD_RETURN: KeyCode = KEY_CMD_BASE + 31;

    /// Freeze/unfreeze display
    ///
    /// Toggles whether the braille display updates automatically.
    /// Corresponds to BrlAPI command index 32.
    pub const KEY_CMD_FREEZE: KeyCode = KEY_CMD_BASE + 32;

    // Character and word movement commands

    /// Move left one character
    ///
    /// Shifts the braille display left by one character.
    /// Corresponds to BrlAPI command index 19.
    pub const KEY_CMD_CHRLT: KeyCode = KEY_CMD_BASE + 19;

    /// Move right one character
    ///
    /// Shifts the braille display right by one character.
    /// Corresponds to BrlAPI command index 20.
    pub const KEY_CMD_CHRRT: KeyCode = KEY_CMD_BASE + 20;

    /// Move left to start of window
    ///
    /// Shifts the braille display to show the leftmost part of the line.
    /// Corresponds to BrlAPI command index 23.
    pub const KEY_CMD_FWINLT: KeyCode = KEY_CMD_BASE + 23;

    /// Move right to end of window
    ///
    /// Shifts the braille display to show the rightmost part of the line.
    /// Corresponds to BrlAPI command index 24.
    pub const KEY_CMD_FWINRT: KeyCode = KEY_CMD_BASE + 24;

    /// Move to beginning of line
    ///
    /// Positions the braille display at the start of the current line.
    /// Corresponds to BrlAPI command index 27.
    pub const KEY_CMD_LNBEG: KeyCode = KEY_CMD_BASE + 27;

    /// Move to end of line
    ///
    /// Positions the braille display at the end of the current line.
    /// Corresponds to BrlAPI command index 28.
    pub const KEY_CMD_LNEND: KeyCode = KEY_CMD_BASE + 28;

    // Commands that accept arguments

    /// Cursor routing command
    ///
    /// Routes the cursor to a specific cell on the braille display.
    /// The cell number is specified in the command argument.
    /// Uses command block 1.
    pub const KEY_CMD_ROUTE: KeyCode = KEY_TYPE_CMD | (1 << 16);

    /// Paste command
    ///
    /// Pastes content at a specific location.
    /// The location is specified in the command argument.
    /// Uses command block 2.
    pub const KEY_CMD_PASTE: KeyCode = KEY_TYPE_CMD | (2 << 16);

    /// Utility functions for working with key codes
    pub mod utils {
        use super::*;

        /// Check if a key code represents a braille command
        pub const fn is_braille_command(key: KeyCode) -> bool {
            (key & KEY_TYPE_MASK) == KEY_TYPE_CMD
        }

        /// Check if a key code represents an X keysym
        pub const fn is_keysym(key: KeyCode) -> bool {
            (key & KEY_TYPE_MASK) == KEY_TYPE_SYM
        }

        /// Extract the command part from a braille command key code
        pub const fn get_command(key: KeyCode) -> u32 {
            ((key & KEY_CMD_BLK_MASK) >> 16) as u32
        }

        /// Extract the argument part from a braille command key code
        pub const fn get_argument(key: KeyCode) -> u32 {
            (key & KEY_CMD_ARG_MASK) as u32
        }

        /// Extract the flags from any key code
        pub const fn get_flags(key: KeyCode) -> u32 {
            ((key & KEY_FLAGS_MASK) >> KEY_FLAGS_SHIFT) as u32
        }

        /// Check if a key code has a specific flag set
        pub const fn has_flag(key: KeyCode, flag: KeyCode) -> bool {
            (key & flag) != 0
        }

        /// Check if a key code represents a Unicode character
        pub const fn is_unicode_keysym(key: KeyCode) -> bool {
            is_keysym(key) && (key & KEY_SYM_UNICODE) != 0
        }

        /// Extract Unicode value from a Unicode keysym
        pub const fn get_unicode_value(key: KeyCode) -> Option<u32> {
            if is_unicode_keysym(key) {
                Some((key & (KEY_SYM_UNICODE - 1)) as u32)
            } else {
                None
            }
        }

        /// Create a braille command key code
        pub const fn make_command(command: u32, argument: u32) -> KeyCode {
            KEY_TYPE_CMD | ((command as KeyCode) << 16) | (argument as KeyCode & KEY_CMD_ARG_MASK)
        }

        /// Create a routing command for a specific cell
        pub const fn make_route_command(cell: u32) -> KeyCode {
            make_command((KEY_CMD_ROUTE >> 16) as u32, cell)
        }

        /// Add flags to a key code
        pub const fn add_flags(key: KeyCode, flags: KeyCode) -> KeyCode {
            key | (flags & KEY_FLAGS_MASK)
        }

        /// Format a key code as a hexadecimal string
        pub fn format_key(key: KeyCode) -> String {
            format!("{:016X}", key)
        }
    }
}

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

    #[test]
    fn test_key_range_creation() {
        let range = KeyRange::new(0x100, 0x200);
        assert_eq!(range.first, 0x100);
        assert_eq!(range.last, 0x200);

        let single = KeyRange::single(0x100);
        assert_eq!(single.first, 0x100);
        assert_eq!(single.last, 0x100);
    }

    #[test]
    fn test_range_type_conversion() {
        assert_eq!(
            brlapi_sys::brlapi_rangeType_t::Type::from(RangeType::All),
            brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_all
        );
        assert_eq!(
            brlapi_sys::brlapi_rangeType_t::Type::from(RangeType::Type),
            brlapi_sys::brlapi_rangeType_t::brlapi_rangeType_type
        );
    }

    #[test]
    fn test_key_constants() {
        use constants::*;

        // Test that key constants are reasonable values
        assert!(KEY_SYM_TAB > 0);
        assert!(KEY_SYM_ESCAPE > 0);
        assert!(KEY_CMD_HOME > 0);

        // Test key type detection
        assert!(constants::utils::is_keysym(KEY_SYM_TAB));
        assert!(constants::utils::is_braille_command(KEY_CMD_HOME));

        // Test command creation
        let route_cmd = constants::utils::make_route_command(5);
        assert!(constants::utils::is_braille_command(route_cmd));
        assert_eq!(constants::utils::get_argument(route_cmd), 5);
    }

    #[test]
    fn test_key_reader_creation() {
        // Test KeyReader creation through the proper API
        use crate::{Connection, TtyMode};

        // Test the API structure without relying on daemon availability
        match Connection::open() {
            Ok(connection) => {
                println!("BrlAPI connection available for KeyReader test");

                // Test that KeyReader can be created from TtyMode
                match TtyMode::enter_auto(&connection, None) {
                    Ok((tty_mode, tty_num)) => {
                        println!("TTY mode entered ({}), creating KeyReader", tty_num);

                        // This demonstrates the correct API usage
                        let key_reader = tty_mode.key_reader();

                        // Verify we can access the underlying types
                        let _tty_ref = key_reader.tty_mode();
                        let _conn_ref = key_reader.connection();

                        println!("KeyReader created successfully through TtyMode");

                        // TTY mode will automatically exit when tty_mode drops
                    }
                    Err(e) => {
                        println!(
                            "TTY mode failed: {} (expected if no daemon or permissions)",
                            e
                        );
                    }
                }

                // Connection will automatically close when connection drops
            }
            Err(e) => {
                println!("BrlAPI connection failed: {} (expected if no daemon)", e);
                // Test still passes - we're just checking API structure
            }
        }

        // Test always passes - we're documenting the correct usage pattern
        assert!(true, "KeyReader API structure test completed");
    }

    #[test]
    fn test_key_expansion_and_description() {
        use crate::{Connection, TtyMode};
        use constants::*;

        // Test that key expansion and description work without requiring actual keys
        match Connection::open() {
            Ok(connection) => {
                println!("BrlAPI connection available for key expansion test");

                match TtyMode::enter_auto(&connection, None) {
                    Ok((tty_mode, tty_num)) => {
                        println!("TTY mode entered ({}), testing key expansion", tty_num);

                        let key_reader = tty_mode.key_reader();

                        // Test expansion of a simple command key
                        match key_reader.expand_key_code(KEY_CMD_HOME) {
                            Ok(expansion) => {
                                println!("Key expansion succeeded for KEY_CMD_HOME");
                                println!(
                                    "  Type: {}, Command: {}, Argument: {}, Flags: {}",
                                    expansion.key_type,
                                    expansion.command,
                                    expansion.argument,
                                    expansion.flags
                                );

                                // The command should be non-zero since it's a real command
                                assert!(expansion.command > 0, "Command should be non-zero");
                                assert_eq!(
                                    expansion.argument, 0,
                                    "Simple commands should have no argument"
                                );
                                assert_eq!(
                                    expansion.flags, 0,
                                    "Simple commands should have no flags"
                                );
                            }
                            Err(e) => {
                                println!("Key expansion failed: {} (this may be expected)", e);
                            }
                        }

                        // Test expansion with flags
                        let key_with_flags = KEY_CMD_HOME | KEY_FLG_CONTROL;
                        match key_reader.expand_key_code(key_with_flags) {
                            Ok(expansion) => {
                                println!("Key expansion with flags succeeded");
                                println!("  Flags: {:#x}", expansion.flags);
                                assert!(expansion.flags > 0, "Should have flags set");
                            }
                            Err(e) => {
                                println!(
                                    "Key expansion with flags failed: {} (this may be expected)",
                                    e
                                );
                            }
                        }

                        // Test key description
                        match key_reader.describe_key_code(KEY_CMD_HOME) {
                            Ok(description) => {
                                println!("[SUCCESS] Key description succeeded for KEY_CMD_HOME");
                                if let Some(cmd) = &description.command {
                                    println!("  Command description: {}", cmd);
                                }
                                if let Some(key_type) = &description.key_type {
                                    println!("  Type description: {}", key_type);
                                }

                                // The description should contain useful information
                                assert!(
                                    description.command.is_some() || description.key_type.is_some(),
                                    "Description should contain some information"
                                );
                            }
                            Err(e) => {
                                println!("Key description failed: {} (this may be expected)", e);
                            }
                        }

                        // Test description with flags
                        let key_with_multiple_flags =
                            KEY_CMD_HOME | KEY_FLG_CONTROL | KEY_FLG_SHIFT;
                        match key_reader.describe_key_code(key_with_multiple_flags) {
                            Ok(description) => {
                                println!("[SUCCESS] Key description with flags succeeded");
                                println!(
                                    "  Flag descriptions count: {}",
                                    description.flag_descriptions.len()
                                );
                                for (i, flag_desc) in
                                    description.flag_descriptions.iter().enumerate()
                                {
                                    println!("    Flag {}: {}", i, flag_desc);
                                }

                                // Should have flag descriptions for the modifiers
                                assert!(
                                    !description.flag_descriptions.is_empty(),
                                    "Should have flag descriptions"
                                );
                            }
                            Err(e) => {
                                println!(
                                    "Key description with flags failed: {} (this may be expected)",
                                    e
                                );
                            }
                        }

                        println!("[SUCCESS] Key expansion and description API test completed");
                    }
                    Err(e) => {
                        println!(
                            "TTY mode failed: {} (expected if no daemon or permissions)",
                            e
                        );
                    }
                }
            }
            Err(e) => {
                println!("BrlAPI connection failed: {} (expected if no daemon)", e);
            }
        }

        // Test always passes - we're documenting the API behavior
        assert!(true, "Key expansion and description API test completed");
    }

    #[test]
    fn test_expanded_key_code_from_conversion() {
        use brlapi_sys::brlapi_expandedKeyCode_t;

        // Test that the From trait conversion works correctly
        let raw_expansion = brlapi_expandedKeyCode_t {
            type_: 1,
            command: 2,
            argument: 3,
            flags: 4,
        };

        let expansion = ExpandedKeyCode::from(raw_expansion);

        assert_eq!(expansion.key_type, 1);
        assert_eq!(expansion.command, 2);
        assert_eq!(expansion.argument, 3);
        assert_eq!(expansion.flags, 4);
    }

    #[test]
    fn test_key_utility_functions() {
        use constants::*;

        // Test the utility functions for convenience access
        // These functions should work without requiring a daemon connection for basic tests

        // Test that utility constants are properly defined
        assert!(KEY_CMD_HOME > 0);
        assert!(KEY_FLG_CONTROL > 0);
        assert!(KEY_SYM_TAB > 0);

        // Test utility function behavior
        assert!(constants::utils::is_braille_command(KEY_CMD_HOME));
        assert!(constants::utils::is_keysym(KEY_SYM_TAB));
        assert!(!constants::utils::is_braille_command(KEY_SYM_TAB));
        assert!(!constants::utils::is_keysym(KEY_CMD_HOME));

        // Test flag manipulation
        let key_with_flag = constants::utils::add_flags(KEY_CMD_HOME, KEY_FLG_CONTROL);
        assert!(constants::utils::has_flag(key_with_flag, KEY_FLG_CONTROL));
        assert!(!constants::utils::has_flag(KEY_CMD_HOME, KEY_FLG_CONTROL));

        // Test command creation
        let route_cmd = constants::utils::make_route_command(5);
        assert!(constants::utils::is_braille_command(route_cmd));
        assert_eq!(constants::utils::get_argument(route_cmd), 5);

        // Test key formatting
        let formatted = constants::utils::format_key(KEY_CMD_HOME);
        assert!(formatted.len() == 16); // Should be 16 hex digits
        assert!(
            formatted
                .chars()
                .all(|c| c.is_ascii_hexdigit() || c.is_ascii_uppercase())
        );
    }
}