smartcalc_tauri/
session.rs

1/*
2 * smartcalc v1.0.8
3 * Copyright (c) Erhan BARIS (Ruslan Ognyanov Asenov)
4 * Licensed under the GNU General Public License v2.0.
5 */
6
7use 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    /// Create an empty session.
28    ///
29    /// In order to be executed, a session must have a language and some text.
30    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    /// Set the text to be executed.
41    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    /// Set the language used to interpret input.
51    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    /// Returns the language configured for this session.
83    pub fn get_language(&self) -> String {
84        self.language.to_string()
85    }
86}