node_launchpad/components/popup/
manage_nodes.rs

1// Copyright 2024 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use std::path::PathBuf;
10
11use crate::action::OptionsActions;
12use crate::system::get_available_space_b;
13use color_eyre::Result;
14use crossterm::event::{Event, KeyCode, KeyEvent};
15use ratatui::{prelude::*, widgets::*};
16use tui_input::{backend::crossterm::EventHandler, Input};
17
18use crate::{
19    action::Action,
20    mode::{InputMode, Scene},
21    style::{clear_area, EUCALYPTUS, GHOST_WHITE, LIGHT_PERIWINKLE, VIVID_SKY_BLUE},
22};
23
24use super::super::{utils::centered_rect_fixed, Component};
25
26pub const GB_PER_NODE: usize = 35;
27pub const MB: usize = 1000 * 1000;
28pub const GB: usize = MB * 1000;
29pub const MAX_NODE_COUNT: usize = 50;
30
31pub struct ManageNodes {
32    /// Whether the component is active right now, capturing keystrokes + drawing things.
33    active: bool,
34    available_disk_space_gb: usize,
35    storage_mountpoint: PathBuf,
36    nodes_to_start_input: Input,
37    // cache the old value incase user presses Esc.
38    old_value: String,
39}
40
41impl ManageNodes {
42    pub fn new(nodes_to_start: usize, storage_mountpoint: PathBuf) -> Result<Self> {
43        let nodes_to_start = std::cmp::min(nodes_to_start, MAX_NODE_COUNT);
44        let new = Self {
45            active: false,
46            available_disk_space_gb: get_available_space_b(&storage_mountpoint)? / GB,
47            nodes_to_start_input: Input::default().with_value(nodes_to_start.to_string()),
48            old_value: Default::default(),
49            storage_mountpoint: storage_mountpoint.clone(),
50        };
51        Ok(new)
52    }
53
54    fn get_nodes_to_start_val(&self) -> usize {
55        self.nodes_to_start_input.value().parse().unwrap_or(0)
56    }
57
58    // Returns the max number of nodes to start
59    // It is the minimum of the available disk space and the max nodes limit
60    fn max_nodes_to_start(&self) -> usize {
61        std::cmp::min(self.available_disk_space_gb / GB_PER_NODE, MAX_NODE_COUNT)
62    }
63}
64
65impl Component for ManageNodes {
66    fn handle_key_events(&mut self, key: KeyEvent) -> Result<Vec<Action>> {
67        if !self.active {
68            return Ok(vec![]);
69        }
70
71        // while in entry mode, key bindings are not captured, so gotta exit entry mode from here
72        let send_back = match key.code {
73            KeyCode::Enter => {
74                let nodes_to_start_str = self.nodes_to_start_input.value().to_string();
75                let nodes_to_start =
76                    std::cmp::min(self.get_nodes_to_start_val(), self.max_nodes_to_start());
77
78                // set the new value
79                self.nodes_to_start_input = self
80                    .nodes_to_start_input
81                    .clone()
82                    .with_value(nodes_to_start.to_string());
83
84                debug!(
85                        "Got Enter, value found to be {nodes_to_start} derived from input: {nodes_to_start_str:?} and switching scene",
86                    );
87                vec![
88                    Action::StoreNodesToStart(nodes_to_start),
89                    Action::SwitchScene(Scene::Status),
90                ]
91            }
92            KeyCode::Esc => {
93                debug!(
94                    "Got Esc, restoring the old value {} and switching to home",
95                    self.old_value
96                );
97                // reset to old value
98                self.nodes_to_start_input = self
99                    .nodes_to_start_input
100                    .clone()
101                    .with_value(self.old_value.clone());
102                vec![Action::SwitchScene(Scene::Status)]
103            }
104            KeyCode::Char(c) if c.is_numeric() => {
105                // don't allow leading zeros
106                if c == '0' && self.nodes_to_start_input.value().is_empty() {
107                    return Ok(vec![]);
108                }
109                let number = c.to_string().parse::<usize>().unwrap_or(0);
110                let new_value = format!("{}{}", self.get_nodes_to_start_val(), number)
111                    .parse::<usize>()
112                    .unwrap_or(0);
113                // if it might exceed the available space or if more than max_node_count, then enter the max
114                if new_value * GB_PER_NODE > self.available_disk_space_gb
115                    || new_value > MAX_NODE_COUNT
116                {
117                    self.nodes_to_start_input = self
118                        .nodes_to_start_input
119                        .clone()
120                        .with_value(self.max_nodes_to_start().to_string());
121                    return Ok(vec![]);
122                }
123                self.nodes_to_start_input.handle_event(&Event::Key(key));
124                vec![]
125            }
126            KeyCode::Backspace => {
127                self.nodes_to_start_input.handle_event(&Event::Key(key));
128                vec![]
129            }
130            KeyCode::Up | KeyCode::Down => {
131                let nodes_to_start = {
132                    let current_val = self.get_nodes_to_start_val();
133
134                    if key.code == KeyCode::Up {
135                        if current_val + 1 >= MAX_NODE_COUNT {
136                            MAX_NODE_COUNT
137                        } else if (current_val + 1) * GB_PER_NODE <= self.available_disk_space_gb {
138                            current_val + 1
139                        } else {
140                            current_val
141                        }
142                    } else {
143                        // Key::Down
144                        if current_val == 0 {
145                            0
146                        } else {
147                            current_val - 1
148                        }
149                    }
150                };
151                // set the new value
152                self.nodes_to_start_input = self
153                    .nodes_to_start_input
154                    .clone()
155                    .with_value(nodes_to_start.to_string());
156                vec![]
157            }
158            _ => {
159                vec![]
160            }
161        };
162        Ok(send_back)
163    }
164
165    fn update(&mut self, action: Action) -> Result<Option<Action>> {
166        let send_back = match action {
167            Action::SwitchScene(scene) => match scene {
168                Scene::ManageNodesPopUp => {
169                    self.active = true;
170                    self.old_value = self.nodes_to_start_input.value().to_string();
171                    // set to entry input mode as we want to handle everything within our handle_key_events
172                    // so by default if this scene is active, we capture inputs.
173                    Some(Action::SwitchInputMode(InputMode::Entry))
174                }
175                _ => {
176                    self.active = false;
177                    None
178                }
179            },
180            Action::OptionsActions(OptionsActions::UpdateStorageDrive(mountpoint, _drive_name)) => {
181                self.storage_mountpoint.clone_from(&mountpoint);
182                self.available_disk_space_gb = get_available_space_b(&mountpoint)? / GB;
183                None
184            }
185            _ => None,
186        };
187        Ok(send_back)
188    }
189
190    fn draw(&mut self, f: &mut crate::tui::Frame<'_>, area: Rect) -> Result<()> {
191        if !self.active {
192            return Ok(());
193        }
194
195        let layer_zero = centered_rect_fixed(52, 15, area);
196        let layer_one = Layout::new(
197            Direction::Vertical,
198            [
199                // for the pop_up_border
200                Constraint::Length(2),
201                // for the input field
202                Constraint::Length(1),
203                // for the info field telling how much gb used
204                Constraint::Length(1),
205                // gap before help
206                Constraint::Length(1),
207                // for the help
208                Constraint::Length(7),
209                // for the dash
210                Constraint::Min(1),
211                // for the buttons
212                Constraint::Length(1),
213                // for the pop_up_border
214                Constraint::Length(1),
215            ],
216        )
217        .split(layer_zero);
218        let pop_up_border = Paragraph::new("").block(
219            Block::default()
220                .borders(Borders::ALL)
221                .title(" Manage Nodes ")
222                .bold()
223                .title_style(Style::new().fg(GHOST_WHITE))
224                .title_style(Style::new().fg(EUCALYPTUS))
225                .padding(Padding::uniform(2))
226                .border_style(Style::new().fg(EUCALYPTUS)),
227        );
228        clear_area(f, layer_zero);
229
230        // ==== input field ====
231        let layer_input_field = Layout::new(
232            Direction::Horizontal,
233            [
234                // for the gap
235                Constraint::Min(5),
236                // Start
237                Constraint::Length(5),
238                // Input box
239                Constraint::Length(5),
240                // Nodes(s)
241                Constraint::Length(8),
242                // gap
243                Constraint::Min(5),
244            ],
245        )
246        .split(layer_one[1]);
247
248        let start = Paragraph::new("Start ").style(Style::default().fg(GHOST_WHITE));
249        f.render_widget(start, layer_input_field[1]);
250
251        let width = layer_input_field[2].width.max(3) - 3;
252        let scroll = self.nodes_to_start_input.visual_scroll(width as usize);
253        let input = Paragraph::new(self.get_nodes_to_start_val().to_string())
254            .style(Style::new().fg(VIVID_SKY_BLUE))
255            .scroll((0, scroll as u16))
256            .alignment(Alignment::Center);
257
258        f.render_widget(input, layer_input_field[2]);
259
260        let nodes_text = Paragraph::new("Node(s)").fg(GHOST_WHITE);
261        f.render_widget(nodes_text, layer_input_field[3]);
262
263        // ==== info field ====
264        let available_space_gb = self.available_disk_space_gb;
265        let info_style = Style::default().fg(VIVID_SKY_BLUE);
266        let info = Line::from(vec![
267            Span::styled("Using", info_style),
268            Span::styled(
269                format!(" {}GB ", self.get_nodes_to_start_val() * GB_PER_NODE),
270                info_style.bold(),
271            ),
272            Span::styled(
273                format!("of {available_space_gb}GB available space"),
274                info_style,
275            ),
276        ]);
277        let info = Paragraph::new(info).alignment(Alignment::Center);
278        f.render_widget(info, layer_one[2]);
279
280        // ==== help ====
281        let help = Paragraph::new(vec![
282            Line::raw(format!(
283                "Note: Each node will use a small amount of CPU Memory and Network Bandwidth. \
284                 We recommend starting no more than 5 at a time (max {MAX_NODE_COUNT} nodes)."
285            )),
286            Line::raw(""),
287            Line::raw("▲▼ to change the number of nodes to start."),
288        ])
289        .wrap(Wrap { trim: false })
290        .block(Block::default().padding(Padding::horizontal(4)))
291        .alignment(Alignment::Center)
292        .fg(GHOST_WHITE);
293        f.render_widget(help, layer_one[4]);
294
295        // ==== dash ====
296        let dash = Block::new()
297            .borders(Borders::BOTTOM)
298            .border_style(Style::new().fg(GHOST_WHITE));
299        f.render_widget(dash, layer_one[5]);
300
301        // ==== buttons ====
302        let buttons_layer =
303            Layout::horizontal(vec![Constraint::Percentage(45), Constraint::Percentage(55)])
304                .split(layer_one[6]);
305
306        let button_no = Line::from(vec![Span::styled(
307            "  Close [Esc]",
308            Style::default().fg(LIGHT_PERIWINKLE),
309        )]);
310        f.render_widget(button_no, buttons_layer[0]);
311        let button_yes = Line::from(vec![Span::styled(
312            "Start Node(s) [Enter]  ",
313            Style::default().fg(EUCALYPTUS),
314        )]);
315        let button_yes = Paragraph::new(button_yes).alignment(Alignment::Right);
316        f.render_widget(button_yes, buttons_layer[1]);
317
318        f.render_widget(pop_up_border, layer_zero);
319
320        Ok(())
321    }
322}