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 headers_footers: bool,
85}
86
87impl Default for TextOptions {
88 fn default() -> Self {
89 Self {
90 hidden_text: false,
91 notes: true,
92 headers_footers: true,
93 }
94 }
95}
96
97impl TextOptions {
98 #[must_use]
99 pub fn hidden_text(mut self, include: bool) -> Self {
100 self.hidden_text = include;
101 self
102 }
103
104 #[must_use]
105 pub fn notes(mut self, include: bool) -> Self {
106 self.notes = include;
107 self
108 }
109
110 #[must_use]
111 pub fn headers_footers(mut self, include: bool) -> Self {
112 self.headers_footers = include;
113 self
114 }
115
116 pub fn includes(&self, block: &StyleBlock) -> bool {
117 let part = match block.part {
118 Part::Body => true,
119 Part::NoteReference(_) | Part::Note(_) => self.notes,
120 Part::Header | Part::Footer => self.headers_footers,
121 };
122 part && (self.hidden_text || !block.painter.hidden)
123 }
124}
125
126#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
127#[cfg_attr(feature = "jsbindings", wasm_bindgen(getter_with_clone))]
128#[non_exhaustive]
129pub struct RtfDocument {
130 pub header: RtfHeader,
131 pub info: DocumentInfo,
132 pub body: Vec<StyleBlock>,
133}
134
135impl TryFrom<String> for RtfDocument {
136 type Error = RtfError;
137 fn try_from(file_content: String) -> Result<Self, Self::Error> {
138 Self::try_from(file_content.as_str())
139 }
140}
141
142impl TryFrom<&str> for RtfDocument {
143 type Error = RtfError;
144 fn try_from(file_content: &str) -> Result<Self, Self::Error> {
145 let tokens = Lexer::scan(file_content)?;
146 Ok(Parser::new(tokens).parse()?)
147 }
148}
149
150impl TryFrom<&mut fs::File> for RtfDocument {
151 type Error = RtfError;
152 fn try_from(file: &mut fs::File) -> Result<Self, Self::Error> {
153 let mut bytes = Vec::new();
154 file.read_to_end(&mut bytes)?;
155 Self::from_bytes(&bytes)
156 }
157}
158
159impl RtfDocument {
160 pub fn from_filepath(filename: &str) -> Result<RtfDocument, RtfError> {
162 Self::from_bytes(&fs::read(filename)?)
163 }
164
165 pub fn from_bytes(bytes: &[u8]) -> Result<RtfDocument, RtfError> {
168 match std::str::from_utf8(bytes) {
169 Ok(text) => Self::try_from(text),
170 Err(_) => Self::try_from(decode_document_bytes(bytes).as_str()),
171 }
172 }
173
174 pub fn get_text(&self) -> String {
176 self.get_text_with(TextOptions::default())
177 }
178
179 pub fn get_text_with(&self, options: TextOptions) -> String {
180 self.body.iter().filter(|block| options.includes(block)).map(|block| block.text.as_str()).collect()
181 }
182}
183
184#[cfg(test)]
185pub(crate) mod tests {
186 use super::*;
187 use crate::document::RtfDocument;
188
189 #[test]
190 fn get_text_from_document() {
191 let rtf = r#"{ \rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard Voici du texte en {\b gras}.\par }"#;
192 let document = RtfDocument::try_from(rtf).unwrap();
193 assert_eq!(document.get_text(), "Voici du texte en gras.\n")
194 }
195
196 #[test]
197 fn create_document_from_file() {
198 let mut file = fs::File::open("./resources/tests/test-file.rtf").unwrap();
199 let document = RtfDocument::try_from(&mut file).unwrap();
200 assert_eq!(document.header.font_table.get(&0).unwrap().name, String::from("Helvetica"));
201 }
202
203 #[test]
204 fn create_document_from_filepath() {
205 let filename = "./resources/tests/test-file.rtf";
206 let document = RtfDocument::from_filepath(filename).unwrap();
207 assert_eq!(document.header.font_table.get(&0).unwrap().name, String::from("Helvetica"));
208 }
209
210 #[test]
211 fn create_document_from_code_page_bytes() {
212 let document = RtfDocument::from_bytes(b"{\\rtf1\\ansi\\ansicpg1251 \xCF\xF0\xE8\xE2\xE5\xF2}").unwrap();
213 assert_eq!(document.get_text(), "\u{41F}\u{440}\u{438}\u{432}\u{435}\u{442}");
214 }
215
216 #[test]
217 fn text_options_choose_what_get_text_includes() {
218 let rtf = r"{\rtf1\ansi{\header Head\par}Shown{\v Hidden} body{\super\chftn}{\footnote\pard\plain{\super\chftn} Note.}\par}";
219 let doc = RtfDocument::try_from(rtf).unwrap();
220 let only = |hidden_text, notes, headers_footers| doc.get_text_with(TextOptions::default().hidden_text(hidden_text).notes(notes).headers_footers(headers_footers));
221 assert_eq!(doc.get_text(), "Shown body1\n1 Note.\nHead\n");
222 assert_eq!(only(true, true, true), "ShownHidden body1\n1 Note.\nHead\n");
223 assert_eq!(only(false, false, true), "Shown body\nHead\n");
224 assert_eq!(only(false, true, false), "Shown body1\n1 Note.\n");
225 assert_eq!(only(false, false, false), "Shown body\n");
226 }
227
228 #[test]
229 fn leaving_out_notes_keeps_the_body_line_break() {
230 let doc = RtfDocument::try_from(r"{\rtf1\ansi Body{\super\chftn}{\footnote\pard\plain{\super\chftn} N.}}").unwrap();
231 assert_eq!(doc.get_text(), "Body1\n1 N.");
232 assert_eq!(doc.get_text_with(TextOptions::default().notes(false)), "Body\n");
233 }
234
235 #[test]
236 fn default_text_options() {
237 assert_eq!(
238 TextOptions::default(),
239 TextOptions {
240 hidden_text: false,
241 notes: true,
242 headers_footers: true
243 }
244 );
245 }
246
247 #[test]
248 fn parse_rtf_returns_an_error_instead_of_panicking() {
249 assert!(parse_rtf(r"{\rtf1 Hello \'zz world}".to_string()).is_err());
250 assert_eq!(parse_rtf(r"{\rtf1 Hello}".to_string()).unwrap().get_text(), "Hello");
251 }
252}