ctb_renderer/
renderer.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//! Rendering subsystem for UI views, terminal interfaces, and graphics.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace prelude"
33)]
34pub use ctb_utilities::ipc::service_prelude::*;
35
36use ctb_formats_dcstring::{
37    DcChar, DcMixedChunk, DcMstr, DcMstring, SyntaxRuleResolver,
38    apply_semantic_to_text_with_resolver,
39};
40use serde::{Deserialize, Serialize};
41
42// use ctb_workspace_ipc::router::IpcPeer;
43
44/// Render mode for the renderer service.
45///
46/// This type is marked as an IPC DTO source so `ctb-utilities` can generate a
47/// dependency-free mirror for IPC service traits.
48#[ipc_dto]
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub enum RenderMode {
51    /// Render everything immediately without interactive features.
52    Immediate,
53    /// Render with interactive features enabled.
54    Interactive,
55}
56
57/// Render target for the renderer service.
58///
59/// This is marked as an IPC DTO source so `ctb-utilities` can generate a
60/// dependency-free mirror for IPC service traits.
61#[ipc_dto]
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub enum RenderTarget {
64    /// Character-based output similar to a teletype (plain text).
65    Teletype,
66    /// Video terminal with cursor control and escape sequences.
67    Videoterminal,
68    /// Web-based output (HTML/CSS/JS).
69    Web,
70    /// Raster graphics (bitmap images).
71    Raster,
72    /// Vector graphics (SVG, PDF).
73    Vector,
74    /// Print-ready output.
75    Print,
76}
77
78/// Render settings for the renderer service.
79///
80/// This is marked as an IPC DTO source so `ctb-utilities` can generate a
81/// dependency-free mirror for IPC service traits.
82#[ipc_dto]
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub struct RenderSettings {
85    /// The rendering mode.
86    pub mode: RenderMode,
87    /// The rendering target.
88    pub target: RenderTarget,
89}
90
91/// Renders an evaluated [`DcMstr`] document snapshot according to `settings`
92/// using the bundled `HEAD` System-graph syntax resolver (unless `doc` carries
93/// its own leading `Dc 641` pin description).
94///
95/// Currently supports [`RenderTarget::Teletype`] via the graph-resident StageR 3
96/// `FormatId::SemanticToText` (`f19` `"Semantic Dcs to text"`) lowering routine
97/// (`std/teletype.sr3`).
98///
99/// # Errors
100/// Returns an error if `settings.target` is not yet implemented or if `f19`
101/// execution fails.
102pub fn render_dc_document(
103    doc: &DcMstr,
104    settings: &RenderSettings,
105) -> Result<Vec<u8>> {
106    let default_resolver =
107        ctb_formats_dcstring::syntax::default_syntax_resolver();
108    render_dc_document_with_resolver(doc, settings, default_resolver.as_ref())
109}
110
111/// Renders an evaluated [`DcMstr`] document snapshot according to `settings`
112/// against the supplied `resolver` (honoring historical `Dc 641` pins).
113///
114/// # Errors
115/// Returns an error if `settings.target` is not yet implemented or if `f19`
116/// execution fails.
117pub fn render_dc_document_with_resolver(
118    doc: &DcMstr,
119    settings: &RenderSettings,
120    resolver: &dyn SyntaxRuleResolver,
121) -> Result<Vec<u8>> {
122    ctb_wasm_substitutes::ensure_registered();
123    match settings.target {
124        RenderTarget::Teletype => render_teletype_dc_document(doc, resolver),
125        RenderTarget::Videoterminal
126        | RenderTarget::Web
127        | RenderTarget::Raster
128        | RenderTarget::Vector
129        | RenderTarget::Print => {
130            bail!(
131                "RenderTarget::{:?} is not yet implemented for Dc document rendering (only RenderTarget::Teletype is currently implemented)",
132                settings.target
133            )
134        }
135    }
136}
137
138fn render_teletype_dc_document(
139    doc: &DcMstr,
140    resolver: &dyn SyntaxRuleResolver,
141) -> Result<Vec<u8>> {
142    let lowered = apply_semantic_to_text_with_resolver(doc, resolver)?;
143    let mut out = Vec::with_capacity(lowered.len());
144    let mut utf8_buf = [0u8; 4];
145    for chunk in lowered.chunks() {
146        match chunk {
147            DcMixedChunk::Text(text) => {
148                for ch in text.chars() {
149                    // Reason for fallback: Any residual non-Unicode or surrogate Dc after f19 lowering renders as U+FFFD in Teletype plain-text output.
150                    let scalar = u32::try_from(ch.to_u128())
151                        .ok()
152                        .and_then(char::from_u32)
153                        .unwrap_or('\u{FFFD}');
154                    out.extend_from_slice(
155                        scalar.encode_utf8(&mut utf8_buf).as_bytes(),
156                    );
157                }
158            }
159            DcMixedChunk::Binary { data, .. }
160            | DcMixedChunk::BinaryWithMetadata { data, .. } => {
161                let placeholder =
162                    format!("[binary data: {} bytes]", data.len());
163                out.extend_from_slice(placeholder.as_bytes());
164            }
165        }
166    }
167    Ok(out)
168}
169
170/// Render the provided document string according to the provided settings.
171#[ipc_method]
172pub fn render_from_string(
173    #[ipc(shm)] document: String,
174    settings: RenderSettings,
175) -> String {
176    render_from_str(&document, settings)
177}
178
179pub fn render_from_str(document: &str, settings: RenderSettings) -> String {
180    if settings.target == RenderTarget::Teletype {
181        let mut mstr = DcMstring::new();
182        for ch in document.chars() {
183            mstr.push_char(DcChar::from(ch));
184        }
185        if let Ok(bytes) = render_dc_document(&mstr, &settings)
186            && let Ok(rendered) = String::from_utf8(bytes)
187        {
188            return rendered;
189        }
190    }
191    document.to_string()
192}
193
194#[ipc_method]
195/// Prepend a string to the document and return the result.
196pub fn test_prepend(#[ipc(shm)] document: String, prepend: &str) -> String {
197    format!("{prepend}{document}")
198}
199
200#[ipc_method]
201/// Test helper that echoes the document 3 times.
202pub fn test_echo_3x(#[ipc(shm)] document: String) -> String {
203    document.clone().repeat(3)
204}
205
206#[cfg(test)]
207#[allow(
208    clippy::panic,
209    clippy::expect_used,
210    clippy::unwrap_used,
211    clippy::unwrap_in_result,
212    clippy::panic_in_result_fn,
213    clippy::indexing_slicing,
214    clippy::arithmetic_side_effects,
215    reason = "Standard repository test boilerplate"
216)]
217mod tests {
218    use super::*;
219
220    fn teletype_settings() -> RenderSettings {
221        RenderSettings {
222            mode: RenderMode::Immediate,
223            target: RenderTarget::Teletype,
224        }
225    }
226
227    #[crate::ctb_test]
228    fn renders_semantic_short_dcs_to_teletype_utf8() -> Result<()> {
229        // Short Dcs for "Hello, World!" followed by Dc 120 (Ambiguous line feed -> '\n').
230        let short_ids: [u32; 14] =
231            [57, 86, 93, 93, 96, 30, 18, 72, 96, 99, 93, 85, 19, 120];
232        let mut doc = DcMstring::new();
233        for id in short_ids {
234            doc.push_char(DcChar::from_short(id));
235        }
236        let bytes = render_dc_document(&doc, &teletype_settings())?;
237        assert_eq!(String::from_utf8(bytes)?, "Hello, World!\n");
238        Ok(())
239    }
240
241    #[crate::ctb_test]
242    fn strips_styling_formats_errors_and_replaces_unmappables() -> Result<()> {
243        let mut doc = DcMstring::new();
244        // Dc 286 (Begin italic), Dc 304 + Dc 288 (Red), 'H', 'i', Dc 305, Dc 287, '\n'
245        doc.push_char(DcChar::from_short(286));
246        doc.push_char(DcChar::from_short(304));
247        doc.push_char(DcChar::from_short(288));
248        doc.push_str("Hi");
249        doc.push_char(DcChar::from_short(305));
250        doc.push_char(DcChar::from_short(287));
251        doc.push_char(DcChar::from('\n'));
252        // Structured error record: Dc 552 "bad" Dc 553
253        doc.push_char(DcChar::from_short(552));
254        doc.push_str("bad");
255        doc.push_char(DcChar::from_short(553));
256        // Unmappable control Dc 256 (`lang.say` atom left unrendered) -> U+FFFD
257        doc.push_char(DcChar::from_short(255));
258        doc.push_char(DcChar::from_short(256));
259
260        let bytes = render_dc_document(&doc, &teletype_settings())?;
261        assert_eq!(
262            String::from_utf8(bytes)?,
263            "Hi\n[error: bad]\n\u{FFFD}"
264        );
265        Ok(())
266    }
267
268    #[crate::ctb_test]
269    fn renders_historical_pinned_document_on_teletype() -> Result<()> {
270        let pin = 8_589_958_834u128;
271        let resolver =
272            ctb_formats_dcstring::syntax::syntax_resolver_at_most_recent(pin)?;
273        let mut doc = DcMstring::new();
274        doc.push_char(DcChar::from_short(641));
275        doc.push_char(DcChar::from_long(pin));
276        for id in [57u32, 86, 120] {
277            doc.push_char(DcChar::from_short(id));
278        }
279        let bytes = render_dc_document_with_resolver(
280            &doc,
281            &teletype_settings(),
282            resolver.as_ref(),
283        )?;
284        assert_eq!(String::from_utf8(bytes)?, "He\n");
285        Ok(())
286    }
287
288    #[crate::ctb_test]
289    fn rejects_unimplemented_non_teletype_targets() {
290        let doc = DcMstring::from("hello");
291        let err = render_dc_document(
292            &doc,
293            &RenderSettings {
294                mode: RenderMode::Immediate,
295                target: RenderTarget::Videoterminal,
296            },
297        )
298        .unwrap_err();
299        assert!(err.to_string().contains("Videoterminal"));
300    }
301}