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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#![allow(non_snake_case)]
#![allow(clippy::needless_return)]
use std::cell::RefCell;
use sxd_document::parser;
use sxd_document::Package;
use sxd_document::dom::*;
use crate::errors::*;
use regex::Regex;
use crate::navigate::*;
use crate::pretty_print::mml_to_string;
use crate::xpath_functions::is_leaf;
fn cleanup_mathml(mathml: Element) -> Result<Element> {
trim_element(&mathml);
let mathml = crate::canonicalize::canonicalize(mathml)?;
let mathml = add_ids(mathml);
return Ok(mathml);
}
thread_local!{
pub static MATHML_INSTANCE: RefCell<Package> = init_mathml_instance();
}
fn init_mathml_instance() -> RefCell<Package> {
let package = parser::parse("<math></math>")
.expect("Internal error in 'init_mathml_instance;: didn't parse initializer string");
return RefCell::new( package );
}
pub fn set_rules_dir(dir: String) -> Result<()> {
use std::path::PathBuf;
return crate::prefs::PreferenceManager::initialize(PathBuf::from(dir));
}
pub fn set_mathml(mathml_str: String) -> Result<String> {
lazy_static! {
static ref MATHJAX_V2: Regex = Regex::new(r#"class *= *['"]MJX-.*?['"]"#).unwrap();
static ref MATHJAX_V3: Regex = Regex::new(r#"class *= *['"]data-mjx-.*?['"]"#).unwrap();
}
NAVIGATION_STATE.with(|nav_stack| {
nav_stack.borrow_mut().reset();
});
return MATHML_INSTANCE.with(|old_package| {
let mathml_str = mathml_str.replace("<", "<")
.replace(">", ">")
.replace("&", "&")
.replace(" ", " ");
let mathml_str = MATHJAX_V2.replace_all(&mathml_str, "");
let mathml_str = MATHJAX_V3.replace_all(&mathml_str, "");
let new_package = parser::parse(&mathml_str);
if let Err(e) = new_package {
bail!("Invalid MathML input:\n{}\nError is: {}", &mathml_str, &e.to_string());
}
crate::speech::SPEECH_RULES.with(|speech_rules| -> Result<()> {
if let Some(e) = speech_rules.borrow().get_error() {bail!("{}", e)} else {Ok(())}
})?;
let new_package = new_package.unwrap();
let mathml = cleanup_mathml(get_element(&new_package))?;
let mathml_string = mml_to_string(&mathml);
old_package.replace(new_package);
return Ok( mathml_string );
})
}
pub fn get_spoken_text() -> Result<String> {
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
let new_package = Package::new();
let intent = crate::speech::intent_from_mathml(mathml, new_package.as_document())?;
debug!("Intent tree:\n{}", mml_to_string(&intent));
let speech = crate::speech::speak_intent(intent)?;
return Ok( speech );
});
}
pub fn get_overview_text() -> Result<String> {
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
let speech = crate::speech::overview_mathml(mathml)?;
return Ok( speech );
});
}
pub fn get_preference(name: String) -> Option<String> {
use yaml_rust::Yaml;
return crate::speech::SPEECH_RULES.with(|rules| {
let rules = rules.borrow();
let pref_manager = rules.pref_manager.borrow();
let prefs = pref_manager.merge_prefs();
return match prefs.get(&name) {
None => None,
Some(yaml) => match yaml {
Yaml::String(s) => Some(s.clone()),
Yaml::Boolean(b) => Some( (if *b {"true"} else {"false"}).to_string() ),
Yaml::Integer(i) => Some( format!("{}", *i)),
Yaml::Real(s) => Some(s.clone()),
_ => None,
},
}
});
}
pub fn set_preference(name: String, value: String) -> Result<()> {
return crate::speech::SPEECH_RULES.with(|rules| {
let mut rules = rules.borrow_mut();
if let Some(error_string) = rules.get_error() {
bail!("{}", error_string);
}
match name.as_str() {
"SpeechStyle" => {
let files_changed;
{
let mut pref_manager = rules.pref_manager.borrow_mut();
files_changed = pref_manager.set_user_prefs("SpeechStyle", &value);
};
rules.invalidate(files_changed);
},
"Language" => {
if !( value.len() == 2 ||
(value.len() == 5 && value.as_bytes()[2] == b'-') ) {
bail!("Improper format for 'Language' preference '{}'. Should be of form 'en' or 'en-gb'", value);
}
let files_changed = rules.pref_manager.borrow_mut().set_user_prefs(&name, &value);
rules.invalidate(files_changed);
},
"BrailleCode" => {
let files_changed = rules.pref_manager.borrow_mut().set_user_prefs(&name, &value);
crate::speech::BRAILLE_RULES.with(|braille_rules| {
braille_rules.borrow_mut().invalidate(files_changed);
})
},
"Pitch" | "Rate" | "Volume" => {
rules.pref_manager.borrow_mut().set_api_float_pref(&name, to_float(&name, value)?);
},
"Bookmark" => {
rules.pref_manager.borrow_mut().set_api_boolean_pref(&name, value.to_lowercase()=="true");
},
_ => {
rules.pref_manager.borrow_mut().set_user_prefs(&name, &value);
}
}
return Ok( () );
});
fn to_float(name: &str, value: String) -> Result<f64> {
match value.parse::<f64>() {
Ok(val) => return Ok(val),
Err(_) => bail!("SetPreference: preference'{}'s value '{}' must be a float", name, value),
};
}
}
pub fn get_braille(nav_node_id: String) -> Result<String> {
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
let braille = crate::braille::braille_mathml(mathml, nav_node_id)?;
return Ok( braille );
});
}
pub fn do_navigate_keypress(key: usize, shift_key: bool, control_key: bool, alt_key: bool, meta_key: bool) -> Result<String> {
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
return do_mathml_navigate_key_press(mathml, key, shift_key, control_key, alt_key, meta_key);
});
}
pub fn do_navigate_command(command: String) -> Result<String> {
let command = NAV_COMMANDS.get_key(&command);
if command.is_none() {
bail!("Unknown command in call to DoNavigateCommand()");
};
let command = *command.unwrap();
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
return do_navigate_command_string(mathml, command);
});
}
pub fn get_navigation_mathml() -> Result<(String, usize)> {
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
return NAVIGATION_STATE.with(|nav_stack| {
return match nav_stack.borrow_mut().get_navigation_mathml(mathml) {
Err(e) => Err(e),
Ok( (found, offset) ) => Ok( (mml_to_string(&found), offset) ),
}
} )
});
}
pub fn get_navigation_mathml_id() -> Result<(String, usize)> {
return MATHML_INSTANCE.with(|package_instance| {
let package_instance = package_instance.borrow();
let mathml = get_element(&*package_instance);
return Ok( NAVIGATION_STATE.with(|nav_stack| {
return nav_stack.borrow().get_navigation_mathml_id(mathml);
}) )
});
}
pub fn errors_to_string(e:&Error) -> String {
let mut result = String::default();
let mut first_time = true;
for e in e.iter() {
if first_time {
result = format!("{}\n", e);
first_time = false;
} else {
result += &format!("caused by: {}\n", e);
}
}
return result;
}
fn add_ids<'a>(mathml: Element<'a>) -> Element<'a> {
use std::time::SystemTime;
let time = if cfg!(target_family = "wasm") {
rand::random::<usize>()
} else {
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as usize
};
let time_part = radix_fmt::radix(time, 36).to_string();
let random_part = radix_fmt::radix(rand::random::<usize>(), 36).to_string();
let prefix = "M".to_string() + &time_part[time_part.len()-3..] + &random_part[random_part.len()-4..] + "-";
add_ids_to_all(mathml, &prefix, 0);
return mathml;
fn add_ids_to_all<'a>(mathml: Element<'a>, id_prefix: &str, count: usize) -> usize {
let mut count = count;
if mathml.attribute("id").is_none() {
mathml.set_attribute_value("id", (id_prefix.to_string() + &count.to_string()).as_str());
mathml.set_attribute_value("data-id-added", "true");
count += 1;
};
if crate::xpath_functions::is_leaf(mathml) {
return count;
}
for child in mathml.children() {
let child = crate::canonicalize::as_element(child);
count = add_ids_to_all(child, id_prefix, count);
}
return count;
}
}
pub fn get_element<'a>(package: &'a Package) -> Element<'a> {
let doc = package.as_document();
let mut result = None;
for root_child in doc.root().children() {
if let ChildOfRoot::Element(e) = root_child {
assert!(result == None);
result = Some(e);
}
};
return result.unwrap();
}
#[allow(dead_code)]
fn trim_doc(doc: &Document) {
for root_child in doc.root().children() {
if let ChildOfRoot::Element(e) = root_child {
trim_element(&e);
} else {
doc.root().remove_child(root_child);
}
};
}
pub fn trim_element(e: &Element) {
if is_leaf(*e) {
make_leaf_element(*e);
return;
}
let mut single_text = "".to_string();
for child in e.children() {
match child {
ChildOfElement::Element(c) => {
trim_element(&c);
},
ChildOfElement::Text(t) => {
single_text += t.text();
e.remove_child(child);
},
_ => {
e.remove_child(child);
}
}
}
const TEMP_NBSP: &str = "\u{F8FB}";
let trimmed_text = single_text.replace(" ", TEMP_NBSP).trim().replace(TEMP_NBSP, " ");
if !e.children().is_empty() && !trimmed_text.is_empty() {
error!("trim_element: both element and textual children which shouldn't happen -- ignoring text '{}'", single_text);
}
if e.children().is_empty() && !single_text.is_empty() {
e.set_text(&trimmed_text);
}
fn make_leaf_element(mathml_leaf: Element) {
let children = mathml_leaf.children();
if children.is_empty() {
return;
}
let mut text ="".to_string();
for child in children {
match child {
ChildOfElement::Element(e) => {
make_leaf_element(e);
match e.children()[0] {
ChildOfElement::Text(t) => text += t.text(),
_ => panic!("as_text: internal error -- make_leaf_element found non-text child"),
}
}
ChildOfElement::Text(t) => text += t.text(),
_ => (),
}
}
mathml_leaf.clear_children();
mathml_leaf.set_text(&text);
}
}
#[allow(dead_code)]
fn is_same_doc(doc1: &Document, doc2: &Document) -> bool {
if doc1.root().children().len() != doc2.root().children().len() {
return false;
}
for root_child in doc1.root().children().iter().zip(doc2.root().children().iter()) {
let (c1, c2) = root_child;
match c1 {
ChildOfRoot::Element(e1) => {
if let ChildOfRoot::Element(e2) = c2 {
if is_same_element(e1, e2) {
continue;
}
}
return false;
},
ChildOfRoot::Comment(com1) => {
if let ChildOfRoot::Comment(com2) = c2 {
if com1.text() == com2.text() {
continue;
}
}
return false;
}
ChildOfRoot::ProcessingInstruction(p1) => {
if let ChildOfRoot::ProcessingInstruction(p2) = c2 {
if p1.target() == p2.target() && p1.value() == p2.value() {
continue;
}
}
return false;
}
}
};
return true;
}
#[allow(dead_code)]
pub fn is_same_element(e1: &Element, e2: &Element) -> bool {
if e1.children().len() != e2.children().len() {
return false;
}
for element_child in e1.children().iter().zip(e2.children().iter()) {
let (c1, c2) = element_child;
match c1 {
ChildOfElement::Element(child1) => {
if let ChildOfElement::Element(child2) = c2 {
if is_same_element(child1, child2) {
continue;
}
}
return false;
},
ChildOfElement::Comment(com1) => {
if let ChildOfElement::Comment(com2) = c2 {
if com1.text() == com2.text() {
continue;
}
}
return false;
}
ChildOfElement::ProcessingInstruction(p1) => {
if let ChildOfElement::ProcessingInstruction(p2) = c2 {
if p1.target() == p2.target() && p1.value() == p2.value() {
continue;
}
}
return false;
}
ChildOfElement::Text(t1) => {
if let ChildOfElement::Text(t2) = c2 {
if t1.text() == t2.text() {
continue;
}
}
return false;
}
}
};
return true;
}
#[cfg(test)]
mod tests {
use super::*;
fn are_parsed_strs_equal(str1: &str, str2: &str) -> bool {
let package1 = &parser::parse(str1).expect("Failed to parse input");
let doc1 = package1.as_document();
trim_doc(&doc1);
debug!("doc1:\n{}", mml_to_string(&get_element(&package1)));
let package2 = parser::parse(str2).expect("Failed to parse input");
let doc2 = package2.as_document();
trim_doc(&doc2);
debug!("doc2:\n{}", mml_to_string(&get_element(&package2)));
is_same_doc(&doc1, &doc2)
}
#[test]
fn trim_same() {
let trimmed_str = "<math><mrow><mo>-</mo><mi>a</mi></mrow></math>";
assert!(are_parsed_strs_equal(trimmed_str, trimmed_str));
}
#[test]
fn trim_whitespace() {
let trimmed_str = "<math><mrow><mo>-</mo><mi> a </mi></mrow></math>";
let whitespace_str = "<math> <mrow ><mo>-</mo><mi> a </mi></mrow ></math>";
assert!(are_parsed_strs_equal(trimmed_str, whitespace_str));
}
#[test]
fn no_trim_whitespace_nbsp() {
let trimmed_str = "<math><mrow><mo>-</mo><mtext>  a </mtext></mrow></math>";
let whitespace_str = "<math> <mrow ><mo>-</mo><mtext>  a </mtext></mrow ></math>";
assert!(are_parsed_strs_equal(trimmed_str, whitespace_str));
}
#[test]
fn trim_comment() {
let whitespace_str = "<math> <mrow ><mo>-</mo><mi> a </mi></mrow ></math>";
let comment_str = "<math><mrow><mo>-</mo><!--a comment --><mi> a </mi></mrow></math>";
assert!(are_parsed_strs_equal(comment_str, whitespace_str));
}
#[test]
fn trim_differs() {
let whitespace_str = "<math> <mrow ><mo>-</mo><mi> a </mi></mrow ></math>";
let different_str = "<math> <mrow ><mo>-</mo><mi> b </mi></mrow ></math>";
assert!(!are_parsed_strs_equal(different_str, whitespace_str));
}
}