ctb_formats_encoding/
altura.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Altura `Mac2Win` character translation tables.
21//!
22//! Altura `Mac2Win` is/was a cross-platform compatibility runtime used by
23//! applications such as Panorama for Windows. Internal data in `.pan` files is
24//! stored in Mac OS Roman across platforms; when running on Windows, Altura
25//! `Mac2Win` uses 128-byte lookup tables (covering bytes `0x80`..=`0xFF`) to
26//! translate between Mac OS Roman and Windows ANSI (Windows-1252).
27//! Some characters that are not shared between the encodings are changed to
28//! different characters when files are transferred between operating systems.
29//!
30//! Altura is not a unique character encoding itself: internal file contents are
31//! standard Mac OS Roman, and the translated output is standard Windows-1252
32//! (Windows ANSI). This module provides Altura's specific 128-byte lookup
33//! tables (`0x80`..=`0xFF`) used to transliterate between Mac OS Roman and
34//! Windows-1252, including Altura's fallback substitutions for glyphs that do
35//! not exist in both sets.
36
37#[allow(
38    unused_imports,
39    clippy::wildcard_imports,
40    reason = "Standard workspace module prelude"
41)]
42use crate::utilities::*;
43
44use ctb_utilities::anyhow::anyhow;
45use std::sync::LazyLock;
46
47fn parse_hex_table(file_path: &str) -> Result<[u8; 128]> {
48    let bytes = crate::get_encoding_data(file_path).ok_or_else(|| {
49        anyhow!("Missing Altura Mac2Win data file: {file_path}")
50    })?;
51    let text = String::from_utf8(bytes)
52        .with_context(|| format!("Data file {file_path} is not valid UTF-8"))?;
53
54    let mut table = [0u8; 128];
55    let tokens = text.split_whitespace().collect::<Vec<_>>();
56    ensure!(
57        tokens.len() == 128,
58        "Expected 128 hex entries in {file_path}, found {}",
59        tokens.len()
60    );
61
62    for (index, token) in tokens.iter().enumerate() {
63        let val = u8::from_str_radix(token, 16).with_context(|| {
64            format!("Invalid hex token '{token}' in {file_path}")
65        })?;
66        let slot = table.get_mut(index).context("Table index out of bounds")?;
67        *slot = val;
68    }
69
70    Ok(table)
71}
72
73#[expect(
74    clippy::expect_used,
75    reason = "Embedded static translation tables are validated at compile time and infallible"
76)]
77static MAC_ROMAN_TO_ANSI: LazyLock<[u8; 128]> = LazyLock::new(|| {
78    parse_hex_table("altura-mac2win/MacRoman to ANSI.csv")
79        .expect("Failed to load Altura MacRoman to ANSI table")
80});
81
82#[expect(
83    clippy::expect_used,
84    reason = "Embedded static translation tables are validated at compile time and infallible"
85)]
86static ANSI_TO_MAC_ROMAN: LazyLock<[u8; 128]> = LazyLock::new(|| {
87    parse_hex_table("altura-mac2win/ANSI to MacRoman.csv")
88        .expect("Failed to load Altura ANSI to MacRoman table")
89});
90
91/// Translates a single Mac OS Roman byte to Altura Windows ANSI.
92#[inline]
93#[must_use]
94pub fn mac_roman_to_ansi_byte(b: u8) -> u8 {
95    if b < 0x80 {
96        b
97    } else {
98        let idx = usize::from(b.saturating_sub(0x80));
99        // Reason for fallback: only the 128 high bytes are remapped; retain others
100        MAC_ROMAN_TO_ANSI.get(idx).copied().unwrap_or(b)
101    }
102}
103
104/// Translates a single Altura Windows ANSI byte to Mac OS Roman.
105#[inline]
106#[must_use]
107pub fn ansi_to_mac_roman_byte(b: u8) -> u8 {
108    if b < 0x80 {
109        b
110    } else {
111        let idx = usize::from(b.saturating_sub(0x80));
112        // Reason for fallback: only the 128 high bytes are remapped; retain others
113        ANSI_TO_MAC_ROMAN.get(idx).copied().unwrap_or(b)
114    }
115}
116
117/// Translates a slice of Mac OS Roman bytes to Altura Windows ANSI bytes.
118#[must_use]
119pub fn mac_roman_to_ansi(bytes: &[u8]) -> Vec<u8> {
120    bytes.iter().map(|&b| mac_roman_to_ansi_byte(b)).collect()
121}
122
123/// Translates a slice of Altura Windows ANSI bytes to Mac OS Roman bytes.
124#[must_use]
125pub fn ansi_to_mac_roman(bytes: &[u8]) -> Vec<u8> {
126    bytes.iter().map(|&b| ansi_to_mac_roman_byte(b)).collect()
127}
128
129/// Converts Mac OS Roman bytes into a UTF-8 string from the Windows user
130/// perspective (translating via the Altura ANSI table and decoding as
131/// Windows-1252).
132pub fn mac_roman_to_utf8_windows(bytes: &[u8]) -> Result<String> {
133    let ansi_bytes = mac_roman_to_ansi(bytes);
134    crate::standard::WINDOWS_1252_MAPPING.decode(&ansi_bytes)
135}
136
137/// Converts a UTF-8 string into Mac OS Roman bytes from the Windows user
138/// perspective (encoding as Windows-1252 and translating via the Altura ANSI
139/// table).
140pub fn utf8_windows_to_mac_roman(text: &str) -> Result<Vec<u8>> {
141    let ansi_bytes = crate::standard::WINDOWS_1252_MAPPING.encode(text)?;
142    Ok(ansi_to_mac_roman(&ansi_bytes))
143}
144
145#[cfg(test)]
146#[allow(
147    clippy::panic,
148    clippy::expect_used,
149    clippy::unwrap_used,
150    clippy::unwrap_in_result,
151    clippy::panic_in_result_fn,
152    clippy::indexing_slicing,
153    clippy::arithmetic_side_effects,
154    reason = "Standard repository test boilerplate"
155)]
156mod tests {
157    use super::*;
158
159    #[crate::ctb_test]
160    fn test_altura_tables_load_and_have_128_entries() -> Result<()> {
161        ensure!(MAC_ROMAN_TO_ANSI.len() == 128);
162        ensure!(ANSI_TO_MAC_ROMAN.len() == 128);
163        Ok(())
164    }
165
166    #[crate::ctb_test]
167    fn test_altura_mac_roman_to_ansi_known_mappings() -> Result<()> {
168        // 0x80 (Ä in MacRoman) -> 0xC4 (Ä in Windows-1252)
169        ensure!(mac_roman_to_ansi_byte(0x80) == 0xC4);
170        // 0x85 (Ö in MacRoman) -> 0xD6 (Ö in Windows-1252)
171        ensure!(mac_roman_to_ansi_byte(0x85) == 0xD6);
172        // 0xA5 (• bullet in MacRoman) -> 0x95 (• bullet in Windows-1252)
173        ensure!(mac_roman_to_ansi_byte(0xA5) == 0x95);
174        // 0xAA (™ trademark in MacRoman) -> 0x99 (™ trademark in Windows-1252)
175        ensure!(mac_roman_to_ansi_byte(0xAA) == 0x99);
176        // 0xC9 (… ellipsis in MacRoman) -> 0x85 (… ellipsis in Windows-1252)
177        ensure!(mac_roman_to_ansi_byte(0xC9) == 0x85);
178        // 0xD1 (— em dash in MacRoman) -> 0x97 (— em dash in Windows-1252)
179        ensure!(mac_roman_to_ansi_byte(0xD1) == 0x97);
180        // 0xD5 (’ right single quote in MacRoman) -> 0x92 (’ in Windows-1252)
181        ensure!(mac_roman_to_ansi_byte(0xD5) == 0x92);
182        // 0xB0 (∞ infinity sign in MacRoman) -> 0x81 (€ in Windows-1252)
183        ensure!(mac_roman_to_ansi_byte(0xB0) == 0x81);
184        Ok(())
185    }
186
187    #[crate::ctb_test]
188    fn test_altura_ansi_to_mac_roman_known_mappings() -> Result<()> {
189        // 0xC4 (Ä in Windows-1252) -> 0x80 (Ä in MacRoman)
190        ensure!(ansi_to_mac_roman_byte(0xC4) == 0x80);
191        // 0xD6 (Ö in Windows-1252) -> 0x85 (Ö in MacRoman)
192        ensure!(ansi_to_mac_roman_byte(0xD6) == 0x85);
193        // 0x95 (• bullet in Windows-1252) -> 0xA5 (• bullet in MacRoman)
194        ensure!(ansi_to_mac_roman_byte(0x95) == 0xA5);
195        // 0x99 (™ trademark in Windows-1252) -> 0xAA (™ trademark in MacRoman)
196        ensure!(ansi_to_mac_roman_byte(0x99) == 0xAA);
197        // 0x85 (… ellipsis in Windows-1252) -> 0xC9 (… ellipsis in MacRoman)
198        ensure!(ansi_to_mac_roman_byte(0x85) == 0xC9);
199        // 0x97 (— em dash in Windows-1252) -> 0xD1 (— em dash in MacRoman)
200        ensure!(ansi_to_mac_roman_byte(0x97) == 0xD1);
201        // 0x92 (’ right single quote in Windows-1252) -> 0xD5 (’ in MacRoman)
202        ensure!(ansi_to_mac_roman_byte(0x92) == 0xD5);
203        // 0x81 (€ Euro sign in Windows-1252) -> 0xB0 (∞ in MacRoman)
204        ensure!(mac_roman_to_ansi_byte(0xB0) == 0x81);
205        Ok(())
206    }
207
208    #[crate::ctb_test]
209    fn test_altura_utf8_windows_conversions() -> Result<()> {
210        let mac_bytes = [0x54, 0x65, 0x73, 0x74, 0xC9]; // "Test…" in MacRoman
211        let utf8_win = mac_roman_to_utf8_windows(&mac_bytes)?;
212        ensure!(utf8_win == "Test…");
213
214        let roundtrip_mac = utf8_windows_to_mac_roman(&utf8_win)?;
215        ensure!(roundtrip_mac == mac_bytes);
216        Ok(())
217    }
218}