smartcalc_tauri/
session.rs1use core::cell::{Cell, RefCell};
8use alloc::collections::BTreeMap;
9use alloc::string::{String, ToString};
10
11use alloc::{rc::Rc, vec::Vec};
12use regex::Regex;
13
14use crate::variable::VariableInfo;
15
16#[derive(Default)]
17pub struct Session {
18 text: String,
19 text_parts: Vec<String>,
20 language: String,
21 position: Cell<usize>,
22
23 pub(crate) variables: RefCell<BTreeMap<String, Rc<VariableInfo>>>
24}
25
26impl Session {
27 pub fn new() -> Session {
31 Session {
32 text: String::new(),
33 text_parts: Vec::new(),
34 language: String::new(),
35 variables: RefCell::new(BTreeMap::new()),
36 position: Cell::default()
37 }
38 }
39
40 pub fn set_text(&mut self, text: String) {
42 self.text = text;
43
44 self.text_parts = match Regex::new(r"\r\n|\n") {
45 Ok(re) => re.split(&self.text).map(|item| item.to_string()).collect::<Vec<_>>(),
46 _ => self.text.lines().map(|item| item.to_string()).collect::<Vec<_>>()
47 };
48 }
49
50 pub fn set_language(&mut self, language: String) {
52 self.language = language;
53 }
54
55 pub(crate) fn current_line(&self) -> &'_ String {
56 &self.text_parts[self.position.get()]
57 }
58
59 pub(crate) fn has_value(&self) -> bool {
60 self.text_parts.len() > self.position.get()
61 }
62
63 pub(crate) fn line_count(&self) -> usize {
64 self.text_parts.len()
65 }
66
67 pub(crate) fn next_line(&self) -> Option<&'_ String> {
68 match self.text_parts.len() > self.position.get() + 1 {
69 true => {
70 let current = Some(self.current_line());
71 self.position.set(self.position.get() + 1);
72 current
73 }
74 false => None
75 }
76 }
77
78 pub(crate) fn add_variable(&self, variable_info: Rc<VariableInfo>) {
79 self.variables.borrow_mut().insert(variable_info.to_string(), variable_info);
80 }
81
82 pub fn get_language(&self) -> String {
84 self.language.to_string()
85 }
86}