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

//! Text output operations for braille displays
//!
//! This module provides functionality for writing text to braille displays.
//! All text operations require the connection to be in TTY mode.

use crate::{Result, brlapi_call};
use brlapi_sys::*;
use libc::wchar_t;
use std::ffi::CString;

/// Cursor position for text display operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CursorPosition {
    /// Leave cursor position unchanged
    Leave,
    /// Turn cursor off (no cursor displayed)
    Off,
    /// Position cursor at specific character position (0-based)
    At(u32),
}

impl From<CursorPosition> for i32 {
    fn from(pos: CursorPosition) -> i32 {
        match pos {
            CursorPosition::Leave => BRLAPI_CURSOR_LEAVE,
            CursorPosition::Off => BRLAPI_CURSOR_OFF as i32,
            CursorPosition::At(position) => position as i32,
        }
    }
}

/// Text writer for handling braille display output
///
/// This struct provides methods for writing text to the braille display
/// in various formats. It requires an active TTY mode and borrows from
/// the `TtyMode` to ensure TTY mode remains active during its lifetime.
///
/// # Safety
///
/// `TextWriter` can only be created from an active `TtyMode`, ensuring
/// that text operations are only performed when TTY mode is properly active.
/// This prevents runtime errors from attempting text operations without TTY mode.
///
/// # Example
/// ```no_run
/// use brlapi::{Connection, TtyMode, text::CursorPosition};
///
/// fn main() -> Result<(), brlapi::BrlApiError> {
///     let connection = Connection::open()?;
///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
///     let writer = tty_mode.writer();
///
///     // Write text with cursor positioning
///     writer.write_with_cursor("Hello World!", CursorPosition::At(0))?;
///
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct TextWriter<'a> {
    tty_mode: &'a crate::TtyMode<'a>,
}

impl<'a> TextWriter<'a> {
    /// Create a new text writer from an active TTY mode
    ///
    /// This is the safe way to create a TextWriter, ensuring that TTY mode
    /// is active and will remain active for the lifetime of the TextWriter.
    ///
    /// # Safety
    ///
    /// This constructor ensures that text 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::writer()` 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)
    }

    /// Write text to the braille display
    ///
    /// The text will be displayed starting at the beginning of the display.
    /// The cursor position is left unchanged, allowing BRLTTY to continue
    /// managing cursor positioning based on screen reader focus tracking.
    /// This is appropriate for status displays and notifications that shouldn't
    /// interfere with the user's current cursor context.
    ///
    /// For messages that don't need cursor indication, use
    /// `write_notification()` or `write_with_cursor(text, CursorPosition::Off)`.
    pub fn write_text(&self, text: &str) -> Result<()> {
        self.write_with_cursor(text, CursorPosition::Leave)
    }

    /// Write text to the braille display with cursor positioning
    ///
    /// # Arguments
    /// * `text` - The text to display
    /// * `cursor` - Where to position the cursor
    ///
    /// # Important Note about Contractions
    ///
    /// This function writes text directly to the braille display using BrlAPI's
    /// simple character-to-braille mapping. It does NOT apply contractions.
    /// BrlAPI requires client-side contraction processing - see the `write_contracted()`
    /// methods for proper contraction support using liblouis.
    ///
    /// # Examples
    /// ```no_run
    /// use brlapi::{Connection, TtyMode, text::{TextWriter, CursorPosition}};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let writer = tty_mode.writer();
    ///     
    ///     // Position cursor at character 5
    ///     writer.write_with_cursor("Hello world", CursorPosition::At(5))?;
    ///     
    ///     // Turn cursor off
    ///     writer.write_with_cursor("No cursor", CursorPosition::Off)?;
    ///     
    ///     // Leave cursor unchanged
    ///     writer.write_with_cursor("Keep cursor", CursorPosition::Leave)?;
    ///     
    ///     // TTY mode automatically exited when tty_mode is dropped
    ///     Ok(())
    /// }
    /// ```
    pub fn write_with_cursor(&self, text: &str, cursor: CursorPosition) -> Result<()> {
        let c_text = CString::new(text)?;

        // SAFETY: self.tty_mode.connection().handle_ptr() returns a valid handle in TTY mode.
        // cursor.into() converts to valid BrlAPI cursor constant.
        // c_text.as_ptr() points to valid null-terminated C string.
        brlapi_call!(unsafe {
            brlapi__writeText(
                self.tty_mode.connection().handle_ptr(),
                cursor.into(),
                c_text.as_ptr(),
            )
        })?;
        Ok(())
    }

    /// Write text to the braille display with cursor turned off
    ///
    /// This is a convenience method for notifications and temporary messages
    /// that don't need cursor indication. Equivalent to
    /// `write_with_cursor(text, CursorPosition::Off)`.
    pub fn write_notification(&self, text: &str) -> Result<()> {
        self.write_with_cursor(text, CursorPosition::Off)
    }

    /// Write text with contraction using liblouis
    ///
    /// This function translates text using the specified liblouis contraction table,
    /// then writes the contracted braille to the display. This provides proper
    /// literary braille output with contractions as expected by braille readers.
    ///
    /// # Arguments
    /// * `text` - The text to contract and display
    /// * `table` - The liblouis table name (e.g., "en-us-g2.ctb")
    /// * `cursor` - Where to position the cursor
    ///
    /// # Examples
    /// ```no_run
    /// use brlapi::{Connection, TtyMode, text::CursorPosition};
    /// use liblouis::Table;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let writer = tty_mode.writer();
    ///
    ///     // Write contracted text using US Grade 2 braille
    ///     writer.write_contracted("Hello and welcome", "en-us-g2.ctb", CursorPosition::Off)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn write_contracted(&self, text: &str, table: &str, cursor: CursorPosition) -> Result<()> {
        let translator = liblouis::Translator::new();
        let contracted_text = translator.translate_string(table, text)?;
        self.write_with_cursor(&contracted_text, cursor)
    }

    /// Write text with contraction using liblouis and cursor tracking
    ///
    /// This function translates text using the specified liblouis contraction table
    /// and properly maps cursor positions from the original text to the contracted output.
    ///
    /// # Arguments
    /// * `text` - The text to contract and display
    /// * `table` - The liblouis table name (e.g., "en-us-g2.ctb")
    /// * `cursor_pos` - Original cursor position in uncontracted text
    ///
    /// # Returns
    /// Returns the new cursor position in the contracted text
    ///
    /// # Examples
    /// ```no_run
    /// use brlapi::{Connection, TtyMode};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let writer = tty_mode.writer();
    ///
    ///     // Write with cursor tracking
    ///     let new_cursor_pos = writer.write_contracted_with_cursor_tracking(
    ///         "Hello and welcome", "en-us-g2.ctb", 6
    ///     )?;
    ///     println!("Cursor moved to position {}", new_cursor_pos);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn write_contracted_with_cursor_tracking(
        &self,
        text: &str,
        table: &str,
        cursor_pos: usize,
    ) -> Result<usize> {
        let translator = liblouis::Translator::new();
        let (contracted_text, new_cursor_pos) =
            translator.translate_string_with_cursor(table, text, cursor_pos)?;
        self.write_with_cursor(&contracted_text, CursorPosition::At(new_cursor_pos as u32))?;
        Ok(new_cursor_pos)
    }

    /// Write text using user's configured contraction table (convenience method)
    ///
    /// This method reads the user's preferred literary braille table from BRLTTY preferences
    /// and uses it for contraction. Falls back to "en-us-g2.ctb" if preferences cannot be read.
    ///
    /// This respects the user's accessibility preferences rather than hardcoding a table.
    pub fn write_contracted_user_preference(
        &self,
        text: &str,
        cursor: CursorPosition,
    ) -> Result<()> {
        let connection = self.tty_mode.connection();
        let table = connection.user_contraction_table()?;
        self.write_contracted(text, &table, cursor)
    }

    /// Write text using US English Grade 2 contractions (convenience method)
    ///
    /// This is a convenience method that explicitly uses US English Grade 2.
    /// Consider using `write_contracted_user_preference()` to respect user's table choice.
    pub fn write_contracted_en_us_g2(&self, text: &str, cursor: CursorPosition) -> Result<()> {
        self.write_contracted(text, "en-us-g2.ctb", cursor)
    }

    /// Write text using UK English Grade 2 contractions (convenience method)
    ///
    /// This is a convenience method for UK English Grade 2 contractions.
    /// Equivalent to `write_contracted(text, "en-gb-g2.ctb", cursor)`.
    pub fn write_contracted_en_gb_g2(&self, text: &str, cursor: CursorPosition) -> Result<()> {
        self.write_contracted(text, "en-gb-g2.ctb", cursor)
    }

    /// Write text using a liblouis Table (type-safe method)
    ///
    /// This method uses the liblouis::Table type for type-safe table management.
    ///
    /// # Examples
    /// ```no_run
    /// use brlapi::{Connection, TtyMode, text::CursorPosition};
    /// use liblouis::Table;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let writer = tty_mode.writer();
    ///
    ///     let table = Table::en_us_g2();
    ///     writer.write_with_table(&table, "Hello world", CursorPosition::Off)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn write_with_table(
        &self,
        table: &liblouis::Table,
        text: &str,
        cursor: CursorPosition,
    ) -> Result<()> {
        let translator = liblouis::Translator::new();
        let contracted_text = table.translate(&translator, text)?;
        self.write_with_cursor(&contracted_text, cursor)
    }

    /// Write text optimized for computer braille (uncontracted)
    ///
    /// This function is explicitly intended for computer braille output where
    /// character-by-character representation is desired. It's suitable for:
    /// - Programming code
    /// - Technical text
    /// - When precise character representation is needed
    pub fn write_computer_braille(&self, text: &str, cursor: CursorPosition) -> Result<()> {
        self.write_with_cursor(text, cursor)
    }

    /// Write Unicode text to the braille display
    ///
    /// This function writes Unicode text directly to the display without
    /// encoding conversion. It's useful for applications that work with
    /// wide characters or need precise Unicode handling.
    ///
    /// # Arguments
    /// * `text` - Unicode text as a string slice
    /// * `cursor` - Where to position the cursor
    ///
    /// # Examples
    /// ```no_run
    /// use brlapi::{Connection, TtyMode, text::{TextWriter, CursorPosition}};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let writer = tty_mode.writer();
    ///     
    ///     // Write Unicode text
    ///     writer.write_unicode("Hello World!", CursorPosition::Off)?;
    ///     
    ///     // TTY mode automatically exited when tty_mode is dropped
    ///     Ok(())
    /// }
    /// ```
    pub fn write_unicode(&self, text: &str, cursor: CursorPosition) -> Result<()> {
        // Convert UTF-8 string to wide string (wchar_t)
        // wchar_t size varies by platform - use proper conversion
        let wide_text: Vec<wchar_t> = text
            .chars()
            .map(|c| c as wchar_t)
            .chain(std::iter::once(0))
            .collect();

        // SAFETY: self.tty_mode.connection().handle_ptr() returns a valid handle in TTY mode.
        // cursor.into() converts to valid BrlAPI cursor constant.
        // wide_text.as_ptr() points to valid null-terminated wide character array.
        brlapi_call!(unsafe {
            brlapi__writeWText(
                self.tty_mode.connection().handle_ptr(),
                cursor.into(),
                wide_text.as_ptr(),
            )
        })?;
        Ok(())
    }

    /// Write raw braille dots to the display
    ///
    /// This function allows direct control over each braille cell by specifying
    /// the dot pattern for each character position. Each byte represents one
    /// braille cell with dots encoded according to ISO/TR 11548-1:
    /// - bit 0: dot 1
    /// - bit 1: dot 2
    /// - bit 2: dot 3
    /// - bit 3: dot 4
    /// - bit 4: dot 5
    /// - bit 5: dot 6
    /// - bit 6: dot 7
    /// - bit 7: dot 8
    ///
    /// # Arguments
    /// * `dots` - Array of dot patterns, one per display cell
    ///
    /// # Examples
    /// ```no_run
    /// use brlapi::{Connection, TtyMode, text::TextWriter, Display};
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     let connection = Connection::open()?;
    ///     let display = Display::from_connection(&connection)?;
    ///     let (tty_mode, _) = TtyMode::enter_auto(&connection, None)?;
    ///     let writer = tty_mode.writer();
    ///     
    ///     // Create a pattern of alternating dots
    ///     let mut pattern = Vec::new();
    ///     for i in 0..display.width() {
    ///         if i % 2 == 0 {
    ///             pattern.push(0b10101010); // dots 2,4,6,8
    ///         } else {
    ///             pattern.push(0b01010101); // dots 1,3,5,7
    ///         }
    ///     }
    ///     
    ///     writer.write_dots(&pattern)?;
    ///     
    ///     // TTY mode automatically exited when tty_mode is dropped
    ///     Ok(())
    /// }
    /// ```
    pub fn write_dots(&self, dots: &[u8]) -> Result<()> {
        // SAFETY: self.tty_mode.connection().handle_ptr() returns a valid handle in TTY mode.
        // dots.as_ptr() points to valid byte array representing braille dot patterns.
        // BrlAPI expects dots array to be null-terminated or match display width.
        brlapi_call!(unsafe {
            brlapi__writeDots(self.tty_mode.connection().handle_ptr(), dots.as_ptr())
        })?;
        Ok(())
    }

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

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

/// Utility functions for text output
pub mod util {
    use super::*;
    use crate::Connection;

    /// Write a quick message to the braille display (convenience function)
    ///
    /// This handles connection establishment, TTY mode management, and cleanup automatically.
    /// It's the most convenient way to send a single message.
    ///
    /// For multiple messages, it's more efficient to maintain a connection and use
    /// `TtyMode` with `TextWriter`.
    ///
    /// # Example
    /// ```no_run
    /// use brlapi::text::util;
    ///
    /// fn main() -> Result<(), brlapi::BrlApiError> {
    ///     util::send_message("Hello from BrlAPI!")?;
    ///     Ok(())
    /// }
    /// ```
    pub fn send_message(text: &str) -> Result<()> {
        let connection = Connection::open()?;
        write_message(&connection, text)
    }

    /// Write a quick message using an existing connection (convenience function)
    ///
    /// This automatically enters TTY mode, writes the text, and exits TTY mode.
    /// More efficient than `send_message()` when you already have a connection.
    pub fn write_message(connection: &Connection, text: &str) -> Result<()> {
        use crate::TtyMode;
        let (tty_mode, _) = TtyMode::enter_auto(connection, None)?;
        let writer = tty_mode.writer();
        writer.write_text(text)
    }

    /// Write a quick message with cursor positioning using an existing connection
    ///
    /// This automatically enters TTY mode, writes the text, and exits TTY mode.
    pub fn write_message_with_cursor(
        connection: &Connection,
        text: &str,
        cursor: CursorPosition,
    ) -> Result<()> {
        use crate::TtyMode;
        // Validate text early to avoid entering TTY mode unnecessarily
        let _ = CString::new(text)?;

        let (tty_mode, _) = TtyMode::enter_auto(connection, None)?;
        let writer = tty_mode.writer();
        writer.write_with_cursor(text, cursor)
    }

    /// Write a notification message using an existing connection
    ///
    /// This is a convenience function for temporary messages that don't need cursor indication.
    pub fn write_notification(connection: &Connection, text: &str) -> Result<()> {
        write_message_with_cursor(connection, text, CursorPosition::Off)
    }

    /// Write contracted text using an existing connection (convenience function)
    ///
    /// This automatically enters TTY mode, contracts and writes the text, then exits TTY mode.
    pub fn write_contracted_message(
        connection: &Connection,
        text: &str,
        table: &str,
    ) -> Result<()> {
        use crate::TtyMode;
        let (tty_mode, _) = TtyMode::enter_auto(connection, None)?;
        let writer = tty_mode.writer();
        writer.write_contracted(text, table, CursorPosition::Off)
    }

    /// Write contracted text using user's preferred table (convenience function)
    ///
    /// This is the most convenient way to send a single contracted message using
    /// the user's configured contraction table from BRLTTY preferences.
    /// Falls back to "en-us-g2.ctb" if preferences cannot be read.
    pub fn send_contracted_message(text: &str) -> Result<()> {
        let connection = Connection::open()?;
        let table = connection.user_contraction_table()?;
        write_contracted_message(&connection, text, &table)
    }

    /// Write contracted text using US English Grade 2 (explicit function)
    ///
    /// This explicitly uses US English Grade 2 regardless of user preferences.
    /// Consider using `send_contracted_message()` to respect user's table choice.
    pub fn send_contracted_message_en_us_g2(text: &str) -> Result<()> {
        let connection = Connection::open()?;
        write_contracted_message(&connection, text, "en-us-g2.ctb")
    }
}