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
// SPDX-License-Identifier: LGPL-2.1

//! Error handling for BrlAPI high-level wrapper

use std::ffi::NulError;
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use thiserror::Error;

/// Comprehensive error type for BrlAPI operations
///
/// This enum encompasses both BrlAPI-specific errors and Rust binding-specific errors
/// to provide clear and actionable error information.
#[derive(Debug, Error)]
pub enum BrlApiError {
    // === BrlAPI Protocol Errors ===
    /// Success (should not occur in error contexts)
    #[doc(hidden)]
    #[error("Success")]
    Success,

    /// Not enough memory
    #[error("Out of memory. The system may be low on available memory")]
    NoMem,

    /// A connection is already running in this TTY
    #[error(
        "The TTY is already in use by another BrlAPI connection. Try a different TTY or close other braille applications"
    )]
    TTYBusy,

    /// A connection is already using RAW or suspend mode
    #[error("The braille device is busy. Another application may be using it in RAW mode")]
    DeviceBusy,

    /// Not implemented in protocol
    #[error("This operation is not implemented in the BrlAPI protocol")]
    UnknownInstruction,

    /// Forbidden in current mode
    #[error("Operation forbidden in current mode")]
    IllegalInstruction,

    /// Out of range or invalid parameter
    #[error("Invalid parameter value provided")]
    InvalidParameter,

    /// Invalid packet size
    #[error("Invalid packet size")]
    InvalidPacket,

    /// Connection refused
    #[error(
        "Failed to connect to BrlAPI server. Is BRLTTY running? Try 'sudo systemctl start brltty'"
    )]
    ConnectionRefused,

    /// Operation not supported
    #[error("This operation is not supported by your braille display or BRLTTY version")]
    OperationNotSupported,

    /// Network address resolution error
    #[error("Network address resolution error")]
    GetAddrInfoError,

    /// System library error
    #[error("System library error occurred")]
    LibCError,

    /// Couldn't find out the TTY number
    #[error(
        "Could not determine which TTY to use. Try running from a console (Ctrl+Alt+F2) or use enter_tty_mode_auto()"
    )]
    UnknownTTY,

    /// Bad protocol version
    #[error(
        "BrlAPI protocol version mismatch. Your BrlAPI library and BRLTTY daemon versions may be incompatible"
    )]
    ProtocolVersion,

    /// Unexpected end of file
    #[error("Unexpected end of file or connection closed")]
    UnexpectedEndOfFile,

    /// Key file empty
    #[error("BrlAPI authentication key file is empty")]
    EmptyKey,

    /// Packet returned by driver too large
    #[error(
        "Braille display driver error. Check your braille device connection and BRLTTY configuration"
    )]
    DriverError,

    /// Authentication failed
    #[error("BrlAPI authentication failed. Check your BrlAPI key or permissions")]
    AuthenticationFailed,

    /// Parameter cannot be changed
    #[error("Parameter cannot be changed (read-only)")]
    ParameterCannotBeChanged,

    // === Rust Binding-Specific Errors ===
    /// Connection timeout (custom error for Rust bindings)
    #[error("Connection attempt timed out. The BrlAPI daemon may be unresponsive or unreachable")]
    ConnectionTimeout,

    /// String contains null bytes (cannot convert to C string)
    #[error("String contains null bytes and cannot be converted to C string: {0}")]
    NullByteInString(#[from] NulError),

    /// Invalid UTF-8 sequence encountered
    #[error("Invalid UTF-8 sequence: {0}")]
    InvalidUtf8(#[from] Utf8Error),

    /// String conversion from bytes failed
    #[error("Failed to convert bytes to UTF-8 string: {0}")]
    StringConversion(#[from] FromUtf8Error),

    /// Unexpected return value from BrlAPI function
    #[error(
        "BrlAPI function returned unexpected value: {value}. This may indicate a protocol error or library bug"
    )]
    UnexpectedReturnValue { value: i32 },

    /// I/O error occurred
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Join error from threading operations
    #[error("Thread join error: {0}")]
    ThreadJoin(String),

    /// Channel communication error for timeout operations
    #[error("Channel communication error during timeout operation")]
    ChannelError,

    /// Contraction/translation error from liblouis
    #[error("Text contraction failed: {0}")]
    ContractionError(#[from] liblouis::LouisError),

    /// Generic error with custom message for extensibility
    #[error("{message}")]
    Custom { message: String },
}

impl BrlApiError {
    /// Convert a BrlAPI C error code to a Rust error
    pub fn from_c_error(error_code: i32) -> Self {
        match error_code as u32 {
            brlapi_sys::brlapi_error::BRLAPI_ERROR_SUCCESS => BrlApiError::Success,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_NOMEM => BrlApiError::NoMem,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_TTYBUSY => BrlApiError::TTYBusy,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_DEVICEBUSY => BrlApiError::DeviceBusy,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_UNKNOWN_INSTRUCTION => {
                BrlApiError::UnknownInstruction
            }
            brlapi_sys::brlapi_error::BRLAPI_ERROR_ILLEGAL_INSTRUCTION => {
                BrlApiError::IllegalInstruction
            }
            brlapi_sys::brlapi_error::BRLAPI_ERROR_INVALID_PARAMETER => {
                BrlApiError::InvalidParameter
            }
            brlapi_sys::brlapi_error::BRLAPI_ERROR_INVALID_PACKET => BrlApiError::InvalidPacket,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_CONNREFUSED => BrlApiError::ConnectionRefused,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_OPNOTSUPP => BrlApiError::OperationNotSupported,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_GAIERR => BrlApiError::GetAddrInfoError,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_LIBCERR => BrlApiError::LibCError,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_UNKNOWNTTY => BrlApiError::UnknownTTY,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_PROTOCOL_VERSION => BrlApiError::ProtocolVersion,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_EOF => BrlApiError::UnexpectedEndOfFile,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_EMPTYKEY => BrlApiError::EmptyKey,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_DRIVERERROR => BrlApiError::DriverError,
            brlapi_sys::brlapi_error::BRLAPI_ERROR_AUTHENTICATION => {
                BrlApiError::AuthenticationFailed
            }
            brlapi_sys::brlapi_error::BRLAPI_ERROR_READONLY_PARAMETER => {
                BrlApiError::ParameterCannotBeChanged
            }
            65536 => BrlApiError::ConnectionTimeout, // Custom timeout error
            _ => BrlApiError::OperationNotSupported, // Default for unknown errors
        }
    }

    /// Get the current BrlAPI error from the global error variables
    ///
    /// This should be called immediately after a BrlAPI function fails
    /// to get the actual error that occurred.
    ///
    /// Note: Falls back to retrieving error from error location if
    /// global errno is not available.
    pub fn get_last_error() -> Self {
        // SAFETY: brlapi_error_location() returns either a valid pointer to error structure
        // or null. If not null, the returned pointer points to valid error data.
        unsafe {
            // Try to get error from error location structure first
            let error_ptr = brlapi_sys::brlapi_error_location();
            if !error_ptr.is_null() {
                let error_struct = &*error_ptr;
                return Self::from_c_error(error_struct.brlerrno as i32);
            }

            // Fall back to a generic error if we can't get the actual error
            BrlApiError::OperationNotSupported
        }
    }

    /// Get error information as a string from BrlAPI
    ///
    /// This retrieves detailed error information from the BrlAPI library.
    pub fn get_error_message() -> Option<String> {
        // SAFETY: brlapi_error_location() returns either a valid pointer to error structure
        // or null. Safe to call and check for null.
        unsafe {
            let error_ptr = brlapi_sys::brlapi_error_location();
            if error_ptr.is_null() {
                return None;
            }

            let message_ptr = brlapi_sys::brlapi_strerror(error_ptr);
            if message_ptr.is_null() {
                return None;
            }

            let c_str = std::ffi::CStr::from_ptr(message_ptr);
            c_str.to_str().ok().map(|s| s.to_string())
        }
    }

    /// Create a BrlApiError from the current BrlAPI error state
    ///
    /// This combines error code conversion with detailed error message retrieval.
    pub fn from_brlapi_error() -> Self {
        Self::get_last_error()
    }

    /// Create a custom error with a message
    pub fn custom(message: impl Into<String>) -> Self {
        BrlApiError::Custom {
            message: message.into(),
        }
    }

    /// Create an error for raw mode not supported by driver
    pub fn raw_mode_not_supported(driver: &str) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Raw mode not supported by driver '{}'. Raw mode is only available for certain hardware drivers.",
                driver
            ),
        }
    }

    /// Create an error for raw mode already in use
    pub fn raw_mode_in_use() -> Self {
        BrlApiError::DeviceBusy // This maps to the existing DeviceBusy variant
    }

    /// Create an error for receive timeout in raw mode
    pub fn raw_mode_receive_timeout(timeout_secs: u64) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Raw mode receive operation timed out after {} seconds. The device may not be responding.",
                timeout_secs
            ),
        }
    }

    /// Create an error for device communication failure in raw mode
    pub fn raw_mode_device_error(details: &str) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Raw mode device communication failed: {}. The device may be disconnected or unresponsive.",
                details
            ),
        }
    }

    /// Create an error for suspend mode operation failure
    pub fn suspend_failed(driver: &str, details: &str) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Failed to suspend driver '{}': {}. The driver may be busy or not support suspension.",
                driver, details
            ),
        }
    }

    /// Create an error for resume mode operation failure
    pub fn resume_failed(driver: &str, details: &str) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Failed to resume driver '{}': {}. Manual intervention may be required.",
                driver, details
            ),
        }
    }

    /// Create an error for driver not found
    pub fn driver_not_found(driver: &str) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Driver '{}' not found or not currently active. Check that the driver is loaded and the device is connected.",
                driver
            ),
        }
    }

    /// Create an error for suspend mode not supported by driver
    pub fn suspend_mode_not_supported(driver: &str) -> Self {
        BrlApiError::Custom {
            message: format!(
                "Suspend mode not supported by driver '{}'. Only certain hardware drivers support complete suspension.",
                driver
            ),
        }
    }

    /// Create an error for when no driver is suspended
    pub fn not_suspended() -> Self {
        BrlApiError::Custom {
            message: "No driver is currently suspended. Resume can only be called when a driver is suspended.".to_string(),
        }
    }

    /// Create an unexpected return value error
    pub fn unexpected_return_value(value: i32) -> Self {
        BrlApiError::UnexpectedReturnValue { value }
    }

    /// Check if this error indicates a connection problem
    pub fn is_connection_error(&self) -> bool {
        matches!(
            self,
            BrlApiError::ConnectionRefused
                | BrlApiError::AuthenticationFailed
                | BrlApiError::GetAddrInfoError
                | BrlApiError::LibCError
                | BrlApiError::ProtocolVersion
                | BrlApiError::UnexpectedEndOfFile
                | BrlApiError::ConnectionTimeout
                | BrlApiError::ChannelError
        )
    }

    /// Check if this error indicates a resource unavailability
    pub fn is_resource_busy(&self) -> bool {
        matches!(
            self,
            BrlApiError::TTYBusy | BrlApiError::DeviceBusy | BrlApiError::NoMem
        )
    }

    /// Check if this error indicates an operation or parameter issue
    pub fn is_operation_error(&self) -> bool {
        matches!(
            self,
            BrlApiError::OperationNotSupported
                | BrlApiError::UnknownInstruction
                | BrlApiError::IllegalInstruction
                | BrlApiError::InvalidParameter
                | BrlApiError::InvalidPacket
                | BrlApiError::ParameterCannotBeChanged
                | BrlApiError::UnexpectedReturnValue { .. }
        )
    }

    /// Check if this error indicates a data conversion issue
    pub fn is_conversion_error(&self) -> bool {
        matches!(
            self,
            BrlApiError::NullByteInString(_)
                | BrlApiError::InvalidUtf8(_)
                | BrlApiError::StringConversion(_)
        )
    }

    /// Check if this error indicates a contraction/translation problem
    pub fn is_contraction_error(&self) -> bool {
        matches!(self, BrlApiError::ContractionError(_))
    }

    /// Get suggestions for resolving this error
    pub fn suggestions(&self) -> Vec<&'static str> {
        match self {
            BrlApiError::ConnectionRefused => vec![
                "Start BRLTTY daemon: sudo systemctl start brltty",
                "Check if BRLTTY is running: systemctl status brltty",
                "Verify BrlAPI is enabled in /etc/brltty.conf",
            ],
            BrlApiError::AuthenticationFailed => vec![
                "Check BrlAPI key file permissions: ls -la /etc/brlapi.key",
                "Add your user to the brlapi group: sudo usermod -a -G brlapi $USER",
                "Restart your session after adding to group",
            ],
            BrlApiError::TTYBusy => vec![
                "Close other braille applications",
                "Try a different virtual console (TTY 2-6)",
                "Check for running braille applications: ps aux | grep brl",
            ],
            BrlApiError::UnknownTTY => vec![
                "Run from a text console: press Ctrl+Alt+F2",
                "Use enter_tty_mode_auto() for automatic TTY detection",
                "Specify a TTY explicitly with enter_tty_mode_with_tty(Some(2))",
            ],
            BrlApiError::DriverError => vec![
                "Check braille display connection (USB/Bluetooth)",
                "Verify correct driver in /etc/brltty.conf",
                "Test display with: sudo brltty -l debug",
            ],
            BrlApiError::ConnectionTimeout => vec![
                "Check if BRLTTY daemon is running: systemctl status brltty",
                "Start BRLTTY daemon: sudo systemctl start brltty",
                "Increase connection timeout with ConnectionSettings::set_timeout()",
                "Check network connectivity if connecting to remote host",
            ],
            BrlApiError::NullByteInString(_) => vec![
                "Remove null bytes (\\0) from your string",
                "Use a different string that doesn't contain null characters",
            ],
            BrlApiError::InvalidUtf8(_) | BrlApiError::StringConversion(_) => vec![
                "Ensure input text is valid UTF-8",
                "Check the source of the text data for encoding issues",
            ],
            _ => vec![],
        }
    }
}

// Implement From traits for easy error conversion
impl<T> From<std::sync::mpsc::SendError<T>> for BrlApiError {
    fn from(_: std::sync::mpsc::SendError<T>) -> Self {
        BrlApiError::ChannelError
    }
}

impl From<std::sync::mpsc::RecvError> for BrlApiError {
    fn from(_: std::sync::mpsc::RecvError) -> Self {
        BrlApiError::ChannelError
    }
}

impl From<std::sync::mpsc::RecvTimeoutError> for BrlApiError {
    fn from(err: std::sync::mpsc::RecvTimeoutError) -> Self {
        match err {
            std::sync::mpsc::RecvTimeoutError::Timeout => BrlApiError::ConnectionTimeout,
            std::sync::mpsc::RecvTimeoutError::Disconnected => BrlApiError::ChannelError,
        }
    }
}

impl<T: std::fmt::Debug> From<std::sync::PoisonError<T>> for BrlApiError {
    fn from(err: std::sync::PoisonError<T>) -> Self {
        BrlApiError::custom(format!("Mutex poisoned: {:?}", err))
    }
}

/// Result type alias for BrlAPI operations
pub type Result<T> = std::result::Result<T, BrlApiError>;

/// Helper macro to convert BrlAPI C function return codes to Results
///
/// This macro wraps BrlAPI function calls and automatically converts
/// error return values to proper BrlApiError types by retrieving the
/// actual error from the BrlAPI error system.
#[macro_export]
macro_rules! brlapi_call {
    ($call:expr) => {{
        let result = $call;
        if result == -1 {
            Err($crate::error::BrlApiError::from_brlapi_error())
        } else {
            Ok(result)
        }
    }};
}