stama 1.1.1

A terminal user interface for monitoring and managing slurm jobs.
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
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEventKind};
use ratatui::{
    prelude::*,
    style::{Color, Style},
    widgets::*,
};

use crate::{app::Action, mouse_input::MouseInput};

use crate::menus::help::HelpContext;
use crate::menus::{centered_popup, wrap_index, Menu, OpenMenu, PopupSize};

use super::salloc_list::SallocList;
use super::{entry_menu::EntryMenu, salloc_entry::SallocEntry};

/// Which part of the menu is in focus
pub enum Focus {
    List,
    Entry,
}

/// Job Allocation Menu
///
/// Contains a list of editable presets
pub struct SallocMenu {
    /// Whether the menu is open (rendered and handling input)
    open: bool,
    /// The rectangle where to render the menu (for mouse input)
    rect: Rect,
    /// The presets pane:
    /// Rectangle where the presets list is rendered
    preset_pane: Rect,
    /// The settings pane:
    /// Rectangle where the settings list is rendered
    settings_pane: Rect,
    /// The list of salloc entries
    salloc_list: SallocList<SallocEntry>,
    /// The entry info menu
    entry_menu: EntryMenu,
    /// The selection state
    state: ListState,
    /// Which part of the menu is in Focus
    focus: Focus,
}

// ====================================================================
//  CONSTRUCTOR
// ====================================================================

impl Default for SallocMenu {
    fn default() -> Self {
        Self::new()
    }
}

impl SallocMenu {
    pub fn new() -> SallocMenu {
        let salloc_list = SallocList::load(None).unwrap_or_else(|_| SallocList::new());
        let mut salloc_menu = SallocMenu {
            open: false,
            salloc_list,
            rect: Rect::default(),
            preset_pane: Rect::default(),
            settings_pane: Rect::default(),
            entry_menu: EntryMenu::new(None),
            state: ListState::default(),
            focus: Focus::List,
        };
        salloc_menu.set_index(0);
        salloc_menu
    }
}

// ====================================================================
//  METHODS
// ====================================================================

impl SallocMenu {
    /// Activate the menu
    pub fn activate(&mut self) {
        self.open = true;
    }

    /// Deactivate the menu
    pub fn deactivate(&mut self) {
        self.open = false;
        let _ = self.salloc_list.save(None);
    }

    /// Set the index of list state. The list has one synthetic
    /// trailing row ("Create new"), so index == len is a valid
    /// selection and the wrap length is len + 1.
    pub fn set_index(&mut self, index: i32) {
        let new_index = wrap_index(index as isize, 0, self.salloc_list.len() + 1);
        self.state.select(Some(new_index));
        self.entry_menu = EntryMenu::new(self.get_salloc_entry());
    }

    /// Select the next salloc entry
    fn next(&mut self) {
        let index = self.state.selected();
        if let Some(ind) = index {
            self.set_index(ind as i32 + 1)
        };
    }

    /// Select the previous salloc entry
    fn previous(&mut self) {
        let index = self.state.selected();
        if let Some(ind) = index {
            self.set_index(ind as i32 - 1)
        };
    }

    /// Acitvate the Presets Menu
    fn focus_preset(&mut self) {
        self.entry_menu.is_active = false;
        // save the entry (ignore errors)
        let _ = self.salloc_list.save(None);
        self.focus = Focus::List
    }

    /// Activate the Settings Menu
    fn focus_settings(&mut self) {
        self.entry_menu.is_active = true;
        self.focus = Focus::Entry
    }

    /// Switch focus between list and entry
    fn toggle_focus(&mut self) {
        match self.focus {
            Focus::List => self.focus_settings(),
            Focus::Entry => self.focus_preset(),
        }
    }

    /// Get the currently selected Salloc Entry
    /// Returns None if no entry is selected
    fn get_salloc_entry(&self) -> Option<&SallocEntry> {
        let index = self.state.selected()?;
        self.salloc_list.entries.get(index)
    }

    /// Create a new salloc entry
    fn create_new_salloc_entry(&mut self) {
        self.salloc_list.entries.push(SallocEntry::new());
    }

    /// set the current entry to the given entry
    fn set_entry(&mut self, entry: SallocEntry) {
        let index = match self.state.selected() {
            Some(ind) => ind,
            None => return,
        };
        if index < self.salloc_list.len() {
            self.salloc_list.entries[index] = entry;
        } else {
            // the selection is on the "Create new" row:
            // editing it creates a new entry. The selected index now
            // points to the pushed entry, so further edits update it.
            self.salloc_list.entries.push(entry);
        }
    }

    /// Start the selected salloc entry
    /// If no entry is selected, create a new one
    fn start_salloc(&mut self, action: &mut Action) {
        match self.get_salloc_entry() {
            Some(entry) => {
                let cmd = entry.start();
                *action = Action::StartSalloc(cmd);
                self.deactivate();
            }
            None => {
                self.create_new_salloc_entry();
            }
        }
    }

    /// Delete the currently selected entry
    /// If the selection is on the create new entry, do nothing
    pub fn delete_current_entry(&mut self) {
        let index = match self.state.selected() {
            Some(ind) => ind,
            None => return,
        };
        if index == self.salloc_list.len() {
            return;
        }
        self.salloc_list.entries.remove(index);
        // saturate on the usize so deleting the first entry keeps the
        // selection at index 0 instead of wrapping to the "Create new" row
        self.set_index(index.saturating_sub(1) as i32);
    }
}

// ====================================================================
//  MENU TRAIT (RENDERING + INPUT)
// ====================================================================

impl Menu for SallocMenu {
    fn is_open(&self) -> bool {
        self.open
    }

    /// Render the full salloc menu
    /// This is the main render function
    fn render(&mut self, f: &mut Frame, _area: &Rect) {
        let rect = centered_popup(f.area(), PopupSize::Fraction(0.8), PopupSize::Fraction(0.8));
        self.rect = rect;

        // clear the rect
        f.render_widget(Clear, rect); //this clears out the background

        let block = Block::default()
            .title_top(Line::from(" SALLOC ").alignment(Alignment::Center))
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Blue))
            .title_style(
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            );

        f.render_widget(block.clone(), rect);

        // create two columns:
        //  - left column: list of salloc entries
        //  - right column: the selected salloc entry
        let layout = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
            .split(block.inner(rect));

        // update the panes
        self.preset_pane = layout[0];
        self.settings_pane = layout[1];

        self.render_list(f, &layout[0]);
        self.render_entry(f, &layout[1]);
    }

    /// Handle user input for the salloc menu
    /// Always returns true (no input is passed to windows below)
    fn input(&mut self, action: &mut Action, key_event: KeyEvent) -> bool {
        if key_event.code == KeyCode::Tab {
            self.toggle_focus();
            return true;
        }

        match self.focus {
            Focus::List => self.input_list(action, key_event),
            Focus::Entry => self.input_entry(action, key_event),
        }
    }

    fn mouse_input(&mut self, action: &mut Action, mouse_input: &mut MouseInput) {
        // first update the focused window pane
        if let Some(MouseEventKind::Down(MouseButton::Left)) = mouse_input.kind() {
            // close the window if the user clicks outside of it
            if !self.rect.contains(mouse_input.get_position()) {
                self.deactivate();
                mouse_input.click();
                return;
            }
            if self.preset_pane.contains(mouse_input.get_position()) {
                self.focus_preset();
            } else if self.settings_pane.contains(mouse_input.get_position()) {
                self.focus_settings();
            }
        };

        // handle the mouse input for the focused window pane
        match self.focus {
            Focus::List => self.mouse_input_list(action, mouse_input),
            Focus::Entry => self.entry_menu.mouse_input(action, mouse_input),
        }

        // Set the mouse event to handled
        mouse_input.handled = true;
    }
}

// ====================================================================
//  RENDER HELPERS
// ====================================================================

impl SallocMenu {
    /// Render the list of salloc entries
    /// This renders the left column
    fn render_list(&mut self, f: &mut Frame, area: &Rect) {
        let mut items: Vec<ListItem> = self
            .salloc_list
            .entries
            .iter()
            .map(|entry| ListItem::new(entry.preset_name.clone()))
            .collect();
        items.push(ListItem::new("Create new".to_string()));

        let highlight_style = match self.focus {
            Focus::List => Style::default().fg(Color::Blue),
            Focus::Entry => Style::default(),
        };
        let control_hint = match self.focus {
            Focus::List => "",
            Focus::Entry => "<tab>",
        };

        let list = List::new(items)
            .block(
                Block::default()
                    .title("Presets:")
                    .title_top(Line::from(control_hint).alignment(Alignment::Right))
                    .borders(Borders::ALL)
                    .border_style(highlight_style),
            )
            .highlight_style(Style::default().add_modifier(Modifier::BOLD))
            .highlight_style(highlight_style.reversed());

        f.render_stateful_widget(list, *area, &mut self.state);
    }

    /// Render the selected salloc entry
    /// This renders the right column
    fn render_entry(&mut self, f: &mut Frame, area: &Rect) {
        let highlight_style = match self.focus {
            Focus::List => Style::default(),
            Focus::Entry => Style::default().fg(Color::Blue),
        };
        let control_hint = match self.focus {
            Focus::List => "<tab>",
            Focus::Entry => "",
        };

        let block = Block::default()
            .title("Settings:")
            .title_top(Line::from(control_hint).alignment(Alignment::Right))
            .borders(Borders::ALL)
            .border_style(highlight_style);

        f.render_widget(block.clone(), *area);
        self.entry_menu.render(f, &block.inner(*area));
    }
}

// ====================================================================
//  USER INPUT
// ====================================================================

impl SallocMenu {
    /// Handle user input for the list window
    /// Always return true (no input is passed to windows below)
    fn input_list(&mut self, action: &mut Action, key_event: KeyEvent) -> bool {
        match key_event.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                self.deactivate();
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.next();
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.previous();
            }
            KeyCode::Enter | KeyCode::Char('l') => {
                self.start_salloc(action);
            }
            KeyCode::Char('d')
                // check if the user is trying to delete an existing entry
                if self.get_salloc_entry().is_some() => {
                    *action = Action::RemoveSallocEntryDialog;
                }
            KeyCode::Char('?') => {
                *action = Action::OpenMenu(OpenMenu::Help(HelpContext::AllocationMenu));
            }

            _ => {}
        }
        true
    }

    /// Handle user input for the entry window
    /// Always return true (no input is passed to windows below)
    fn input_entry(&mut self, action: &mut Action, key_event: KeyEvent) -> bool {
        // first handle the input for the entry menu
        let status = self.entry_menu.input(action, key_event);
        // if the input was handled, return true
        if status {
            let new_entry = self.entry_menu.get_entry();
            self.set_entry(new_entry);
            return true;
        }
        // else check for other key events
        match key_event.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                self.deactivate();
                return true;
            }
            KeyCode::Char('?') => {
                *action = Action::OpenMenu(OpenMenu::Help(HelpContext::AllocationMenu));
                return true;
            }

            _ => {}
        }

        true
    }
}

// ====================================================================
//  MOUSE INPUT
// ====================================================================

impl SallocMenu {
    /// Handle mouse input for the list window
    fn mouse_input_list(&mut self, action: &mut Action, mouse_input: &mut MouseInput) {
        if let Some(mouse_event_kind) = mouse_input.kind() {
            match mouse_event_kind {
                // clicking
                MouseEventKind::Down(MouseButton::Left) => {
                    let mouse_pos = mouse_input.get_position();
                    let mut rel_y = mouse_pos.y.saturating_sub(self.preset_pane.y);
                    // adjust for the border
                    rel_y = rel_y.saturating_sub(1);
                    let new_index = rel_y as usize + self.state.offset();
                    self.set_index(new_index as i32);
                    if mouse_input.is_double_click() {
                        self.start_salloc(action);
                    }
                    mouse_input.click();
                }
                // scrolling
                MouseEventKind::ScrollUp => {
                    self.previous();
                }
                MouseEventKind::ScrollDown => {
                    self.next();
                }
                _ => {}
            }
        }
    }
}

// ====================================================================
//  TESTS
// ====================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::menus::Menu;
    use crossterm::event::KeyModifiers;

    /// Build a menu with the given entries whose selection starts at
    /// index 0, without touching the config file on disk
    fn menu_with_entries(entries: Vec<SallocEntry>) -> SallocMenu {
        let mut menu = SallocMenu::new();
        menu.salloc_list = SallocList { entries };
        menu.set_index(0);
        menu
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// Regression test: on a fresh install (no presets), the selection
    /// sits on the synthetic "Create new" row (index == entries.len()).
    /// Pressing Tab and then any key handled by the entry menu used to
    /// panic with an index out of bounds in `set_entry`.
    #[test]
    fn test_input_on_create_new_row_does_not_panic() {
        let mut menu = menu_with_entries(vec![]);
        menu.activate();
        assert_eq!(menu.state.selected(), Some(0));
        assert!(menu.get_salloc_entry().is_none());

        let mut action = Action::None;
        // Tab moves the focus to the settings pane
        menu.input(&mut action, key(KeyCode::Tab));
        // any key handled by the entry menu triggers `set_entry`,
        // which used to index out of bounds
        menu.input(&mut action, key(KeyCode::Down));

        // editing the "Create new" row creates a new entry
        assert_eq!(menu.salloc_list.len(), 1);
        assert_eq!(menu.state.selected(), Some(0));
    }

    /// Calling `set_entry` directly while on the "Create new" row
    /// pushes a new entry instead of panicking
    #[test]
    fn test_set_entry_on_create_new_row_pushes_entry() {
        let mut menu = menu_with_entries(vec![SallocEntry::new()]);
        // select the "Create new" row (index == entries.len())
        menu.set_index(1);

        let mut entry = SallocEntry::new();
        entry.preset_name = "created".to_string();
        menu.set_entry(entry);

        assert_eq!(menu.salloc_list.len(), 2);
        assert_eq!(menu.salloc_list.entries[1].preset_name, "created");
        // further edits update the pushed entry instead of adding more
        let mut entry = SallocEntry::new();
        entry.preset_name = "updated".to_string();
        menu.set_entry(entry);
        assert_eq!(menu.salloc_list.len(), 2);
        assert_eq!(menu.salloc_list.entries[1].preset_name, "updated");
    }

    /// Regression test: deleting the first preset used to wrap the
    /// selection to the "Create new" row instead of keeping it on the
    /// new first entry
    #[test]
    fn test_delete_first_entry_keeps_selection_on_first() {
        let mut first = SallocEntry::new();
        first.preset_name = "first".to_string();
        let mut second = SallocEntry::new();
        second.preset_name = "second".to_string();
        let mut menu = menu_with_entries(vec![first, second]);

        menu.delete_current_entry();

        assert_eq!(menu.salloc_list.len(), 1);
        assert_eq!(menu.state.selected(), Some(0));
        assert_eq!(menu.get_salloc_entry().unwrap().preset_name, "second");
    }

    /// Deleting the only entry leaves the selection on the
    /// "Create new" row (the only remaining row)
    #[test]
    fn test_delete_only_entry_selects_create_new() {
        let mut menu = menu_with_entries(vec![SallocEntry::new()]);

        menu.delete_current_entry();

        assert_eq!(menu.salloc_list.len(), 0);
        assert_eq!(menu.state.selected(), Some(0));
        assert!(menu.get_salloc_entry().is_none());
    }
}