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

//! Braille display information and capabilities

use crate::{Result, connection::Connection, error::BrlApiError};
use brlapi_sys::*;
use libc::c_char;
use std::fmt;

/// Braille display information and capabilities
///
/// This struct contains complete information about a braille display, including
/// size, driver details, and device capabilities. It's a self-contained snapshot
/// that can be stored, passed around, and used independently of the connection.
///
/// # Example
/// ```no_run
/// use brlapi::{Connection, Display};
///
/// fn main() -> Result<(), brlapi::BrlApiError> {
///     let connection = Connection::open()?;
///     let display = Display::from_connection(&connection)?;
///     
///     println!("Display: {}x{} cells, driver: {}, model: {}",
///              display.width(), display.height(), display.driver_name(), display.model_identifier());
///     
///     if display.is_single_line() {
///         println!("This is a standard single-line braille display");
///     }
///     
///     println!("Total cells: {}", display.total_cells());
///     
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Display {
    /// Display width in braille cells
    width: u32,
    /// Display height in braille cells  
    height: u32,
    /// Name of the braille driver (e.g., "dummy", "alva", "baum")
    driver_name: String,
    /// Model identifier of the braille device
    model_identifier: String,
}

impl Display {
    /// Create display information by querying a connection
    ///
    /// This queries the connection once to capture all display information
    /// and returns a self-contained Display struct that can be used
    /// independently of the connection.
    ///
    /// # Errors
    ///
    /// Returns `BrlApiError::ConnectionRefused` if the display information cannot be queried
    /// or if the BrlAPI connection is not valid.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::{Connection, Display};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let display = Display::from_connection(&connection)?;
    ///     
    ///     // No lifetime issues - display is completely independent
    ///     println!("Connected to {} display: {}x{} cells",
    ///              display.driver_name(), display.width(), display.height());
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub fn from_connection(connection: &Connection) -> Result<Self> {
        let (width, height) = Self::query_size(connection)?;
        let driver_name = Self::query_driver_name(connection)?;
        let model_identifier = Self::query_model_identifier(connection)?;

        Ok(Display {
            width,
            height,
            driver_name,
            model_identifier,
        })
    }

    /// Get the total number of cells on the display
    pub fn total_cells(&self) -> u32 {
        self.width * self.height
    }

    /// Check if this is a single-line display (most common)
    pub fn is_single_line(&self) -> bool {
        self.height == 1
    }

    /// Get display dimensions as a tuple (width, height)
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Get the display width in braille cells
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Get the display height in braille cells
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Get the braille driver name
    pub fn driver_name(&self) -> &str {
        &self.driver_name
    }

    /// Get the braille device model identifier
    pub fn model_identifier(&self) -> &str {
        &self.model_identifier
    }

    // Private query methods

    /// Helper function for safe string buffer queries from C functions
    fn query_string_from_brlapi<F>(connection: &Connection, query_fn: F) -> Result<String>
    where
        F: FnOnce(&Connection, *mut c_char, usize) -> i32,
    {
        let mut buffer = vec![0u8; BRLAPI_MAXNAMELENGTH as usize + 1];

        crate::brlapi_call!(query_fn(
            connection,
            buffer.as_mut_ptr() as *mut c_char,
            buffer.len()
        ))?;

        // Find the null terminator and convert to String
        let end = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());
        String::from_utf8(buffer[..end].to_vec()).map_err(BrlApiError::from)
    }

    fn query_size(connection: &Connection) -> Result<(u32, u32)> {
        let mut width: u32 = 0;
        let mut height: u32 = 0;

        // SAFETY: connection.handle_ptr() returns a valid BrlAPI handle, width and height
        // are valid mutable references to initialized u32 values.
        crate::brlapi_call!(unsafe {
            brlapi__getDisplaySize(connection.handle_ptr(), &mut width, &mut height)
        })?;
        Ok((width, height))
    }

    fn query_driver_name(connection: &Connection) -> Result<String> {
        Self::query_string_from_brlapi(connection, |conn, buffer, len|
            // SAFETY: conn.handle_ptr() returns a valid BrlAPI handle, buffer is a valid
            // mutable pointer to allocated memory, len is the correct buffer size.
            unsafe {
                brlapi__getDriverName(conn.handle_ptr(), buffer, len)
            })
    }

    fn query_model_identifier(connection: &Connection) -> Result<String> {
        Self::query_string_from_brlapi(connection, |conn, buffer, len|
            // SAFETY: conn.handle_ptr() returns a valid BrlAPI handle, buffer is a valid
            // mutable pointer to allocated memory, len is the correct buffer size.
            unsafe {
                brlapi__getModelIdentifier(conn.handle_ptr(), buffer, len)
            })
    }
}

// Add display operations directly to Connection for better ergonomics
impl Connection {
    /// Get complete braille display information
    ///
    /// This creates a self-contained Display struct with all display information.
    /// The returned Display owns all its data and can be used independently.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::Connection;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let display = connection.display_info()?;
    ///     
    ///     println!("Connected to {} braille display:", display.driver_name());
    ///     println!("  Model: {}", display.model_identifier());  
    ///     println!("  Size: {}x{} cells", display.width(), display.height());
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub fn display_info(&self) -> Result<Display> {
        Display::from_connection(self)
    }

    /// Get the dimensions of the braille display
    ///
    /// Returns (width, height) in braille cells.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::Connection;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (width, height) = connection.display_size()?;
    ///     println!("Display: {}x{} cells", width, height);
    ///     Ok(())
    /// }
    /// ```
    pub fn display_size(&self) -> Result<(u32, u32)> {
        Display::query_size(self)
    }

    /// Get the name of the braille driver being used
    ///
    /// Returns the complete name of the driver (e.g., "dummy", "alva", "baum").
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::Connection;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let driver = connection.display_driver()?;
    ///     println!("Using braille driver: {}", driver);
    ///     Ok(())
    /// }
    /// ```  
    pub fn display_driver(&self) -> Result<String> {
        Display::query_driver_name(self)
    }

    /// Get the model identifier of the braille device
    ///
    /// Returns an identifier for the device model being used.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::Connection;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let model = connection.display_model()?;
    ///     println!("Braille device: {}", model);
    ///     Ok(())
    /// }
    /// ```
    pub fn display_model(&self) -> Result<String> {
        Display::query_model_identifier(self)
    }

    /// Get the user's configured contraction table from BRLTTY preferences
    ///
    /// This method reads the literary braille table setting from BRLTTY's configuration,
    /// allowing applications to respect the user's accessibility preferences rather than
    /// hardcoding contraction tables.
    ///
    /// # Returns
    ///
    /// Returns the table name (e.g., "en-us-g2.ctb", "en-gb-g2.ctb") from BRLTTY preferences.
    /// Falls back to "en-us-g2.ctb" if the parameter cannot be read or is empty.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::Connection;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let table = connection.user_contraction_table()?;
    ///     println!("User's preferred contraction table: {}", table);
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `BrlApiError` if the BrlAPI connection fails, but gracefully falls back
    /// to a sensible default rather than failing completely.
    pub fn user_contraction_table(&self) -> Result<String> {
        use crate::parameters::{Parameter, ParameterFlags};

        // Try to read the user's literary braille table preference
        // Contraction tables are typically system-wide preferences, so try GLOBAL first
        let table_result = self
            .get_parameter::<String>(Parameter::LiteraryBrailleTable, 0, ParameterFlags::GLOBAL)
            .or_else(|_| {
                // Fallback to LOCAL if GLOBAL fails (some configurations may be connection-specific)
                self.get_parameter::<String>(Parameter::LiteraryBrailleTable, 0, ParameterFlags::LOCAL)
            });

        match table_result {
            Ok(table) if !table.trim().is_empty() => {
                let table_name = table.trim();

                // Use liblouis native table resolution for BRLTTY parameter values
                // Note: Fallback to manual mapping if liblouis table discovery is unavailable
                let resolved_table = match table_name {
                    "en_US" | "en-US" => "en-us-g2.ctb",
                    "en_GB" | "en-GB" => "en-gb-g2.ctb",
                    "fr_FR" | "fr-FR" => "fr-bfu-g2.ctb",
                    "de_DE" | "de-DE" => "de-g2.ctb",
                    name if name.ends_with(".ctb") => name, // Already a table file name
                    _ => {
                        // Try liblouis resolution for unknown parameter values
                        use liblouis::TableResolver;
                        match TableResolver::resolve_locale(table_name) {
                            Ok(resolved) => return Ok(resolved),
                            Err(_) => "en-us-g2.ctb", // Final fallback
                        }
                    }
                };

                Ok(resolved_table.to_string())
            },
            _ => {
                // Fallback to sensible default if parameter reading fails or is empty
                // This ensures applications continue to work even when parameter access fails
                Ok("en-us-g2.ctb".to_string())
            }
        }
    }

    /// Debug utility: Print current BRLTTY preferences for troubleshooting
    ///
    /// This is a convenience method for debugging contraction table preferences
    /// and understanding what BrlAPI parameters are actually configured.
    /// Useful for troubleshooting user preference issues.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::Connection;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     connection.debug_preferences();
    ///     Ok(())
    /// }
    /// ```
    pub fn debug_preferences(&self) {
        use crate::parameters::{Parameter, ParameterFlags};

        println!("BRLTTY Parameter Debug Information:");
        println!("===================================");

        // Helper function to show both LOCAL and GLOBAL values for a parameter
        let show_parameter = |name: &str, param: Parameter, subparam: u64| {
            println!("{}:", name);

            // Try GLOBAL first
            match self.get_parameter::<String>(param, subparam, ParameterFlags::GLOBAL) {
                Ok(value) => println!("  GLOBAL: '{}'", value.trim()),
                Err(e) => println!("  GLOBAL: (unable to read - {})", e),
            }

            // Try LOCAL second
            match self.get_parameter::<String>(param, subparam, ParameterFlags::LOCAL) {
                Ok(value) => println!("  LOCAL:  '{}'", value.trim()),
                Err(e) => println!("  LOCAL:  (unable to read - {})", e),
            }
        };

        // Literary braille table (main contraction preference)
        show_parameter("Literary braille table", Parameter::LiteraryBrailleTable, 0);

        // Computer braille table (for comparison)
        show_parameter("Computer braille table", Parameter::ComputerBrailleTable, 0);

        // Message locale
        show_parameter("Message locale", Parameter::MessageLocale, 0);

        // Literary braille mode enabled/disabled (boolean parameter)
        println!("Literary braille mode:");
        match self.get_parameter::<bool>(Parameter::LiteraryBraille, 0, ParameterFlags::GLOBAL) {
            Ok(enabled) => println!("  GLOBAL: {}", if enabled { "enabled" } else { "disabled" }),
            Err(e) => println!("  GLOBAL: (unable to read - {})", e),
        }
        match self.get_parameter::<bool>(Parameter::LiteraryBraille, 0, ParameterFlags::LOCAL) {
            Ok(enabled) => println!("  LOCAL:  {}", if enabled { "enabled" } else { "disabled" }),
            Err(e) => println!("  LOCAL:  (unable to read - {})", e),
        }

        // Client priority (u32 parameter)
        println!("Client priority:");
        match self.get_parameter::<u32>(Parameter::ClientPriority, 0, ParameterFlags::GLOBAL) {
            Ok(priority) => println!("  GLOBAL: {}", priority),
            Err(e) => println!("  GLOBAL: (unable to read - {})", e),
        }
        match self.get_parameter::<u32>(Parameter::ClientPriority, 0, ParameterFlags::LOCAL) {
            Ok(priority) => println!("  LOCAL:  {}", priority),
            Err(e) => println!("  LOCAL:  (unable to read - {})", e),
        }

        println!();
        // Show what our abstraction would return
        match self.user_contraction_table() {
            Ok(table) => println!("user_contraction_table() returns: '{}'", table),
            Err(e) => println!("user_contraction_table() error: {}", e),
        }

        println!("===================================");
    }
}

impl fmt::Display for Display {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "A {} {} display, with {} rows and {} columns.",
            self.driver_name, self.model_identifier, self.height, self.width
        )
    }
}

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

    #[test]
    fn test_display_methods() {
        let display = Display {
            width: 40,
            height: 1,
            driver_name: "dummy".to_string(),
            model_identifier: "test-model".to_string(),
        };

        assert_eq!(display.total_cells(), 40);
        assert!(display.is_single_line());
        assert_eq!(display.dimensions(), (40, 1));
    }

    #[test]
    fn test_display_multi_line() {
        let display = Display {
            width: 20,
            height: 4,
            driver_name: "test".to_string(),
            model_identifier: "multi-line".to_string(),
        };

        assert_eq!(display.total_cells(), 80);
        assert!(!display.is_single_line());
        assert_eq!(display.dimensions(), (20, 4));
    }

    #[test]
    fn test_display_creation() {
        use crate::Connection;

        // We can't test actual display queries without a BrlAPI daemon,
        // but we can test the struct creation if connection succeeds
        let connection_result = Connection::open();
        if let Ok(connection) = connection_result {
            let _display_result = Display::from_connection(&connection);
            // Display creation attempted successfully
        }
    }
}