1use std::fmt;
2use std::fs;
3use std::io::Read;
4
5use serde::{Deserialize, Serialize};
6#[cfg(feature = "jsbindings")]
7use wasm_bindgen::prelude::wasm_bindgen;
8
9use crate::encoding::decode_document_bytes;
10use crate::header::RtfHeader;
11use crate::lexer::{Lexer, LexerError};
12use crate::parser::{Parser, ParserError, Part, StyleBlock};
13
14#[cfg_attr(feature = "jsbindings", wasm_bindgen)]
15pub fn parse_rtf(rtf: String) -> Result<RtfDocument, RtfError> {
16 RtfDocument::try_from(rtf)
17}
18
19#[derive(Debug, Clone)]
20#[non_exhaustive]
21pub enum RtfError {
22 Lexer(LexerError),
23 Parser(ParserError),
24 Io(String),
25}
26
27impl std::error::Error for RtfError {}
28
29impl fmt::Display for RtfError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 match self {
32 RtfError::Lexer(error) => write!(f, "{error}"),
33 RtfError::Parser(error) => write!(f, "{error}"),
34 RtfError::Io(error) => write!(f, "[RTF] : {error}"),
35 }
36 }
37}
38
39impl From<LexerError> for RtfError {
40 fn from(error: LexerError) -> Self {
41 RtfError::Lexer(error)
42 }
43}
44
45impl From<ParserError> for RtfError {
46 fn from(error: ParserError) -> Self {
47 RtfError::Parser(error)
48 }
49}
50
51impl From<std::io::Error> for RtfError {
52 fn from(error: std::io::Error) -> Self {
53 RtfError::Io(error.to_string())
54 }
55}
56
57#[cfg(feature = "jsbindings")]
58impl From<RtfError> for wasm_bindgen::JsValue {
59 fn from(error: RtfError) -> Self {
60 wasm_bindgen::JsValue::from_str(&error.to_string())
61 }
62}
63
64#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
65#[cfg_attr(feature = "jsbindings", wasm_bindgen(getter_with_clone))]
66#[non_exhaustive]
67pub struct DocumentInfo {
68 pub title: Option<String>,
69 pub subject: Option<String>,
70 pub author: Option<String>,
71 pub manager: Option<String>,
72 pub company: Option<String>,
73 pub operator: Option<String>,
74 pub category: Option<String>,
75 pub keywords: Option<String>,
76 pub comment: Option<String>,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
80#[non_exhaustive]
81pub struct TextOptions {
82 pub hidden_text: bool,
83 pub notes: bool,
84 pub note_numbers: bool,
85 pub headers_footers: bool,
86}
87
88impl Default for TextOptions {
89 fn default() -> Self {
90 Self {
91 hidden_text: false,
92 notes: true,
93 note_numbers: true,
94 headers_footers: true,
95 }
96 }
97}
98
99impl TextOptions {
100 #[must_use]
101 pub fn hidden_text(mut self, include: bool) -> Self {
102 self.hidden_text = include;
103 self
104 }
105
106 #[must_use]
107 pub fn notes(mut self, include: bool) -> Self {
108 self.notes = include;
109 self
110 }
111
112 #[must_use]
113 pub fn note_numbers(mut self, include: bool) -> Self {
114 self.note_numbers = include;
115 self
116 }
117
118 #[must_use]
119 pub fn headers_footers(mut self, include: bool) -> Self {
120 self.headers_footers = include;
121 self
122 }
123
124 pub fn includes(&self, block: &StyleBlock) -> bool {
125 let part = match block.part {
126 Part::Body => true,
127 Part::NoteReference(_) | Part::Note(_) => self.notes,
128 Part::NoteNumber(_) => self.notes && self.note_numbers,
129 Part::Header | Part::Footer => self.headers_footers,
130 };
131 part && (self.hidden_text || !block.painter.hidden)
132 }
133}
134
135#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
136#[cfg_attr(feature = "jsbindings", wasm_bindgen(getter_with_clone))]
137#[non_exhaustive]
138pub struct RtfDocument {
139 pub header: RtfHeader,
140 pub info: DocumentInfo,
141 pub body: Vec<StyleBlock>,
142}
143
144impl TryFrom<String> for RtfDocument {
145 type Error = RtfError;
146 fn try_from(file_content: String) -> Result<Self, Self::Error> {
147 Self::try_from(file_content.as_str())
148 }
149}
150
151impl TryFrom<&str> for RtfDocument {
152 type Error = RtfError;
153 fn try_from(file_content: &str) -> Result<Self, Self::Error> {
154 let tokens = Lexer::scan(file_content)?;
155 Ok(Parser::new(tokens).parse()?)
156 }
157}
158
159impl TryFrom<&mut fs::File> for RtfDocument {
160 type Error = RtfError;
161 fn try_from(file: &mut fs::File) -> Result<Self, Self::Error> {
162 let mut bytes = Vec::new();
163 file.read_to_end(&mut bytes)?;
164 Self::from_bytes(&bytes)
165 }
166}
167
168impl RtfDocument {
169 pub fn from_filepath(filename: &str) -> Result<RtfDocument, RtfError> {
171 Self::from_bytes(&fs::read(filename)?)
172 }
173
174 pub fn from_bytes(bytes: &[u8]) -> Result<RtfDocument, RtfError> {
177 match std::str::from_utf8(bytes) {
178 Ok(text) => Self::try_from(text),
179 Err(_) => Self::try_from(decode_document_bytes(bytes).as_str()),
180 }
181 }
182
183 pub fn get_text(&self) -> String {
185 self.get_text_with(TextOptions::default())
186 }
187
188 pub fn get_text_with(&self, options: TextOptions) -> String {
189 self.body.iter().filter(|block| options.includes(block)).map(|block| block.text.as_str()).collect()
190 }
191}
192
193#[cfg(test)]
194pub(crate) mod tests {
195 use super::*;
196 use crate::document::RtfDocument;
197
198 #[test]
199 fn get_text_from_document() {
200 let rtf = r#"{ \rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard Voici du texte en {\b gras}.\par }"#;
201 let document = RtfDocument::try_from(rtf).unwrap();
202 assert_eq!(document.get_text(), "Voici du texte en gras.\n")
203 }
204
205 #[test]
206 fn create_document_from_file() {
207 let mut file = fs::File::open("./resources/tests/test-file.rtf").unwrap();
208 let document = RtfDocument::try_from(&mut file).unwrap();
209 assert_eq!(document.header.font_table.get(&0).unwrap().name, String::from("Helvetica"));
210 }
211
212 #[test]
213 fn create_document_from_filepath() {
214 let filename = "./resources/tests/test-file.rtf";
215 let document = RtfDocument::from_filepath(filename).unwrap();
216 assert_eq!(document.header.font_table.get(&0).unwrap().name, String::from("Helvetica"));
217 }
218
219 #[test]
220 fn create_document_from_code_page_bytes() {
221 let document = RtfDocument::from_bytes(b"{\\rtf1\\ansi\\ansicpg1251 \xCF\xF0\xE8\xE2\xE5\xF2}").unwrap();
222 assert_eq!(document.get_text(), "\u{41F}\u{440}\u{438}\u{432}\u{435}\u{442}");
223 }
224
225 #[test]
226 fn text_options_choose_what_get_text_includes() {
227 let rtf = r"{\rtf1\ansi{\header Head\par}Shown{\v Hidden} body{\super\chftn}{\footnote\pard\plain{\super\chftn} Note.}\par}";
228 let doc = RtfDocument::try_from(rtf).unwrap();
229 let only = |hidden_text, notes, headers_footers| doc.get_text_with(TextOptions::default().hidden_text(hidden_text).notes(notes).headers_footers(headers_footers));
230 assert_eq!(doc.get_text(), "Shown body1\n1 Note.\nHead\n");
231 assert_eq!(only(true, true, true), "ShownHidden body1\n1 Note.\nHead\n");
232 assert_eq!(only(false, false, true), "Shown body\nHead\n");
233 assert_eq!(only(false, true, false), "Shown body1\n1 Note.\n");
234 assert_eq!(only(false, false, false), "Shown body\n");
235 assert_eq!(doc.get_text_with(TextOptions::default().note_numbers(false)), "Shown body1\n Note.\nHead\n");
236 }
237
238 #[test]
239 fn leaving_out_note_numbers_keeps_the_note_line_break() {
240 let doc = RtfDocument::try_from(r"{\rtf1\ansi A{\super\chftn}{\footnote\chftn} B{\super\chftn}{\footnote\chftn Two.}}").unwrap();
241 assert_eq!(doc.get_text(), "A1 B2\n1\n2Two.");
242 assert_eq!(doc.get_text_with(TextOptions::default().note_numbers(false)), "A1 B2\n\nTwo.");
243 }
244
245 #[test]
246 fn leaving_out_notes_keeps_the_body_line_break() {
247 let doc = RtfDocument::try_from(r"{\rtf1\ansi Body{\super\chftn}{\footnote\pard\plain{\super\chftn} N.}}").unwrap();
248 assert_eq!(doc.get_text(), "Body1\n1 N.");
249 assert_eq!(doc.get_text_with(TextOptions::default().notes(false)), "Body\n");
250 }
251
252 #[test]
253 fn default_text_options() {
254 assert_eq!(
255 TextOptions::default(),
256 TextOptions {
257 hidden_text: false,
258 notes: true,
259 note_numbers: true,
260 headers_footers: true
261 }
262 );
263 }
264
265 #[test]
266 fn parse_rtf_returns_an_error_instead_of_panicking() {
267 assert!(parse_rtf(r"{\rtf1 Hello \'zz world}".to_string()).is_err());
268 assert_eq!(parse_rtf(r"{\rtf1 Hello}".to_string()).unwrap().get_text(), "Hello");
269 }
270}