repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/search.rs
zellij-server/src/panes/search.rs
use super::Selection; use crate::panes::terminal_character::TerminalCharacter; use crate::panes::{Grid, Row}; use std::borrow::Cow; use std::fmt::Debug; use zellij_utils::input::actions::SearchDirection; use zellij_utils::position::Position; // If char is neither alphanumeric nor an underscore do we consider it a word-boundary fn is_word_boundary(x: &Option<char>) -> bool { x.map_or(true, |c| !c.is_ascii_alphanumeric() && c != '_') } #[derive(Debug)] enum SearchSource<'a> { Main(&'a Row), Tail(&'a Row), } impl<'a> SearchSource<'a> { /// Returns true, if a new source was found, false otherwise (reached the end of the tail). /// If we are in the middle of a line, nothing will be changed. /// Only, when we have to switch to a new line, will the source update itself, /// as well as the corresponding indices. fn get_next_source( &mut self, ridx: &mut usize, hidx: &mut usize, tailit: &mut std::slice::Iter<&'a Row>, start: &Option<Position>, ) -> bool { match self { SearchSource::Main(row) => { // If we are at the end of the main row, we need to start looking into the tail if hidx >= &mut row.columns.len() { let curr_tail = tailit.next(); // If we are at the end and found a partial hit, we have to extend the search into the next line if let Some(curr_tail) = start.and(curr_tail) { *ridx += 1; // Go one line down *hidx = 0; // and start from the beginning of the new line *self = SearchSource::Tail(curr_tail); } else { return false; // We reached the end of the tail } } }, SearchSource::Tail(tail) => { if hidx >= &mut tail.columns.len() { // If we are still searching (didn't hit a mismatch yet) and there is still more tail to go // just continue with the next line if let Some(curr_tail) = tailit.next() { *ridx += 1; // Go one line down *hidx = 0; // and start from the beginning of the new line *self = SearchSource::Tail(curr_tail); } else { return false; // We reached the end of the tail } } }, } // We have found a new source, or we are in the middle of a line, so no need to change anything true } // Get the char at hidx and, if existing, the following char as well fn get_next_two_chars(&self, hidx: usize, whole_word_search: bool) -> (char, Option<char>) { // Get the current haystack character let haystack_char = match self { SearchSource::Main(row) => row.columns[hidx].character, SearchSource::Tail(tail) => tail.columns[hidx].character, }; // Get the next haystack character (relevant for whole-word search only) let next_haystack_char = if whole_word_search { // Everything (incl. end of line) that is not [a-zA-Z0-9_] is considered a word boundary match self { SearchSource::Main(row) => row.columns.get(hidx + 1).map(|c| c.character), SearchSource::Tail(tail) => tail.columns.get(hidx + 1).map(|c| c.character), } } else { None // Doesn't get used, when not doing whole-word search }; (haystack_char, next_haystack_char) } } #[derive(Debug, Clone, Default)] pub struct SearchResult { // What we have already found in the viewport pub selections: Vec<Selection>, // Which of the selections we found is currently 'active' (highlighted differently) pub active: Option<Selection>, // What we are looking for pub needle: String, // Does case matter? pub case_insensitive: bool, // Only search whole words, not parts inside a word pub whole_word_only: bool, // TODO // Jump from the bottom to the top (or vice versa), if we run out of lines to search pub wrap_search: bool, } impl SearchResult { /// This is only used for Debug formatting Grid, which itself is only used /// for tests. #[allow(clippy::ptr_arg)] pub(crate) fn mark_search_results_in_row(&self, row: &mut Cow<Row>, ridx: usize) { for s in &self.selections { if s.contains_row(ridx) { let replacement_char = if Some(s) == self.active.as_ref() { '_' } else { '#' }; let (skip, take) = if ridx as isize == s.start.line() { let skip = s.start.column(); let take = if s.end.line() == s.start.line() { s.end.column() - s.start.column() } else { // Just mark the rest of the line. This number is certainly too big but the iterator takes care of this row.columns.len() }; (skip, take) } else if ridx as isize == s.end.line() { // We wrapped a line and the end is in this row, so take from the beginning to the end (0, s.end.column()) } else { // We are in the middle (start is above and end is below), so mark all (0, row.columns.len()) }; row.to_mut() .columns .iter_mut() .skip(skip) .take(take) .for_each(|x| *x = TerminalCharacter::new(replacement_char)); } } } pub fn has_modifiers_set(&self) -> bool { self.wrap_search || self.whole_word_only || self.case_insensitive } fn check_if_haystack_char_matches_needle( &self, nidx: usize, needle_char: char, haystack_char: char, prev_haystack_char: Option<char>, ) -> bool { let mut chars_match = if self.case_insensitive { // Case insensitive search // Currently only ascii, as this whole search-function is very sub-optimal anyways haystack_char.to_ascii_lowercase() == needle_char.to_ascii_lowercase() } else { // Case sensitive search haystack_char == needle_char }; // Whole-word search // It's a match only, if the first haystack char that is _not_ a hit, is a word-boundary if chars_match && self.whole_word_only && nidx == 0 && !is_word_boundary(&prev_haystack_char) { // Start of the match is not a word boundary, so this is not a hit chars_match = false; } chars_match } /// Search a row and its tail. /// The tail are all the non-canonical lines below `row`, with `row` not necessarily being canonical itself. pub(crate) fn search_row(&self, mut ridx: usize, row: &Row, tail: &[&Row]) -> Vec<Selection> { let mut res = Vec::new(); if self.needle.is_empty() || row.columns.is_empty() { return res; } let mut tailit = tail.iter(); let mut source = SearchSource::Main(row); // Where we currently get the haystack-characters from let orig_ridx = ridx; let mut start = None; // If we find a hit, this is where it starts let mut nidx = 0; // Needle index let mut hidx = 0; // Haystack index let mut prev_haystack_char: Option<char> = None; loop { // Get the current and next haystack character let (mut haystack_char, next_haystack_char) = source.get_next_two_chars(hidx, self.whole_word_only); // Get current needle character let needle_char = self.needle.chars().nth(nidx).unwrap(); // Unwrapping is safe here // Check if needle and haystack match (with search-options) let chars_match = self.check_if_haystack_char_matches_needle( nidx, needle_char, haystack_char, prev_haystack_char, ); if chars_match { // If the needle is only 1 long, the next `if` could also happen, so we are not merging it into one big if-else if nidx == 0 { start = Some(Position::new(ridx as i32, hidx as u16)); } if nidx == self.needle.len() - 1 { let mut end_found = true; // If we search whole-word-only, the next non-needle char needs to be a word-boundary, // otherwise its not a hit (e.g. some occurrence inside a longer word). if self.whole_word_only && !is_word_boundary(&next_haystack_char) { // The end of the match is not a word boundary, so this is not a hit! // We have to jump back from where we started (plus one char) nidx = 0; ridx = start.unwrap().line() as usize; hidx = start.unwrap().column(); // Will be incremented below if start.unwrap().line() as usize == orig_ridx { source = SearchSource::Main(row); haystack_char = row.columns[hidx].character; // so that prev_char gets set correctly } else { // The -1 comes from the main row let tail_idx = start.unwrap().line() as usize - orig_ridx - 1; // We have to reset the tail-iterator as well. tailit = tail[tail_idx..].iter(); let trow = tailit.next().unwrap(); haystack_char = trow.columns[hidx].character; // so that prev_char gets set correctly source = SearchSource::Tail(trow); } start = None; end_found = false; } if end_found { let mut selection = Selection::default(); selection.start(start.unwrap()); selection.end(Position::new(ridx as i32, (hidx + 1) as u16)); res.push(selection); nidx = 0; if matches!(source, SearchSource::Tail(..)) { // When searching the tail, we can only find one additional selection, so stopping here break; } } } else { nidx += 1; } } else { // Chars don't match. Start searching the needle from the beginning start = None; nidx = 0; if matches!(source, SearchSource::Tail(..)) { // When searching the tail and we find a mismatch, just quit right now break; } } hidx += 1; prev_haystack_char = Some(haystack_char); // We might need to switch to a new line in the tail if !source.get_next_source(&mut ridx, &mut hidx, &mut tailit, &start) { break; } } // The tail may have not been wrapped yet (when coming from lines_below), // so it could be that the end extends across more characters than the row is wide. // Therefore we need to reflow the end: for s in res.iter_mut() { while s.end.column() > row.width() { s.end.column.0 -= row.width(); s.end.line.0 += 1; } } res } pub(crate) fn move_active_selection_to_next(&mut self) { if let Some(active_idx) = self.active { self.active = self .selections .iter() .skip_while(|s| *s != &active_idx) .nth(1) .cloned(); } else { self.active = self.selections.first().cloned(); } } pub(crate) fn move_active_selection_to_prev(&mut self) { if let Some(active_idx) = self.active { self.active = self .selections .iter() .rev() .skip_while(|s| *s != &active_idx) .nth(1) .cloned(); } else { self.active = self.selections.last().cloned(); } } pub(crate) fn unset_active_selection_if_nonexistent(&mut self) { if let Some(active_idx) = self.active { if !self.selections.contains(&active_idx) { self.active = None; } } } pub(crate) fn move_down( &mut self, amount: usize, viewport: &[Row], grid_height: usize, ) -> bool { let mut found_something = false; self.selections .iter_mut() .chain(self.active.iter_mut()) .for_each(|x| x.move_down(amount)); // Throw out all search-results outside of the new viewport self.adjust_selections_to_moved_viewport(grid_height); // Search the new line for our needle if !self.needle.is_empty() { if let Some(row) = viewport.first() { let mut tail = Vec::new(); loop { let tail_idx = 1 + tail.len(); if tail_idx < viewport.len() && !viewport[tail_idx].is_canonical { tail.push(&viewport[tail_idx]); } else { break; } } let selections = self.search_row(0, row, &tail); for selection in selections.iter().rev() { self.selections.insert(0, *selection); found_something = true; } } } found_something } pub(crate) fn move_up( &mut self, amount: usize, viewport: &[Row], lines_below: &[Row], grid_height: usize, ) -> bool { let mut found_something = false; self.selections .iter_mut() .chain(self.active.iter_mut()) .for_each(|x| x.move_up(amount)); // Throw out all search-results outside of the new viewport self.adjust_selections_to_moved_viewport(grid_height); // Search the new line for our needle if !self.needle.is_empty() { if let Some(row) = viewport.last() { let tail: Vec<&Row> = lines_below.iter().take_while(|r| !r.is_canonical).collect(); let selections = self.search_row(viewport.len() - 1, row, &tail); for selection in selections { // We are only interested in results that start in the this new row if selection.start.line() as usize == viewport.len() - 1 { self.selections.push(selection); found_something = true; } } } } found_something } fn adjust_selections_to_moved_viewport(&mut self, grid_height: usize) { // Throw out all search-results outside of the new viewport self.selections .retain(|s| (s.start.line() as usize) < grid_height && s.end.line() >= 0); // If we have thrown out the active element, set it to None self.unset_active_selection_if_nonexistent(); } } impl Grid { pub fn search_down(&mut self) { self.search_scrollbuffer(SearchDirection::Down); } pub fn search_up(&mut self) { self.search_scrollbuffer(SearchDirection::Up); } pub fn clear_search(&mut self) { // Clearing all previous highlights for res in &self.search_results.selections { self.output_buffer .update_lines(res.start.line() as usize, res.end.line() as usize); } self.search_results = Default::default(); } pub fn set_search_string(&mut self, needle: &str) { self.search_results.needle = needle.to_string(); self.search_viewport(); // If the current viewport does not contain any hits, // we jump around until we find something. Starting // going backwards. if self.search_results.selections.is_empty() { self.search_up(); } if self.search_results.selections.is_empty() { self.search_down(); } // We still don't want to pre-select anything at this stage self.search_results.active = None; self.is_scrolled = true; } pub fn search_viewport(&mut self) { for ridx in 0..self.viewport.len() { let row = &self.viewport[ridx]; let mut tail = Vec::new(); loop { let tail_idx = ridx + tail.len() + 1; if tail_idx < self.viewport.len() && !self.viewport[tail_idx].is_canonical { tail.push(&self.viewport[tail_idx]); } else { break; } } let selections = self.search_results.search_row(ridx, row, &tail); for sel in &selections { // Cast works because we can' be negative here self.output_buffer .update_lines(sel.start.line() as usize, sel.end.line() as usize); } for selection in selections { self.search_results.selections.push(selection); } } } pub fn toggle_search_case_sensitivity(&mut self) { self.search_results.case_insensitive = !self.search_results.case_insensitive; for line in self.search_results.selections.drain(..) { self.output_buffer .update_lines(line.start.line() as usize, line.end.line() as usize); } self.search_viewport(); // Maybe the selection we had is now gone self.search_results.unset_active_selection_if_nonexistent(); } pub fn toggle_search_wrap(&mut self) { self.search_results.wrap_search = !self.search_results.wrap_search; } pub fn toggle_search_whole_words(&mut self) { self.search_results.whole_word_only = !self.search_results.whole_word_only; for line in self.search_results.selections.drain(..) { self.output_buffer .update_lines(line.start.line() as usize, line.end.line() as usize); } self.search_results.active = None; self.search_viewport(); // Maybe the selection we had is now gone self.search_results.unset_active_selection_if_nonexistent(); } fn search_scrollbuffer(&mut self, dir: SearchDirection) { let first_sel = self.search_results.selections.first(); let last_sel = self.search_results.selections.last(); let search_viewport_for_the_first_time = self.search_results.active.is_none() && !self.search_results.selections.is_empty(); // We are not at the end yet, so we can iterate to the next search-result within the current viewport let search_viewport_again = !self.search_results.selections.is_empty() && self.search_results.active.is_some() && match dir { SearchDirection::Up => self.search_results.active.as_ref() != first_sel, SearchDirection::Down => self.search_results.active.as_ref() != last_sel, }; if search_viewport_for_the_first_time || search_viewport_again { // We can stay in the viewport and just move the active selection self.search_viewport_again(search_viewport_for_the_first_time, dir); } else { // Need to move the viewport let found_something = self.search_viewport_move(dir); // We haven't found anything, but we are allowed to wrap around if !found_something && self.search_results.wrap_search { self.search_viewport_wrap(dir); } } } fn search_viewport_again( &mut self, search_viewport_for_the_first_time: bool, dir: SearchDirection, ) { let new_active = match dir { SearchDirection::Up => self.search_results.selections.last().cloned().unwrap(), SearchDirection::Down => self.search_results.selections.first().cloned().unwrap(), }; // We can stay in the viewport and just move the active selection let active_idx = self.search_results.active.get_or_insert(new_active); self.output_buffer.update_lines( active_idx.start.line() as usize, active_idx.end.line() as usize, ); if !search_viewport_for_the_first_time { match dir { SearchDirection::Up => self.search_results.move_active_selection_to_prev(), SearchDirection::Down => self.search_results.move_active_selection_to_next(), }; if let Some(new_active) = self.search_results.active { self.output_buffer.update_lines( new_active.start.line() as usize, new_active.end.line() as usize, ); } } } fn search_reached_opposite_end(&mut self, dir: SearchDirection) -> bool { match dir { SearchDirection::Up => self.lines_above.is_empty(), SearchDirection::Down => self.lines_below.is_empty(), } } fn search_viewport_move(&mut self, dir: SearchDirection) -> bool { // We need to move the viewport let mut rows = 0; let mut found_something = false; // We might loose the current selection, if we can't find anything let current_active_selection = self.search_results.active; while !found_something && !self.search_reached_opposite_end(dir) { rows += 1; found_something = match dir { SearchDirection::Up => self.scroll_up_one_line(), SearchDirection::Down => self.scroll_down_one_line(), }; } if found_something { self.search_adjust_to_new_selection(dir); } else { // We didn't find something, so we scroll back to the start for _ in 0..rows { match dir { SearchDirection::Up => self.scroll_down_one_line(), SearchDirection::Down => self.scroll_up_one_line(), }; } self.search_results.active = current_active_selection; } found_something } fn search_adjust_to_new_selection(&mut self, dir: SearchDirection) { match dir { SearchDirection::Up => { self.search_results.move_active_selection_to_prev(); }, SearchDirection::Down => { // We may need to scroll a bit further, because we are at the beginning of the // search result, but the end might be invisible if let Some(last) = self.search_results.selections.last() { let distance = (last.end.line() - last.start.line()) as usize; if distance < self.height { for _ in 0..distance { self.scroll_down_one_line(); } } } self.search_results.move_active_selection_to_next(); }, } self.output_buffer.update_all_lines(); } fn search_viewport_wrap(&mut self, dir: SearchDirection) { // We might loose the current selection, if we can't find anything let current_active_selection = self.search_results.active; // UP // Go to the opposite end (bottom when searching up and top when searching down) let mut rows = self.move_viewport_to_opposite_end(dir); // We are at the bottom or top. Maybe we found already something there // If not, scroll back again, until we find something let mut found_something = match dir { SearchDirection::Up => self.search_results.selections.last().is_some(), SearchDirection::Down => self.search_results.selections.first().is_some(), }; // We didn't find anything at the opposing end of the scrollbuffer, so we scroll back until we find something if !found_something { while rows >= 0 && !found_something { rows -= 1; found_something = match dir { SearchDirection::Up => self.scroll_up_one_line(), SearchDirection::Down => self.scroll_down_one_line(), }; } } if found_something { self.search_results.active = match dir { SearchDirection::Up => self.search_results.selections.last().cloned(), SearchDirection::Down => { // We need to scroll until the found item is at the top if let Some(first) = self.search_results.selections.first() { for _ in 0..first.start.line() { self.scroll_down_one_line(); } } self.search_results.selections.first().cloned() }, }; self.output_buffer.update_all_lines(); } else { // We didn't find anything, so we reset the old active selection self.search_results.active = current_active_selection; } } fn move_viewport_to_opposite_end(&mut self, dir: SearchDirection) -> isize { let mut rows = 0; match dir { SearchDirection::Up => { // Go to the bottom while !self.lines_below.is_empty() { rows += 1; self.scroll_down_one_line(); } }, SearchDirection::Down => { // Go to the top while !self.lines_above.is_empty() { rows += 1; self.scroll_up_one_line(); } }, } rows } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/plugin_pane.rs
zellij-server/src/panes/plugin_pane.rs
use std::collections::{BTreeSet, HashMap}; use std::time::Instant; use crate::output::{CharacterChunk, SixelImageChunk}; use crate::panes::{ grid::Grid, sixel::SixelImageStore, terminal_pane::{BRACKETED_PASTE_BEGIN, BRACKETED_PASTE_END}, LinkHandler, PaneId, }; use crate::plugins::PluginInstruction; use crate::pty::VteBytes; use crate::tab::{AdjustedInput, Pane}; use crate::ui::{ loading_indication::LoadingIndication, pane_boundaries_frame::{FrameParams, PaneFrame}, }; use crate::ClientId; use std::cell::RefCell; use std::rc::Rc; use vte; use zellij_utils::data::PaneContents; use zellij_utils::data::{ BareKey, KeyWithModifier, PermissionStatus, PermissionType, PluginPermission, }; use zellij_utils::pane_size::{Offset, SizeInPixels}; use zellij_utils::position::Position; use zellij_utils::{ channels::SenderWithContext, data::{Event, InputMode, Mouse, Palette, PaletteColor, Style, Styling}, errors::prelude::*, input::layout::Run, input::mouse::{MouseEvent, MouseEventType}, pane_size::PaneGeom, shared::make_terminal_title, }; macro_rules! style { ($fg:expr) => { ansi_term::Style::new().fg(match $fg { PaletteColor::Rgb((r, g, b)) => ansi_term::Color::RGB(r, g, b), PaletteColor::EightBit(color) => ansi_term::Color::Fixed(color), }) }; } macro_rules! get_or_create_grid { ($self:ident, $client_id:ident) => {{ let rows = $self.get_content_rows(); let cols = $self.get_content_columns(); let explicitly_disable_kitty_keyboard_protocol = false; // N/A for plugins $self.grids.entry($client_id).or_insert_with(|| { let mut grid = Grid::new( rows, cols, $self.terminal_emulator_colors.clone(), $self.terminal_emulator_color_codes.clone(), $self.link_handler.clone(), $self.character_cell_size.clone(), $self.sixel_image_store.clone(), $self.style.clone(), $self.debug, $self.arrow_fonts, $self.styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); grid.hide_cursor(); grid }) }}; } pub(crate) struct PluginPane { pub pid: u32, pub should_render: HashMap<ClientId, bool>, pub selectable: bool, pub geom: PaneGeom, pub geom_override: Option<PaneGeom>, pub content_offset: Offset, pub send_plugin_instructions: SenderWithContext<PluginInstruction>, pub active_at: Instant, pub pane_title: String, pub pane_name: String, pub style: Style, sixel_image_store: Rc<RefCell<SixelImageStore>>, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, link_handler: Rc<RefCell<LinkHandler>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, vte_parsers: HashMap<ClientId, vte::Parser>, grids: HashMap<ClientId, Grid>, cursor_visibility: HashMap<ClientId, Option<(usize, usize)>>, prev_pane_name: String, frame: HashMap<ClientId, PaneFrame>, borderless: bool, exclude_from_sync: bool, pane_frame_color_override: Option<(PaletteColor, Option<String>)>, invoked_with: Option<Run>, loading_indication: LoadingIndication, requesting_permissions: Option<PluginPermission>, debug: bool, arrow_fonts: bool, styled_underlines: bool, should_be_suppressed: bool, text_being_pasted: Option<Vec<u8>>, supports_mouse_selection: bool, } impl PluginPane { pub fn new( pid: u32, position_and_size: PaneGeom, send_plugin_instructions: SenderWithContext<PluginInstruction>, title: String, pane_name: String, sixel_image_store: Rc<RefCell<SixelImageStore>>, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, link_handler: Rc<RefCell<LinkHandler>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, currently_connected_clients: Vec<ClientId>, style: Style, invoked_with: Option<Run>, debug: bool, arrow_fonts: bool, styled_underlines: bool, ) -> Self { let loading_indication = LoadingIndication::new(title.clone()).with_colors(style.colors); let initial_loading_message = loading_indication.to_string(); let mut plugin = PluginPane { pid, should_render: HashMap::new(), selectable: true, geom: position_and_size, geom_override: None, send_plugin_instructions, active_at: Instant::now(), frame: HashMap::new(), content_offset: Offset::default(), pane_title: title, borderless: false, pane_name: pane_name.clone(), prev_pane_name: pane_name, terminal_emulator_colors, terminal_emulator_color_codes, exclude_from_sync: false, link_handler, character_cell_size, sixel_image_store, vte_parsers: HashMap::new(), grids: HashMap::new(), cursor_visibility: HashMap::new(), style, pane_frame_color_override: None, invoked_with, loading_indication, requesting_permissions: None, debug, arrow_fonts, styled_underlines, should_be_suppressed: false, text_being_pasted: None, supports_mouse_selection: false, }; for client_id in currently_connected_clients { plugin.handle_plugin_bytes(client_id, initial_loading_message.as_bytes().to_vec()); } plugin } } impl Pane for PluginPane { // FIXME: These position and size things should all be moved to default trait implementations, // with something like a get_pos_and_sz() method underpinning all of them. Alternatively and // preferably, just use an enum and not a trait object fn x(&self) -> usize { self.geom_override.unwrap_or(self.geom).x } fn y(&self) -> usize { self.geom_override.unwrap_or(self.geom).y } fn rows(&self) -> usize { self.geom_override.unwrap_or(self.geom).rows.as_usize() } fn cols(&self) -> usize { self.geom_override.unwrap_or(self.geom).cols.as_usize() } fn get_content_x(&self) -> usize { self.x() + self.content_offset.left } fn get_content_y(&self) -> usize { self.y() + self.content_offset.top } fn get_content_columns(&self) -> usize { // content columns might differ from the pane's columns if the pane has a frame // in that case they would be 2 less self.cols() .saturating_sub(self.content_offset.left + self.content_offset.right) } fn get_content_rows(&self) -> usize { // content rows might differ from the pane's rows if the pane has a frame // in that case they would be 2 less self.rows() .saturating_sub(self.content_offset.top + self.content_offset.bottom) } fn reset_size_and_position_override(&mut self) { self.geom_override = None; self.resize_grids(); self.set_should_render(true); } fn set_geom(&mut self, position_and_size: PaneGeom) { let is_pinned = self.geom.is_pinned; self.geom = position_and_size; self.geom.is_pinned = is_pinned; self.resize_grids(); self.set_should_render(true); } fn set_geom_override(&mut self, pane_geom: PaneGeom) { self.geom_override = Some(pane_geom); self.resize_grids(); self.set_should_render(true); } fn handle_plugin_bytes(&mut self, client_id: ClientId, bytes: VteBytes) { self.set_client_should_render(client_id, true); let mut vte_bytes = bytes; if let Some(plugin_permission) = &self.requesting_permissions { vte_bytes = self .display_request_permission_message(plugin_permission) .into(); } let grid = get_or_create_grid!(self, client_id); // this is part of the plugin contract, whenever we update the plugin and call its render function, we delete the existing viewport // and scroll, reset the cursor position and make sure all the viewport is rendered grid.delete_viewport_and_scroll(); grid.reset_cursor_position(); grid.render_full_viewport(); let vte_parser = self .vte_parsers .entry(client_id) .or_insert_with(|| vte::Parser::new()); for &byte in &vte_bytes { vte_parser.advance(grid, byte); } self.should_render.insert(client_id, true); } fn cursor_coordinates(&self, client_id: Option<ClientId>) -> Option<(usize, usize)> { let own_content_columns = self.get_content_columns(); let own_content_rows = self.get_content_rows(); let Offset { top, left, .. } = self.content_offset; if let Some(coordinates) = client_id.and_then(|client_id| self.cursor_visibility.get(&client_id)) { coordinates .map(|(x, y)| (x + left, y + top)) .and_then(|(x, y)| { if x >= own_content_columns || y >= own_content_rows { None } else { Some((x, y)) // these are 0 indexed } }) } else { None } } fn adjust_input_to_terminal( &mut self, key_with_modifier: &Option<KeyWithModifier>, mut raw_input_bytes: Vec<u8>, _raw_input_bytes_are_kitty: bool, client_id: Option<ClientId>, ) -> Option<AdjustedInput> { if client_id .and_then(|c| self.grids.get(&c)) .map(|g| g.has_selection()) .unwrap_or(false) { self.reset_selection(client_id); None } else if let Some(requesting_permissions) = &self.requesting_permissions { let permissions = requesting_permissions.permissions.clone(); if let Some(key_with_modifier) = key_with_modifier { match key_with_modifier.bare_key { BareKey::Char('y') if key_with_modifier.has_no_modifiers() => { Some(AdjustedInput::PermissionRequestResult( permissions, PermissionStatus::Granted, )) }, BareKey::Char('n') if key_with_modifier.has_no_modifiers() => { Some(AdjustedInput::PermissionRequestResult( permissions, PermissionStatus::Denied, )) }, _ => None, } } else { match raw_input_bytes.as_slice() { // Y or y &[89] | &[121] => Some(AdjustedInput::PermissionRequestResult( permissions, PermissionStatus::Granted, )), // N or n &[78] | &[110] => Some(AdjustedInput::PermissionRequestResult( permissions, PermissionStatus::Denied, )), _ => None, } } } else if let Some(key_with_modifier) = key_with_modifier { Some(AdjustedInput::WriteKeyToPlugin(key_with_modifier.clone())) } else if raw_input_bytes.as_slice() == BRACKETED_PASTE_BEGIN { self.text_being_pasted = Some(vec![]); None } else if raw_input_bytes.as_slice() == BRACKETED_PASTE_END { if let Some(text_being_pasted) = self.text_being_pasted.take() { match String::from_utf8(text_being_pasted) { Ok(pasted_text) => { let _ = self .send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), client_id, Event::PastedText(pasted_text), )])); }, Err(e) => { log::error!("Failed to convert pasted bytes as utf8 {:?}", e); }, } } None } else if let Some(pasted_text) = self.text_being_pasted.as_mut() { pasted_text.append(&mut raw_input_bytes); None } else { Some(AdjustedInput::WriteBytesToTerminal(raw_input_bytes)) } } fn position_and_size(&self) -> PaneGeom { self.geom } fn current_geom(&self) -> PaneGeom { self.geom_override.unwrap_or(self.geom) } fn geom_override(&self) -> Option<PaneGeom> { self.geom_override } fn should_render(&self) -> bool { // set should_render for all clients self.should_render.values().any(|v| *v) } fn set_should_render(&mut self, should_render: bool) { self.should_render .values_mut() .for_each(|v| *v = should_render); } fn render_full_viewport(&mut self) { // this marks the pane for a full re-render, rather than just rendering the // diff as it usually does with the OutputBuffer self.frame.clear(); for grid in self.grids.values_mut() { grid.render_full_viewport(); } } fn selectable(&self) -> bool { self.selectable } fn set_selectable(&mut self, selectable: bool) { self.selectable = selectable; } fn show_cursor(&mut self, client_id: ClientId, cursor_position: Option<(usize, usize)>) { self.cursor_visibility.insert(client_id, cursor_position); self.should_render.insert(client_id, true); } fn request_permissions_from_user(&mut self, permissions: Option<PluginPermission>) { self.requesting_permissions = permissions; self.handle_plugin_bytes_for_all_clients(Default::default()); // to trigger the render of // the permission message } fn render( &mut self, client_id: Option<ClientId>, ) -> Result<Option<(Vec<CharacterChunk>, Option<String>, Vec<SixelImageChunk>)>> { if client_id.is_none() { return Ok(None); } if let Some(client_id) = client_id { if self.should_render.get(&client_id).copied().unwrap_or(false) { let content_x = self.get_content_x(); let content_y = self.get_content_y(); let rows = self.get_content_rows(); let columns = self.get_content_columns(); if rows < 1 || columns < 1 { return Ok(None); } if let Some(grid) = self.grids.get_mut(&client_id) { match grid.render(content_x, content_y, &self.style) { Ok(rendered_assets) => { self.should_render.insert(client_id, false); return Ok(rendered_assets); }, e => return e, } } } } Ok(None) } fn render_frame( &mut self, client_id: ClientId, frame_params: FrameParams, input_mode: InputMode, ) -> Result<Option<(Vec<CharacterChunk>, Option<String>)>> { if self.borderless { return Ok(None); } let frame_geom = self.current_geom(); let grid = get_or_create_grid!(self, client_id); let err_context = || format!("failed to render frame for client {client_id}"); let pane_title = if let Some(text_color_override) = self .pane_frame_color_override .as_ref() .and_then(|(_color, text)| text.as_ref()) { text_color_override.into() } else if self.pane_name.is_empty() && input_mode == InputMode::RenamePane && frame_params.is_main_client { String::from("Enter name...") } else if self.pane_name.is_empty() { grid.title .clone() .unwrap_or_else(|| self.pane_title.clone()) } else { self.pane_name.clone() }; let is_pinned = frame_geom.is_pinned; let mut frame = PaneFrame::new( frame_geom.into(), grid.scrollback_position_and_length(), pane_title, frame_params, ) .is_pinned(is_pinned); if let Some((frame_color_override, _text)) = self.pane_frame_color_override.as_ref() { frame.override_color(*frame_color_override); } let res = match self.frame.get(&client_id) { // TODO: use and_then or something? Some(last_frame) => { if &frame != last_frame || is_pinned { if !self.borderless { let frame_output = frame.render().with_context(err_context)?; self.frame.insert(client_id, frame); Some(frame_output) } else { None } } else { None } }, None => { if !self.borderless { let frame_output = frame.render().with_context(err_context)?; self.frame.insert(client_id, frame); Some(frame_output) } else { None } }, }; Ok(res) } fn render_fake_cursor( &mut self, _cursor_color: PaletteColor, _text_color: PaletteColor, ) -> Option<String> { None } fn render_terminal_title(&mut self, input_mode: InputMode) -> String { let pane_title = if self.pane_name.is_empty() && input_mode == InputMode::RenamePane { "Enter name..." } else if self.pane_name.is_empty() { &self.pane_title } else { &self.pane_name }; make_terminal_title(pane_title) } fn update_name(&mut self, name: &str) { match name { "\0" => { self.pane_name = String::new(); }, "\u{007F}" | "\u{0008}" => { //delete and backspace keys self.pane_name.pop(); }, c => { self.pane_name.push_str(c); }, } } fn pid(&self) -> PaneId { PaneId::Plugin(self.pid) } fn reduce_height(&mut self, percent: f64) { if let Some(p) = self.geom.rows.as_percent() { self.geom.rows.set_percent(p - percent); self.resize_grids(); self.set_should_render(true); } } fn increase_height(&mut self, percent: f64) { if let Some(p) = self.geom.rows.as_percent() { self.geom.rows.set_percent(p + percent); self.resize_grids(); self.set_should_render(true); } } fn reduce_width(&mut self, percent: f64) { if let Some(p) = self.geom.cols.as_percent() { self.geom.cols.set_percent(p - percent); self.resize_grids(); self.set_should_render(true); } } fn increase_width(&mut self, percent: f64) { if let Some(p) = self.geom.cols.as_percent() { self.geom.cols.set_percent(p + percent); self.resize_grids(); self.set_should_render(true); } } fn push_down(&mut self, count: usize) { self.geom.y += count; self.resize_grids(); self.set_should_render(true); } fn push_right(&mut self, count: usize) { self.geom.x += count; self.resize_grids(); self.set_should_render(true); } fn pull_left(&mut self, count: usize) { self.geom.x -= count; self.resize_grids(); self.set_should_render(true); } fn pull_up(&mut self, count: usize) { self.geom.y -= count; self.resize_grids(); self.set_should_render(true); } fn dump_screen(&self, full: bool, client_id: Option<ClientId>) -> String { client_id .and_then(|c| self.grids.get(&c)) .map(|g| g.dump_screen(full)) .unwrap_or_else(|| "".to_owned()) } fn scroll_up(&mut self, count: usize, client_id: ClientId) { self.send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::ScrollUp(count)), )])) .unwrap(); } fn scroll_down(&mut self, count: usize, client_id: ClientId) { self.send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::ScrollDown(count)), )])) .unwrap(); } fn clear_screen(&mut self) { // do nothing } fn clear_scroll(&mut self) { // noop } fn start_selection(&mut self, start: &Position, client_id: ClientId) { if self.supports_mouse_selection { if let Some(grid) = self.grids.get_mut(&client_id) { grid.start_selection(start); self.set_should_render(true); } } else { self.send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::LeftClick(start.line.0, start.column.0)), )])) .unwrap(); } } fn update_selection(&mut self, position: &Position, client_id: ClientId) { if self.supports_mouse_selection { if let Some(grid) = self.grids.get_mut(&client_id) { grid.update_selection(position); self.set_should_render(true); // TODO: no?? } } else { self.send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::Hold(position.line.0, position.column.0)), )])) .unwrap(); } } fn end_selection(&mut self, end: &Position, client_id: ClientId) { if self.supports_mouse_selection { if let Some(grid) = self.grids.get_mut(&client_id) { grid.end_selection(end); } } else { self.send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::Release(end.line(), end.column())), )])) .unwrap(); } } fn reset_selection(&mut self, client_id: Option<ClientId>) { if let Some(grid) = client_id.and_then(|c| self.grids.get_mut(&c)) { grid.reset_selection(); self.set_should_render(true); } } fn supports_mouse_selection(&self) -> bool { self.supports_mouse_selection } fn get_selected_text(&self, client_id: ClientId) -> Option<String> { if let Some(grid) = self.grids.get(&client_id) { grid.get_selected_text() } else { None } } fn is_scrolled(&self) -> bool { false } fn active_at(&self) -> Instant { self.active_at } fn set_active_at(&mut self, time: Instant) { self.active_at = time; } fn set_frame(&mut self, _frame: bool) { self.frame.clear(); } fn set_content_offset(&mut self, offset: Offset) { self.content_offset = offset; self.resize_grids(); } fn get_content_offset(&self) -> Offset { self.content_offset } fn store_pane_name(&mut self) { if self.pane_name != self.prev_pane_name { self.prev_pane_name = self.pane_name.clone() } } fn load_pane_name(&mut self) { if self.pane_name != self.prev_pane_name { self.pane_name = self.prev_pane_name.clone() } } fn set_borderless(&mut self, borderless: bool) { self.borderless = borderless; } fn borderless(&self) -> bool { self.borderless } fn set_exclude_from_sync(&mut self, exclude_from_sync: bool) { self.exclude_from_sync = exclude_from_sync; } fn exclude_from_sync(&self) -> bool { self.exclude_from_sync } fn handle_right_click(&mut self, to: &Position, client_id: ClientId) { self.send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::RightClick(to.line.0, to.column.0)), )])) .unwrap(); } fn add_red_pane_frame_color_override(&mut self, error_text: Option<String>) { self.pane_frame_color_override = Some((self.style.colors.exit_code_error.base, error_text)); } fn add_highlight_pane_frame_color_override( &mut self, text: Option<String>, _client_id: Option<ClientId>, ) { // TODO: if we have a client_id, we should only highlight the frame for this client self.pane_frame_color_override = Some((self.style.colors.frame_highlight.base, text)); } fn clear_pane_frame_color_override(&mut self, _client_id: Option<ClientId>) { // TODO: if we have a client_id, we should only clear the highlight for this client self.pane_frame_color_override = None; } fn frame_color_override(&self) -> Option<PaletteColor> { self.pane_frame_color_override .as_ref() .map(|(color, _text)| *color) } fn invoked_with(&self) -> &Option<Run> { &self.invoked_with } fn set_title(&mut self, title: String) { self.pane_title = title; } fn update_loading_indication(&mut self, loading_indication: LoadingIndication) { if self.loading_indication.ended && !loading_indication.is_error() { return; } self.loading_indication.merge(loading_indication); self.handle_plugin_bytes_for_all_clients( self.loading_indication.to_string().as_bytes().to_vec(), ); } fn start_loading_indication(&mut self, loading_indication: LoadingIndication) { self.loading_indication.merge(loading_indication); self.handle_plugin_bytes_for_all_clients( self.loading_indication.to_string().as_bytes().to_vec(), ); } fn progress_animation_offset(&mut self) { if self.loading_indication.ended { return; } self.loading_indication.progress_animation_offset(); self.handle_plugin_bytes_for_all_clients( self.loading_indication.to_string().as_bytes().to_vec(), ); } fn current_title(&self) -> String { if self.pane_name.is_empty() { self.pane_title.to_owned() } else { self.pane_name.to_owned() } } fn custom_title(&self) -> Option<String> { if self.pane_name.is_empty() { None } else { Some(self.pane_name.clone()) } } fn rename(&mut self, buf: Vec<u8>) { self.pane_name = String::from_utf8_lossy(&buf).to_string(); self.set_should_render(true); } fn update_theme(&mut self, theme: Styling) { self.style.colors = theme.clone(); for grid in self.grids.values_mut() { grid.update_theme(theme.clone()); } } fn update_arrow_fonts(&mut self, should_support_arrow_fonts: bool) { self.arrow_fonts = should_support_arrow_fonts; for grid in self.grids.values_mut() { grid.update_arrow_fonts(should_support_arrow_fonts); } self.set_should_render(true); } fn update_rounded_corners(&mut self, rounded_corners: bool) { self.style.rounded_corners = rounded_corners; self.frame.clear(); } fn set_should_be_suppressed(&mut self, should_be_suppressed: bool) { self.should_be_suppressed = should_be_suppressed; } fn query_should_be_suppressed(&self) -> bool { self.should_be_suppressed } fn toggle_pinned(&mut self) { self.geom.is_pinned = !self.geom.is_pinned; } fn set_pinned(&mut self, should_be_pinned: bool) { self.geom.is_pinned = should_be_pinned; } fn intercept_left_mouse_click(&mut self, position: &Position, client_id: ClientId) -> bool { if self.position_is_on_frame(position) { let relative_position = self.relative_position(position); if let Some(client_frame) = self.frame.get_mut(&client_id) { if client_frame.clicked_on_pinned(relative_position) { self.toggle_pinned(); return true; } } } false } fn intercept_mouse_event_on_frame(&mut self, event: &MouseEvent, client_id: ClientId) -> bool { if self.position_is_on_frame(&event.position) { let relative_position = self.relative_position(&event.position); if let MouseEventType::Press = event.event_type { if let Some(client_frame) = self.frame.get_mut(&client_id) { if client_frame.clicked_on_pinned(relative_position) { self.toggle_pinned(); return true; } } } } false } fn reset_logical_position(&mut self) { self.geom.logical_position = None; } fn mouse_event(&self, event: &MouseEvent, client_id: ClientId) -> Option<String> { match event.event_type { MouseEventType::Motion if !event.left && !event.right && !event.middle && !event.wheel_up && !event.wheel_down => { let _ = self .send_plugin_instructions .send(PluginInstruction::Update(vec![( Some(self.pid), Some(client_id), Event::Mouse(Mouse::Hover(event.position.line(), event.position.column())), )])); }, _ => {}, } None } fn set_mouse_selection_support(&mut self, selection_support: bool) { self.supports_mouse_selection = selection_support; if !selection_support { let client_ids_with_grids: Vec<ClientId> = self.grids.keys().copied().collect(); for client_id in client_ids_with_grids { self.reset_selection(Some(client_id)); } } } fn pane_contents( &self, client_id: Option<ClientId>, get_full_scrollback: bool, ) -> PaneContents { client_id .and_then(|c| self.grids.get(&c)) .map(|g| g.pane_contents(get_full_scrollback)) .unwrap_or_else(Default::default) } } impl PluginPane { fn resize_grids(&mut self) { let content_rows = self.get_content_rows(); let content_columns = self.get_content_columns(); for grid in self.grids.values_mut() { grid.change_size(content_rows, content_columns); } self.set_should_render(true); } fn set_client_should_render(&mut self, client_id: ClientId, should_render: bool) { self.should_render.insert(client_id, should_render); } fn handle_plugin_bytes_for_all_clients(&mut self, bytes: VteBytes) { let client_ids: Vec<ClientId> = self.grids.keys().copied().collect(); for client_id in client_ids {
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/alacritty_functions.rs
zellij-server/src/panes/alacritty_functions.rs
use crate::panes::AnsiCode; use std::convert::TryFrom; pub fn parse_sgr_color(params: &mut dyn Iterator<Item = u16>) -> Option<AnsiCode> { match params.next() { Some(2) => Some(AnsiCode::RgbCode(( u8::try_from(params.next()?).ok()?, u8::try_from(params.next()?).ok()?, u8::try_from(params.next()?).ok()?, ))), Some(5) => Some(AnsiCode::ColorIndex(u8::try_from(params.next()?).ok()?)), _ => None, } } /// Parse colors in XParseColor format. pub fn xparse_color(color: &[u8]) -> Option<AnsiCode> { if !color.is_empty() && color[0] == b'#' { parse_legacy_color(&color[1..]) } else if color.len() >= 4 && &color[..4] == b"rgb:" { parse_rgb_color(&color[4..]) } else { None } } /// Parse colors in `rgb:r(rrr)/g(ggg)/b(bbb)` format. pub fn parse_rgb_color(color: &[u8]) -> Option<AnsiCode> { let colors = std::str::from_utf8(color) .ok()? .split('/') .collect::<Vec<_>>(); if colors.len() != 3 { return None; } // Scale values instead of filling with `0`s. let scale = |input: &str| { if input.len() > 4 { None } else { let max = u32::pow(16, input.len() as u32) - 1; let value = u32::from_str_radix(input, 16).ok()?; Some((255 * value / max) as u8) } }; Some(AnsiCode::RgbCode(( scale(colors[0])?, scale(colors[1])?, scale(colors[2])?, ))) } /// Parse colors in `#r(rrr)g(ggg)b(bbb)` format. pub fn parse_legacy_color(color: &[u8]) -> Option<AnsiCode> { let item_len = color.len() / 3; // Truncate/Fill to two byte precision. let color_from_slice = |slice: &[u8]| { let col = usize::from_str_radix(std::str::from_utf8(slice).ok()?, 16).ok()? << 4; Some((col >> (4 * slice.len().saturating_sub(1))) as u8) }; Some(AnsiCode::RgbCode(( color_from_slice(&color[0..item_len])?, color_from_slice(&color[item_len..item_len * 2])?, color_from_slice(&color[item_len * 2..])?, ))) } pub fn parse_number(input: &[u8]) -> Option<u8> { if input.is_empty() { return None; } let mut num: u8 = 0; for c in input { let c = *c as char; if let Some(digit) = c.to_digit(10) { num = match num.checked_mul(10).and_then(|v| v.checked_add(digit as u8)) { Some(v) => v, None => return None, } } else { return None; } } Some(num) } // these functions are copied verbatim (with slight modifications) from alacritty, mainly in order // to be able to use the VTE API provided by their great package of the same name more easily // The following license refers to this file and the functions // within it only // // Apache License // Version 2.0, January 2004 // http://www.apache.org/licenses/ // // TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION // // 1. Definitions. // // "License" shall mean the terms and conditions for use, reproduction, // and distribution as defined by Sections 1 through 9 of this document. // // "Licensor" shall mean the copyright owner or entity authorized by // the copyright owner that is granting the License. // // "Legal Entity" shall mean the union of the acting entity and all // other entities that control, are controlled by, or are under common // control with that entity. For the purposes of this definition, // "control" means (i) the power, direct or indirect, to cause the // direction or management of such entity, whether by contract or // otherwise, or (ii) ownership of fifty percent (50%) or more of the // outstanding shares, or (iii) beneficial ownership of such entity. // // "You" (or "Your") shall mean an individual or Legal Entity // exercising permissions granted by this License. // // "Source" form shall mean the preferred form for making modifications, // including but not limited to software source code, documentation // source, and configuration files. // // "Object" form shall mean any form resulting from mechanical // transformation or translation of a Source form, including but // not limited to compiled object code, generated documentation, // and conversions to other media types. // // "Work" shall mean the work of authorship, whether in Source or // Object form, made available under the License, as indicated by a // copyright notice that is included in or attached to the work // (an example is provided in the Appendix below). // // "Derivative Works" shall mean any work, whether in Source or Object // form, that is based on (or derived from) the Work and for which the // editorial revisions, annotations, elaborations, or other modifications // represent, as a whole, an original work of authorship. For the purposes // of this License, Derivative Works shall not include works that remain // separable from, or merely link (or bind by name) to the interfaces of, // the Work and Derivative Works thereof. // // "Contribution" shall mean any work of authorship, including // the original version of the Work and any modifications or additions // to that Work or Derivative Works thereof, that is intentionally // submitted to Licensor for inclusion in the Work by the copyright owner // or by an individual or Legal Entity authorized to submit on behalf of // the copyright owner. For the purposes of this definition, "submitted" // means any form of electronic, verbal, or written communication sent // to the Licensor or its representatives, including but not limited to // communication on electronic mailing lists, source code control systems, // and issue tracking systems that are managed by, or on behalf of, the // Licensor for the purpose of discussing and improving the Work, but // excluding communication that is conspicuously marked or otherwise // designated in writing by the copyright owner as "Not a Contribution." // // "Contributor" shall mean Licensor and any individual or Legal Entity // on behalf of whom a Contribution has been received by Licensor and // subsequently incorporated within the Work. // // 2. Grant of Copyright License. Subject to the terms and conditions of // this License, each Contributor hereby grants to You a perpetual, // worldwide, non-exclusive, no-charge, royalty-free, irrevocable // copyright license to reproduce, prepare Derivative Works of, // publicly display, publicly perform, sublicense, and distribute the // Work and such Derivative Works in Source or Object form. // // 3. Grant of Patent License. Subject to the terms and conditions of // this License, each Contributor hereby grants to You a perpetual, // worldwide, non-exclusive, no-charge, royalty-free, irrevocable // (except as stated in this section) patent license to make, have made, // use, offer to sell, sell, import, and otherwise transfer the Work, // where such license applies only to those patent claims licensable // by such Contributor that are necessarily infringed by their // Contribution(s) alone or by combination of their Contribution(s) // with the Work to which such Contribution(s) was submitted. If You // institute patent litigation against any entity (including a // cross-claim or counterclaim in a lawsuit) alleging that the Work // or a Contribution incorporated within the Work constitutes direct // or contributory patent infringement, then any patent licenses // granted to You under this License for that Work shall terminate // as of the date such litigation is filed. // // 4. Redistribution. You may reproduce and distribute copies of the // Work or Derivative Works thereof in any medium, with or without // modifications, and in Source or Object form, provided that You // meet the following conditions: // // (a) You must give any other recipients of the Work or // Derivative Works a copy of this License; and // // (b) You must cause any modified files to carry prominent notices // stating that You changed the files; and // // (c) You must retain, in the Source form of any Derivative Works // that You distribute, all copyright, patent, trademark, and // attribution notices from the Source form of the Work, // excluding those notices that do not pertain to any part of // the Derivative Works; and // // (d) If the Work includes a "NOTICE" text file as part of its // distribution, then any Derivative Works that You distribute must // include a readable copy of the attribution notices contained // within such NOTICE file, excluding those notices that do not // pertain to any part of the Derivative Works, in at least one // of the following places: within a NOTICE text file distributed // as part of the Derivative Works; within the Source form or // documentation, if provided along with the Derivative Works; or, // within a display generated by the Derivative Works, if and // wherever such third-party notices normally appear. The contents // of the NOTICE file are for informational purposes only and // do not modify the License. You may add Your own attribution // notices within Derivative Works that You distribute, alongside // or as an addendum to the NOTICE text from the Work, provided // that such additional attribution notices cannot be construed // as modifying the License. // // You may add Your own copyright statement to Your modifications and // may provide additional or different license terms and conditions // for use, reproduction, or distribution of Your modifications, or // for any such Derivative Works as a whole, provided Your use, // reproduction, and distribution of the Work otherwise complies with // the conditions stated in this License. // // 5. Submission of Contributions. Unless You explicitly state otherwise, // any Contribution intentionally submitted for inclusion in the Work // by You to the Licensor shall be under the terms and conditions of // this License, without any additional terms or conditions. // Notwithstanding the above, nothing herein shall supersede or modify // the terms of any separate license agreement you may have executed // with Licensor regarding such Contributions. // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor, // except as required for reasonable and customary use in describing the // origin of the Work and reproducing the content of the NOTICE file. // // 7. Disclaimer of Warranty. Unless required by applicable law or // agreed to in writing, Licensor provides the Work (and each // Contributor provides its Contributions) on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied, including, without limitation, any warranties or conditions // of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A // PARTICULAR PURPOSE. You are solely responsible for determining the // appropriateness of using or redistributing the Work and assume any // risks associated with Your exercise of permissions under this License. // // 8. Limitation of Liability. In no event and under no legal theory, // whether in tort (including negligence), contract, or otherwise, // unless required by applicable law (such as deliberate and grossly // negligent acts) or agreed to in writing, shall any Contributor be // liable to You for damages, including any direct, indirect, special, // incidental, or consequential damages of any character arising as a // result of this License or out of the use or inability to use the // Work (including but not limited to damages for loss of goodwill, // work stoppage, computer failure or malfunction, or any and all // other commercial damages or losses), even if such Contributor // has been advised of the possibility of such damages. // // 9. Accepting Warranty or Additional Liability. While redistributing // the Work or Derivative Works thereof, You may choose to offer, // and charge a fee for, acceptance of support, warranty, indemnity, // or other liability obligations and/or rights consistent with this // License. However, in accepting such obligations, You may act only // on Your own behalf and on Your sole responsibility, not on behalf // of any other Contributor, and only if You agree to indemnify, // defend, and hold each Contributor harmless for any liability // incurred by, or claims asserted against, such Contributor by reason // of your accepting any such warranty or additional liability. // // END OF TERMS AND CONDITIONS // // APPENDIX: How to apply the Apache License to your work. // // To apply the Apache License to your work, attach the following // boilerplate notice, with the fields enclosed by brackets "[]" // replaced with your own identifying information. (Don't include // the brackets!) The text should be enclosed in the appropriate // comment syntax for the file format. We also recommend that a // file or class name and description of purpose be included on the // same "printed page" as the copyright notice for easier // identification within third-party archives. // // Copyright 2020 The Alacritty Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/grid.rs
zellij-server/src/panes/grid.rs
use super::sixel::{PixelRect, SixelGrid, SixelImageStore}; use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use zellij_utils::data::Style; use zellij_utils::errors::prelude::*; use std::{ cmp::Ordering, collections::{BTreeSet, VecDeque}, fmt::{self, Debug, Formatter}, str, }; use vte; use zellij_utils::{ consts::{DEFAULT_SCROLL_BUFFER_SIZE, SCROLL_BUFFER_SIZE}, data::{Palette, PaletteColor, Styling}, input::mouse::{MouseEvent, MouseEventType}, pane_size::SizeInPixels, position::Position, }; const TABSTOP_WIDTH: usize = 8; // TODO: is this always right? pub const MAX_TITLE_STACK_SIZE: usize = 1000; use vte::{Params, Perform}; use zellij_utils::{consts::VERSION, shared::version_number}; use crate::output::{CharacterChunk, OutputBuffer, SixelImageChunk}; use crate::panes::alacritty_functions::{parse_number, xparse_color}; use crate::panes::hyperlink_tracker::HyperlinkTracker; use crate::panes::link_handler::LinkHandler; use crate::panes::search::SearchResult; use crate::panes::terminal_character::{ AnsiCode, CharsetIndex, Cursor, CursorShape, RcCharacterStyles, StandardCharset, TerminalCharacter, EMPTY_TERMINAL_CHARACTER, }; use crate::panes::Selection; use crate::ui::components::UiComponentParser; use zellij_utils::data::PaneContents; fn get_top_non_canonical_rows(rows: &mut Vec<Row>) -> Vec<Row> { let mut index_of_last_non_canonical_row = None; for (i, row) in rows.iter().enumerate() { if row.is_canonical { break; } else { index_of_last_non_canonical_row = Some(i); } } match index_of_last_non_canonical_row { Some(index_of_last_non_canonical_row) => { rows.drain(..=index_of_last_non_canonical_row).collect() }, None => vec![], } } fn get_lines_above_bottom_canonical_row_and_wraps(rows: &mut VecDeque<Row>) -> Vec<Row> { let mut index_of_last_non_canonical_row = None; for (i, row) in rows.iter().enumerate().rev() { index_of_last_non_canonical_row = Some(i); if row.is_canonical { break; } } match index_of_last_non_canonical_row { Some(index_of_last_non_canonical_row) => { rows.drain(index_of_last_non_canonical_row..).collect() }, None => vec![], } } fn get_viewport_bottom_canonical_row_and_wraps(viewport: &mut Vec<Row>) -> Vec<Row> { let mut index_of_last_non_canonical_row = None; for (i, row) in viewport.iter().enumerate().rev() { index_of_last_non_canonical_row = Some(i); if row.is_canonical { break; } } match index_of_last_non_canonical_row { Some(index_of_last_non_canonical_row) => { viewport.drain(index_of_last_non_canonical_row..).collect() }, None => vec![], } } fn get_top_canonical_row_and_wraps(rows: &mut Vec<Row>) -> Vec<Row> { let mut index_of_first_non_canonical_row = None; let mut end_index_of_first_canonical_line = None; for (i, row) in rows.iter().enumerate() { if row.is_canonical && end_index_of_first_canonical_line.is_none() { index_of_first_non_canonical_row = Some(i); end_index_of_first_canonical_line = Some(i); continue; } if row.is_canonical && end_index_of_first_canonical_line.is_some() { break; } if index_of_first_non_canonical_row.is_some() { end_index_of_first_canonical_line = Some(i); continue; } } match ( index_of_first_non_canonical_row, end_index_of_first_canonical_line, ) { (Some(first_index), Some(last_index)) => rows.drain(first_index..=last_index).collect(), (Some(first_index), None) => rows.drain(first_index..).collect(), _ => vec![], } } fn transfer_rows_from_lines_above_to_viewport( lines_above: &mut VecDeque<Row>, viewport: &mut Vec<Row>, sixel_grid: &mut SixelGrid, count: usize, max_viewport_width: usize, ) -> usize { let mut next_lines: Vec<Row> = vec![]; let mut lines_added_to_viewport: isize = 0; loop { if lines_added_to_viewport as usize == count { break; } if next_lines.is_empty() { match lines_above.pop_back() { Some(next_line) => { let mut top_non_canonical_rows_in_dst = get_top_non_canonical_rows(viewport); lines_added_to_viewport -= top_non_canonical_rows_in_dst.len() as isize; next_lines.push(next_line); next_lines.append(&mut top_non_canonical_rows_in_dst); next_lines = Row::from_rows(next_lines).split_to_rows_of_length(max_viewport_width); if next_lines.is_empty() { // no more lines at lines_above, the line we popped was probably empty break; } }, None => break, // no more rows } } viewport.insert(0, next_lines.pop().unwrap()); lines_added_to_viewport += 1; } if !next_lines.is_empty() { let excess_row = Row::from_rows(next_lines); bounded_push(lines_above, sixel_grid, excess_row); } match usize::try_from(lines_added_to_viewport) { Ok(n) => n, _ => 0, } } fn transfer_rows_from_viewport_to_lines_above( viewport: &mut Vec<Row>, lines_above: &mut VecDeque<Row>, sixel_grid: &mut SixelGrid, count: usize, max_viewport_width: usize, ) -> isize { let mut transferred_rows_count: isize = 0; let drained_lines = std::cmp::min(count, viewport.len()); for next_line in viewport.drain(..drained_lines) { let mut next_lines: Vec<Row> = vec![]; transferred_rows_count += calculate_row_display_height(next_line.width(), max_viewport_width) as isize; if !next_line.is_canonical { let mut bottom_canonical_row_and_wraps_in_dst = get_lines_above_bottom_canonical_row_and_wraps(lines_above); next_lines.append(&mut bottom_canonical_row_and_wraps_in_dst); } next_lines.push(next_line); let dropped_line_width = bounded_push(lines_above, sixel_grid, Row::from_rows(next_lines)); if let Some(width) = dropped_line_width { transferred_rows_count -= calculate_row_display_height(width, max_viewport_width) as isize; } } transferred_rows_count } fn transfer_rows_from_lines_below_to_viewport( lines_below: &mut Vec<Row>, viewport: &mut Vec<Row>, count: usize, max_viewport_width: usize, ) { let mut next_lines: Vec<Row> = vec![]; for _ in 0..count { let mut lines_pulled_from_viewport = 0; if next_lines.is_empty() { if !lines_below.is_empty() { let mut top_non_canonical_rows_in_lines_below = get_top_non_canonical_rows(lines_below); if !top_non_canonical_rows_in_lines_below.is_empty() { let mut canonical_line = get_viewport_bottom_canonical_row_and_wraps(viewport); lines_pulled_from_viewport += canonical_line.len(); canonical_line.append(&mut top_non_canonical_rows_in_lines_below); next_lines = Row::from_rows(canonical_line).split_to_rows_of_length(max_viewport_width); } else { let canonical_row = get_top_canonical_row_and_wraps(lines_below); next_lines = Row::from_rows(canonical_row).split_to_rows_of_length(max_viewport_width); } } else { break; // no more rows } } for _ in 0..(lines_pulled_from_viewport + 1) { if !next_lines.is_empty() { viewport.push(next_lines.remove(0)); } } } if !next_lines.is_empty() { let excess_row = Row::from_rows(next_lines); lines_below.insert(0, excess_row); } } fn bounded_push(vec: &mut VecDeque<Row>, sixel_grid: &mut SixelGrid, value: Row) -> Option<usize> { let mut dropped_line_width = None; if vec.len() >= *SCROLL_BUFFER_SIZE.get().unwrap() { let line = vec.pop_front(); if let Some(line) = line { sixel_grid.offset_grid_top(); dropped_line_width = Some(line.width()); } } vec.push_back(value); dropped_line_width } pub fn create_horizontal_tabstops(columns: usize) -> BTreeSet<usize> { let mut i = TABSTOP_WIDTH; let mut horizontal_tabstops = BTreeSet::new(); loop { if i > columns { break; } horizontal_tabstops.insert(i); i += TABSTOP_WIDTH; } horizontal_tabstops } fn calculate_row_display_height(row_width: usize, viewport_width: usize) -> usize { if row_width <= viewport_width { return 1; } (row_width as f64 / viewport_width as f64).ceil() as usize } fn subtract_isize_from_usize(u: usize, i: isize) -> usize { if i.is_negative() { u - i.abs() as usize } else { u + i as usize } } macro_rules! dump_screen { ($lines:expr) => {{ let mut is_first = true; let mut buf = String::with_capacity($lines.iter().map(|l| l.len()).sum()); for line in &$lines { if line.is_canonical && !is_first { buf.push_str("\n"); } let s: String = (&line.columns).into_iter().map(|x| x.character).collect(); // Replace the spaces at the end of the line. Sometimes, the lines are // collected with spaces until the end of the panel. buf.push_str(&s.trim_end_matches(' ')); is_first = false; } buf }}; } fn utf8_mouse_coordinates(column: usize, line: isize) -> Vec<u8> { let mut coordinates = vec![]; let mouse_pos_encode = |pos: usize| -> Vec<u8> { let pos = 32 + pos; let first = 0xC0 + pos / 64; let second = 0x80 + (pos & 63); vec![first as u8, second as u8] }; if column > 95 { coordinates.append(&mut mouse_pos_encode(column)); } else { coordinates.push(32 + column as u8); } if line > 95 { coordinates.append(&mut mouse_pos_encode(line as usize)); } else { coordinates.push(32 + line as u8); } coordinates } #[derive(Clone)] pub struct Grid { pub(crate) lines_above: VecDeque<Row>, pub(crate) viewport: Vec<Row>, pub(crate) lines_below: Vec<Row>, horizontal_tabstops: BTreeSet<usize>, alternate_screen_state: Option<AlternateScreenState>, cursor: Cursor, cursor_is_hidden: bool, saved_cursor_position: Option<Cursor>, scroll_region: (usize, usize), active_charset: CharsetIndex, preceding_char: Option<TerminalCharacter>, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, pub(crate) output_buffer: OutputBuffer, title_stack: Vec<String>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, sixel_grid: SixelGrid, pub changed_colors: Option<[Option<AnsiCode>; 256]>, pub should_render: bool, pub lock_renders: bool, pub cursor_key_mode: bool, // DECCKM - when set, cursor keys should send ANSI direction codes (eg. "OD") instead of the arrow keys (eg. "") pub bracketed_paste_mode: bool, // when set, paste instructions to the terminal should be escaped with a special sequence pub erasure_mode: bool, // ERM pub sixel_scrolling: bool, // DECSDM pub insert_mode: bool, pub disable_linewrap: bool, pub new_line_mode: bool, // Automatic newline LNM pub clear_viewport_before_rendering: bool, pub width: usize, pub height: usize, pub pending_messages_to_pty: Vec<Vec<u8>>, pub selection: Selection, pub title: Option<String>, pub is_scrolled: bool, pub link_handler: Rc<RefCell<LinkHandler>>, pub ring_bell: bool, scrollback_buffer_lines: usize, pub mouse_mode: MouseMode, pub mouse_tracking: MouseTracking, pub focus_event_tracking: bool, pub search_results: SearchResult, pub pending_clipboard_update: Option<String>, ui_component_bytes: Option<Vec<u8>>, style: Style, debug: bool, arrow_fonts: bool, styled_underlines: bool, pub supports_kitty_keyboard_protocol: bool, // has the app requested kitty keyboard support? explicitly_disable_kitty_keyboard_protocol: bool, // has kitty keyboard support been explicitly // disabled by user config? click: Click, hyperlink_tracker: HyperlinkTracker, } const CLICK_TIME_THRESHOLD: u128 = 400; // Doherty Threshold #[derive(Clone, Debug, Default)] struct Click { position_and_time: Option<(Position, std::time::Instant)>, count: usize, } impl Click { pub fn record_click(&mut self, position: Position) { let click_is_same_position_as_last_click = self .position_and_time .map(|(p, _t)| p == position) .unwrap_or(false); let click_is_within_time_threshold = self .position_and_time .map(|(_p, t)| t.elapsed().as_millis() <= CLICK_TIME_THRESHOLD) .unwrap_or(false); if click_is_same_position_as_last_click && click_is_within_time_threshold { self.count += 1; } else { self.count = 1; } self.position_and_time = Some((position, std::time::Instant::now())); if self.count == 4 { self.reset(); } } pub fn is_double_click(&self) -> bool { self.count == 2 } pub fn is_triple_click(&self) -> bool { self.count == 3 } pub fn reset(&mut self) { self.count = 0; } } #[derive(Clone, Debug)] pub enum MouseMode { NoEncoding, Utf8, Sgr, } impl Default for MouseMode { fn default() -> Self { MouseMode::NoEncoding } } #[derive(Clone, Debug)] pub enum MouseTracking { Off, Normal, ButtonEventTracking, AnyEventTracking, } impl Default for MouseTracking { fn default() -> Self { MouseTracking::Off } } impl Debug for Grid { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut buffer: Vec<Row> = self.viewport.clone(); // pad buffer for _ in buffer.len()..self.height { buffer.push(Row::new().canonical()); } // display sixel placeholder let sixel_indication_character = |x| { let sixel_indication_word = "Sixel"; sixel_indication_word .chars() .nth(x % sixel_indication_word.len()) .unwrap() }; for image_coordinates in self .sixel_grid .image_cell_coordinates_in_viewport(self.height, self.lines_above.len()) { let (image_top_edge, image_bottom_edge, image_left_edge, image_right_edge) = image_coordinates; for y in image_top_edge..image_bottom_edge { let row = buffer.get_mut(y).unwrap(); for x in image_left_edge..image_right_edge { let fake_sixel_terminal_character = TerminalCharacter::new_singlewidth(sixel_indication_character(x)); row.add_character_at(fake_sixel_terminal_character, x); } } } // display terminal characters with stripped styles for (i, row) in buffer.iter().enumerate() { let mut cow_row = Cow::Borrowed(row); self.search_results .mark_search_results_in_row(&mut cow_row, i); if row.is_canonical { writeln!(f, "{:02?} (C): {:?}", i, cow_row)?; } else { writeln!(f, "{:02?} (W): {:?}", i, cow_row)?; } } Ok(()) } } impl Grid { pub fn new( rows: usize, columns: usize, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, link_handler: Rc<RefCell<LinkHandler>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, sixel_image_store: Rc<RefCell<SixelImageStore>>, style: Style, // TODO: consolidate this with terminal_emulator_colors debug: bool, arrow_fonts: bool, styled_underlines: bool, explicitly_disable_kitty_keyboard_protocol: bool, ) -> Self { let sixel_grid = SixelGrid::new(character_cell_size.clone(), sixel_image_store); // make sure this is initialized as it is used internally // if it was already initialized (which should happen normally unless this is a test or // something changed since this comment was written), we get an Error which we ignore // I don't know why this needs to be a OneCell, but whatevs let _ = SCROLL_BUFFER_SIZE.set(DEFAULT_SCROLL_BUFFER_SIZE); Grid { lines_above: VecDeque::new(), viewport: vec![Row::new().canonical()], lines_below: vec![], horizontal_tabstops: create_horizontal_tabstops(columns), cursor: Cursor::new(0, 0, styled_underlines), cursor_is_hidden: false, saved_cursor_position: None, scroll_region: (0, rows.saturating_sub(1)), preceding_char: None, width: columns, height: rows, should_render: true, cursor_key_mode: false, bracketed_paste_mode: false, erasure_mode: false, sixel_scrolling: false, insert_mode: false, disable_linewrap: false, new_line_mode: false, alternate_screen_state: None, clear_viewport_before_rendering: false, active_charset: Default::default(), pending_messages_to_pty: vec![], terminal_emulator_colors, terminal_emulator_color_codes, output_buffer: Default::default(), selection: Default::default(), title_stack: vec![], title: None, changed_colors: None, is_scrolled: false, link_handler, ring_bell: false, scrollback_buffer_lines: 0, mouse_mode: MouseMode::default(), mouse_tracking: MouseTracking::default(), focus_event_tracking: false, character_cell_size, search_results: Default::default(), sixel_grid, pending_clipboard_update: None, ui_component_bytes: None, style, debug, arrow_fonts, styled_underlines, lock_renders: false, supports_kitty_keyboard_protocol: false, explicitly_disable_kitty_keyboard_protocol, click: Click::default(), hyperlink_tracker: HyperlinkTracker::new(), } } pub fn render_full_viewport(&mut self) { self.output_buffer.update_all_lines(); } pub fn update_line_for_rendering(&mut self, line_index: usize) { self.output_buffer.update_line(line_index); } pub fn advance_to_next_tabstop(&mut self, styles: RcCharacterStyles) { let next_tabstop = self .horizontal_tabstops .iter() .copied() .find(|&tabstop| tabstop > self.cursor.x && tabstop < self.width); match next_tabstop { Some(tabstop) => { self.cursor.x = tabstop; }, None => { self.cursor.x = self.width.saturating_sub(1); }, } let mut empty_character = EMPTY_TERMINAL_CHARACTER; empty_character.styles = styles; self.pad_current_line_until(self.cursor.x, empty_character); self.output_buffer.update_line(self.cursor.y); } pub fn move_to_previous_tabstop(&mut self) { let previous_tabstop = self .horizontal_tabstops .iter() .rev() .copied() .find(|&tabstop| tabstop < self.cursor.x); match previous_tabstop { Some(tabstop) => { self.cursor.x = tabstop; }, None => { self.cursor.x = 0; }, } } pub fn cursor_shape(&self) -> CursorShape { self.cursor.get_shape() } pub fn scrollback_position_and_length(&self) -> (usize, usize) { // (position, length) ( self.lines_below.len(), (self.scrollback_buffer_lines + self.lines_below.len()), ) } fn recalculate_scrollback_buffer_count(&self) -> usize { let mut scrollback_buffer_count = 0; for row in &self.lines_above { let row_width = row.width(); // rows in lines_above are unwrapped, so we need to account for that if row_width > self.width { scrollback_buffer_count += calculate_row_display_height(row_width, self.width); } else { scrollback_buffer_count += 1; } } scrollback_buffer_count } fn set_horizontal_tabstop(&mut self) { self.horizontal_tabstops.insert(self.cursor.x); } fn clear_tabstop(&mut self, position: usize) { self.horizontal_tabstops.remove(&position); } fn clear_all_tabstops(&mut self) { self.horizontal_tabstops.clear(); } fn save_cursor_position(&mut self) { self.saved_cursor_position = Some(self.cursor.clone()); } fn restore_cursor_position(&mut self) { if let Some(saved_cursor_position) = &self.saved_cursor_position { self.cursor = saved_cursor_position.clone(); } } fn configure_charset(&mut self, charset: StandardCharset, index: CharsetIndex) { self.cursor.charsets[index] = charset; } fn set_active_charset(&mut self, index: CharsetIndex) { self.active_charset = index; } fn cursor_canonical_line_index(&self) -> usize { let mut cursor_canonical_line_index = 0; let mut canonical_lines_traversed = 0; for (i, line) in self.viewport.iter().enumerate() { if line.is_canonical { cursor_canonical_line_index = canonical_lines_traversed; canonical_lines_traversed += 1; } if i == self.cursor.y { break; } } cursor_canonical_line_index } // TODO: merge these two functions fn cursor_index_in_canonical_line(&self) -> usize { let mut cursor_canonical_line_index = 0; let mut cursor_index_in_canonical_line = 0; for (i, line) in self.viewport.iter().enumerate() { if line.is_canonical { cursor_canonical_line_index = i; } if i == self.cursor.y { let line_wraps = self.cursor.y.saturating_sub(cursor_canonical_line_index); cursor_index_in_canonical_line = (line_wraps * self.width) + self.cursor.x; break; } } cursor_index_in_canonical_line } fn saved_cursor_index_in_canonical_line(&self) -> Option<usize> { if let Some(saved_cursor_position) = self.saved_cursor_position.as_ref() { let mut cursor_canonical_line_index = 0; let mut cursor_index_in_canonical_line = 0; for (i, line) in self.viewport.iter().enumerate() { if line.is_canonical { cursor_canonical_line_index = i; } if i == saved_cursor_position.y { let line_wraps = saved_cursor_position.y - cursor_canonical_line_index; cursor_index_in_canonical_line = (line_wraps * self.width) + saved_cursor_position.x; break; } } Some(cursor_index_in_canonical_line) } else { None } } fn canonical_line_y_coordinates(&self, canonical_line_index: usize) -> usize { let mut canonical_lines_traversed = 0; let mut y_coordinates = 0; for (i, line) in self.viewport.iter().enumerate() { if line.is_canonical { canonical_lines_traversed += 1; y_coordinates = i; if canonical_lines_traversed == canonical_line_index + 1 { break; } } } y_coordinates } pub fn scroll_up_one_line(&mut self) -> bool { let mut found_something = false; if !self.lines_above.is_empty() && self.viewport.len() == self.height { self.is_scrolled = true; let line_to_push_down = self.viewport.pop().unwrap(); self.lines_below.insert(0, line_to_push_down); let transferred_rows_height = transfer_rows_from_lines_above_to_viewport( &mut self.lines_above, &mut self.viewport, &mut self.sixel_grid, 1, self.width, ); self.scrollback_buffer_lines = self .scrollback_buffer_lines .saturating_sub(transferred_rows_height); self.selection.move_down(1); // Move all search-selections down one line as well found_something = self .search_results .move_down(1, &self.viewport, self.height); } self.output_buffer.update_all_lines(); found_something } pub fn scroll_down_one_line(&mut self) -> bool { let mut found_something = false; if !self.lines_below.is_empty() && self.viewport.len() == self.height { let mut line_to_push_up = self.viewport.remove(0); self.scrollback_buffer_lines += calculate_row_display_height(line_to_push_up.width(), self.width); let line_to_push_up = if line_to_push_up.is_canonical { line_to_push_up } else { match self.lines_above.pop_back() { Some(mut last_line_above) => { last_line_above.append(&mut line_to_push_up.columns); last_line_above }, None => { // in this case, this line was not canonical but its beginning line was // dropped out of scope, so we make it canonical and push it up line_to_push_up.canonical() }, } }; let dropped_line_width = bounded_push(&mut self.lines_above, &mut self.sixel_grid, line_to_push_up); if let Some(width) = dropped_line_width { let dropped_line_height = calculate_row_display_height(width, self.width); self.scrollback_buffer_lines = self .scrollback_buffer_lines .saturating_sub(dropped_line_height); } transfer_rows_from_lines_below_to_viewport( &mut self.lines_below, &mut self.viewport, 1, self.width, ); self.selection.move_up(1); // Move all search-selections up one line as well found_something = self.search_results .move_up(1, &self.viewport, &self.lines_below, self.height); self.output_buffer.update_all_lines(); } if self.lines_below.is_empty() { self.is_scrolled = false; } found_something } pub fn force_change_size(&mut self, new_rows: usize, new_columns: usize) { // this is an ugly hack - it's here because sometimes we need to change_size to the // existing size (eg. when resizing an alternative_grid to the current height/width) and // the change_size method is a no-op in that case. Should be fixed by making the // change_size method atomic let intermediate_rows = if new_rows == self.height { new_rows + 1 } else { new_rows }; let intermediate_columns = if new_columns == self.width { new_columns + 1 } else { new_columns }; self.change_size(intermediate_rows, intermediate_columns); self.change_size(new_rows, new_columns); } pub fn change_size(&mut self, new_rows: usize, new_columns: usize) { // Do nothing if this pane hasn't been given a proper size yet if new_columns == 0 || new_rows == 0 { return; } if self.alternate_screen_state.is_some() { // in alternate screen we do nothing but log the new size, the program in the terminal // is in control now... self.height = new_rows; self.width = new_columns; return; } self.selection.reset(); self.sixel_grid.character_cell_size_possibly_changed(); let cursors = if new_columns != self.width { self.horizontal_tabstops = create_horizontal_tabstops(new_columns); let mut cursor_canonical_line_index = self.cursor_canonical_line_index(); let cursor_index_in_canonical_line = self.cursor_index_in_canonical_line(); let saved_cursor_index_in_canonical_line = self.saved_cursor_index_in_canonical_line(); let mut viewport_canonical_lines = vec![]; for mut row in self.viewport.drain(..) { if !row.is_canonical && viewport_canonical_lines.is_empty() && !self.lines_above.is_empty() { let mut first_line_above = self.lines_above.pop_back().unwrap(); first_line_above.append(&mut row.columns); viewport_canonical_lines.push(first_line_above); cursor_canonical_line_index += 1; } else if row.is_canonical { viewport_canonical_lines.push(row); } else { match viewport_canonical_lines.last_mut() { Some(last_line) => { last_line.append(&mut row.columns); }, None => { // the state is corrupted somehow // this is a bug and I'm not yet sure why it happens // usually it fixes itself and is a result of some race // TODO: investigate why this happens and solve it return; }, } } } // trim lines after the last empty space that has no following character, because // terminals don't trim empty lines for line in &mut viewport_canonical_lines { let mut trim_at = None; for (index, character) in line.columns.iter().enumerate() { if character.character != EMPTY_TERMINAL_CHARACTER.character { trim_at = None; } else if trim_at.is_none() { trim_at = Some(index); } } if let Some(trim_at) = trim_at { let excess_width_until_trim_at = line.excess_width_until(trim_at); line.truncate(trim_at + excess_width_until_trim_at); } } let mut new_viewport_rows = vec![]; for mut canonical_line in viewport_canonical_lines { let mut canonical_line_parts: Vec<Row> = vec![]; if canonical_line.columns.is_empty() { canonical_line_parts.push(Row::new().canonical()); } while !canonical_line.columns.is_empty() { let next_wrap = canonical_line.drain_until(new_columns); // If the next character is wider than the grid (i.e. there is nothing in // `next_wrap`, then just abort the resizing if next_wrap.is_empty() { break;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/sixel.rs
zellij-server/src/panes/sixel.rs
use crate::output::SixelImageChunk; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use sixel_image::{SixelDeserializer, SixelImage}; use sixel_tokenizer::SixelEvent; use std::fmt::Debug; use zellij_utils::pane_size::SizeInPixels; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct PixelRect { pub x: usize, pub y: isize, // this can potentially be negative (eg. when the image top has scrolled past the edge of the scrollbuffer) pub width: usize, pub height: usize, } impl PixelRect { pub fn new(x: usize, y: usize, height: usize, width: usize) -> Self { PixelRect { x, y: y as isize, width, height, } } pub fn intersecting_rect(&self, other: &PixelRect) -> Option<PixelRect> { // if the two rects intersect, this returns a PixelRect *relative to self* let self_top_edge = self.y; let self_bottom_edge = self.y + self.height as isize; let self_left_edge = self.x; let self_right_edge = self.x + self.width; let other_top_edge = other.y; let other_bottom_edge = other.y + other.height as isize; let other_left_edge = other.x; let other_right_edge = other.x + other.width; let absolute_x = std::cmp::max(self_left_edge, other_left_edge); let absolute_y = std::cmp::max(self_top_edge, other_top_edge); let absolute_right_edge = std::cmp::min(self_right_edge, other_right_edge); let absolute_bottom_edge = std::cmp::min(self_bottom_edge, other_bottom_edge); let width = absolute_right_edge.saturating_sub(absolute_x); let height = absolute_bottom_edge.saturating_sub(absolute_y); let x = absolute_x - self.x; let y = absolute_y - self.y; if width > 0 && height > 0 { Some(PixelRect { x, y, width, height: height as usize, }) } else { None } } } #[derive(Debug, Clone, Default)] pub struct SixelGrid { sixel_image_locations: HashMap<usize, PixelRect>, previous_cell_size: Option<SizeInPixels>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, currently_parsing: Option<SixelDeserializer>, image_ids_to_reap: Vec<usize>, sixel_parser: Option<sixel_tokenizer::Parser>, pub sixel_image_store: Rc<RefCell<SixelImageStore>>, } impl SixelGrid { pub fn new( character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, sixel_image_store: Rc<RefCell<SixelImageStore>>, ) -> Self { let previous_cell_size = *character_cell_size.borrow(); SixelGrid { previous_cell_size, character_cell_size, sixel_image_store, ..Default::default() } } pub fn handle_byte(&mut self, byte: u8) { self.sixel_parser .as_mut() .unwrap() .advance(&byte, |sixel_event| { if let Some(currently_parsing) = self.currently_parsing.as_mut() { let _ = currently_parsing.handle_event(sixel_event); } }); } pub fn handle_event(&mut self, sixel_event: SixelEvent) { if let Some(currently_parsing) = self.currently_parsing.as_mut() { let _ = currently_parsing.handle_event(sixel_event); } } pub fn is_parsing(&self) -> bool { self.sixel_parser.is_some() } pub fn start_image( &mut self, max_height_in_pixels: Option<usize>, dcs_intermediates: Vec<&u8>, dcs_params: Vec<&[u16]>, ) { self.sixel_parser = Some(sixel_tokenizer::Parser::new()); match max_height_in_pixels { Some(max_height_in_pixels) => { self.currently_parsing = Some(SixelDeserializer::new().max_height(max_height_in_pixels)); }, None => { self.currently_parsing = Some(SixelDeserializer::new()); }, } self.handle_byte(27); self.handle_byte(b'P'); for byte in dcs_intermediates { self.handle_byte(*byte); } // send DCS event to parser for (i, param) in dcs_params.iter().enumerate() { if i != 0 { self.handle_byte(b';'); } for subparam in param.iter() { let mut b = [0; 4]; for digit in subparam.to_string().chars() { let len = digit.encode_utf8(&mut b).len(); for byte in b.iter().take(len) { self.handle_byte(*byte); } } } } self.handle_byte(b'q'); } pub fn end_image( &mut self, new_image_id: usize, x_pixel_coordinates: usize, y_pixel_coordinates: usize, ) -> Option<SixelImage> { // usize is image_id self.sixel_parser = None; if let Some(sixel_deserializer) = self.currently_parsing.as_mut() { if let Ok(sixel_image) = sixel_deserializer.create_image() { let image_pixel_size = sixel_image.pixel_size(); let image_size_and_coordinates = PixelRect::new( x_pixel_coordinates, y_pixel_coordinates, image_pixel_size.0, image_pixel_size.1, ); // here we remove images which this image covers completely to save on system // resources - TODO: also do this with partial covers, eg. if several images // together cover one image for (image_id, pixel_rect) in &self.sixel_image_locations { if let Some(intersecting_rect) = pixel_rect.intersecting_rect(&image_size_and_coordinates) { if intersecting_rect.x == pixel_rect.x && intersecting_rect.y == pixel_rect.y && intersecting_rect.height == pixel_rect.height && intersecting_rect.width == pixel_rect.width { self.image_ids_to_reap.push(*image_id); } } } for image_id in &self.image_ids_to_reap { self.sixel_image_locations.remove(image_id); } self.sixel_image_locations .insert(new_image_id, image_size_and_coordinates); self.currently_parsing = None; Some(sixel_image) } else { None } } else { None } } pub fn image_coordinates(&self) -> impl Iterator<Item = (usize, &PixelRect)> { self.sixel_image_locations .iter() .map(|(image_id, pixel_rect)| (*image_id, pixel_rect)) } pub fn cut_off_rect_from_images( &mut self, rect_to_cut_out: PixelRect, ) -> Option<Vec<(usize, PixelRect)>> { // if there is an image at this cursor location, this returns the image ID and the PixelRect inside the image to be removed let mut ret = None; for (image_id, pixel_rect) in &self.sixel_image_locations { if let Some(intersecting_rect) = pixel_rect.intersecting_rect(&rect_to_cut_out) { let ret = ret.get_or_insert(vec![]); ret.push((*image_id, intersecting_rect)); } } ret } pub fn offset_grid_top(&mut self) { if let Some(character_cell_size) = *self.character_cell_size.borrow() { let height_to_reduce = character_cell_size.height as isize; for (sixel_image_id, pixel_rect) in self.sixel_image_locations.iter_mut() { pixel_rect.y -= height_to_reduce; if pixel_rect.y + pixel_rect.height as isize <= 0 { self.image_ids_to_reap.push(*sixel_image_id); } } for image_id in &self.image_ids_to_reap { self.sixel_image_locations.remove(image_id); } } } pub fn drain_image_ids_to_reap(&mut self) -> Option<Vec<usize>> { let images_to_reap = self.image_ids_to_reap.drain(..); if images_to_reap.len() > 0 { Some(images_to_reap.collect()) } else { None } } pub fn character_cell_size_possibly_changed(&mut self) { if let (Some(previous_cell_size), Some(character_cell_size)) = (self.previous_cell_size, *self.character_cell_size.borrow()) { if previous_cell_size != character_cell_size { for (_image_id, pixel_rect) in self.sixel_image_locations.iter_mut() { pixel_rect.x = (pixel_rect.x / previous_cell_size.width) * character_cell_size.width; pixel_rect.y = (pixel_rect.y / previous_cell_size.height as isize) * character_cell_size.height as isize; } } } self.previous_cell_size = *self.character_cell_size.borrow(); } pub fn clear(&mut self) -> Option<Vec<usize>> { // returns image ids to reap let mut image_ids: Vec<usize> = self .sixel_image_locations .drain() .map(|(image_id, _image_rect)| image_id) .collect(); image_ids.append(&mut self.image_ids_to_reap); if !image_ids.is_empty() { Some(image_ids) } else { None } } pub fn next_image_id(&self) -> usize { self.sixel_image_store.borrow().sixel_images.keys().len() } pub fn new_sixel_image(&mut self, sixel_image_id: usize, sixel_image: SixelImage) { self.sixel_image_store .borrow_mut() .sixel_images .insert(sixel_image_id, (sixel_image, HashMap::new())); } pub fn remove_pixels_from_image(&mut self, image_id: usize, pixel_rect: PixelRect) { if let Some((sixel_image, sixel_image_cache)) = self .sixel_image_store .borrow_mut() .sixel_images .get_mut(&image_id) { sixel_image.cut_out( pixel_rect.x, pixel_rect.y as usize, pixel_rect.width, pixel_rect.height, ); sixel_image_cache.clear(); // TODO: more intelligent cache clearing } } pub fn reap_images(&mut self, ids_to_reap: Vec<usize>) { for id in ids_to_reap { drop(self.sixel_image_store.borrow_mut().sixel_images.remove(&id)); } } pub fn image_cell_coordinates_in_viewport( &self, viewport_height: usize, scrollback_height: usize, ) -> Vec<(usize, usize, usize, usize)> { match *self.character_cell_size.borrow() { Some(character_cell_size) => self .sixel_image_locations .iter() .map(|(_image_id, pixel_rect)| { let scrollback_size_in_pixels = scrollback_height * character_cell_size.height; let y_pixel_coordinates_in_viewport = pixel_rect.y - scrollback_size_in_pixels as isize; let image_y = std::cmp::max(y_pixel_coordinates_in_viewport, 0) as usize / character_cell_size.height; let image_x = pixel_rect.x / character_cell_size.width; let image_height_in_pixels = if y_pixel_coordinates_in_viewport < 0 { pixel_rect.height as isize + y_pixel_coordinates_in_viewport } else { pixel_rect.height as isize }; let image_height = image_height_in_pixels as usize / character_cell_size.height; let image_width = pixel_rect.width / character_cell_size.width; let height_remainder = if image_height_in_pixels as usize % character_cell_size.height > 0 { 1 } else { 0 }; let width_remainder = if pixel_rect.width % character_cell_size.width > 0 { 1 } else { 0 }; let image_top_edge = image_y; let image_bottom_edge = std::cmp::min(image_y + image_height + height_remainder, viewport_height); let image_left_edge = image_x; let image_right_edge = image_x + image_width + width_remainder; ( image_top_edge, image_bottom_edge, image_left_edge, image_right_edge, ) }) .collect(), None => vec![], } } pub fn changed_sixel_chunks_in_viewport( &self, changed_rects: HashMap<usize, usize>, scrollback_size_in_lines: usize, viewport_width_in_cells: usize, viewport_x_offset: usize, viewport_y_offset: usize, ) -> Vec<SixelImageChunk> { let mut changed_sixel_image_chunks = vec![]; if let Some(character_cell_size) = { *self.character_cell_size.borrow() } { for (sixel_image_id, sixel_image_pixel_rect) in self.image_coordinates() { for (line_index, line_count) in &changed_rects { let changed_rect_pixel_height = line_count * character_cell_size.height; let changed_rect_top_edge = ((line_index + scrollback_size_in_lines) * character_cell_size.height) as isize; let changed_rect_bottom_edge = changed_rect_top_edge + changed_rect_pixel_height as isize; let sixel_image_top_edge = sixel_image_pixel_rect.y; let sixel_image_bottom_edge = sixel_image_pixel_rect.y + sixel_image_pixel_rect.height as isize; let cell_x_in_current_pane = sixel_image_pixel_rect.x / character_cell_size.width; let cell_x = viewport_x_offset + cell_x_in_current_pane; let sixel_image_pixel_width = if sixel_image_pixel_rect.x + sixel_image_pixel_rect.width <= (viewport_width_in_cells * character_cell_size.width) { sixel_image_pixel_rect.width } else { (viewport_width_in_cells * character_cell_size.width) .saturating_sub(sixel_image_pixel_rect.x) }; if sixel_image_pixel_width == 0 { continue; } let sixel_image_cell_distance_from_scrollback_top = sixel_image_top_edge as usize / character_cell_size.height; // if the image is above the rect top, this will be 0 let sixel_image_cell_distance_from_changed_rect_top = sixel_image_cell_distance_from_scrollback_top .saturating_sub(line_index + scrollback_size_in_lines); let cell_y = viewport_y_offset + line_index + sixel_image_cell_distance_from_changed_rect_top; let sixel_image_pixel_x = 0; // if the image is above the rect top, this will be 0 let sixel_image_pixel_y = (changed_rect_top_edge as usize) .saturating_sub(sixel_image_top_edge as usize) as usize; let sixel_image_pixel_height = std::cmp::min( (std::cmp::min(changed_rect_bottom_edge, sixel_image_bottom_edge) - std::cmp::max(changed_rect_top_edge, sixel_image_top_edge)) as usize, sixel_image_pixel_rect.height, ); if (sixel_image_top_edge >= changed_rect_top_edge && sixel_image_top_edge <= changed_rect_bottom_edge) || (sixel_image_bottom_edge >= changed_rect_top_edge && sixel_image_bottom_edge <= changed_rect_bottom_edge) || (sixel_image_bottom_edge >= changed_rect_bottom_edge && sixel_image_top_edge <= changed_rect_top_edge) { changed_sixel_image_chunks.push(SixelImageChunk { cell_x, cell_y, sixel_image_pixel_x, sixel_image_pixel_y, sixel_image_pixel_width, sixel_image_pixel_height, sixel_image_id, }); } } } } changed_sixel_image_chunks } } type SixelImageCache = HashMap<PixelRect, String>; #[derive(Debug, Clone, Default)] pub struct SixelImageStore { sixel_images: HashMap<usize, (SixelImage, SixelImageCache)>, } impl SixelImageStore { pub fn serialize_image( &mut self, image_id: usize, pixel_x: usize, pixel_y: usize, pixel_width: usize, pixel_height: usize, ) -> Option<String> { self.sixel_images .get_mut(&image_id) .map(|(sixel_image, sixel_image_cache)| { if let Some(cached_image) = sixel_image_cache.get(&PixelRect::new( pixel_x, pixel_y, pixel_height, pixel_width, )) { cached_image.clone() } else { let serialized_image = sixel_image.serialize_range(pixel_x, pixel_y, pixel_width, pixel_height); sixel_image_cache.insert( PixelRect::new(pixel_x, pixel_y, pixel_height, pixel_width), serialized_image.clone(), ); serialized_image } }) } pub fn image_count(&self) -> usize { self.sixel_images.len() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/terminal_character.rs
zellij-server/src/panes/terminal_character.rs
use std::convert::From; use std::fmt::{self, Debug, Display, Formatter}; use std::ops::{Index, IndexMut}; use std::rc::Rc; use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthStr; use vte::ParamsIter; use zellij_utils::data::StyleDeclaration; use zellij_utils::data::{PaletteColor, Style}; use zellij_utils::input::command::RunCommand; use crate::panes::alacritty_functions::parse_sgr_color; pub const EMPTY_TERMINAL_CHARACTER: TerminalCharacter = TerminalCharacter { character: ' ', width: 1, styles: RcCharacterStyles::Reset, }; pub const RESET_STYLES: CharacterStyles = CharacterStyles { foreground: Some(AnsiCode::Reset), background: Some(AnsiCode::Reset), underline_color: Some(AnsiCode::Reset), strike: Some(AnsiCode::Reset), hidden: Some(AnsiCode::Reset), reverse: Some(AnsiCode::Reset), slow_blink: Some(AnsiCode::Reset), fast_blink: Some(AnsiCode::Reset), underline: Some(AnsiCode::Reset), bold: Some(AnsiCode::Reset), dim: Some(AnsiCode::Reset), italic: Some(AnsiCode::Reset), link_anchor: Some(LinkAnchor::End), styled_underlines_enabled: false, }; // Prefer to use RcCharacterStyles::default() where it makes sense // as it will reduce memory usage pub const DEFAULT_STYLES: CharacterStyles = CharacterStyles { foreground: None, background: None, underline_color: None, strike: None, hidden: None, reverse: None, slow_blink: None, fast_blink: None, underline: None, bold: None, dim: None, italic: None, link_anchor: None, styled_underlines_enabled: false, }; thread_local! { static RC_DEFAULT_STYLES: RcCharacterStyles = RcCharacterStyles::Rc(Rc::new(DEFAULT_STYLES)); } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AnsiCode { On, Reset, NamedColor(NamedColor), RgbCode((u8, u8, u8)), ColorIndex(u8), Underline(Option<AnsiStyledUnderline>), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AnsiStyledUnderline { Double, Undercurl, Underdotted, Underdashed, } impl From<PaletteColor> for AnsiCode { fn from(palette_color: PaletteColor) -> Self { match palette_color { PaletteColor::Rgb((r, g, b)) => AnsiCode::RgbCode((r, g, b)), PaletteColor::EightBit(index) => AnsiCode::ColorIndex(index), } } } #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum NamedColor { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, } impl NamedColor { fn to_foreground_ansi_code(self) -> String { let v = match self { NamedColor::Black => 30, NamedColor::Red => 31, NamedColor::Green => 32, NamedColor::Yellow => 33, NamedColor::Blue => 34, NamedColor::Magenta => 35, NamedColor::Cyan => 36, NamedColor::White => 37, NamedColor::BrightBlack => 90, NamedColor::BrightRed => 91, NamedColor::BrightGreen => 92, NamedColor::BrightYellow => 93, NamedColor::BrightBlue => 94, NamedColor::BrightMagenta => 95, NamedColor::BrightCyan => 96, NamedColor::BrightWhite => 97, }; v.to_string() } fn to_background_ansi_code(self) -> String { let v = match self { NamedColor::Black => 40, NamedColor::Red => 41, NamedColor::Green => 42, NamedColor::Yellow => 43, NamedColor::Blue => 44, NamedColor::Magenta => 45, NamedColor::Cyan => 46, NamedColor::White => 47, NamedColor::BrightBlack => 100, NamedColor::BrightRed => 101, NamedColor::BrightGreen => 102, NamedColor::BrightYellow => 103, NamedColor::BrightBlue => 104, NamedColor::BrightMagenta => 105, NamedColor::BrightCyan => 106, NamedColor::BrightWhite => 107, }; v.to_string() } } // This enum carefully only has two variants so // enum niche optimisations can keep it at the same byte size as pointers #[derive(Clone, Debug, PartialEq)] pub enum RcCharacterStyles { Reset, Rc(Rc<CharacterStyles>), } #[cfg(target_arch = "x86_64")] const _: [(); 8] = [(); std::mem::size_of::<RcCharacterStyles>()]; impl From<CharacterStyles> for RcCharacterStyles { fn from(styles: CharacterStyles) -> Self { if styles == RESET_STYLES { RcCharacterStyles::Reset } else { RcCharacterStyles::Rc(Rc::new(styles)) } } } impl Default for RcCharacterStyles { fn default() -> Self { RC_DEFAULT_STYLES.with(|s| s.clone()) } } impl std::ops::Deref for RcCharacterStyles { type Target = CharacterStyles; fn deref(&self) -> &Self::Target { match self { RcCharacterStyles::Reset => &RESET_STYLES, RcCharacterStyles::Rc(styles) => &*styles, } } } impl Display for RcCharacterStyles { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let styles: &CharacterStyles = &*self; Display::fmt(&styles, f) } } impl RcCharacterStyles { pub fn reset() -> Self { Self::Reset } pub fn update(&mut self, f: impl FnOnce(&mut CharacterStyles)) { let mut styles: CharacterStyles = **self; f(&mut styles); *self = styles.into(); } } #[derive(Clone, Copy, Debug)] pub struct CharacterStyles { pub foreground: Option<AnsiCode>, pub background: Option<AnsiCode>, pub underline_color: Option<AnsiCode>, pub strike: Option<AnsiCode>, pub hidden: Option<AnsiCode>, pub reverse: Option<AnsiCode>, pub slow_blink: Option<AnsiCode>, pub fast_blink: Option<AnsiCode>, pub underline: Option<AnsiCode>, pub bold: Option<AnsiCode>, pub dim: Option<AnsiCode>, pub italic: Option<AnsiCode>, pub link_anchor: Option<LinkAnchor>, pub styled_underlines_enabled: bool, } impl PartialEq for CharacterStyles { fn eq(&self, other: &Self) -> bool { self.foreground == other.foreground && self.background == other.background && self.underline_color == other.underline_color && self.strike == other.strike && self.hidden == other.hidden && self.reverse == other.reverse && self.slow_blink == other.slow_blink && self.fast_blink == other.fast_blink && self.underline == other.underline && self.bold == other.bold && self.dim == other.dim && self.italic == other.italic && self.link_anchor == other.link_anchor } } impl CharacterStyles { pub fn foreground(mut self, foreground_code: Option<AnsiCode>) -> Self { self.foreground = foreground_code; self } pub fn background(mut self, background_code: Option<AnsiCode>) -> Self { self.background = background_code; self } pub fn underline_color(mut self, underline_color_code: Option<AnsiCode>) -> Self { self.underline_color = underline_color_code; self } pub fn bold(mut self, bold_code: Option<AnsiCode>) -> Self { self.bold = bold_code; self } pub fn dim(mut self, dim_code: Option<AnsiCode>) -> Self { self.dim = dim_code; self } pub fn italic(mut self, italic_code: Option<AnsiCode>) -> Self { self.italic = italic_code; self } pub fn underline(mut self, underline_code: Option<AnsiCode>) -> Self { self.underline = underline_code; self } pub fn blink_slow(mut self, slow_blink_code: Option<AnsiCode>) -> Self { self.slow_blink = slow_blink_code; self } pub fn blink_fast(mut self, fast_blink_code: Option<AnsiCode>) -> Self { self.fast_blink = fast_blink_code; self } pub fn reverse(mut self, reverse_code: Option<AnsiCode>) -> Self { self.reverse = reverse_code; self } pub fn hidden(mut self, hidden_code: Option<AnsiCode>) -> Self { self.hidden = hidden_code; self } pub fn strike(mut self, strike_code: Option<AnsiCode>) -> Self { self.strike = strike_code; self } pub fn link_anchor(mut self, link_anchor: Option<LinkAnchor>) -> Self { self.link_anchor = link_anchor; self } pub fn enable_styled_underlines(mut self, enabled: bool) -> Self { self.styled_underlines_enabled = enabled; self } pub fn clear(&mut self) { self.foreground = None; self.background = None; self.underline_color = None; self.strike = None; self.hidden = None; self.reverse = None; self.slow_blink = None; self.fast_blink = None; self.underline = None; self.bold = None; self.dim = None; self.italic = None; self.link_anchor = None; } pub fn update_and_return_diff( &mut self, new_styles: &CharacterStyles, changed_colors: Option<[Option<AnsiCode>; 256]>, ) -> Option<CharacterStyles> { if self == new_styles && changed_colors.is_none() { return None; } if *new_styles == RESET_STYLES { *self = RESET_STYLES.enable_styled_underlines(self.styled_underlines_enabled); return Some(RESET_STYLES.enable_styled_underlines(self.styled_underlines_enabled)); } // create diff from all changed styles let mut diff = DEFAULT_STYLES.enable_styled_underlines(self.styled_underlines_enabled); if self.foreground != new_styles.foreground { diff.foreground = new_styles.foreground; } if self.background != new_styles.background { diff.background = new_styles.background; } if self.underline_color != new_styles.underline_color { diff.underline_color = new_styles.underline_color; } if self.strike != new_styles.strike { diff.strike = new_styles.strike; } if self.hidden != new_styles.hidden { diff.hidden = new_styles.hidden; } if self.reverse != new_styles.reverse { diff.reverse = new_styles.reverse; } if self.slow_blink != new_styles.slow_blink { diff.slow_blink = new_styles.slow_blink; } if self.fast_blink != new_styles.fast_blink { diff.fast_blink = new_styles.fast_blink; } if self.underline != new_styles.underline { diff.underline = new_styles.underline; } if self.bold != new_styles.bold { diff.bold = new_styles.bold; } if self.dim != new_styles.dim { diff.dim = new_styles.dim; } if self.italic != new_styles.italic { diff.italic = new_styles.italic; } if self.link_anchor != new_styles.link_anchor { diff.link_anchor = new_styles.link_anchor; } // apply new styles *self = new_styles.enable_styled_underlines(self.styled_underlines_enabled); if let Some(changed_colors) = changed_colors { if let Some(AnsiCode::ColorIndex(color_index)) = diff.foreground { if let Some(changed_color) = changed_colors[color_index as usize] { diff.foreground = Some(changed_color); } } if let Some(AnsiCode::ColorIndex(color_index)) = diff.background { if let Some(changed_color) = changed_colors[color_index as usize] { diff.background = Some(changed_color); } } } Some(diff) } fn reset_ansi(&mut self) { self.foreground = Some(AnsiCode::Reset); self.background = Some(AnsiCode::Reset); self.underline_color = Some(AnsiCode::Reset); self.bold = Some(AnsiCode::Reset); self.dim = Some(AnsiCode::Reset); self.italic = Some(AnsiCode::Reset); self.underline = Some(AnsiCode::Reset); self.slow_blink = Some(AnsiCode::Reset); self.fast_blink = Some(AnsiCode::Reset); self.reverse = Some(AnsiCode::Reset); self.hidden = Some(AnsiCode::Reset); self.strike = Some(AnsiCode::Reset); // Deliberately don't end link anchor } pub fn add_style_from_ansi_params(&mut self, params: &mut ParamsIter) { while let Some(param) = params.next() { match param { [] | [0] => self.reset_ansi(), [1] => *self = self.bold(Some(AnsiCode::On)), [2] => *self = self.dim(Some(AnsiCode::On)), [3] => *self = self.italic(Some(AnsiCode::On)), [4, 0] => *self = self.underline(Some(AnsiCode::Reset)), [4, 1] => *self = self.underline(Some(AnsiCode::Underline(None))), [4, 2] => { *self = self.underline(Some(AnsiCode::Underline(Some(AnsiStyledUnderline::Double)))) }, [4, 3] => { *self = self.underline(Some(AnsiCode::Underline(Some( AnsiStyledUnderline::Undercurl, )))) }, [4, 4] => { *self = self.underline(Some(AnsiCode::Underline(Some( AnsiStyledUnderline::Underdotted, )))) }, [4, 5] => { *self = self.underline(Some(AnsiCode::Underline(Some( AnsiStyledUnderline::Underdashed, )))) }, [4] => *self = self.underline(Some(AnsiCode::Underline(None))), [5] => *self = self.blink_slow(Some(AnsiCode::On)), [6] => *self = self.blink_fast(Some(AnsiCode::On)), [7] => *self = self.reverse(Some(AnsiCode::On)), [8] => *self = self.hidden(Some(AnsiCode::On)), [9] => *self = self.strike(Some(AnsiCode::On)), [21] => *self = self.bold(Some(AnsiCode::Reset)), [22] => { *self = self.bold(Some(AnsiCode::Reset)); *self = self.dim(Some(AnsiCode::Reset)); }, [23] => *self = self.italic(Some(AnsiCode::Reset)), [24] => *self = self.underline(Some(AnsiCode::Reset)), [25] => { *self = self.blink_slow(Some(AnsiCode::Reset)); *self = self.blink_fast(Some(AnsiCode::Reset)); }, [27] => *self = self.reverse(Some(AnsiCode::Reset)), [28] => *self = self.hidden(Some(AnsiCode::Reset)), [29] => *self = self.strike(Some(AnsiCode::Reset)), [30] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Black))), [31] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Red))), [32] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Green))), [33] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Yellow))), [34] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Blue))), [35] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Magenta))), [36] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::Cyan))), [37] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::White))), [38] => { let mut iter = params.map(|param| param[0]); if let Some(ansi_code) = parse_sgr_color(&mut iter) { *self = self.foreground(Some(ansi_code)); } }, [38, params @ ..] => { let rgb_start = if params.len() > 4 { 2 } else { 1 }; let rgb_iter = params[rgb_start..].iter().copied(); let mut iter = std::iter::once(params[0]).chain(rgb_iter); if let Some(ansi_code) = parse_sgr_color(&mut iter) { *self = self.foreground(Some(ansi_code)); } }, [39] => *self = self.foreground(Some(AnsiCode::Reset)), [40] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Black))), [41] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Red))), [42] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Green))), [43] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Yellow))), [44] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Blue))), [45] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Magenta))), [46] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::Cyan))), [47] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::White))), [48] => { let mut iter = params.map(|param| param[0]); if let Some(ansi_code) = parse_sgr_color(&mut iter) { *self = self.background(Some(ansi_code)); } }, [48, params @ ..] => { let rgb_start = if params.len() > 4 { 2 } else { 1 }; let rgb_iter = params[rgb_start..].iter().copied(); let mut iter = std::iter::once(params[0]).chain(rgb_iter); if let Some(ansi_code) = parse_sgr_color(&mut iter) { *self = self.background(Some(ansi_code)); } }, [49] => *self = self.background(Some(AnsiCode::Reset)), [58] => { let mut iter = params.map(|param| param[0]); if let Some(ansi_code) = parse_sgr_color(&mut iter) { *self = self.underline_color(Some(ansi_code)); } }, [58, params @ ..] => { let rgb_start = if params.len() > 4 { 2 } else { 1 }; let rgb_iter = params[rgb_start..].iter().copied(); let mut iter = std::iter::once(params[0]).chain(rgb_iter); if let Some(ansi_code) = parse_sgr_color(&mut iter) { *self = self.underline_color(Some(ansi_code)); } }, [59] => *self = self.underline_color(Some(AnsiCode::Reset)), [90] => { *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightBlack))) }, [91] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightRed))), [92] => { *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightGreen))) }, [93] => { *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightYellow))) }, [94] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightBlue))), [95] => { *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightMagenta))) }, [96] => *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightCyan))), [97] => { *self = self.foreground(Some(AnsiCode::NamedColor(NamedColor::BrightWhite))) }, [100] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightBlack))) }, [101] => *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightRed))), [102] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightGreen))) }, [103] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightYellow))) }, [104] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightBlue))) }, [105] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightMagenta))) }, [106] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightCyan))) }, [107] => { *self = self.background(Some(AnsiCode::NamedColor(NamedColor::BrightWhite))) }, _ => { return; }, } } } } impl Display for CharacterStyles { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if self.foreground == Some(AnsiCode::Reset) && self.background == Some(AnsiCode::Reset) && self.underline_color == Some(AnsiCode::Reset) && self.strike == Some(AnsiCode::Reset) && self.hidden == Some(AnsiCode::Reset) && self.reverse == Some(AnsiCode::Reset) && self.fast_blink == Some(AnsiCode::Reset) && self.slow_blink == Some(AnsiCode::Reset) && self.underline == Some(AnsiCode::Reset) && self.bold == Some(AnsiCode::Reset) && self.dim == Some(AnsiCode::Reset) && self.italic == Some(AnsiCode::Reset) { write!(f, "\u{1b}[m")?; // reset all return Ok(()); } if let Some(ansi_code) = self.foreground { match ansi_code { AnsiCode::RgbCode((r, g, b)) => { write!(f, "\u{1b}[38;2;{};{};{}m", r, g, b)?; }, AnsiCode::ColorIndex(color_index) => { write!(f, "\u{1b}[38;5;{}m", color_index)?; }, AnsiCode::Reset => { write!(f, "\u{1b}[39m")?; }, AnsiCode::NamedColor(named_color) => { write!(f, "\u{1b}[{}m", named_color.to_foreground_ansi_code())?; }, _ => {}, } }; if let Some(ansi_code) = self.background { match ansi_code { AnsiCode::RgbCode((r, g, b)) => { write!(f, "\u{1b}[48;2;{};{};{}m", r, g, b)?; }, AnsiCode::ColorIndex(color_index) => { write!(f, "\u{1b}[48;5;{}m", color_index)?; }, AnsiCode::Reset => { write!(f, "\u{1b}[49m")?; }, AnsiCode::NamedColor(named_color) => { write!(f, "\u{1b}[{}m", named_color.to_background_ansi_code())?; }, _ => {}, } } if self.styled_underlines_enabled { if let Some(ansi_code) = self.underline_color { match ansi_code { AnsiCode::RgbCode((r, g, b)) => { write!(f, "\u{1b}[58:2::{}:{}:{}m", r, g, b)?; }, AnsiCode::ColorIndex(color_index) => { write!(f, "\u{1b}[58:5:{}m", color_index)?; }, AnsiCode::Reset => { write!(f, "\u{1b}[59m")?; }, _ => {}, } }; } if let Some(ansi_code) = self.strike { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[9m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[29m")?; }, _ => {}, } } if let Some(ansi_code) = self.hidden { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[8m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[28m")?; }, _ => {}, } } if let Some(ansi_code) = self.reverse { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[7m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[27m")?; }, _ => {}, } } if let Some(ansi_code) = self.fast_blink { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[6m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[25m")?; }, _ => {}, } } if let Some(ansi_code) = self.slow_blink { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[5m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[25m")?; }, _ => {}, } } if let Some(ansi_code) = self.bold { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[1m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[22m\u{1b}[24m")?; // TODO: this cancels bold + underline, if this behaviour is indeed correct, we // need to properly handle it in the struct methods etc like dim }, _ => {}, } } // notice the order is important here, bold must be before underline // because the bold reset also resets underline, and would override it // otherwise if let Some(ansi_code) = self.underline { match ansi_code { AnsiCode::Underline(None) => { write!(f, "\u{1b}[4m")?; }, AnsiCode::Underline(Some(styled)) => { if self.styled_underlines_enabled { match styled { AnsiStyledUnderline::Double => { write!(f, "\u{1b}[4:2m")?; }, AnsiStyledUnderline::Undercurl => { write!(f, "\u{1b}[4:3m")?; }, AnsiStyledUnderline::Underdotted => { write!(f, "\u{1b}[4:4m")?; }, AnsiStyledUnderline::Underdashed => { write!(f, "\u{1b}[4:5m")?; }, } } }, AnsiCode::Reset => { write!(f, "\u{1b}[24m")?; }, _ => {}, } } if let Some(ansi_code) = self.dim { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[2m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[22m")?; // ⬑ this SGR also clears bold, so reapply it if let Some(AnsiCode::On) = self.bold { write!(f, "\u{1b}[1m")?; } }, _ => {}, } } if let Some(ansi_code) = self.italic { match ansi_code { AnsiCode::On => { write!(f, "\u{1b}[3m")?; }, AnsiCode::Reset => { write!(f, "\u{1b}[23m")?; }, _ => {}, } }; Ok(()) } } impl From<StyleDeclaration> for CharacterStyles { fn from(declaration: StyleDeclaration) -> Self { RESET_STYLES.foreground(Some(declaration.base.into())) } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LinkAnchor { Start(u16), End, } #[derive(Clone, Copy, Debug)] pub enum CharsetIndex { G0, G1, G2, G3, } impl Default for CharsetIndex { fn default() -> Self { CharsetIndex::G0 } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum StandardCharset { Ascii, UK, SpecialCharacterAndLineDrawing, } impl Default for StandardCharset { fn default() -> Self { StandardCharset::Ascii } } impl StandardCharset { /// Switch/Map character to the active charset. Ascii is the common case and /// for that we want to do as little as possible. #[inline] pub fn map(self, c: char) -> char { match self { StandardCharset::Ascii => c, StandardCharset::UK => match c { '#' => '£', _ => c, }, StandardCharset::SpecialCharacterAndLineDrawing => match c { '`' => '◆', 'a' => '▒', 'b' => '␉', 'c' => '␌', 'd' => '␍', 'e' => '␊', 'f' => '°', 'g' => '±', 'h' => '␤', 'i' => '␋', 'j' => '┘', 'k' => '┐', 'l' => '┌', 'm' => '└', 'n' => '┼', 'o' => '⎺', 'p' => '⎻', 'q' => '─', 'r' => '⎼', 's' => '⎽', 't' => '├', 'u' => '┤', 'v' => '┴', 'w' => '┬', 'x' => '│', 'y' => '≤', 'z' => '≥', '{' => 'π', '|' => '≠', '}' => '£', '~' => '·', _ => c, }, } } } #[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] pub struct Charsets([StandardCharset; 4]); impl Index<CharsetIndex> for Charsets { type Output = StandardCharset; fn index(&self, index: CharsetIndex) -> &StandardCharset { &self.0[index as usize] } } impl IndexMut<CharsetIndex> for Charsets { fn index_mut(&mut self, index: CharsetIndex) -> &mut StandardCharset { &mut self.0[index as usize] } } #[derive(Clone, Copy, Debug)] pub enum CursorShape { Initial, Block, BlinkingBlock, Underline, BlinkingUnderline, Beam, BlinkingBeam, } impl CursorShape { pub fn get_csi_str(&self) -> &str { match self { CursorShape::Initial => "\u{1b}[0 q", CursorShape::Block => "\u{1b}[2 q", CursorShape::BlinkingBlock => "\u{1b}[1 q", CursorShape::Underline => "\u{1b}[4 q", CursorShape::BlinkingUnderline => "\u{1b}[3 q", CursorShape::Beam => "\u{1b}[6 q", CursorShape::BlinkingBeam => "\u{1b}[5 q", } } } #[derive(Clone, Debug)] pub struct Cursor { pub x: usize, pub y: usize, pub pending_styles: RcCharacterStyles, pub charsets: Charsets, shape: CursorShape, } impl Cursor { pub fn new(x: usize, y: usize, styled_underlines: bool) -> Self { Cursor { x, y, pending_styles: RESET_STYLES .enable_styled_underlines(styled_underlines) .into(), charsets: Default::default(), shape: CursorShape::Initial, } } pub fn change_shape(&mut self, shape: CursorShape) { self.shape = shape; } pub fn get_shape(&self) -> CursorShape { self.shape } } #[derive(Clone, PartialEq)] pub struct TerminalCharacter { pub character: char, pub styles: RcCharacterStyles, width: u8, } // This size has significant memory and CPU implications for long lines, // be careful about allowing it to grow #[cfg(target_arch = "x86_64")] const _: [(); 16] = [(); std::mem::size_of::<TerminalCharacter>()]; impl TerminalCharacter { #[inline]
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/mod.rs
zellij-server/src/panes/mod.rs
pub mod alacritty_functions; pub mod grid; pub mod hyperlink_tracker; pub mod link_handler; pub mod selection; pub mod sixel; pub mod terminal_character; mod active_panes; pub mod floating_panes; mod plugin_pane; mod search; pub mod terminal_pane; mod tiled_panes; pub use active_panes::*; pub use alacritty_functions::*; pub use floating_panes::*; pub use grid::*; pub use link_handler::*; pub(crate) use plugin_pane::*; pub use selection::Selection; pub use sixel::*; pub(crate) use terminal_character::*; pub use terminal_pane::*; pub use tiled_panes::*;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/selection.rs
zellij-server/src/panes/selection.rs
use std::{collections::HashSet, ops::Range}; use zellij_utils::position::Position; // The selection is empty when start == end // it includes the character at start, and everything before end. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Selection { pub start: Position, pub end: Position, active: bool, // used to handle moving the selection up and down last_added_word_position: Option<(Position, Position)>, // (start / end) last_added_line_index: Option<isize>, } impl Default for Selection { fn default() -> Self { Self { start: Position::new(0, 0), end: Position::new(0, 0), active: false, last_added_word_position: None, last_added_line_index: None, } } } impl Selection { pub fn start(&mut self, start: Position) { self.active = true; self.start = start; self.end = start; } pub fn to(&mut self, to: Position) { self.end = to } pub fn end(&mut self, end: Position) { self.active = false; self.end = end; } pub fn set_start_and_end_positions(&mut self, start: Position, end: Position) { self.active = true; self.start = start; self.end = end; self.last_added_word_position = Some((start, end)); self.last_added_line_index = Some(start.line.0); } pub fn add_word_to_position(&mut self, word_start: Position, word_end: Position) { // here we assume word_start is smaller or equal to word_end let already_added = self .last_added_word_position .map(|(last_word_start, last_word_end)| { last_word_start == word_start && last_word_end == word_end }) .unwrap_or(false); if already_added { return; } let word_is_above_last_added_word = self .last_added_word_position .map(|(l_start, _l_end)| word_start.line < l_start.line) .unwrap_or(false); let word_is_below_last_added_word = self .last_added_word_position .map(|(_l_start, l_end)| word_end.line > l_end.line) .unwrap_or(false); if word_is_above_last_added_word && word_start.line < self.start.line { // extend line above self.start = word_start; } else if word_is_below_last_added_word && word_end.line > self.end.line { // extend line below self.end = word_end; } else if word_is_below_last_added_word && word_start.line > self.start.line { // reduce from above self.start = word_start; } else if word_is_above_last_added_word && word_end.line < self.end.line { // reduce from below self.end = word_end; } else { let word_end_is_to_the_left_of_last_word_start = self .last_added_word_position .map(|(l_start, _l_end)| word_end.column <= l_start.column) .unwrap_or(false); let word_start_is_to_the_right_of_last_word_end = self .last_added_word_position .map(|(_l_start, l_end)| word_start.column >= l_end.column) .unwrap_or(false); let last_word_start_equals_word_end = self .last_added_word_position .map(|(l_start, _l_end)| l_start.column == word_end.column) .unwrap_or(false); let last_word_end_equals_word_start = self .last_added_word_position .map(|(_l_start, l_end)| l_end.column == word_start.column) .unwrap_or(false); let selection_start_column_is_to_the_right_of_word_start = self.start.column > word_start.column; let selection_start_is_on_same_line_as_word_start = self.start.line == word_start.line; let selection_end_is_to_the_left_of_word_end = self.end.column < word_end.column; let selection_end_is_on_same_line_as_word_end = self.end.line == word_end.line; if word_end_is_to_the_left_of_last_word_start && selection_start_column_is_to_the_right_of_word_start && selection_start_is_on_same_line_as_word_start { // extend selection left self.start.column = word_start.column; } else if word_start_is_to_the_right_of_last_word_end && selection_end_is_to_the_left_of_word_end && selection_end_is_on_same_line_as_word_end { // extend selection right self.end.column = word_end.column; } else if last_word_start_equals_word_end { // reduce selection from the right self.end.column = word_end.column; } else if last_word_end_equals_word_start { // reduce selection from the left self.start.column = word_start.column; } } self.last_added_word_position = Some((word_start, word_end)); } pub fn add_line_to_position(&mut self, line_index: isize, last_index_in_line: usize) { let already_added = self .last_added_line_index .map(|last_added_line_index| last_added_line_index == line_index) .unwrap_or(false); if already_added { return; } let line_index_is_smaller_than_last_added_line_index = self .last_added_line_index .map(|last| line_index < last) .unwrap_or(false); let line_index_is_larger_than_last_added_line_index = self .last_added_line_index .map(|last| line_index > last) .unwrap_or(false); if line_index_is_smaller_than_last_added_line_index && self.start.line.0 > line_index { // extend selection one line upwards self.start = Position::new(line_index as i32, 0); } else if line_index_is_larger_than_last_added_line_index && self.end.line.0 < line_index { // extend selection one line downwards self.end = Position::new(line_index as i32, last_index_in_line as u16); } else if line_index_is_smaller_than_last_added_line_index && self.end.line.0 > line_index { // reduce selection one line from below self.end = Position::new(line_index as i32, last_index_in_line as u16); } else if line_index_is_larger_than_last_added_line_index && self.start.line.0 < line_index { // reduce selection one line from above self.start = Position::new(line_index as i32, 0); } self.last_added_line_index = Some(line_index); } pub fn contains(&self, row: usize, col: usize) -> bool { let row = row as isize; let (start, end) = if self.start <= self.end { (self.start, self.end) } else { (self.end, self.start) }; if (start.line.0) < row && row < end.line.0 { return true; } if start.line == end.line { return row == start.line.0 && start.column.0 <= col && col < end.column.0; } if start.line.0 == row && col >= start.column.0 { return true; } end.line.0 == row && col < end.column.0 } pub fn contains_row(&self, row: usize) -> bool { let row = row as isize; let (start, end) = if self.start <= self.end { (self.start, self.end) } else { (self.end, self.start) }; start.line.0 <= row && end.line.0 >= row } pub fn is_empty(&self) -> bool { self.start == self.end } pub fn reset(&mut self) { self.start = Position::new(0, 0); self.end = self.start; } pub fn sorted(&self) -> Self { let (start, end) = if self.start <= self.end { (self.start, self.end) } else { (self.end, self.start) }; Self { start, end, active: self.active, last_added_word_position: self.last_added_word_position, last_added_line_index: self.last_added_line_index, } } pub fn line_indices(&self) -> std::ops::RangeInclusive<isize> { let sorted = self.sorted(); sorted.start.line.0..=sorted.end.line.0 } pub fn move_up(&mut self, lines: usize) { self.start.line.0 -= lines as isize; if !self.active { self.end.line.0 -= lines as isize; } } pub fn move_down(&mut self, lines: usize) { self.start.line.0 += lines as isize; if !self.active { self.end.line.0 += lines as isize; } } pub fn offset(mut self, offset_x: usize, offset_y: usize) -> Self { self.start.line.0 += offset_y as isize; self.end.line.0 += offset_y as isize; self.start.column.0 += offset_x; self.end.column.0 += offset_x; self } /// Return an iterator over the line indices, up to max, that are not present in both self and other, /// except for the indices of the first and last line of both self and s2, that are always included. pub fn diff(&self, other: &Self, max: usize) -> impl Iterator<Item = isize> { let mut lines_to_update = HashSet::new(); lines_to_update.insert(self.start.line.0); lines_to_update.insert(self.end.line.0); lines_to_update.insert(other.start.line.0); lines_to_update.insert(other.end.line.0); let old_lines: HashSet<isize> = self.get_visible_indices(max).collect(); let new_lines: HashSet<isize> = other.get_visible_indices(max).collect(); old_lines.symmetric_difference(&new_lines).for_each(|&l| { let _ = lines_to_update.insert(l); }); lines_to_update .into_iter() .filter(move |&l| l >= 0 && l < max as isize) } fn get_visible_indices(&self, max: usize) -> Range<isize> { let Selection { start, end, .. } = self.sorted(); let start = start.line.0.max(0); let end = end.line.0.min(max as isize); start..end } } #[cfg(test)] #[path = "./unit/selection_tests.rs"] mod selection_tests;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/hyperlink_tracker.rs
zellij-server/src/panes/hyperlink_tracker.rs
use crate::panes::grid::Row; use crate::panes::link_handler::LinkHandler; use crate::panes::terminal_character::{Cursor, LinkAnchor}; use std::collections::VecDeque; #[derive(Debug, Clone)] struct DetectedLink { url: String, start_position: HyperlinkPosition, end_position: HyperlinkPosition, } #[derive(Debug, Clone, Copy)] struct HyperlinkPosition { x: isize, y: isize, } impl HyperlinkPosition { fn from_cursor(cursor: &Cursor) -> Self { Self { x: cursor.x as isize, y: cursor.y as isize, } } } #[derive(Clone)] pub struct HyperlinkTracker { buffer: String, cursor_positions: Vec<HyperlinkPosition>, start_position: Option<HyperlinkPosition>, last_cursor: Option<HyperlinkPosition>, } impl HyperlinkTracker { pub fn new() -> Self { Self { buffer: String::new(), cursor_positions: Vec::new(), start_position: None, last_cursor: None, } } pub fn update( &mut self, ch: char, cursor: &Cursor, viewport: &mut Vec<Row>, lines_above: &mut VecDeque<Row>, link_handler: &mut LinkHandler, ) { if ch == ' ' && cursor.x == 0 { // skip carriage return return; } let current_pos = HyperlinkPosition::from_cursor(cursor); // Check if cursor moved non-contiguously if self.should_reset_due_to_cursor_jump(&current_pos) { if self.is_currently_tracking() { // Finalize the current URL before resetting self.finalize_and_apply(viewport, lines_above, link_handler); } else { self.clear(); } } if self.is_currently_tracking() { if self.is_url_terminator(ch) { self.finalize_and_apply(viewport, lines_above, link_handler); } else { self.buffer.push(ch); self.cursor_positions.push(current_pos.clone()); } } else { if matches!(ch, 'h' | 'f' | 'm') { self.buffer.push(ch); self.cursor_positions.push(current_pos.clone()); self.start_position = Some(current_pos.clone()); } } self.last_cursor = Some(current_pos); } pub fn offset_cursor_lines(&mut self, offset: isize) { // Offset all stored cursor positions for pos in &mut self.cursor_positions { pos.y -= offset; } if let Some(start_pos) = &mut self.start_position { start_pos.y -= offset; } if let Some(last_cursor) = &mut self.last_cursor { last_cursor.y -= offset; } } fn should_reset_due_to_cursor_jump(&self, current_pos: &HyperlinkPosition) -> bool { if let Some(last_pos) = &self.last_cursor { // Check if cursor moved non-contiguously let is_contiguous = // Same line, next column (current_pos.y == last_pos.y && current_pos.x == last_pos.x + 1) || // Next line, first column (line wrap) (current_pos.y == last_pos.y + 1 && current_pos.x == 0) || // Same position (overwrite) (current_pos.y == last_pos.y && current_pos.x == last_pos.x); !is_contiguous } else { false } } fn is_currently_tracking(&self) -> bool { self.start_position.is_some() } fn is_url_terminator(&self, ch: char) -> bool { matches!( ch, ' ' | '\n' | '\r' | '\t' | '"' | '\'' | '<' | '>' | '(' | ')' | '[' | ']' | '{' | '}' | '⏎' ) } fn finalize_and_apply( &mut self, viewport: &mut Vec<Row>, lines_above: &mut VecDeque<Row>, link_handler: &mut LinkHandler, ) { let original_len = self.buffer.chars().count(); let trimmed_url = self.trim_trailing_punctuation(&self.buffer); let trimmed_len = trimmed_url.chars().count(); if self.is_valid_url(&trimmed_url) { // Calculate how many characters we trimmed let chars_trimmed = original_len.saturating_sub(trimmed_len); // Find the end position by walking back from the last position let end_position = if chars_trimmed > 0 && trimmed_len > 0 { // Use the position of the last character that's actually in the trimmed URL self.cursor_positions.get(trimmed_len.saturating_sub(1)) } else { // No trimming occurred, use the last position self.cursor_positions.last() }; let Some(end_position) = end_position.copied() else { return; }; let detected_link = DetectedLink { url: trimmed_url.clone(), start_position: self.start_position.clone().unwrap(), end_position, }; self.apply_hyperlink_to_grid(&detected_link, viewport, lines_above, link_handler); } self.clear(); } fn apply_hyperlink_to_grid( &self, link: &DetectedLink, viewport: &mut Vec<Row>, lines_above: &mut VecDeque<Row>, link_handler: &mut LinkHandler, ) { let link_anchor_start = link_handler.new_link_from_url(link.url.clone()); let start_pos = &link.start_position; let end_pos = &link.end_position; for y in start_pos.y..=end_pos.y { let row = if y < 0 { // Row is in lines_above let lines_above_index = (lines_above.len() as isize + y) as usize; lines_above.get_mut(lines_above_index) } else if (y as usize) < viewport.len() { // Row is in viewport viewport.get_mut(y as usize) } else { // Row is beyond bounds, skip None }; if let Some(row) = row { let start_x = if y == start_pos.y { start_pos.x.max(0) as usize } else { 0 }; let end_x = if y == end_pos.y { (end_pos.x + 1).max(0) as usize } else { row.width() }; // Convert width-based positions to character indices let start_char_index = row.absolute_character_index(start_x); let end_char_index = row.absolute_character_index(end_x.min(row.width())); for char_index in start_char_index..=end_char_index.min(row.columns.len().saturating_sub(1)) { if let Some(character) = row.columns.get_mut(char_index) { character.styles.update(|styles| { if y == start_pos.y && char_index == start_char_index { // First character gets the start anchor styles.link_anchor = Some(link_anchor_start.clone()); } else if y == end_pos.y && char_index == end_char_index { // Last character gets the end anchor styles.link_anchor = Some(LinkAnchor::End); } else { // Middle characters get the same start anchor styles.link_anchor = Some(link_anchor_start.clone()); } }); } } } } } fn trim_trailing_punctuation(&self, url: &str) -> String { let mut chars: Vec<char> = url.chars().collect(); while let Some(&last_char) = chars.last() { if matches!(last_char, '.' | ',' | ';' | '!' | '?' | '\n' | '\r' | '⏎') { chars.pop(); } else { break; } } chars.into_iter().collect() } fn is_valid_url(&self, url: &str) -> bool { if url.len() < 8 { return false; } if url.starts_with("http://") || url.starts_with("https://") { if let Some(protocol_end) = url.find("://") { let after_protocol = &url[protocol_end.saturating_add(3)..]; return !after_protocol.is_empty() && after_protocol.contains('.'); } } if url.starts_with("ftp://") { let after_protocol = url.get(6..).unwrap_or(""); return !after_protocol.is_empty(); } if url.starts_with("mailto:") { let after_colon = url.get(7..).unwrap_or(""); return after_colon.contains('@'); } false } fn clear(&mut self) { self.buffer.clear(); self.cursor_positions.clear(); self.start_position = None; // Don't clear last_cursor here - we need it for jump detection } } #[cfg(test)] mod tests { use super::*; use crate::panes::grid::Row; use crate::panes::link_handler::LinkHandler; use crate::panes::terminal_character::{LinkAnchor, TerminalCharacter}; use std::collections::VecDeque; fn create_test_cursor(x: usize, y: usize) -> Cursor { Cursor::new(x, y, true) } fn create_test_row(width: usize) -> Row { let mut columns = VecDeque::new(); for _ in 0..width { columns.push_back(TerminalCharacter::new(' ')); } Row::from_columns(columns).canonical() } fn populate_row_with_text(row: &mut Row, text: &str, start_x: usize) { for (i, ch) in text.chars().enumerate() { let char_index = row.absolute_character_index(start_x + i); if let Some(character) = row.columns.get_mut(char_index) { character.character = ch; } } } fn create_test_viewport(rows: usize, cols: usize) -> Vec<Row> { (0..rows).map(|_| create_test_row(cols)).collect() } #[test] fn test_new_tracker_is_empty() { let tracker = HyperlinkTracker::new(); assert!(tracker.buffer.is_empty()); assert!(tracker.cursor_positions.is_empty()); assert!(tracker.start_position.is_none()); assert!(tracker.last_cursor.is_none()); } #[test] fn test_simple_http_url_detection() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url = "http://example.com"; populate_row_with_text(&mut viewport[0], url, 0); for (i, ch) in url.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url.len(), 0); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[0]; let mut link_id = None; for i in 0..url.len() { let char_index = row.absolute_character_index(i); if let Some(character) = row.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "Character at position {} should have link anchor", i ); if i == 0 { if let Some(LinkAnchor::Start(id)) = &character.styles.link_anchor { link_id = Some(*id); } } } } if let Some(id) = link_id { let links = link_handler.links(); let stored_link = links.get(&id); assert!( stored_link.is_some(), "Link should be stored in LinkHandler" ); if let Some(link) = stored_link { assert_eq!(link.uri, url, "Stored URL should match the detected URL"); assert_eq!(link.id, Some(id.to_string()), "Link ID should be set"); } } else { panic!("Should have found a link ID"); } } #[test] fn test_https_url_detection() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url = "https://secure.example.com"; populate_row_with_text(&mut viewport[0], url, 0); for (i, ch) in url.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url.len(), 0); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[0]; let mut link_id = None; for i in 0..url.len() { let char_index = row.absolute_character_index(i); if let Some(character) = row.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "HTTPS URL character at position {} should have link anchor", i ); if i == 0 { if let Some(LinkAnchor::Start(id)) = &character.styles.link_anchor { link_id = Some(*id); } } } } if let Some(id) = link_id { let links = link_handler.links(); let stored_link = links.get(&id); assert!( stored_link.is_some(), "HTTPS link should be stored in LinkHandler" ); if let Some(link) = stored_link { assert_eq!( link.uri, url, "Stored HTTPS URL should match the detected URL" ); } } } #[test] fn test_ftp_url_detection() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url = "ftp://files.example.com"; populate_row_with_text(&mut viewport[0], url, 0); for (i, ch) in url.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url.len(), 0); tracker.update( '\n', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[0]; for i in 0..url.len() { let char_index = row.absolute_character_index(i); if let Some(character) = row.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "FTP URL character at position {} should have link anchor", i ); } } } #[test] fn test_mailto_url_detection() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url = "mailto:user@example.com"; populate_row_with_text(&mut viewport[0], url, 0); for (i, ch) in url.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url.len(), 0); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[0]; for i in 0..url.len() { let char_index = row.absolute_character_index(i); if let Some(character) = row.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "Mailto URL character at position {} should have link anchor", i ); } } } #[test] fn test_url_with_trailing_punctuation() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url_with_punct = "http://example.com."; let expected_trimmed_url = "http://example.com"; populate_row_with_text(&mut viewport[0], url_with_punct, 0); for (i, ch) in url_with_punct.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url_with_punct.len(), 0); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[0]; let mut link_id = None; let first_char_index = row.absolute_character_index(0); if let Some(character) = row.columns.get(first_char_index) { if let Some(LinkAnchor::Start(id)) = &character.styles.link_anchor { link_id = Some(*id); } } if let Some(id) = link_id { let links = link_handler.links(); let stored_link = links.get(&id); assert!( stored_link.is_some(), "Link should be stored in LinkHandler" ); if let Some(link) = stored_link { assert_eq!( link.uri, expected_trimmed_url, "Stored URL should be trimmed (without trailing punctuation)" ); } } else { panic!("Should have found a link ID"); } } #[test] fn test_invalid_url_rejection() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let short_url = "http://"; populate_row_with_text(&mut viewport[0], short_url, 0); for (i, ch) in short_url.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(short_url.len(), 0); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[0]; for i in 0..short_url.len() { let char_index = row.absolute_character_index(i); if let Some(character) = row.columns.get(char_index) { assert!( character.styles.link_anchor.is_none(), "Invalid URL character at position {} should not have link anchor", i ); } } } #[test] fn test_cursor_jump_resets_tracking() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let partial_url = "http://exam"; for (i, ch) in partial_url.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } assert!(tracker.is_currently_tracking()); let cursor = create_test_cursor(50, 5); tracker.update( 'h', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); assert_eq!(tracker.buffer, "h"); assert_eq!(tracker.cursor_positions.len(), 1); } #[test] fn test_line_wrap_continuation() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let cursor1 = create_test_cursor(79, 0); tracker.update( 'h', &cursor1, &mut viewport, &mut lines_above, &mut link_handler, ); let cursor2 = create_test_cursor(0, 1); tracker.update( 't', &cursor2, &mut viewport, &mut lines_above, &mut link_handler, ); assert!(tracker.is_currently_tracking()); assert_eq!(tracker.buffer, "ht"); assert_eq!(tracker.cursor_positions.len(), 2); } #[test] fn test_offset_cursor_lines() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let cursor = create_test_cursor(0, 5); tracker.update( 'h', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); tracker.offset_cursor_lines(2); assert_eq!(tracker.start_position.unwrap().y, 3); assert_eq!(tracker.last_cursor.unwrap().y, 3); assert_eq!(tracker.cursor_positions[0].y, 3); } #[test] fn test_multiline_url_detection() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url_part1 = "http://very-long-"; let url_part2 = "domain.example.com"; let full_url = format!("{}{}", url_part1, url_part2); populate_row_with_text(&mut viewport[0], url_part1, 0); populate_row_with_text(&mut viewport[1], url_part2, 0); for (i, ch) in url_part1.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } for (i, ch) in url_part2.chars().enumerate() { let cursor = create_test_cursor(i, 1); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url_part2.len(), 1); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row0 = &viewport[0]; let mut link_id = None; let first_char_index = row0.absolute_character_index(0); if let Some(character) = row0.columns.get(first_char_index) { if let Some(LinkAnchor::Start(id)) = &character.styles.link_anchor { link_id = Some(*id); } } if let Some(id) = link_id { let links = link_handler.links(); let stored_link = links.get(&id); assert!( stored_link.is_some(), "Multiline link should be stored in LinkHandler" ); if let Some(link) = stored_link { assert_eq!( link.uri, full_url, "Stored URL should be the complete multiline URL" ); } } else { panic!("Should have found a link ID for multiline URL"); } let row0 = &viewport[0]; for i in 0..url_part1.len() { let char_index = row0.absolute_character_index(i); if let Some(character) = row0.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "Multiline URL part 1 character at position {} should have link anchor", i ); } } let row1 = &viewport[1]; for i in 0..url_part2.len() { let char_index = row1.absolute_character_index(i); if let Some(character) = row1.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "Multiline URL part 2 character at position {} should have link anchor", i ); } } } #[test] fn test_url_terminators() { let terminators = vec![ ' ', '\n', '\r', '\t', '"', '\'', '<', '>', '(', ')', '[', ']', '{', '}', '⏎', ]; for (idx, terminator) in terminators.iter().enumerate() { if idx >= 10 { break; } let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url = "http://example.com"; populate_row_with_text(&mut viewport[idx], url, 0); for (i, ch) in url.chars().enumerate() { let cursor = create_test_cursor(i, idx); tracker.update( ch, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); } let cursor = create_test_cursor(url.len(), idx); tracker.update( *terminator, &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); let row = &viewport[idx]; for i in 0..url.len() { let char_index = row.absolute_character_index(i); if let Some(character) = row.columns.get(char_index) { assert!( character.styles.link_anchor.is_some(), "URL terminated by {:?} should have link anchor at position {}", terminator, i ); } } } } #[test] fn test_skip_carriage_return_at_line_start() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let cursor = create_test_cursor(0, 0); tracker.update( ' ', &cursor, &mut viewport, &mut lines_above, &mut link_handler, ); assert!(!tracker.is_currently_tracking()); assert!(tracker.buffer.is_empty()); } #[test] fn test_tracking_state_methods() { let mut tracker = HyperlinkTracker::new(); assert!(!tracker.is_currently_tracking()); tracker.start_position = Some(HyperlinkPosition { x: 0, y: 0 }); assert!(tracker.is_currently_tracking()); tracker.clear(); assert!(!tracker.is_currently_tracking()); assert!(tracker.buffer.is_empty()); assert!(tracker.cursor_positions.is_empty()); assert!(tracker.start_position.is_none()); } #[test] fn test_hyperlink_position_from_cursor() { let cursor = create_test_cursor(10, 5); let pos = HyperlinkPosition::from_cursor(&cursor); assert_eq!(pos.x, 10); assert_eq!(pos.y, 5); } #[test] fn test_contiguous_cursor_movement() { let mut tracker = HyperlinkTracker::new(); tracker.last_cursor = Some(HyperlinkPosition { x: 5, y: 2 }); let next_col = HyperlinkPosition { x: 6, y: 2 }; assert!(!tracker.should_reset_due_to_cursor_jump(&next_col)); let next_line = HyperlinkPosition { x: 0, y: 3 }; assert!(!tracker.should_reset_due_to_cursor_jump(&next_line)); let same_pos = HyperlinkPosition { x: 5, y: 2 }; assert!(!tracker.should_reset_due_to_cursor_jump(&same_pos)); let jump = HyperlinkPosition { x: 10, y: 5 }; assert!(tracker.should_reset_due_to_cursor_jump(&jump)); } #[test] fn test_trim_trailing_punctuation() { let tracker = HyperlinkTracker::new(); assert_eq!( tracker.trim_trailing_punctuation("http://example.com."), "http://example.com" ); assert_eq!( tracker.trim_trailing_punctuation("http://example.com,"), "http://example.com" ); assert_eq!( tracker.trim_trailing_punctuation("http://example.com;"), "http://example.com" ); assert_eq!( tracker.trim_trailing_punctuation("http://example.com!"), "http://example.com" ); assert_eq!( tracker.trim_trailing_punctuation("http://example.com?"), "http://example.com" ); assert_eq!( tracker.trim_trailing_punctuation("http://example.com..."), "http://example.com" ); assert_eq!( tracker.trim_trailing_punctuation("http://example.com"), "http://example.com" ); } #[test] fn test_is_valid_url() { let tracker = HyperlinkTracker::new(); assert!(tracker.is_valid_url("http://example.com")); assert!(tracker.is_valid_url("https://example.com")); assert!(tracker.is_valid_url("ftp://files.example.com")); assert!(tracker.is_valid_url("mailto:user@example.com")); assert!(tracker.is_valid_url("https://sub.domain.example.com/path")); assert!(!tracker.is_valid_url("http://")); assert!(!tracker.is_valid_url("https://")); assert!(!tracker.is_valid_url("ftp://")); assert!(!tracker.is_valid_url("mailto:")); assert!(!tracker.is_valid_url("mailto:notanemail")); assert!(!tracker.is_valid_url("http://nodot")); assert!(!tracker.is_valid_url("short")); assert!(!tracker.is_valid_url("")); } #[test] fn test_multiple_urls_in_sequence() { let mut tracker = HyperlinkTracker::new(); let mut viewport = create_test_viewport(10, 80); let mut lines_above = VecDeque::new(); let mut link_handler = LinkHandler::new(); let url1 = "http://first.com"; let url2 = "https://second.com"; let full_text = format!("{} {}", url1, url2); populate_row_with_text(&mut viewport[0], &full_text, 0); for (i, ch) in url1.chars().enumerate() { let cursor = create_test_cursor(i, 0); tracker.update( ch, &cursor, &mut viewport, &mut lines_above,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/tiled_panes/pane_resizer.rs
zellij-server/src/panes/tiled_panes/pane_resizer.rs
use super::stacked_panes::StackedPanes; use crate::{panes::PaneId, tab::Pane}; use cassowary::{ strength::{REQUIRED, STRONG}, Expression, Solver, Variable, WeightedRelation::EQ, }; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use zellij_utils::{ errors::prelude::*, input::layout::SplitDirection, pane_size::{Constraint, Dimension, PaneGeom}, }; pub struct PaneResizer<'a> { panes: Rc<RefCell<HashMap<PaneId, &'a mut Box<dyn Pane>>>>, vars: HashMap<PaneId, Variable>, solver: Solver, } // FIXME: Just hold a mutable Pane reference instead of the PaneId, fixed, pos, and size? // Do this after panes are no longer trait-objects! #[derive(Debug, Clone, Copy)] struct Span { pid: PaneId, direction: SplitDirection, pos: usize, size: Dimension, size_var: Variable, } type Grid = Vec<Vec<Span>>; impl<'a> PaneResizer<'a> { pub fn new(panes: Rc<RefCell<HashMap<PaneId, &'a mut Box<dyn Pane>>>>) -> Self { let mut vars = HashMap::new(); for &pane_id in panes.borrow().keys() { vars.insert(pane_id, Variable::new()); } PaneResizer { panes, vars, solver: Solver::new(), } } pub fn layout(&mut self, direction: SplitDirection, space: usize) -> Result<()> { self.solver.reset(); let grid = self .solve(direction, space) .map_err(|err| anyhow!("{}", err))?; let spans = self .discretize_spans(grid, space) .map_err(|err| anyhow!("{}", err))?; if self.is_layout_valid(&spans) { self.apply_spans(spans)?; } Ok(()) } fn solve(&mut self, direction: SplitDirection, space: usize) -> Result<Grid, String> { let grid: Grid = self .grid_boundaries(direction) .into_iter() .map(|b| self.spans_in_boundary(direction, b)) .collect(); let constraints: HashSet<_> = grid .iter() .flat_map(|s| constrain_spans(space, s)) .collect(); self.solver .add_constraints(&constraints) .map_err(|e| format!("{:?}", e))?; Ok(grid) } fn discretize_spans(&mut self, mut grid: Grid, space: usize) -> Result<Vec<Span>, String> { let mut rounded_sizes: HashMap<_, _> = grid .iter() .flatten() .map(|s| { ( s.size_var, stable_round(self.solver.get_value(s.size_var)) as isize, ) }) .collect(); // Round f64 pane sizes to usize without gaps or overlap let mut finalised = Vec::new(); for spans in &mut grid { let rounded_size: isize = spans.iter().map(|s| rounded_sizes[&s.size_var]).sum(); let mut error = space as isize - rounded_size; let mut flex_spans: Vec<_> = spans .iter_mut() .filter(|s| !s.size.is_fixed() && !finalised.contains(&s.pid)) .collect(); flex_spans.sort_by_key(|s| rounded_sizes[&s.size_var]); if error < 0 { flex_spans.reverse(); } for span in flex_spans { rounded_sizes .entry(span.size_var) .and_modify(|s| *s += error.signum()); error -= error.signum(); } finalised.extend(spans.iter().map(|s| s.pid)); } // Update span positions based on their rounded sizes for spans in &mut grid { let mut offset = 0; for span in spans { span.pos = offset; let sz = rounded_sizes[&span.size_var]; if sz < 1 { return Err("Ran out of room for spans".into()); } span.size.set_inner(sz as usize); offset += span.size.as_usize(); } } Ok(grid.into_iter().flatten().collect()) } // HACK: This whole function is a bit of a hack — it's here to stop us from breaking the layout if we've been given // a bad state to start with. If this function returns false, nothing is resized. fn is_layout_valid(&self, spans: &[Span]) -> bool { // If pane stacks are too tall to fit on the screen, abandon ship before the status bar gets caught up in // any erroneous resizing... for span in spans { let pane_is_stacked = self .panes .borrow() .get(&span.pid) .unwrap() .current_geom() .is_stacked(); if pane_is_stacked && span.direction == SplitDirection::Vertical { let min_stack_height = StackedPanes::new(self.panes.clone()) .min_stack_height(&span.pid) .unwrap(); if span.size.as_usize() < min_stack_height { return false; } } } true } fn apply_spans(&mut self, spans: Vec<Span>) -> Result<()> { let err_context = || format!("Failed to apply spans"); let mut geoms_changed = false; for span in spans { let pane_is_stacked = self .panes .borrow() .get(&span.pid) .unwrap() .current_geom() .is_stacked(); if pane_is_stacked { let current_geom = StackedPanes::new(self.panes.clone()) .position_and_size_of_stack(&span.pid) .unwrap(); let new_geom = match span.direction { SplitDirection::Horizontal => PaneGeom { x: span.pos, cols: span.size, ..current_geom }, SplitDirection::Vertical => PaneGeom { y: span.pos, rows: span.size, ..current_geom }, }; StackedPanes::new(self.panes.clone()).resize_panes_in_stack(&span.pid, new_geom)?; if new_geom.rows.as_usize() != current_geom.rows.as_usize() || new_geom.cols.as_usize() != current_geom.cols.as_usize() { geoms_changed = true; } } else { let mut panes = self.panes.borrow_mut(); let pane = panes.get_mut(&span.pid).unwrap(); let current_geom = pane.position_and_size(); let new_geom = match span.direction { SplitDirection::Horizontal => PaneGeom { x: span.pos, cols: span.size, ..pane.current_geom() }, SplitDirection::Vertical => PaneGeom { y: span.pos, rows: span.size, ..pane.current_geom() }, }; if new_geom.rows.as_usize() != current_geom.rows.as_usize() || new_geom.cols.as_usize() != current_geom.cols.as_usize() { geoms_changed = true; } if pane.geom_override().is_some() { pane.set_geom_override(new_geom); } else { pane.set_geom(new_geom); } } } if geoms_changed { Ok(()) } else { // probably a rounding issue - this might be considered an error depending on who // called us - if it's an explicit resize operation, it's clearly an error (the user // wanted to resize and doesn't care about percentage rounding), if it's resizing the // terminal window as a whole, it might not be Err(ZellijError::PaneSizeUnchanged).with_context(err_context) } } // FIXME: Functions like this should have unit tests! fn grid_boundaries(&self, direction: SplitDirection) -> Vec<(usize, usize)> { // Select the spans running *perpendicular* to the direction of resize let spans: Vec<Span> = self .panes .borrow() .values() .filter_map(|p| self.get_span(!direction, p.as_ref())) .collect(); let mut last_edge = 0; let mut bounds = Vec::new(); let mut edges: Vec<usize> = spans.iter().map(|s| s.pos + s.size.as_usize()).collect(); edges.sort_unstable(); edges.dedup(); for next in edges { let next_edge = next; bounds.push((last_edge, next_edge)); last_edge = next_edge; } bounds } fn spans_in_boundary(&self, direction: SplitDirection, boundary: (usize, usize)) -> Vec<Span> { let bwn = |v, (s, e)| s <= v && v < e; let mut spans: Vec<_> = self .panes .borrow() .values() .filter(|p| match self.get_span(!direction, p.as_ref()) { Some(s) => { let span_bounds = (s.pos, s.pos + s.size.as_usize()); bwn(span_bounds.0, boundary) || (bwn(boundary.0, span_bounds) && (bwn(boundary.1, span_bounds) || boundary.1 == span_bounds.1)) }, None => false, }) .filter_map(|p| self.get_span(direction, p.as_ref())) .collect(); spans.sort_unstable_by_key(|s| s.pos); spans } fn get_span(&self, direction: SplitDirection, pane: &dyn Pane) -> Option<Span> { let position_and_size = { let pas = pane.current_geom(); if pas.is_stacked() && pas.rows.is_percent() { // this is the main pane of the stack StackedPanes::new(self.panes.clone()).position_and_size_of_stack(&pane.pid()) } else if pas.is_stacked() { // this is a one-liner stacked pane and should be handled as the same rect with // the rest of the stack, represented by the main pane in the if branch above None } else { // non-stacked pane, treat normally Some(pas) } }?; let size_var = *self.vars.get(&pane.pid()).unwrap(); match direction { SplitDirection::Horizontal => Some(Span { pid: pane.pid(), direction, pos: position_and_size.x, size: position_and_size.cols, size_var, }), SplitDirection::Vertical => Some(Span { pid: pane.pid(), direction, pos: position_and_size.y, size: position_and_size.rows, size_var, }), } } } fn constrain_spans(space: usize, spans: &[Span]) -> HashSet<cassowary::Constraint> { let mut constraints = HashSet::new(); // Calculating "flexible" space (space not consumed by fixed-size spans) let new_flex_space = spans.iter().fold(space, |a, s| { if let Constraint::Fixed(sz) = s.size.constraint { a.saturating_sub(sz) } else { a } }); // Spans must use all of the available space let full_size = spans .iter() .fold(Expression::from_constant(0.0), |acc, s| acc + s.size_var); constraints.insert(full_size.clone() | EQ(REQUIRED) | space as f64); // Try to maintain ratios and lock non-flexible sizes for span in spans { match span.size.constraint { Constraint::Fixed(s) => constraints.insert(span.size_var | EQ(REQUIRED) | s as f64), Constraint::Percent(p) => constraints .insert((span.size_var / new_flex_space as f64) | EQ(STRONG) | (p / 100.0)), }; } constraints } fn stable_round(x: f64) -> f64 { ((x * 100.0).round() / 100.0).round() }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/tiled_panes/tiled_pane_grid.rs
zellij-server/src/panes/tiled_panes/tiled_pane_grid.rs
use super::is_inside_viewport; use super::pane_resizer::PaneResizer; use super::stacked_panes::StackedPanes; use crate::tab::{MIN_TERMINAL_HEIGHT, MIN_TERMINAL_WIDTH}; use crate::{panes::PaneId, tab::Pane}; use std::cmp::{Ordering, Reverse}; use std::collections::{HashMap, HashSet}; use zellij_utils::data::{Direction, Resize, ResizeStrategy}; use zellij_utils::{ errors::prelude::*, input::layout::SplitDirection, pane_size::{Dimension, PaneGeom, Size, Viewport}, }; use std::cell::RefCell; use std::rc::Rc; pub const RESIZE_PERCENT: f64 = 5.0; const DEFAULT_CURSOR_HEIGHT_WIDTH_RATIO: usize = 4; type BorderAndPaneIds = (usize, Vec<PaneId>); // For error reporting fn no_pane_id(pane_id: &PaneId) -> String { format!("no floating pane with ID {:?} found", pane_id) } pub struct TiledPaneGrid<'a> { panes: Rc<RefCell<HashMap<PaneId, &'a mut Box<dyn Pane>>>>, display_area: Size, // includes all panes (including eg. the status bar and tab bar in the default layout) viewport: Viewport, // includes all non-UI panes } impl<'a> TiledPaneGrid<'a> { pub fn new( panes: impl IntoIterator<Item = (&'a PaneId, &'a mut Box<dyn Pane>)>, panes_to_hide: &HashSet<PaneId>, display_area: Size, viewport: Viewport, ) -> Self { let panes: HashMap<_, _> = panes .into_iter() .filter(|(p_id, _)| !panes_to_hide.contains(p_id)) .map(|(p_id, p)| (*p_id, p)) .collect(); TiledPaneGrid { panes: Rc::new(RefCell::new(panes)), display_area, viewport, } } pub fn layout(&mut self, direction: SplitDirection, space: usize) -> Result<()> { let mut pane_resizer = PaneResizer::new(self.panes.clone()); pane_resizer.layout(direction, space) } pub fn get_pane_geom(&self, pane_id: &PaneId) -> Option<PaneGeom> { let panes = self.panes.borrow(); let pane_to_check = panes.get(pane_id)?; let pane_geom = pane_to_check.current_geom(); if pane_geom.is_stacked() { let mut stack_geom = StackedPanes::new(self.panes.clone()).position_and_size_of_stack(&pane_id); if let Some(stack_geom) = stack_geom.as_mut() { stack_geom.stacked = pane_geom.stacked; // to get the stack id } stack_geom } else { Some(pane_geom) } } fn pane_is_flexible(&self, direction: SplitDirection, pane_id: &PaneId) -> Result<bool> { let err_context = || format!("failed to determine if pane {pane_id:?} is flexible in {direction:?}"); let pane_geom = self .get_pane_geom(pane_id) .with_context(|| no_pane_id(pane_id)) .with_context(err_context)?; Ok(!match direction { SplitDirection::Vertical => pane_geom.rows, SplitDirection::Horizontal => pane_geom.cols, } .is_fixed()) } fn neighbor_pane_ids(&self, pane_id: &PaneId, direction: Direction) -> Result<Vec<PaneId>> { let err_context = || format!("Failed to get neighboring panes"); // Shorthand use Direction as Dir; let mut neighbor_terminals = self .pane_ids_directly_next_to(pane_id, &direction) .with_context(err_context)?; let neighbor_terminal_borders: HashSet<_> = if direction.is_horizontal() { neighbor_terminals .iter() .filter_map(|t| self.get_pane_geom(t).map(|p| p.y)) .collect() } else { neighbor_terminals .iter() .filter_map(|t| self.get_pane_geom(t).map(|p| p.x)) .collect() }; // Only return those neighbors that are aligned and between pane borders let (some_direction, other_direction) = match direction { Dir::Left | Dir::Right => (Dir::Up, Dir::Down), Dir::Down | Dir::Up => (Dir::Left, Dir::Right), }; let (some_borders, _some_terminals) = self .contiguous_panes_with_alignment( pane_id, &neighbor_terminal_borders, &direction, &some_direction, ) .with_context(err_context)?; let (other_borders, _other_terminals) = self .contiguous_panes_with_alignment( pane_id, &neighbor_terminal_borders, &direction, &other_direction, ) .with_context(err_context)?; neighbor_terminals.retain(|t| { if direction.is_horizontal() { self.pane_is_between_horizontal_borders(t, some_borders, other_borders) } else { self.pane_is_between_vertical_borders(t, some_borders, other_borders) } }); Ok(neighbor_terminals) } // Check if panes in the desired direction can be resized. Returns the maximum resize that's // possible (at most `change_by`). pub fn can_change_pane_size( &self, pane_id: &PaneId, strategy: &ResizeStrategy, change_by: (f64, f64), ) -> Result<bool> { let err_context = || format!("failed to determine if pane {pane_id:?} can {strategy}"); if let Some(direction) = strategy.direction { if !self .pane_is_flexible(direction.into(), pane_id) .unwrap_or(false) { let pane_ids = match pane_id { PaneId::Terminal(id) => vec![(*id, true)], PaneId::Plugin(id) => vec![(*id, false)], }; return Err(ZellijError::CantResizeFixedPanes { pane_ids }) .with_context(err_context); } let pane_ids = self .neighbor_pane_ids(pane_id, direction) .with_context(err_context)?; let fixed_panes: Vec<PaneId> = pane_ids .iter() .filter(|p| !self.pane_is_flexible(direction.into(), p).unwrap_or(false)) .copied() .collect(); if !fixed_panes.is_empty() { let mut pane_ids = vec![]; for fixed_pane in fixed_panes { match fixed_pane { PaneId::Terminal(id) => pane_ids.push((id, true)), PaneId::Plugin(id) => pane_ids.push((id, false)), }; } return Err(ZellijError::CantResizeFixedPanes { pane_ids }) .with_context(err_context); } if pane_ids.is_empty() { // TODO: proper error return Ok(false); } if direction.is_horizontal() { match strategy.resize { Resize::Increase => { for id in pane_ids { if !self .can_reduce_pane_width(&id, change_by.0 as f64) .with_context(err_context)? { return Ok(false); } } Ok(true) }, Resize::Decrease => self .can_reduce_pane_width(pane_id, change_by.0 as f64) .with_context(err_context), } } else { match strategy.resize { Resize::Increase => { for id in pane_ids { if !self .can_reduce_pane_height(&id, change_by.1 as f64) .with_context(err_context)? { return Ok(false); } } Ok(true) }, Resize::Decrease => self .can_reduce_pane_height(pane_id, change_by.1 as f64) .with_context(err_context), } } } else { // Undirected resize, this is checked elsewhere Ok(true) } } /// Change a tiled panes size based on the given strategy. /// /// Returns true upon successful resize, false otherwise. pub fn change_pane_size( &mut self, pane_id: &PaneId, strategy: &ResizeStrategy, change_by: (f64, f64), ) -> Result<bool> { let err_context = || format!("failed to {strategy} by {change_by:?} for pane {pane_id:?}"); // Shorthand use Direction as Dir; let mut fixed_panes_blocking_resize = vec![]; // Default behavior is to only increase pane size, unless the direction being resized to is // a boundary. In this case, decrease size from the other side (invert strategy)! let can_invert_strategy_if_needed = strategy.resize_increase() // Only invert when increasing && strategy.invert_on_boundaries // Only invert if configured to do so && strategy.direction.is_some(); // Only invert if there's a direction let can_change_pane_size_in_main_direction = self .can_change_pane_size(pane_id, &strategy, change_by) .unwrap_or_else(|err| { if let Some(ZellijError::CantResizeFixedPanes { pane_ids }) = err.downcast_ref::<ZellijError>() { fixed_panes_blocking_resize.append(&mut pane_ids.clone()); } false }); let can_change_pane_size_in_inverted_direction = if can_invert_strategy_if_needed { let strategy = strategy.invert(); self.can_change_pane_size(pane_id, &strategy, change_by) .unwrap_or_else(|err| { if let Some(ZellijError::CantResizeFixedPanes { pane_ids }) = err.downcast_ref::<ZellijError>() { fixed_panes_blocking_resize.append(&mut pane_ids.clone()); } false }) } else { false }; if strategy.direction.is_some() && !can_change_pane_size_in_main_direction && !can_change_pane_size_in_inverted_direction { // we can't resize in any direction, not playing the blame game, but I'm looking at // you: fixed_panes_blocking_resize return Err(ZellijError::CantResizeFixedPanes { pane_ids: fixed_panes_blocking_resize, }) .with_context(err_context); } let strategy = if can_change_pane_size_in_main_direction { *strategy } else { strategy.invert() }; if let Some(direction) = strategy.direction { let mut neighbor_terminals = self .pane_ids_directly_next_to(pane_id, &direction) .with_context(err_context)?; if neighbor_terminals.is_empty() { // Nothing to do. return Ok(false); } let neighbor_terminal_borders: HashSet<_> = if direction.is_horizontal() { neighbor_terminals .iter() .filter_map(|p| self.get_pane_geom(p).map(|p| p.y)) .collect() } else { neighbor_terminals .iter() .filter_map(|p| self.get_pane_geom(p).map(|p| p.x)) .collect() }; // Only resize those neighbors that are aligned and between pane borders let (some_direction, other_direction) = match direction { Dir::Left | Dir::Right => (Dir::Up, Dir::Down), Dir::Down | Dir::Up => (Dir::Left, Dir::Right), }; let (some_borders, some_terminals) = self .contiguous_panes_with_alignment( pane_id, &neighbor_terminal_borders, &direction, &some_direction, ) .with_context(err_context)?; let (other_borders, other_terminals) = self .contiguous_panes_with_alignment( pane_id, &neighbor_terminal_borders, &direction, &other_direction, ) .with_context(err_context)?; neighbor_terminals.retain(|t| { if direction.is_horizontal() { self.pane_is_between_horizontal_borders(t, some_borders, other_borders) } else { self.pane_is_between_vertical_borders(t, some_borders, other_borders) } }); // Perform the resize let change_by = match direction { Dir::Left | Dir::Right => change_by.0, Dir::Down | Dir::Up => change_by.1, }; if strategy.resize_increase() && direction.is_horizontal() { [*pane_id] .iter() .chain(&some_terminals) .chain(&other_terminals) .for_each(|pane| self.increase_pane_width(pane, change_by)); neighbor_terminals .iter() .for_each(|pane| self.reduce_pane_width(pane, change_by)); } else if strategy.resize_increase() && direction.is_vertical() { [*pane_id] .iter() .chain(&some_terminals) .chain(&other_terminals) .for_each(|pane| self.increase_pane_height(pane, change_by)); neighbor_terminals .iter() .for_each(|pane| self.reduce_pane_height(pane, change_by)); } else if strategy.resize_decrease() && direction.is_horizontal() { [*pane_id] .iter() .chain(&some_terminals) .chain(&other_terminals) .for_each(|pane| self.reduce_pane_width(pane, change_by)); neighbor_terminals .iter() .for_each(|pane| self.increase_pane_width(pane, change_by)); } else if strategy.resize_decrease() && direction.is_vertical() { [*pane_id] .iter() .chain(&some_terminals) .chain(&other_terminals) .for_each(|pane| self.reduce_pane_height(pane, change_by)); neighbor_terminals .iter() .for_each(|pane| self.increase_pane_height(pane, change_by)); } else { return Err(anyhow!( "Don't know how to perform resize operation: '{strategy}'" )) .with_context(err_context); } // Update grid let mut pane_resizer = PaneResizer::new(self.panes.clone()); if direction.is_horizontal() { pane_resizer .layout(SplitDirection::Horizontal, self.display_area.cols) .with_context(err_context)?; } else { pane_resizer .layout(SplitDirection::Vertical, self.display_area.rows) .with_context(err_context)?; } } else { // Get panes aligned at corners, so we can change their sizes manually afterwards let mut aligned_panes = [ None, // right, below None, // left, below None, // right, above None, // left, above ]; // For the borrow checker { // let panes = self.panes.borrow(); let active_pane = self .get_pane_geom(pane_id) .with_context(|| no_pane_id(pane_id)) .with_context(err_context)?; for p_id in self.viewport_pane_ids_directly_below(pane_id) { let pane = self .get_pane_geom(&p_id) .with_context(|| no_pane_id(&p_id)) .with_context(err_context)?; if active_pane.x + active_pane.cols.as_usize() == pane.x { // right aligned aligned_panes[0] = Some(p_id); } else if active_pane.x == pane.x + pane.cols.as_usize() { // left aligned aligned_panes[1] = Some(p_id); } } for p_id in self.viewport_pane_ids_directly_above(pane_id) { let pane = self .get_pane_geom(&p_id) .with_context(|| no_pane_id(&p_id)) .with_context(err_context)?; if active_pane.x + active_pane.cols.as_usize() == pane.x { // right aligned aligned_panes[2] = Some(p_id); } else if active_pane.x == pane.x + pane.cols.as_usize() { // left aligned aligned_panes[3] = Some(p_id); } } } // Resize pane in every direction that fits let options = [ (Dir::Right, Some(Dir::Down), Some(Dir::Left), 0), (Dir::Left, Some(Dir::Down), Some(Dir::Right), 1), (Dir::Right, Some(Dir::Up), Some(Dir::Left), 2), (Dir::Left, Some(Dir::Up), Some(Dir::Right), 3), (Dir::Right, None, None, 0), (Dir::Down, None, None, 0), (Dir::Left, None, None, 0), (Dir::Up, None, None, 0), ]; for (main_dir, sub_dir, adjust_dir, adjust_pane) in options { if let Some(sub_dir) = sub_dir { let main_strategy = ResizeStrategy { direction: Some(main_dir), invert_on_boundaries: false, ..strategy }; let sub_strategy = ResizeStrategy { direction: Some(sub_dir), invert_on_boundaries: false, ..strategy }; // TODO: instead of unwrap_or(false) here we need to do the same with the fixed // panes error above, only make sure that we only error if we cannot resize in // any directions and have blocking fixed panes if self .can_change_pane_size(pane_id, &main_strategy, change_by) .unwrap_or(false) && self .can_change_pane_size(pane_id, &sub_strategy, change_by) .unwrap_or(false) { let result = self .change_pane_size(pane_id, &main_strategy, change_by) .and_then(|ret| { Ok(ret && self.change_pane_size(pane_id, &sub_strategy, change_by)?) }) .and_then(|ret| { if let Some(aligned_pane) = aligned_panes[adjust_pane] { Ok(ret && self.change_pane_size( &aligned_pane, &ResizeStrategy { direction: adjust_dir, invert_on_boundaries: false, resize: strategy.resize.invert(), }, change_by, )?) } else { Ok(ret) } }) .with_context(err_context)?; return Ok(result); } } else { let new_strategy = ResizeStrategy { direction: Some(main_dir), invert_on_boundaries: false, ..strategy }; if self .change_pane_size(pane_id, &new_strategy, change_by) .unwrap_or(false) { return Ok(true); } } } return Ok(false); } Ok(true) } fn can_reduce_pane_width(&self, pane_id: &PaneId, reduce_by: f64) -> Result<bool> { let err_context = || format!("failed to determine if pane {pane_id:?} can reduce width by {reduce_by} %"); let pane = self .get_pane_geom(pane_id) .with_context(|| no_pane_id(pane_id)) .with_context(err_context)?; let current_fixed_cols = pane.cols.as_usize(); let will_reduce_by = ((self.display_area.cols as f64 / 100.0) * reduce_by) as usize; if current_fixed_cols.saturating_sub(will_reduce_by) < MIN_TERMINAL_WIDTH { Ok(false) } else if let Some(cols) = pane.cols.as_percent() { Ok(cols - reduce_by >= RESIZE_PERCENT) } else { Ok(false) } } fn can_reduce_pane_height(&self, pane_id: &PaneId, reduce_by: f64) -> Result<bool> { let err_context = || { format!("failed to determine if pane {pane_id:?} can reduce height by {reduce_by} %") }; let pane = self .get_pane_geom(pane_id) .with_context(|| no_pane_id(pane_id)) .with_context(err_context)?; let min_terminal_height = if pane.is_stacked() { StackedPanes::new(self.panes.clone()).min_stack_height(pane_id)? } else { MIN_TERMINAL_HEIGHT }; let current_fixed_rows = pane.rows.as_usize(); let will_reduce_by = ((self.display_area.rows as f64 / 100.0) * reduce_by) as usize; if current_fixed_rows.saturating_sub(will_reduce_by) < min_terminal_height { Ok(false) } else if let Some(rows) = pane.rows.as_percent() { Ok(rows - reduce_by >= RESIZE_PERCENT) } else { Ok(false) } } fn reduce_pane_height(&mut self, id: &PaneId, percent: f64) { if self.can_reduce_pane_height(id, percent).unwrap_or(false) { let current_pane_is_stacked = self .panes .borrow() .get(id) .unwrap() .current_geom() .is_stacked(); if current_pane_is_stacked { let _ = StackedPanes::new(self.panes.clone()).reduce_stack_height(&id, percent); } else { let mut panes = self.panes.borrow_mut(); let terminal = panes.get_mut(id).unwrap(); terminal.reduce_height(percent); } } } fn increase_pane_height(&mut self, id: &PaneId, percent: f64) { let current_pane_is_stacked = self .panes .borrow() .get(id) .unwrap() .current_geom() .is_stacked(); if current_pane_is_stacked { let _ = StackedPanes::new(self.panes.clone()).increase_stack_height(&id, percent); } else { let mut panes = self.panes.borrow_mut(); let terminal = panes.get_mut(id).unwrap(); terminal.increase_height(percent); } } fn increase_pane_width(&mut self, id: &PaneId, percent: f64) { let current_pane_is_stacked = self .panes .borrow() .get(id) .unwrap() .current_geom() .is_stacked(); if current_pane_is_stacked { let _ = StackedPanes::new(self.panes.clone()).increase_stack_width(&id, percent); } else { let mut panes = self.panes.borrow_mut(); let pane = panes.get_mut(id).unwrap(); pane.increase_width(percent); } } fn reduce_pane_width(&mut self, id: &PaneId, percent: f64) { if self.can_reduce_pane_width(id, percent).unwrap() { let current_pane_is_stacked = self .panes .borrow() .get(id) .unwrap() .current_geom() .is_stacked(); if current_pane_is_stacked { let _ = StackedPanes::new(self.panes.clone()).reduce_stack_width(&id, percent); } else { let mut panes = self.panes.borrow_mut(); let terminal = panes.get_mut(id).unwrap(); terminal.reduce_width(percent); } } } /// Return a vector of [`PaneId`]s directly adjacent to the given [`PaneId`], if any. /// /// The vector is empty for example if the given pane (`id`) is at the boundary of the viewport /// already. fn pane_ids_directly_next_to(&self, id: &PaneId, direction: &Direction) -> Result<Vec<PaneId>> { let err_context = || format!("failed to find panes {direction} from pane {id:?}"); let mut ids = vec![]; let pane_geom_to_check = self .get_pane_geom(id) .with_context(|| no_pane_id(id)) .with_context(err_context)?; let panes = self.panes.borrow(); let mut seen = HashSet::new(); for pid in panes.keys() { let pane = self .get_pane_geom(pid) .with_context(|| no_pane_id(id)) .with_context(err_context)?; if seen.contains(&pane) { continue; } else { seen.insert(pane); } if match direction { Direction::Left => (pane.x + pane.cols.as_usize()) == pane_geom_to_check.x, Direction::Down => { pane.y == (pane_geom_to_check.y + pane_geom_to_check.rows.as_usize()) }, Direction::Up => (pane.y + pane.rows.as_usize()) == pane_geom_to_check.y, Direction::Right => { pane.x == (pane_geom_to_check.x + pane_geom_to_check.cols.as_usize()) }, } { ids.push(*pid); } } Ok(ids) } /// Return a vector of [`PaneId`]s aligned with the given [`PaneId`] on the `direction` border. fn pane_ids_aligned_with( &self, pane_id: &PaneId, direction: &Direction, ) -> Result<Vec<PaneId>> { let err_context = || format!("failed to find panes aligned {direction} with {pane_id:?}"); let pane_to_check = self .get_pane_geom(pane_id) .with_context(|| no_pane_id(pane_id)) .with_context(err_context)?; let mut result = vec![]; let panes = self.panes.borrow(); let mut seen = HashSet::new(); for (pid, _pane) in panes.iter() { let pane = self .get_pane_geom(pid) .with_context(|| no_pane_id(pane_id)) .with_context(err_context)?; if seen.contains(&pane) || pid == pane_id { continue; } else { seen.insert(pane); } if match direction { Direction::Left => pane.x == pane_to_check.x, Direction::Down => { (pane.y + pane.rows.as_usize()) == (pane_to_check.y + pane_to_check.rows.as_usize()) }, Direction::Up => pane.y == pane_to_check.y, Direction::Right => { (pane.x + pane.cols.as_usize()) == (pane_to_check.x + pane_to_check.cols.as_usize()) }, } { result.push(*pid) } } Ok(result) } /// Searches for contiguous panes fn contiguous_panes_with_alignment( &self, id: &PaneId, border: &HashSet<usize>, alignment: &Direction, direction: &Direction, ) -> Result<BorderAndPaneIds> { let err_context = || { format!("failed to find contiguous panes {direction} from pane {id:?} with {alignment} alignment") }; let input_error = anyhow!("Invalid combination of alignment ({alignment}) and direction ({direction})"); let pane_to_check = self .get_pane_geom(id) .with_context(|| no_pane_id(id)) .with_context(err_context)?; let mut result = vec![]; let mut aligned_panes: Vec<_> = self .pane_ids_aligned_with(id, alignment) .and_then(|pane_ids| { Ok(pane_ids .iter() .filter_map(|p_id| self.get_pane_geom(p_id).map(|pane_geom| (*p_id, pane_geom))) .collect()) }) .with_context(err_context)?; use Direction::Down as D; use Direction::Left as L; use Direction::Right as R; use Direction::Up as U; match (alignment, direction) { (&R, &U) | (&L, &U) => aligned_panes.sort_by_key(|(_, a)| Reverse(a.y)), (&R, &D) | (&L, &D) => aligned_panes.sort_by_key(|(_, a)| a.y), (&D, &L) | (&U, &L) => aligned_panes.sort_by_key(|(_, a)| Reverse(a.x)), (&D, &R) | (&U, &R) => aligned_panes.sort_by_key(|(_, a)| a.x), _ => return Err(input_error).with_context(err_context), }; for (pid, pane) in aligned_panes { let pane_to_check = result .last() .map(|(_pid, pane)| pane) .unwrap_or(&pane_to_check); if match (alignment, direction) { (&R, &U) | (&L, &U) => (pane.y + pane.rows.as_usize()) == pane_to_check.y, (&R, &D) | (&L, &D) => pane.y == (pane_to_check.y + pane_to_check.rows.as_usize()), (&D, &L) | (&U, &L) => (pane.x + pane.cols.as_usize()) == pane_to_check.x, (&D, &R) | (&U, &R) => pane.x == (pane_to_check.x + pane_to_check.cols.as_usize()), _ => return Err(input_error).with_context(err_context), } { result.push((pid, pane)); } } let mut resize_border = match direction { &L => 0, &D => self.viewport.y + self.viewport.rows, &U => 0, &R => self.viewport.x + self.viewport.cols, }; for (_, pane) in &result { let pane_boundary = match direction { &L => pane.x + pane.cols.as_usize(), &D => pane.y, &U => pane.y + pane.rows.as_usize(), &R => pane.x, }; if border.get(&pane_boundary).is_some() { match direction { &R | &D => { if pane_boundary < resize_border { resize_border = pane_boundary } }, &L | &U => { if pane_boundary > resize_border { resize_border = pane_boundary } }, } } } result.retain(|(_pid, pane)| match direction { &L => pane.x >= resize_border, &D => (pane.y + pane.rows.as_usize()) <= resize_border, &U => pane.y >= resize_border, &R => (pane.x + pane.cols.as_usize()) <= resize_border, }); let resize_border = if result.is_empty() { match direction { &L => pane_to_check.x,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/tiled_panes/mod.rs
zellij-server/src/panes/tiled_panes/mod.rs
mod pane_resizer; mod stacked_panes; mod tiled_pane_grid; use crate::resize_pty; use tiled_pane_grid::{split, TiledPaneGrid, RESIZE_PERCENT}; use crate::{ os_input_output::ServerOsApi, output::Output, panes::{ActivePanes, PaneId}, plugins::PluginInstruction, tab::{pane_info_for_pane, Pane, MIN_TERMINAL_HEIGHT, MIN_TERMINAL_WIDTH}, thread_bus::ThreadSenders, ui::boundaries::Boundaries, ui::pane_contents_and_ui::PaneContentsAndUi, ClientId, }; use stacked_panes::StackedPanes; use zellij_utils::{ data::{Direction, ModeInfo, PaneInfo, Resize, ResizeStrategy, Style, Styling}, errors::prelude::*, input::{ command::RunCommand, layout::{Run, RunPluginOrAlias, SplitDirection}, }, pane_size::{Offset, PaneGeom, Size, SizeInPixels, Viewport}, }; use std::{ cell::RefCell, collections::{BTreeMap, HashMap, HashSet}, rc::Rc, time::Instant, }; fn pane_content_offset(position_and_size: &PaneGeom, viewport: &Viewport) -> (usize, usize) { // (columns_offset, rows_offset) // if the pane is not on the bottom or right edge on the screen, we need to reserve one space // from its content to leave room for the boundary between it and the next pane (if it doesn't // draw its own frame) let columns_offset = if position_and_size.x + position_and_size.cols.as_usize() < viewport.cols { 1 } else { 0 }; let rows_offset = if position_and_size.y + position_and_size.rows.as_usize() < viewport.rows { 1 } else { 0 }; (columns_offset, rows_offset) } pub struct TiledPanes { pub panes: BTreeMap<PaneId, Box<dyn Pane>>, display_area: Rc<RefCell<Size>>, viewport: Rc<RefCell<Viewport>>, connected_clients: Rc<RefCell<HashSet<ClientId>>>, connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client mode_info: Rc<RefCell<HashMap<ClientId, ModeInfo>>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, stacked_resize: Rc<RefCell<bool>>, default_mode_info: ModeInfo, style: Style, session_is_mirrored: bool, active_panes: ActivePanes, draw_pane_frames: bool, panes_to_hide: HashSet<PaneId>, fullscreen_is_active: Option<PaneId>, senders: ThreadSenders, window_title: Option<String>, client_id_to_boundaries: HashMap<ClientId, Boundaries>, tombstones_before_increase: Option<(PaneId, Vec<HashMap<PaneId, PaneGeom>>)>, tombstones_before_decrease: Option<(PaneId, Vec<HashMap<PaneId, PaneGeom>>)>, } impl TiledPanes { #[allow(clippy::too_many_arguments)] pub fn new( display_area: Rc<RefCell<Size>>, viewport: Rc<RefCell<Viewport>>, connected_clients: Rc<RefCell<HashSet<ClientId>>>, connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client mode_info: Rc<RefCell<HashMap<ClientId, ModeInfo>>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, stacked_resize: Rc<RefCell<bool>>, session_is_mirrored: bool, draw_pane_frames: bool, default_mode_info: ModeInfo, style: Style, os_api: Box<dyn ServerOsApi>, senders: ThreadSenders, ) -> Self { TiledPanes { panes: BTreeMap::new(), display_area, viewport, connected_clients, connected_clients_in_app, mode_info, character_cell_size, stacked_resize, default_mode_info, style, session_is_mirrored, active_panes: ActivePanes::new(&os_api), draw_pane_frames, panes_to_hide: HashSet::new(), fullscreen_is_active: None, senders, window_title: None, client_id_to_boundaries: HashMap::new(), tombstones_before_increase: None, tombstones_before_decrease: None, } } pub fn add_pane_with_existing_geom(&mut self, pane_id: PaneId, mut pane: Box<dyn Pane>) { if self.draw_pane_frames { pane.set_content_offset(Offset::frame(1)); } self.panes.insert(pane_id, pane); } pub fn replace_active_pane( &mut self, pane: Box<dyn Pane>, client_id: ClientId, ) -> Option<Box<dyn Pane>> { let pane_id = pane.pid(); // remove the currently active pane let previously_active_pane = self .active_panes .get(&client_id) .copied() .and_then(|active_pane_id| self.replace_pane(active_pane_id, pane)); // move clients from the previously active pane to the new pane we just inserted if let Some(previously_active_pane) = previously_active_pane.as_ref() { let previously_active_pane_id = previously_active_pane.pid(); self.move_clients_between_panes(previously_active_pane_id, pane_id); } previously_active_pane } pub fn replace_pane( &mut self, pane_id: PaneId, mut with_pane: Box<dyn Pane>, ) -> Option<Box<dyn Pane>> { let with_pane_id = with_pane.pid(); if self.draw_pane_frames && !with_pane.borderless() { with_pane.set_content_offset(Offset::frame(1)); } let removed_pane = self.panes.remove(&pane_id).map(|removed_pane| { let with_pane_id = with_pane.pid(); let removed_pane_geom = removed_pane.position_and_size(); let removed_pane_geom_override = removed_pane.geom_override(); with_pane.set_geom(removed_pane_geom); match removed_pane_geom_override { Some(geom_override) => with_pane.set_geom_override(geom_override), None => with_pane.reset_size_and_position_override(), }; self.panes.insert(with_pane_id, with_pane); removed_pane }); // move clients from the previously active pane to the new pane we just inserted self.move_clients_between_panes(pane_id, with_pane_id); self.reapply_pane_frames(); removed_pane } pub fn insert_pane( &mut self, pane_id: PaneId, pane: Box<dyn Pane>, client_id: Option<ClientId>, ) { let should_relayout = true; self.add_pane(pane_id, pane, should_relayout, client_id); } pub fn set_pane_logical_position(&mut self, pane_id: PaneId, logical_position: usize) { if let Some(pane) = self.panes.get_mut(&pane_id) { let mut position_and_size = pane.position_and_size(); position_and_size.logical_position = Some(logical_position); pane.set_geom(position_and_size); } } pub fn insert_pane_without_relayout( &mut self, pane_id: PaneId, pane: Box<dyn Pane>, client_id: Option<ClientId>, ) { let should_relayout = false; self.add_pane(pane_id, pane, should_relayout, client_id); } pub fn has_room_for_new_pane(&mut self) -> bool { let cursor_height_width_ratio = self.cursor_height_width_ratio(); let pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); let has_room_for_new_pane = pane_grid .find_room_for_new_pane(cursor_height_width_ratio) .is_some(); has_room_for_new_pane || pane_grid.has_room_for_new_stacked_pane() || self.panes.is_empty() } pub fn room_left_in_stack_of_pane_id(&mut self, pane_id: &PaneId) -> Option<usize> { let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); pane_grid.room_left_in_stack_of_pane_id(pane_id) } pub fn assign_geom_for_pane_with_run(&mut self, run: Option<Run>) { // here we're removing the first pane we find with this run instruction and re-adding it so // that it gets a new geom similar to how it would when being added to the tab originally if let Some(pane_id) = self .panes .iter() .find_map(|(pid, p)| { if p.invoked_with() == &run { Some(pid) } else { None } }) .copied() { if let Some(mut pane) = self.panes.remove(&pane_id) { // we must strip the logical position here because it's likely a straggler from // this pane's previous tab and would cause chaos if considered in the new one let mut pane_geom = pane.position_and_size(); pane_geom.logical_position = None; pane.set_geom(pane_geom); self.add_pane_with_existing_geom(pane.pid(), pane); } } } pub fn add_pane_to_stack(&mut self, pane_id_in_stack: &PaneId, mut pane: Box<dyn Pane>) { let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); match pane_grid.make_room_in_stack_of_pane_id_for_pane(pane_id_in_stack) { Ok(new_pane_geom) => { pane.set_geom(new_pane_geom); self.panes.insert(pane.pid(), pane); self.set_force_render(); // TODO: why do we need this? return; }, Err(_e) => { let should_relayout = false; return self.add_pane_without_stacked_resize(pane.pid(), pane, should_relayout); }, } } fn add_pane( &mut self, pane_id: PaneId, pane: Box<dyn Pane>, should_relayout: bool, client_id: Option<ClientId>, ) { if self.panes.is_empty() { self.panes.insert(pane_id, pane); return; } let stacked_resize = { *self.stacked_resize.borrow() }; if let Some(client_id) = client_id { if stacked_resize && self.is_connected(&client_id) { self.add_pane_with_stacked_resize(pane_id, pane, should_relayout, client_id); return; } } self.add_pane_without_stacked_resize(pane_id, pane, should_relayout) } fn add_pane_without_stacked_resize( &mut self, pane_id: PaneId, mut pane: Box<dyn Pane>, should_relayout: bool, ) { let cursor_height_width_ratio = self.cursor_height_width_ratio(); let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); let pane_id_and_split_direction = pane_grid.find_room_for_new_pane(cursor_height_width_ratio); match pane_id_and_split_direction { Some((pane_id_to_split, split_direction)) => { // this unwrap is safe because floating panes should not be visible if there are no floating panes let pane_to_split = self.panes.get_mut(&pane_id_to_split).unwrap(); let size_of_both_panes = pane_to_split.position_and_size(); if let Some((first_geom, second_geom)) = split(split_direction, &size_of_both_panes) { pane_to_split.set_geom(first_geom); pane.set_geom(second_geom); self.panes.insert(pane_id, pane); if should_relayout { self.relayout(!split_direction); } } }, None => { // we couldn't add the pane normally, let's see if there's room in one of the // stacks... match pane_grid.make_room_in_stack_for_pane() { Ok(new_pane_geom) => { pane.set_geom(new_pane_geom); self.panes.insert(pane_id, pane); // TODO: is set_geom the right one? self.expand_pane_in_stack(pane_id); }, Err(e) => { log::error!("Failed to add pane to stack: {:?}", e); }, } }, } } fn add_pane_with_stacked_resize( &mut self, pane_id: PaneId, mut pane: Box<dyn Pane>, should_relayout: bool, client_id: ClientId, ) { let cursor_height_width_ratio = self.cursor_height_width_ratio(); let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); let Some(active_pane_id) = self.active_panes.get(&client_id) else { log::error!("Could not find active pane id for client_id"); return; }; if pane_grid .get_pane_geom(active_pane_id) .map(|p| p.is_stacked()) .unwrap_or(false) { // try to add the pane to the stack of the active pane match pane_grid.make_room_in_stack_of_pane_id_for_pane(active_pane_id) { Ok(new_pane_geom) => { pane.set_geom(new_pane_geom); self.panes.insert(pane_id, pane); self.expand_pane_in_stack(pane_id); return; }, Err(_e) => { return self.add_pane_without_stacked_resize(pane_id, pane, should_relayout); }, } } let pane_id_and_split_direction = pane_grid.split_pane(active_pane_id, cursor_height_width_ratio); match pane_id_and_split_direction { Some((pane_id_to_split, split_direction)) => { // this unwrap is safe because floating panes should not be visible if there are no floating panes let pane_to_split = self.panes.get_mut(&pane_id_to_split).unwrap(); let size_of_both_panes = pane_to_split.position_and_size(); if let Some((first_geom, second_geom)) = split(split_direction, &size_of_both_panes) { pane_to_split.set_geom(first_geom); pane.set_geom(second_geom); self.panes.insert(pane_id, pane); if should_relayout { self.relayout(!split_direction); } } }, None => { // we couldn't add the pane normally, let's see if there's room in one of the // stacks... let _ = pane_grid.make_pane_stacked(active_pane_id); match pane_grid.make_room_in_stack_of_pane_id_for_pane(active_pane_id) { Ok(new_pane_geom) => { pane.set_geom(new_pane_geom); self.panes.insert(pane_id, pane); // TODO: is set_geom the right one? return; }, Err(_e) => { return self.add_pane_without_stacked_resize( pane_id, pane, should_relayout, ); }, } }, } } pub fn add_pane_to_stack_of_active_pane( &mut self, pane_id: PaneId, mut pane: Box<dyn Pane>, client_id: ClientId, ) { let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); let Some(active_pane_id) = self.active_panes.get(&client_id) else { log::error!("Could not find active pane id for client_id"); return; }; let pane_id_is_stacked = pane_grid .get_pane_geom(active_pane_id) .map(|p| p.is_stacked()) .unwrap_or(false); if !pane_id_is_stacked { let _ = pane_grid.make_pane_stacked(&active_pane_id); } match pane_grid.make_room_in_stack_of_pane_id_for_pane(active_pane_id) { Ok(new_pane_geom) => { pane.set_geom(new_pane_geom); self.panes.insert(pane_id, pane); self.set_force_render(); // TODO: why do we need this? return; }, Err(e) => { log::error!("Failed to add pane to stack: {}", e); }, } } pub fn add_pane_to_stack_of_pane_id( &mut self, pane_id: PaneId, mut pane: Box<dyn Pane>, root_pane_id: PaneId, ) { let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); let pane_id_is_stacked = pane_grid .get_pane_geom(&root_pane_id) .map(|p| p.is_stacked()) .unwrap_or(false); if !pane_id_is_stacked { if let Err(e) = pane_grid.make_pane_stacked(&root_pane_id) { log::error!("Failed to make pane stacked: {:?}", e); } } match pane_grid.make_room_in_stack_of_pane_id_for_pane(&root_pane_id) { Ok(new_pane_geom) => { pane.set_geom(new_pane_geom); self.panes.insert(pane_id, pane); self.set_force_render(); // TODO: why do we need this? return; }, Err(e) => { log::error!("Failed to add pane to stack: {}", e); }, } } pub fn fixed_pane_geoms(&self) -> Vec<Viewport> { self.panes .values() .filter_map(|p| { let geom = p.position_and_size(); if geom.cols.is_fixed() || geom.rows.is_fixed() { Some(geom.into()) } else { None } }) .collect() } pub fn borderless_pane_geoms(&self) -> Vec<Viewport> { self.panes .values() .filter_map(|p| { let geom = p.position_and_size(); if p.borderless() { Some(geom.into()) } else { None } }) .collect() } pub fn non_selectable_pane_geoms_inside_viewport(&self) -> Vec<Viewport> { self.panes .values() .filter_map(|p| { let geom = p.position_and_size(); if !p.selectable() && is_inside_viewport(&self.viewport.borrow(), p) { Some(geom.into()) } else { None } }) .collect() } pub fn first_selectable_pane_id(&self) -> Option<PaneId> { self.panes .iter() .filter(|(_id, pane)| pane.selectable()) .map(|(id, _)| id.to_owned()) .next() } pub fn pane_ids(&self) -> impl Iterator<Item = &PaneId> { self.panes.keys() } pub fn relayout(&mut self, direction: SplitDirection) { let mut pane_grid = TiledPaneGrid::new( &mut self.panes, &self.panes_to_hide, *self.display_area.borrow(), *self.viewport.borrow(), ); match direction { SplitDirection::Horizontal => { pane_grid.layout(direction, (*self.display_area.borrow()).cols) }, SplitDirection::Vertical => { pane_grid.layout(direction, (*self.display_area.borrow()).rows) }, } .or_else(|e| Err(anyError::msg(e))) .with_context(|| format!("{:?} relayout of tab failed", direction)) .non_fatal(); self.set_pane_frames(self.draw_pane_frames); } pub fn reapply_pane_frames(&mut self) { // same as set_pane_frames except it reapplies the current situation self.set_pane_frames(self.draw_pane_frames); } pub fn set_pane_frames(&mut self, draw_pane_frames: bool) { self.draw_pane_frames = draw_pane_frames; let viewport = *self.viewport.borrow(); let position_and_sizes_of_stacks = { StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .positions_and_sizes_of_all_stacks() .unwrap_or_else(|| Default::default()) }; for pane in self.panes.values_mut() { if !pane.borderless() { pane.set_frame(draw_pane_frames); } #[allow(clippy::if_same_then_else)] if draw_pane_frames && !pane.borderless() { // there's definitely a frame around this pane, offset its contents pane.set_content_offset(Offset::frame(1)); } else if draw_pane_frames && pane.borderless() { // there's no frame around this pane, and the tab isn't handling the boundaries // between panes (they each draw their own frames as they please) // this one doesn't - do not offset its content pane.set_content_offset(Offset::default()); } else if !is_inside_viewport(&viewport, pane) { // this pane is outside the viewport and has no border - it should not have an offset pane.set_content_offset(Offset::default()); } else { // no draw_pane_frames and this pane should have a separation to other panes // according to its position in the viewport (eg. no separation if its at the // viewport bottom) - offset its content accordingly let mut position_and_size = pane.current_geom(); let is_stacked = position_and_size.is_stacked(); let is_flexible = !position_and_size.rows.is_fixed(); if let Some(position_and_size_of_stack) = position_and_size .stacked .and_then(|s_id| position_and_sizes_of_stacks.get(&s_id)) { // we want to check the offset against the position_and_size of the whole // stack rather than the pane, because the stack needs to have a consistent // offset with itself position_and_size = *position_and_size_of_stack; }; let (pane_columns_offset, pane_rows_offset) = pane_content_offset(&position_and_size, &viewport); if is_stacked && is_flexible { // 1 to save room for the pane title pane.set_content_offset(Offset::shift_right_top_and_bottom( pane_columns_offset, 1, pane_rows_offset, )); } else { pane.set_content_offset(Offset::shift(pane_rows_offset, pane_columns_offset)); } } resize_pty!(pane, self.os_api, self.senders, self.character_cell_size).unwrap(); } self.reset_boundaries(); } pub fn can_split_pane_horizontally(&mut self, client_id: ClientId) -> bool { if let Some(active_pane_id) = &self.active_panes.get(&client_id) { if let Some(active_pane) = self.panes.get_mut(active_pane_id) { let mut full_pane_size = active_pane.position_and_size(); if full_pane_size.is_stacked() { let Some(position_and_size_of_stack) = StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .position_and_size_of_stack(&active_pane_id) else { log::error!("Failed to find position and size of stack"); return false; }; full_pane_size = position_and_size_of_stack; } if full_pane_size.rows.as_usize() < MIN_TERMINAL_HEIGHT * 2 { return false; } else { return split(SplitDirection::Horizontal, &full_pane_size).is_some(); } } } false } pub fn can_split_pane_vertically(&mut self, client_id: ClientId) -> bool { if let Some(active_pane_id) = &self.active_panes.get(&client_id) { if let Some(active_pane) = self.panes.get_mut(active_pane_id) { let mut full_pane_size = active_pane.position_and_size(); if full_pane_size.is_stacked() { let Some(position_and_size_of_stack) = StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .position_and_size_of_stack(&active_pane_id) else { log::error!("Failed to find position and size of stack"); return false; }; full_pane_size = position_and_size_of_stack; } if full_pane_size.cols.as_usize() < MIN_TERMINAL_WIDTH * 2 { return false; } return split(SplitDirection::Vertical, &full_pane_size).is_some(); } } false } pub fn split_pane_horizontally( &mut self, pid: PaneId, mut new_pane: Box<dyn Pane>, client_id: ClientId, ) { let active_pane_id = &self.active_panes.get(&client_id).unwrap(); let mut full_pane_size = self .panes .get(active_pane_id) .map(|p| p.position_and_size()) .unwrap(); if full_pane_size.is_stacked() { match StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .position_and_size_of_stack(&active_pane_id) { Some(position_and_size_of_stack) => { full_pane_size = position_and_size_of_stack; }, None => { log::error!("Failed to find position and size of stack"); }, } } let active_pane = self.panes.get_mut(active_pane_id).unwrap(); if let Some((top_winsize, bottom_winsize)) = split(SplitDirection::Horizontal, &full_pane_size) { if active_pane.position_and_size().is_stacked() { match StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .resize_panes_in_stack(&active_pane_id, top_winsize) { Ok(_) => {}, Err(e) => { log::error!("Failed to resize stack: {}", e); }, } } else { active_pane.set_geom(top_winsize); } new_pane.set_geom(bottom_winsize); self.panes.insert(pid, new_pane); self.relayout(SplitDirection::Vertical); } } pub fn split_pane_vertically( &mut self, pid: PaneId, mut new_pane: Box<dyn Pane>, client_id: ClientId, ) { let active_pane_id = &self.active_panes.get(&client_id).unwrap(); let mut full_pane_size = self .panes .get(active_pane_id) .map(|p| p.position_and_size()) .unwrap(); if full_pane_size.is_stacked() { match StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .position_and_size_of_stack(&active_pane_id) { Some(position_and_size_of_stack) => { full_pane_size = position_and_size_of_stack; }, None => { log::error!("Failed to find position and size of stack"); }, } } let active_pane = self.panes.get_mut(active_pane_id).unwrap(); if let Some((left_winsize, right_winsize)) = split(SplitDirection::Vertical, &full_pane_size) { if active_pane.position_and_size().is_stacked() { match StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .resize_panes_in_stack(&active_pane_id, left_winsize) { Ok(_) => {}, Err(e) => { log::error!("Failed to resize stack: {}", e); }, } } else { active_pane.set_geom(left_winsize); } new_pane.set_geom(right_winsize); self.panes.insert(pid, new_pane); self.relayout(SplitDirection::Horizontal); } } pub fn focus_pane_for_all_clients(&mut self, pane_id: PaneId) { let connected_clients: Vec<ClientId> = self.connected_clients.borrow().iter().copied().collect(); for client_id in connected_clients { if self .panes .get(&pane_id) .map(|p| p.current_geom().is_stacked()) .unwrap_or(false) { let _ = StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .expand_pane(&pane_id); } self.active_panes .insert(client_id, pane_id, &mut self.panes); self.set_pane_active_at(pane_id); } self.set_force_render(); self.reapply_pane_frames(); } pub fn pane_ids_in_stack_of_pane_id(&mut self, pane_id: &PaneId) -> Vec<PaneId> { if let Some(stack_id) = self .panes .get(pane_id) .and_then(|p| p.position_and_size().stacked) { StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .pane_ids_in_stack(stack_id) } else { vec![] } } pub fn focus_pane_for_all_clients_in_stack(&mut self, pane_id: PaneId, stack_id: usize) { let connected_clients: Vec<ClientId> = self.connected_clients.borrow().iter().copied().collect(); let pane_ids_in_stack = { StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .pane_ids_in_stack(stack_id) }; if self .panes .get(&pane_id) .map(|p| p.current_geom().is_stacked()) .unwrap_or(false) { let _ = StackedPanes::new_from_btreemap(&mut self.panes, &self.panes_to_hide) .expand_pane(&pane_id); } for client_id in connected_clients { if self .active_panes .get(&client_id) .map(|p_id| pane_ids_in_stack.contains(p_id)) .unwrap_or(false) { self.active_panes .insert(client_id, pane_id, &mut self.panes); self.set_pane_active_at(pane_id); } } self.set_force_render(); self.reapply_pane_frames(); } pub fn reapply_pane_focus(&mut self) { let connected_clients: Vec<ClientId> = self.connected_clients.borrow().iter().copied().collect(); let mut stack_ids_to_pane_ids_to_expand = vec![]; for client_id in connected_clients { match &self.active_panes.get(&client_id).copied() { Some(pane_id) => { if let Some(stack_id) = self .panes .get(&pane_id) .and_then(|p| p.current_geom().stacked) { stack_ids_to_pane_ids_to_expand.push((stack_id, *pane_id)); } self.active_panes .insert(client_id, *pane_id, &mut self.panes); self.set_pane_active_at(*pane_id); }, None => { if let Some(first_pane_id) = self.first_selectable_pane_id() { let pane_id = first_pane_id;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/tiled_panes/stacked_panes.rs
zellij-server/src/panes/tiled_panes/stacked_panes.rs
use crate::{ panes::PaneId, tab::{Pane, MIN_TERMINAL_HEIGHT}, }; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use zellij_utils::{ errors::prelude::*, pane_size::{Dimension, PaneGeom}, }; pub struct StackedPanes<'a> { panes: Rc<RefCell<HashMap<PaneId, &'a mut Box<dyn Pane>>>>, } impl<'a> StackedPanes<'a> { pub fn new(panes: Rc<RefCell<HashMap<PaneId, &'a mut Box<dyn Pane>>>>) -> Self { StackedPanes { panes } } pub fn new_from_btreemap( panes: impl IntoIterator<Item = (&'a PaneId, &'a mut Box<dyn Pane>)>, panes_to_hide: &HashSet<PaneId>, ) -> Self { let panes: HashMap<_, _> = panes .into_iter() .filter(|(p_id, _)| !panes_to_hide.contains(p_id)) .map(|(p_id, p)| (*p_id, p)) .collect(); let panes = Rc::new(RefCell::new(panes)); StackedPanes { panes } } pub fn move_down( &mut self, source_pane_id: &PaneId, destination_pane_id: &PaneId, ) -> Result<()> { let err_context = || format!("Failed to move stacked pane focus down"); let source_pane_stack_id = self .panes .borrow() .get(source_pane_id) .with_context(err_context)? .position_and_size() .stacked; let destination_pane_stack_id = self .panes .borrow() .get(destination_pane_id) .with_context(err_context)? .position_and_size() .stacked; if source_pane_stack_id == destination_pane_stack_id { let mut panes = self.panes.borrow_mut(); let source_pane = panes.get_mut(source_pane_id).with_context(err_context)?; let mut source_pane_geom = source_pane.position_and_size(); let mut destination_pane_geom = source_pane_geom.clone(); destination_pane_geom.y = source_pane_geom.y + 1; source_pane_geom.rows = Dimension::fixed(1); source_pane.set_geom(source_pane_geom); let destination_pane = panes .get_mut(&destination_pane_id) .with_context(err_context)?; destination_pane.set_geom(destination_pane_geom); } else if destination_pane_stack_id.is_some() { // we're moving down to the highest pane in the stack, we need to expand it and shrink the // expanded stack pane self.make_highest_pane_in_stack_flexible(destination_pane_id)?; } Ok(()) } pub fn move_up(&mut self, source_pane_id: &PaneId, destination_pane_id: &PaneId) -> Result<()> { let err_context = || format!("Failed to move stacked pane focus up"); let source_pane_stack_id = self .panes .borrow() .get(source_pane_id) .with_context(err_context)? .position_and_size() .stacked; let destination_pane_stack_id = self .panes .borrow() .get(destination_pane_id) .with_context(err_context)? .position_and_size() .stacked; if source_pane_stack_id == destination_pane_stack_id { let mut panes = self.panes.borrow_mut(); let source_pane = panes.get_mut(source_pane_id).with_context(err_context)?; let mut source_pane_geom = source_pane.position_and_size(); let mut destination_pane_geom = source_pane_geom.clone(); source_pane_geom.y = (source_pane_geom.y + source_pane_geom.rows.as_usize()) - 1; // -1 because we want to be at the last line of the source pane, not the next line over source_pane_geom.rows = Dimension::fixed(1); source_pane.set_geom(source_pane_geom); destination_pane_geom.y -= 1; let destination_pane = panes .get_mut(&destination_pane_id) .with_context(err_context)?; destination_pane.set_geom(destination_pane_geom); } else if destination_pane_stack_id.is_some() { // we're moving up to the lowest pane in the stack, we need to expand it and shrink the // expanded stack pane self.make_lowest_pane_in_stack_flexible(destination_pane_id)?; } Ok(()) } pub fn expand_pane(&mut self, pane_id: &PaneId) -> Result<Vec<PaneId>> { // returns all the pane ids in the stack let err_context = || format!("Failed to focus stacked pane"); let all_stacked_pane_positions = self.positions_in_stack(pane_id).with_context(err_context)?; let position_of_flexible_pane = self .position_of_flexible_pane(&all_stacked_pane_positions) .with_context(err_context)?; let (flexible_pane_id, mut flexible_pane) = *all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .with_context(err_context)?; if flexible_pane_id != *pane_id { let mut panes = self.panes.borrow_mut(); let height_of_flexible_pane = all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .map(|(_pid, p)| p.rows) .with_context(err_context)?; let position_of_pane_to_focus = all_stacked_pane_positions .iter() .position(|(pid, _p)| pid == pane_id) .with_context(err_context)?; let (_, mut pane_to_focus) = *all_stacked_pane_positions .iter() .nth(position_of_pane_to_focus) .with_context(err_context)?; pane_to_focus.rows = height_of_flexible_pane; panes .get_mut(pane_id) .with_context(err_context)? .set_geom(pane_to_focus); flexible_pane.rows = Dimension::fixed(1); panes .get_mut(&flexible_pane_id) .with_context(err_context)? .set_geom(flexible_pane); for (i, (pid, _position)) in all_stacked_pane_positions.iter().enumerate() { if i > position_of_pane_to_focus && i <= position_of_flexible_pane { // the flexible pane has moved up the stack, we need to push this pane down let pane = panes.get_mut(pid).with_context(err_context)?; let mut pane_position_and_size = pane.position_and_size(); pane_position_and_size.y += height_of_flexible_pane.as_usize() - 1; pane.set_geom(pane_position_and_size); } else if i > position_of_flexible_pane && i <= position_of_pane_to_focus { // the flexible pane has moved down the stack, we need to pull this pane up let pane = panes.get_mut(pid).with_context(err_context)?; let mut pane_position_and_size = pane.position_and_size(); pane_position_and_size.y -= height_of_flexible_pane.as_usize() - 1; pane.set_geom(pane_position_and_size); } } } Ok(all_stacked_pane_positions .iter() .map(|(pane_id, _pane_position)| *pane_id) .collect()) } pub fn flexible_pane_id_in_stack(&self, pane_id_in_stack: &PaneId) -> Option<PaneId> { let all_stacked_pane_positions = self.positions_in_stack(pane_id_in_stack).ok()?; all_stacked_pane_positions .iter() .find(|(_pid, p)| p.rows.is_percent()) .map(|(pid, _p)| *pid) } pub fn position_and_size_of_stack(&self, id: &PaneId) -> Option<PaneGeom> { let all_stacked_pane_positions = self.positions_in_stack(id).ok()?; let position_of_flexible_pane = self .position_of_flexible_pane(&all_stacked_pane_positions) .ok()?; let (_flexible_pane_id, flexible_pane) = all_stacked_pane_positions .iter() .nth(position_of_flexible_pane)?; let (_, first_pane_in_stack) = all_stacked_pane_positions.first()?; let (_, last_pane_in_stack) = all_stacked_pane_positions.last()?; let mut rows = flexible_pane.rows; rows.set_inner( (last_pane_in_stack.y - first_pane_in_stack.y) + last_pane_in_stack.rows.as_usize(), ); Some(PaneGeom { y: first_pane_in_stack.y, x: first_pane_in_stack.x, cols: first_pane_in_stack.cols, rows, stacked: None, // important because otherwise the minimum stack size will not be // respected ..Default::default() }) } pub fn increase_stack_width(&mut self, id: &PaneId, percent: f64) -> Result<()> { let err_context = || format!("Failed to resize panes in stack"); let all_stacked_pane_positions = self.positions_in_stack(id).with_context(err_context)?; for (pane_id, _pane_position) in all_stacked_pane_positions { self.panes .borrow_mut() .get_mut(&pane_id) .with_context(err_context)? .increase_width(percent); } Ok(()) } pub fn reduce_stack_width(&mut self, id: &PaneId, percent: f64) -> Result<()> { let err_context = || format!("Failed to resize panes in stack"); let all_stacked_pane_positions = self.positions_in_stack(id).with_context(err_context)?; for (pane_id, _pane_position) in all_stacked_pane_positions { self.panes .borrow_mut() .get_mut(&pane_id) .with_context(err_context)? .reduce_width(percent); } Ok(()) } pub fn increase_stack_height(&mut self, id: &PaneId, percent: f64) -> Result<()> { let err_context = || format!("Failed to increase_stack_height"); let all_stacked_pane_positions = self.positions_in_stack(id).with_context(err_context)?; let position_of_flexible_pane = self .position_of_flexible_pane(&all_stacked_pane_positions) .with_context(err_context)?; let (flexible_pane_id, _flexible_pane) = all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .with_context(err_context)?; self.panes .borrow_mut() .get_mut(flexible_pane_id) .with_context(err_context)? .increase_height(percent); Ok(()) } pub fn reduce_stack_height(&mut self, id: &PaneId, percent: f64) -> Result<()> { let err_context = || format!("Failed to increase_stack_height"); let all_stacked_pane_positions = self.positions_in_stack(id).with_context(err_context)?; let position_of_flexible_pane = self .position_of_flexible_pane(&all_stacked_pane_positions) .with_context(err_context)?; let (flexible_pane_id, _flexible_pane) = all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .with_context(err_context)?; self.panes .borrow_mut() .get_mut(flexible_pane_id) .with_context(err_context)? .reduce_height(percent); Ok(()) } pub fn min_stack_height(&mut self, id: &PaneId) -> Result<usize> { let err_context = || format!("Failed to increase_stack_height"); let all_stacked_pane_positions = self.positions_in_stack(id).with_context(err_context)?; Ok(all_stacked_pane_positions.len()) } pub fn resize_panes_in_stack( &mut self, id: &PaneId, new_full_stack_geom: PaneGeom, ) -> Result<()> { let err_context = || format!("Failed to resize panes in stack"); let all_stacked_pane_positions = self.positions_in_stack(id).with_context(err_context)?; let position_of_flexible_pane = self.position_of_flexible_pane(&all_stacked_pane_positions)?; let (_flexible_pane_id, flexible_pane) = all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .with_context(err_context)?; let new_rows = new_full_stack_geom.rows.as_usize(); let adjust_stack_geoms = |new_flexible_pane_geom: PaneGeom| -> Result<()> { let new_flexible_pane_geom_rows = new_flexible_pane_geom.rows.as_usize(); for (i, (pane_id, pane_geom)) in all_stacked_pane_positions.iter().enumerate() { let mut new_pane_geom = if i == position_of_flexible_pane { new_flexible_pane_geom } else { *pane_geom }; new_pane_geom.x = new_full_stack_geom.x; new_pane_geom.cols = new_full_stack_geom.cols; if i <= position_of_flexible_pane { new_pane_geom.y = new_full_stack_geom.y + i; } else { new_pane_geom.y = new_full_stack_geom.y + i + (new_flexible_pane_geom_rows - 1); } self.panes .borrow_mut() .get_mut(&pane_id) .with_context(err_context)? .set_geom(new_pane_geom); } Ok(()) }; let new_rows_for_flexible_pane = new_rows.saturating_sub(all_stacked_pane_positions.len()) + 1; let mut new_flexible_pane_geom = new_full_stack_geom; new_flexible_pane_geom.stacked = flexible_pane.stacked; new_flexible_pane_geom.logical_position = flexible_pane.logical_position; new_flexible_pane_geom .rows .set_inner(new_rows_for_flexible_pane); adjust_stack_geoms(new_flexible_pane_geom)?; Ok(()) } fn pane_is_one_liner(&self, id: &PaneId) -> Result<bool> { let err_context = || format!("Cannot determine if pane is one liner or not"); let panes = self.panes.borrow(); let pane_to_close = panes.get(id).with_context(err_context)?; Ok(pane_to_close.position_and_size().rows.is_fixed()) } fn positions_in_stack(&self, id: &PaneId) -> Result<Vec<(PaneId, PaneGeom)>> { // find the full stack of panes around the given id, sorted by pane location top to bottom let err_context = || format!("Failed to find stacked panes"); let panes = self.panes.borrow(); let pane_in_stack = panes.get(id).with_context(err_context)?; let stack_id = pane_in_stack.position_and_size().stacked; let mut all_stacked_pane_positions: Vec<(PaneId, PaneGeom)> = panes .iter() .filter(|(_pid, p)| { p.position_and_size().is_stacked() && p.position_and_size().stacked == stack_id }) .filter(|(_pid, p)| { p.position_and_size().x == pane_in_stack.position_and_size().x && p.position_and_size().cols == pane_in_stack.position_and_size().cols }) .map(|(pid, p)| (*pid, p.position_and_size())) .collect(); all_stacked_pane_positions.sort_by(|(_a_pid, a), (_b_pid, b)| a.y.cmp(&b.y)); Ok(all_stacked_pane_positions) } fn position_of_current_and_flexible_pane( &self, current_pane_id: &PaneId, ) -> Result<(usize, usize)> { // (current_pane, flexible_pane) let err_context = || format!("Failed to position_of_current_and_flexible_pane"); let all_stacked_pane_positions = self.positions_in_stack(current_pane_id)?; let panes = self.panes.borrow(); let pane_to_close = panes.get(current_pane_id).with_context(err_context)?; let position_of_current_pane = self.position_of_current_pane(&all_stacked_pane_positions, &pane_to_close)?; let position_of_flexible_pane = self.position_of_flexible_pane(&all_stacked_pane_positions)?; Ok((position_of_current_pane, position_of_flexible_pane)) } fn position_of_current_pane( &self, all_stacked_pane_positions: &Vec<(PaneId, PaneGeom)>, pane_to_close: &Box<dyn Pane>, ) -> Result<usize> { let err_context = || format!("Failed to find position of current pane"); all_stacked_pane_positions .iter() .position(|(pid, _p)| pid == &pane_to_close.pid()) .with_context(err_context) } fn position_of_flexible_pane( &self, all_stacked_pane_positions: &Vec<(PaneId, PaneGeom)>, ) -> Result<usize> { let err_context = || format!("Failed to find position of flexible pane"); all_stacked_pane_positions .iter() .position(|(_pid, p)| p.rows.is_percent()) .with_context(err_context) } pub fn fill_space_over_pane_in_stack(&mut self, id: &PaneId) -> Result<bool> { if self.pane_is_one_liner(id)? { self.fill_space_over_one_liner_pane(id) } else { self.fill_space_over_visible_stacked_pane(id) } } pub fn stacked_pane_ids_under_and_over_flexible_panes( &self, ) -> Result<(HashSet<PaneId>, HashSet<PaneId>)> { let mut stacked_pane_ids_under_flexible_panes = HashSet::new(); let mut stacked_pane_ids_over_flexible_panes = HashSet::new(); let mut seen = HashSet::new(); let pane_ids_in_stacks: Vec<PaneId> = { self.panes .borrow() .iter() .filter(|(_p_id, p)| p.position_and_size().is_stacked()) .map(|(p_id, _p)| *p_id) .collect() }; for pane_id in pane_ids_in_stacks { if !seen.contains(&pane_id) { let mut current_pane_is_above_stack = true; let positions_in_stack = self.positions_in_stack(&pane_id)?; for (pane_id, pane_geom) in positions_in_stack { seen.insert(pane_id); if pane_geom.rows.is_percent() { // this is the flexible pane current_pane_is_above_stack = false; continue; } if current_pane_is_above_stack { stacked_pane_ids_over_flexible_panes.insert(pane_id); } else { stacked_pane_ids_under_flexible_panes.insert(pane_id); } } seen.insert(pane_id); } } Ok(( stacked_pane_ids_under_flexible_panes, stacked_pane_ids_over_flexible_panes, )) } pub fn stacked_pane_ids_on_top_and_bottom_of_stacks( &self, ) -> Result<(HashSet<PaneId>, HashSet<PaneId>)> { let mut stacked_pane_ids_on_top_of_stacks = HashSet::new(); let mut stacked_pane_ids_on_bottom_of_stacks = HashSet::new(); let all_stacks = self.get_all_stacks()?; for stack in all_stacks { if let Some((first_pane_id, _pane)) = stack.iter().next() { stacked_pane_ids_on_top_of_stacks.insert(*first_pane_id); } if let Some((last_pane_id, _pane)) = stack.iter().last() { stacked_pane_ids_on_bottom_of_stacks.insert(*last_pane_id); } } Ok(( stacked_pane_ids_on_top_of_stacks, stacked_pane_ids_on_bottom_of_stacks, )) } pub fn make_room_for_new_pane(&mut self) -> Result<PaneGeom> { let err_context = || format!("Failed to add pane to stack"); let all_stacks = self.get_all_stacks()?; for stack in all_stacks { if let Some((id_of_flexible_pane_in_stack, _flexible_pane_in_stack)) = stack .iter() .find(|(_p_id, p)| !p.rows.is_fixed() && p.rows.as_usize() > MIN_TERMINAL_HEIGHT) { self.make_lowest_pane_in_stack_flexible(id_of_flexible_pane_in_stack)?; let all_stacked_pane_positions = self.positions_in_stack(id_of_flexible_pane_in_stack)?; let position_of_flexible_pane = self.position_of_flexible_pane(&all_stacked_pane_positions)?; let (flexible_pane_id, mut flexible_pane_geom) = *all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .with_context(err_context)?; let mut position_for_new_pane = flexible_pane_geom.clone(); position_for_new_pane .rows .set_inner(position_for_new_pane.rows.as_usize() - 1); position_for_new_pane.y = position_for_new_pane.y + 1; flexible_pane_geom.rows = Dimension::fixed(1); self.panes .borrow_mut() .get_mut(&flexible_pane_id) .with_context(err_context)? .set_geom(flexible_pane_geom); return Ok(position_for_new_pane); } } Err(anyhow!("Not enough room for another pane!")) } pub fn make_room_for_new_pane_in_stack(&mut self, pane_id: &PaneId) -> Result<PaneGeom> { let err_context = || format!("Failed to add pane to stack"); let stack = self.positions_in_stack(pane_id).with_context(err_context)?; if let Some((id_of_flexible_pane_in_stack, _flexible_pane_in_stack)) = stack .iter() .find(|(_p_id, p)| !p.rows.is_fixed() && p.rows.as_usize() > MIN_TERMINAL_HEIGHT) { self.make_lowest_pane_in_stack_flexible(id_of_flexible_pane_in_stack)?; let all_stacked_pane_positions = self.positions_in_stack(id_of_flexible_pane_in_stack)?; let position_of_flexible_pane = self.position_of_flexible_pane(&all_stacked_pane_positions)?; let (flexible_pane_id, mut flexible_pane_geom) = *all_stacked_pane_positions .iter() .nth(position_of_flexible_pane) .with_context(err_context)?; let mut position_for_new_pane = flexible_pane_geom.clone(); position_for_new_pane .rows .set_inner(position_for_new_pane.rows.as_usize() - 1); position_for_new_pane.y = position_for_new_pane.y + 1; flexible_pane_geom.rows = Dimension::fixed(1); self.panes .borrow_mut() .get_mut(&flexible_pane_id) .with_context(err_context)? .set_geom(flexible_pane_geom); return Ok(position_for_new_pane); } Err(anyhow!("Not enough room for another pane!")) } pub fn room_left_in_stack_of_pane_id(&self, pane_id: &PaneId) -> Option<usize> { // if the pane is stacked, returns the number of panes possible to add to this stack let Ok(stack) = self.positions_in_stack(pane_id) else { return None; }; stack.iter().find_map(|(_p_id, p)| { if !p.rows.is_fixed() { // this is the flexible pane Some(p.rows.as_usize().saturating_sub(MIN_TERMINAL_HEIGHT)) } else { None } }) } pub fn new_stack(&self, root_pane_id: PaneId, pane_count_in_stack: usize) -> Vec<PaneGeom> { let mut stacked_geoms = vec![]; let panes = self.panes.borrow(); let running_stack_geom = panes.get(&root_pane_id).map(|p| p.position_and_size()); let Some(mut running_stack_geom) = running_stack_geom else { log::error!("Pane not found"); // TODO: better error return stacked_geoms; }; let stack_id = self.next_stack_id(); running_stack_geom.stacked = Some(stack_id); let mut pane_index_in_stack = 0; loop { if pane_index_in_stack == pane_count_in_stack { break; } let is_last_pane_in_stack = pane_index_in_stack == pane_count_in_stack.saturating_sub(1); let mut geom_for_pane = running_stack_geom.clone(); if !is_last_pane_in_stack { geom_for_pane.rows = Dimension::fixed(1); running_stack_geom.y += 1; running_stack_geom .rows .set_inner(running_stack_geom.rows.as_usize().saturating_sub(1)); } stacked_geoms.push(geom_for_pane); pane_index_in_stack += 1; } stacked_geoms } fn extract_geoms_from_stack( &self, root_pane_id: PaneId, ) -> Option<(PaneGeom, Vec<(PaneId, PaneGeom)>)> { let panes = self.panes.borrow(); let mut geom_of_main_pane = panes.get(&root_pane_id).map(|p| p.position_and_size())?; let mut extra_stacked_geoms_of_main_pane = vec![]; if geom_of_main_pane.is_stacked() { let other_panes_in_stack = self.positions_in_stack(&root_pane_id).ok()?; for other_pane in other_panes_in_stack { if other_pane.0 != root_pane_id { // so it is not duplicated extra_stacked_geoms_of_main_pane.push(other_pane); } } let logical_position = geom_of_main_pane.logical_position; geom_of_main_pane = self.position_and_size_of_stack(&root_pane_id)?; geom_of_main_pane.logical_position = logical_position; } Some((geom_of_main_pane, extra_stacked_geoms_of_main_pane)) } fn positions_of_panes_and_their_stacks( &self, pane_ids: Vec<PaneId>, ) -> Option<Vec<(PaneId, PaneGeom)>> { let mut positions = vec![]; let panes = self.panes.borrow(); for pane_id in &pane_ids { let geom_of_pane = panes.get(pane_id).map(|p| p.position_and_size())?; if geom_of_pane.is_stacked() { let mut other_panes_in_stack = self.positions_in_stack(pane_id).ok()?; positions.append(&mut other_panes_in_stack); } else { positions.push((*pane_id, geom_of_pane)); } } Some(positions) } fn combine_geoms_horizontally( &self, pane_ids_and_geoms: &Vec<(PaneId, PaneGeom)>, ) -> Option<PaneGeom> { let mut geoms_to_combine = HashSet::new(); for (other_pane_id, other_geom) in pane_ids_and_geoms { if other_geom.is_stacked() { geoms_to_combine.insert(self.position_and_size_of_stack(other_pane_id)?); } else { geoms_to_combine.insert(*other_geom); } } let mut geoms_to_combine: Vec<PaneGeom> = geoms_to_combine.iter().copied().collect(); geoms_to_combine.sort_by(|a_geom, b_geom| a_geom.x.cmp(&b_geom.x)); let geom_to_combine = geoms_to_combine.get(0)?; geom_to_combine .combine_horizontally_with_many(&geoms_to_combine.iter().copied().skip(1).collect()) } fn combine_geoms_vertically( &self, pane_ids_and_geoms: &Vec<(PaneId, PaneGeom)>, ) -> Option<PaneGeom> { let mut geoms_to_combine = HashSet::new(); for (other_pane_id, other_geom) in pane_ids_and_geoms { if other_geom.is_stacked() { geoms_to_combine.insert(self.position_and_size_of_stack(other_pane_id)?); } else { geoms_to_combine.insert(*other_geom); } } let mut geoms_to_combine: Vec<PaneGeom> = geoms_to_combine.iter().copied().collect(); geoms_to_combine.sort_by(|a_geom, b_geom| a_geom.y.cmp(&b_geom.y)); let geom_to_combine = geoms_to_combine.get(0)?; geom_to_combine .combine_vertically_with_many(&geoms_to_combine.iter().copied().skip(1).collect()) } pub fn combine_vertically_aligned_panes_to_stack( &mut self, root_pane_id: &PaneId, neighboring_pane_ids: Vec<PaneId>, ) -> Result<()> { let (geom_of_main_pane, mut extra_stacked_geoms_of_main_pane) = self .extract_geoms_from_stack(*root_pane_id) .ok_or_else(|| anyhow!("Failed to extract geoms from stack"))?; let mut other_pane_ids_and_geoms = self .positions_of_panes_and_their_stacks(neighboring_pane_ids) .ok_or_else(|| anyhow!("Failed to get pane geoms"))?; if other_pane_ids_and_geoms.is_empty() { // nothing to do return Ok(()); }; let Some(geom_to_combine) = self.combine_geoms_horizontally(&other_pane_ids_and_geoms) else { log::error!("Failed to combine geoms horizontally"); return Ok(()); }; let new_stack_geom = if geom_to_combine.y < geom_of_main_pane.y { geom_to_combine.combine_vertically_with(&geom_of_main_pane) } else { geom_of_main_pane.combine_vertically_with(&geom_to_combine) }; let Some(new_stack_geom) = new_stack_geom else { // nothing to do, likely the pane below is fixed return Ok(()); }; let stack_id = self.next_stack_id(); // we add the extra panes in the original stack (if any) so that they will be assigned pane // positions but not affect the stack geometry other_pane_ids_and_geoms.append(&mut extra_stacked_geoms_of_main_pane); let mut panes = self.panes.borrow_mut(); let mut running_y = new_stack_geom.y; let mut geom_of_flexible_pane = new_stack_geom.clone(); geom_of_flexible_pane .rows .decrease_inner(other_pane_ids_and_geoms.len()); geom_of_flexible_pane.stacked = Some(stack_id); let mut all_stack_geoms = other_pane_ids_and_geoms; let original_geom_of_main_pane = panes .get(&root_pane_id) .ok_or_else(|| anyhow!("Failed to find root geom"))? .position_and_size(); // for sorting purposes all_stack_geoms.push((*root_pane_id, original_geom_of_main_pane)); all_stack_geoms.sort_by(|(_a_id, a_geom), (_b_id, b_geom)| { if a_geom.y == b_geom.y { a_geom.x.cmp(&b_geom.x) } else { a_geom.y.cmp(&b_geom.y) } }); for (pane_id, mut pane_geom) in all_stack_geoms { if let Some(pane_in_stack) = panes.get_mut(&pane_id) { if &pane_id == root_pane_id { pane_geom.x = new_stack_geom.x; pane_geom.cols = new_stack_geom.cols; pane_geom.y = running_y; pane_geom.rows = geom_of_flexible_pane.rows; pane_geom.stacked = Some(stack_id); running_y += geom_of_flexible_pane.rows.as_usize(); pane_in_stack.set_geom(pane_geom); } else { pane_geom.x = new_stack_geom.x; pane_geom.cols = new_stack_geom.cols; pane_geom.y = running_y; pane_geom.rows = Dimension::fixed(1); pane_geom.stacked = Some(stack_id); running_y += 1; pane_in_stack.set_geom(pane_geom); } } } Ok(()) } pub fn combine_horizontally_aligned_panes_to_stack( &mut self, root_pane_id: &PaneId, neighboring_pane_ids: Vec<PaneId>, ) -> Result<()> { let (geom_of_main_pane, mut extra_stacked_geoms_of_main_pane) = self .extract_geoms_from_stack(*root_pane_id) .ok_or_else(|| anyhow!("Failed to extract geoms from stack"))?; let mut other_pane_ids_and_geoms = self .positions_of_panes_and_their_stacks(neighboring_pane_ids) .ok_or_else(|| anyhow!("Failed to get pane geoms"))?; if other_pane_ids_and_geoms.is_empty() { // nothing to do return Ok(()); }; let Some(geom_to_combine) = self.combine_geoms_vertically(&other_pane_ids_and_geoms) else { log::error!("Failed to combine geoms vertically"); return Ok(()); }; let new_stack_geom = if geom_to_combine.x < geom_of_main_pane.x { geom_to_combine.combine_horizontally_with(&geom_of_main_pane) } else { geom_of_main_pane.combine_horizontally_with(&geom_to_combine) };
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/tiled_panes/unit/stacked_panes_tests.rs
zellij-server/src/panes/tiled_panes/unit/stacked_panes_tests.rs
use crate::{panes::tiled_panes::StackedPanes, panes::PaneId, tab::Pane}; use insta::assert_snapshot; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use zellij_utils::errors::prelude::*; use zellij_utils::input::layout::Run; use zellij_utils::pane_size::Offset; use zellij_utils::pane_size::{Dimension, PaneGeom}; use crate::ui::pane_boundaries_frame::FrameParams; use crate::{ output::{CharacterChunk, SixelImageChunk}, pty::VteBytes, ClientId, }; use std::time::Instant; use zellij_utils::data::{InputMode, PaletteColor, PaneContents}; macro_rules! mock_pane { ($pane_id:expr, $dimension:expr, $inner:expr, $x:expr, $y:expr, $logical_position:expr, $mock_panes:expr) => { let mut mock_pane_rows = $dimension; mock_pane_rows.set_inner($inner); let mut mock_pane: Box<dyn Pane> = Box::new(MockPane::new(PaneGeom { x: $x, y: $y, rows: mock_pane_rows, cols: Dimension::percent(100.0), logical_position: $logical_position, ..Default::default() })); $mock_panes.insert($pane_id, &mut mock_pane); }; } macro_rules! mock_pane_with_cols { ($pane_id:expr, $rows_dimension:expr, $rows_inner:expr, $cols_dimension:expr, $cols_inner:expr, $x:expr, $y:expr, $logical_position:expr, $mock_panes:expr) => { let mut mock_pane_rows = $rows_dimension; mock_pane_rows.set_inner($rows_inner); let mut mock_pane_cols = $cols_dimension; mock_pane_cols.set_inner($cols_inner); let mut mock_pane: Box<dyn Pane> = Box::new(MockPane::new(PaneGeom { x: $x, y: $y, rows: mock_pane_rows, cols: mock_pane_cols, logical_position: $logical_position, ..Default::default() })); $mock_panes.insert($pane_id, &mut mock_pane); }; } macro_rules! mock_stacked_pane { ($pane_id:expr, $dimension:expr, $inner:expr, $x:expr, $y:expr, $logical_position:expr, $mock_panes:expr) => { let mut mock_pane_rows = $dimension; mock_pane_rows.set_inner($inner); let mut mock_pane: Box<dyn Pane> = Box::new(MockPane::new(PaneGeom { x: $x, y: $y, rows: mock_pane_rows, cols: Dimension::percent(100.0), logical_position: $logical_position, stacked: Some(0), ..Default::default() })); $mock_panes.insert($pane_id, &mut mock_pane); }; } macro_rules! mock_stacked_pane_with_id { ($pane_id:expr, $dimension:expr, $inner:expr, $x:expr, $y:expr, $logical_position:expr, $mock_panes:expr, $stack_id:expr) => { let mut mock_pane_rows = $dimension; mock_pane_rows.set_inner($inner); let mut mock_pane: Box<dyn Pane> = Box::new(MockPane::new(PaneGeom { x: $x, y: $y, rows: mock_pane_rows, cols: Dimension::percent(100.0), logical_position: $logical_position, stacked: Some($stack_id), ..Default::default() })); $mock_panes.insert($pane_id, &mut mock_pane); }; } macro_rules! mock_stacked_pane_with_cols_and_id { ($pane_id:expr, $rows_dimension:expr, $rows_inner:expr, $cols_dimension:expr, $cols_inner:expr, $x:expr, $y:expr, $logical_position:expr, $mock_panes:expr, $stack_id:expr) => { let mut mock_pane_rows = $rows_dimension; mock_pane_rows.set_inner($rows_inner); let mut mock_pane_cols = $cols_dimension; mock_pane_cols.set_inner($cols_inner); let mut mock_pane: Box<dyn Pane> = Box::new(MockPane::new(PaneGeom { x: $x, y: $y, rows: mock_pane_rows, cols: mock_pane_cols, logical_position: $logical_position, stacked: Some($stack_id), ..Default::default() })); $mock_panes.insert($pane_id, &mut mock_pane); }; } #[test] fn combine_vertically_aligned_panes_to_stack() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(50.0), 50, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(50.0), 50, 0, 50, Some(2), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_above = PaneId::Terminal(1); let pane_id_below = PaneId::Terminal(2); StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&pane_id_above, vec![pane_id_below]) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_vertically_aligned_panes_to_stack_when_lower_pane_is_stacked() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_stacked_pane!( PaneId::Terminal(3), Dimension::fixed(1), 1, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::percent(33.3), 33, 0, 67, Some(4), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_above = PaneId::Terminal(2); let pane_id_below = PaneId::Terminal(4); StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&pane_id_above, vec![pane_id_below]) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_vertically_aligned_panes_to_stack_when_lower_pane_is_stacked_and_flexible_pane_is_on_top_of_stack( ) { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_stacked_pane!( PaneId::Terminal(3), Dimension::percent(33.3), 33, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::fixed(1), 1, 0, 99, Some(4), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_above = PaneId::Terminal(2); let pane_id_below = PaneId::Terminal(3); StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&pane_id_above, vec![pane_id_below]) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_vertically_aligned_panes_to_stack_when_lower_pane_is_stacked_and_flexible_pane_is_mid_stack( ) { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_stacked_pane!( PaneId::Terminal(3), Dimension::fixed(1), 1, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::percent(33.3), 32, 0, 67, Some(4), mock_panes ); mock_stacked_pane!( PaneId::Terminal(5), Dimension::fixed(1), 1, 0, 99, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_above = PaneId::Terminal(2); let pane_id_below = PaneId::Terminal(4); StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&pane_id_above, vec![pane_id_below]) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_vertically_aligned_panes_to_stack_when_both_are_stacked() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_stacked_pane_with_id!( PaneId::Terminal(1), Dimension::percent(50.0), 49, 0, 0, Some(1), mock_panes, 0 ); mock_stacked_pane_with_id!( PaneId::Terminal(2), Dimension::fixed(1), 1, 0, 49, Some(2), mock_panes, 0 ); mock_stacked_pane_with_id!( PaneId::Terminal(3), Dimension::fixed(1), 1, 0, 50, Some(3), mock_panes, 1 ); mock_stacked_pane_with_id!( PaneId::Terminal(4), Dimension::percent(50.0), 48, 0, 51, Some(4), mock_panes, 1 ); mock_stacked_pane_with_id!( PaneId::Terminal(5), Dimension::fixed(1), 1, 0, 99, Some(5), mock_panes, 1 ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_above = PaneId::Terminal(2); let pane_id_below = PaneId::Terminal(4); StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&pane_id_above, vec![pane_id_below]) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_vertically_aligned_panes_to_stack_with_multiple_non_stacked_neighbors() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane_with_cols!( PaneId::Terminal(1), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 0, 0, Some(1), mock_panes ); mock_pane_with_cols!( PaneId::Terminal(2), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 50, 0, Some(2), mock_panes ); mock_stacked_pane_with_id!( PaneId::Terminal(3), Dimension::fixed(1), 1, 0, 50, Some(3), mock_panes, 1 ); mock_stacked_pane_with_id!( PaneId::Terminal(4), Dimension::percent(50.0), 48, 0, 51, Some(4), mock_panes, 1 ); mock_stacked_pane_with_id!( PaneId::Terminal(5), Dimension::fixed(1), 1, 0, 99, Some(5), mock_panes, 1 ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let root_pane_id = PaneId::Terminal(4); let pane_ids_above = vec![PaneId::Terminal(1), PaneId::Terminal(2)]; StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&root_pane_id, pane_ids_above) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_vertically_aligned_panes_to_stack_with_multiple_stacked_neighbors() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane_with_cols!( PaneId::Terminal(1), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 0, 0, Some(1), mock_panes ); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(2), Dimension::percent(50.0), 49, Dimension::percent(50.0), 50, 50, 0, Some(2), mock_panes, 2 ); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(3), Dimension::fixed(1), 1, Dimension::percent(50.0), 50, 50, 49, Some(3), mock_panes, 2 ); mock_stacked_pane_with_id!( PaneId::Terminal(4), Dimension::fixed(1), 1, 0, 50, Some(4), mock_panes, 1 ); mock_stacked_pane_with_id!( PaneId::Terminal(5), Dimension::percent(50.0), 48, 0, 51, Some(5), mock_panes, 1 ); mock_stacked_pane_with_id!( PaneId::Terminal(6), Dimension::fixed(1), 1, 0, 99, Some(6), mock_panes, 1 ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let root_pane_id = PaneId::Terminal(5); let pane_ids_above = vec![PaneId::Terminal(1), PaneId::Terminal(2)]; StackedPanes::new(mock_panes.clone()) .combine_vertically_aligned_panes_to_stack(&root_pane_id, pane_ids_above) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_horizontally_aligned_panes_to_stack() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane_with_cols!( PaneId::Terminal(1), Dimension::percent(100.0), 100, Dimension::percent(50.0), 50, 0, 0, Some(1), mock_panes ); mock_pane_with_cols!( PaneId::Terminal(2), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 50, 0, Some(2), mock_panes ); mock_pane_with_cols!( PaneId::Terminal(3), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 50, 50, Some(3), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_of_main_stack = PaneId::Terminal(1); let neighboring_pane_ids = vec![PaneId::Terminal(2), PaneId::Terminal(3)]; StackedPanes::new(mock_panes.clone()) .combine_horizontally_aligned_panes_to_stack(&pane_id_of_main_stack, neighboring_pane_ids) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_horizontally_aligned_panes_to_stack_when_left_pane_is_stacked() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(1), Dimension::percent(100.0), 98, Dimension::percent(50.0), 50, 0, 0, Some(1), mock_panes, 0 ); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(2), Dimension::fixed(1), 1, Dimension::percent(50.0), 50, 0, 98, Some(2), mock_panes, 0 ); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(3), Dimension::fixed(1), 1, Dimension::percent(50.0), 50, 0, 99, Some(3), mock_panes, 0 ); mock_pane_with_cols!( PaneId::Terminal(4), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 50, 0, Some(4), mock_panes ); mock_pane_with_cols!( PaneId::Terminal(5), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 50, 50, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_of_main_stack = PaneId::Terminal(1); let neighboring_pane_ids = vec![PaneId::Terminal(4), PaneId::Terminal(5)]; StackedPanes::new(mock_panes.clone()) .combine_horizontally_aligned_panes_to_stack(&pane_id_of_main_stack, neighboring_pane_ids) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn combine_horizontally_aligned_panes_to_stack_when_right_pane_is_stacked() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(1), Dimension::percent(100.0), 98, Dimension::percent(50.0), 50, 50, 0, Some(1), mock_panes, 0 ); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(2), Dimension::fixed(1), 1, Dimension::percent(50.0), 50, 50, 98, Some(2), mock_panes, 0 ); mock_stacked_pane_with_cols_and_id!( PaneId::Terminal(3), Dimension::fixed(1), 1, Dimension::percent(50.0), 50, 50, 99, Some(3), mock_panes, 0 ); mock_pane_with_cols!( PaneId::Terminal(4), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 0, 0, Some(4), mock_panes ); mock_pane_with_cols!( PaneId::Terminal(5), Dimension::percent(50.0), 50, Dimension::percent(50.0), 50, 0, 50, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let pane_id_of_main_stack = PaneId::Terminal(1); let neighboring_pane_ids = vec![PaneId::Terminal(4), PaneId::Terminal(5)]; StackedPanes::new(mock_panes.clone()) .combine_horizontally_aligned_panes_to_stack(&pane_id_of_main_stack, neighboring_pane_ids) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn break_pane_out_of_stack_top() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_stacked_pane!( PaneId::Terminal(3), Dimension::percent(33.3), 1, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::fixed(1), 32, 0, 67, Some(4), mock_panes ); mock_stacked_pane!( PaneId::Terminal(5), Dimension::fixed(1), 1, 0, 99, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let focused_pane = PaneId::Terminal(3); // here the bottom pane should be broken out because the focused pane is the top one and should // remain in the stack StackedPanes::new(mock_panes.clone()) .break_pane_out_of_stack(&focused_pane) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn break_pane_out_of_stack_middle() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_stacked_pane!( PaneId::Terminal(3), Dimension::fixed(1), 1, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::percent(33.3), 32, 0, 67, Some(4), mock_panes ); mock_stacked_pane!( PaneId::Terminal(5), Dimension::fixed(1), 1, 0, 99, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let focused_pane = PaneId::Terminal(4); // here the bottom pane should be broken out (default behavior) StackedPanes::new(mock_panes.clone()) .break_pane_out_of_stack(&focused_pane) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn break_pane_out_of_stack_bottom() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_stacked_pane!( PaneId::Terminal(3), Dimension::fixed(1), 32, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::fixed(1), 1, 0, 98, Some(4), mock_panes ); mock_stacked_pane!( PaneId::Terminal(5), Dimension::percent(33.3), 1, 0, 99, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let focused_pane = PaneId::Terminal(5); // here the top pane should be broken out, because the focused pane is the bottom one and it // should remain in the stack StackedPanes::new(mock_panes.clone()) .break_pane_out_of_stack(&focused_pane) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } #[test] fn break_next_to_last_pane_out_of_stack() { let mut mock_panes: HashMap<PaneId, &mut Box<dyn Pane>> = HashMap::new(); mock_pane!( PaneId::Terminal(1), Dimension::percent(33.3), 33, 0, 0, Some(1), mock_panes ); mock_pane!( PaneId::Terminal(2), Dimension::percent(33.3), 33, 0, 33, Some(2), mock_panes ); mock_pane!( PaneId::Terminal(3), Dimension::percent(22.1), 22, 0, 66, Some(3), mock_panes ); mock_stacked_pane!( PaneId::Terminal(4), Dimension::percent(11.2), 11, 0, 88, Some(4), mock_panes ); mock_stacked_pane!( PaneId::Terminal(5), Dimension::fixed(1), 1, 0, 99, Some(5), mock_panes ); let mock_panes = Rc::new(RefCell::new(mock_panes)); let focused_pane = PaneId::Terminal(4); StackedPanes::new(mock_panes.clone()) .break_pane_out_of_stack(&focused_pane) .unwrap(); let mut pane_geoms_after: Vec<PaneGeom> = mock_panes .borrow() .values() .map(|p| p.current_geom()) .collect(); pane_geoms_after.sort_by(|a, b| a.logical_position.cmp(&b.logical_position)); assert_snapshot!(format!("{:#?}", pane_geoms_after)); } struct MockPane { pane_geom: PaneGeom, } impl MockPane { pub fn new(pane_geom: PaneGeom) -> Self { MockPane { pane_geom } } } impl Pane for MockPane { fn x(&self) -> usize { unimplemented!() } fn y(&self) -> usize { unimplemented!() } fn rows(&self) -> usize { unimplemented!() } fn cols(&self) -> usize { unimplemented!() } fn get_content_x(&self) -> usize { unimplemented!() } fn get_content_y(&self) -> usize { unimplemented!() } fn get_content_columns(&self) -> usize { unimplemented!() } fn get_content_rows(&self) -> usize { unimplemented!() } fn reset_size_and_position_override(&mut self) { unimplemented!() } fn set_geom(&mut self, position_and_size: PaneGeom) { self.pane_geom = position_and_size; } fn set_geom_override(&mut self, _pane_geom: PaneGeom) { unimplemented!() } fn handle_pty_bytes(&mut self, _bytes: VteBytes) { unimplemented!() } fn handle_plugin_bytes(&mut self, _client_id: ClientId, _bytes: VteBytes) { unimplemented!() } fn cursor_coordinates(&self, _client_id: Option<ClientId>) -> Option<(usize, usize)> { unimplemented!() } fn position_and_size(&self) -> PaneGeom { self.pane_geom.clone() } fn current_geom(&self) -> PaneGeom { self.pane_geom.clone() } fn geom_override(&self) -> Option<PaneGeom> { unimplemented!() } fn should_render(&self) -> bool { unimplemented!() } fn set_should_render(&mut self, _should_render: bool) { unimplemented!() } fn set_should_render_boundaries(&mut self, _should_render: bool) { unimplemented!() } fn selectable(&self) -> bool { unimplemented!() } fn set_selectable(&mut self, _selectable: bool) { unimplemented!() } fn render( &mut self, _client_id: Option<ClientId>, ) -> Result<Option<(Vec<CharacterChunk>, Option<String>, Vec<SixelImageChunk>)>> { unimplemented!() } fn render_frame( &mut self, _client_id: ClientId, _frame_params: FrameParams, _input_mode: InputMode, ) -> Result<Option<(Vec<CharacterChunk>, Option<String>)>> { unimplemented!() } fn render_fake_cursor( &mut self, _cursor_color: PaletteColor, _text_color: PaletteColor, ) -> Option<String> { unimplemented!() } fn render_terminal_title(&mut self, _input_mode: InputMode) -> String { unimplemented!() } fn update_name(&mut self, _name: &str) { unimplemented!() } fn pid(&self) -> PaneId { unimplemented!() } fn reduce_height(&mut self, _percent: f64) { unimplemented!() } fn increase_height(&mut self, _percent: f64) { unimplemented!() } fn reduce_width(&mut self, _percent: f64) { unimplemented!() } fn increase_width(&mut self, _percent: f64) { unimplemented!() } fn push_down(&mut self, _count: usize) { unimplemented!() } fn push_right(&mut self, _count: usize) { unimplemented!() } fn pull_left(&mut self, _count: usize) { unimplemented!() } fn pull_up(&mut self, _count: usize) { unimplemented!() } fn clear_screen(&mut self) { unimplemented!() } fn scroll_up(&mut self, _count: usize, _client_id: ClientId) { unimplemented!() } fn scroll_down(&mut self, _count: usize, _client_id: ClientId) { unimplemented!() } fn clear_scroll(&mut self) { unimplemented!() } fn is_scrolled(&self) -> bool { unimplemented!() } fn active_at(&self) -> Instant { unimplemented!() } fn set_active_at(&mut self, _instant: Instant) { unimplemented!() } fn set_frame(&mut self, _frame: bool) { unimplemented!() } fn set_content_offset(&mut self, _offset: Offset) { unimplemented!() } fn store_pane_name(&mut self) { unimplemented!() } fn load_pane_name(&mut self) { unimplemented!() } fn set_borderless(&mut self, _borderless: bool) { unimplemented!() } fn borderless(&self) -> bool { unimplemented!() } fn set_exclude_from_sync(&mut self, _exclude_from_sync: bool) { unimplemented!() } fn exclude_from_sync(&self) -> bool { unimplemented!() } fn add_red_pane_frame_color_override(&mut self, _error_text: Option<String>) { unimplemented!() } fn clear_pane_frame_color_override(&mut self, _client_id: Option<ClientId>) { unimplemented!() } fn frame_color_override(&self) -> Option<PaletteColor> { unimplemented!() } fn invoked_with(&self) -> &Option<Run> { unimplemented!() } fn set_title(&mut self, _title: String) { unimplemented!() } fn current_title(&self) -> String { unimplemented!() } fn custom_title(&self) -> Option<String> { unimplemented!() } fn pane_contents( &self, _client_id: Option<ClientId>, _get_full_scrollback: bool, ) -> PaneContents { unimplemented!() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/unit/terminal_pane_tests.rs
zellij-server/src/panes/unit/terminal_pane_tests.rs
use super::super::TerminalPane; use crate::panes::sixel::SixelImageStore; use crate::panes::LinkHandler; use crate::tab::Pane; use ::insta::assert_snapshot; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use zellij_utils::{ data::{Palette, Style}, pane_size::{Offset, PaneGeom, SizeInPixels}, position::Position, }; use std::fmt::Write; fn read_fixture(fixture_name: &str) -> Vec<u8> { let mut path_to_file = std::path::PathBuf::new(); path_to_file.push("../src"); path_to_file.push("tests"); path_to_file.push("fixtures"); path_to_file.push(fixture_name); std::fs::read(path_to_file) .unwrap_or_else(|_| panic!("could not read fixture {:?}", &fixture_name)) } #[test] pub fn scrolling_inside_a_pane() { let fake_client_id = 1; let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let mut text_to_fill_pane = String::new(); for i in 0..30 { writeln!(&mut text_to_fill_pane, "\rline {}", i + 1).unwrap(); } terminal_pane.handle_pty_bytes(text_to_fill_pane.into_bytes()); terminal_pane.scroll_up(10, fake_client_id); assert_snapshot!(format!("{:?}", terminal_pane.grid)); terminal_pane.scroll_down(3, fake_client_id); assert_snapshot!(format!("{:?}", terminal_pane.grid)); terminal_pane.clear_scroll(); assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn sixel_image_inside_terminal_pane() { let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let sixel_image_bytes = "\u{1b}Pq #0;2;0;0;0#1;2;100;100;0#2;2;0;100;0 #1~~@@vv@@~~@@~~$ #2??}}GG}}??}}??- #1!14@ \u{1b}\\"; terminal_pane.handle_pty_bytes(Vec::from(sixel_image_bytes.as_bytes())); assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn partial_sixel_image_inside_terminal_pane() { // here we test to make sure we partially render an image that is partially hidden in the // scrollbuffer let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let pane_content = read_fixture("sixel-image-500px.six"); terminal_pane.handle_pty_bytes(pane_content); assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn overflowing_sixel_image_inside_terminal_pane() { // here we test to make sure we properly render an image that overflows both in the width and // height of the pane let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(50); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let pane_content = read_fixture("sixel-image-500px.six"); terminal_pane.handle_pty_bytes(pane_content); assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn scrolling_through_a_sixel_image() { let fake_client_id = 1; let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let mut text_to_fill_pane = String::new(); for i in 0..30 { writeln!(&mut text_to_fill_pane, "\rline {}", i + 1).unwrap(); } writeln!(&mut text_to_fill_pane, "\r").unwrap(); let pane_sixel_content = read_fixture("sixel-image-500px.six"); terminal_pane.handle_pty_bytes(text_to_fill_pane.into_bytes()); terminal_pane.handle_pty_bytes(pane_sixel_content); terminal_pane.scroll_up(10, fake_client_id); assert_snapshot!(format!("{:?}", terminal_pane.grid)); terminal_pane.scroll_down(3, fake_client_id); assert_snapshot!(format!("{:?}", terminal_pane.grid)); terminal_pane.clear_scroll(); assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn multiple_sixel_images_in_pane() { let fake_client_id = 1; let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let mut text_to_fill_pane = String::new(); for i in 0..5 { writeln!(&mut text_to_fill_pane, "\rline {}", i + 1).unwrap(); } writeln!(&mut text_to_fill_pane, "\r").unwrap(); let pane_sixel_content = read_fixture("sixel-image-500px.six"); terminal_pane.handle_pty_bytes(pane_sixel_content.clone()); // one image above text terminal_pane.handle_pty_bytes(text_to_fill_pane.into_bytes()); terminal_pane.handle_pty_bytes(pane_sixel_content); // one image below text terminal_pane.scroll_up(20, fake_client_id); // scroll up to see both images assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn resizing_pane_with_sixel_images() { // here we test, for example, that sixel images don't wrap with other lines let fake_client_id = 1; let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let mut text_to_fill_pane = String::new(); for i in 0..5 { writeln!(&mut text_to_fill_pane, "\rline {}", i + 1).unwrap(); } writeln!(&mut text_to_fill_pane, "\r").unwrap(); let pane_sixel_content = read_fixture("sixel-image-500px.six"); terminal_pane.handle_pty_bytes(pane_sixel_content.clone()); terminal_pane.handle_pty_bytes(text_to_fill_pane.into_bytes()); terminal_pane.handle_pty_bytes(pane_sixel_content); let mut new_win_size = PaneGeom::default(); new_win_size.cols.set_inner(100); new_win_size.rows.set_inner(20); terminal_pane.set_geom(new_win_size); terminal_pane.scroll_up(20, fake_client_id); // scroll up to see both images assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn changing_character_cell_size_with_sixel_images() { let fake_client_id = 1; let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size.clone(), sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let mut text_to_fill_pane = String::new(); for i in 0..5 { writeln!(&mut text_to_fill_pane, "\rline {}", i + 1).unwrap(); } writeln!(&mut text_to_fill_pane, "\r").unwrap(); let pane_sixel_content = read_fixture("sixel-image-500px.six"); terminal_pane.handle_pty_bytes(pane_sixel_content.clone()); terminal_pane.handle_pty_bytes(text_to_fill_pane.into_bytes()); terminal_pane.handle_pty_bytes(pane_sixel_content); // here the new_win_size is the same as the old one, we just update the character_cell_size // which will be picked up upon resize (which is why we're doing set_geom below) let mut new_win_size = PaneGeom::default(); new_win_size.cols.set_inner(121); new_win_size.rows.set_inner(20); *character_cell_size.borrow_mut() = Some(SizeInPixels { width: 8, height: 18, }); terminal_pane.set_geom(new_win_size); terminal_pane.scroll_up(10, fake_client_id); // scroll up to see both images assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn keep_working_after_corrupted_sixel_image() { let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let sixel_image_bytes = "\u{1b}PI AM CORRUPTED BWAHAHAq #0;2;0;0;0#1;2;100;100;0#2;2;0;100;0 #1~~@@vv@@~~@@~~$ #2??}}GG}}??}}??- #1!14@ \u{1b}\\"; terminal_pane.handle_pty_bytes(Vec::from(sixel_image_bytes.as_bytes())); let mut text_to_fill_pane = String::new(); for i in 0..5 { writeln!(&mut text_to_fill_pane, "\rline {}", i + 1).unwrap(); } terminal_pane.handle_pty_bytes(text_to_fill_pane.into_bytes()); assert_snapshot!(format!("{:?}", terminal_pane.grid)); } #[test] pub fn pane_with_frame_position_is_on_frame() { let mut fake_win_size = PaneGeom { x: 10, y: 10, ..PaneGeom::default() }; fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index terminal_pane.set_content_offset(Offset::frame(1)); // row above pane: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 129))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 131))); // first row: border for 10 <= col <= 130 assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 9))); assert!(terminal_pane.position_is_on_frame(&Position::new(10, 10))); assert!(terminal_pane.position_is_on_frame(&Position::new(10, 11))); assert!(terminal_pane.position_is_on_frame(&Position::new(10, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(10, 129))); assert!(terminal_pane.position_is_on_frame(&Position::new(10, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 131))); // second row: border only at col=10,130 assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 9))); assert!(terminal_pane.position_is_on_frame(&Position::new(11, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(11, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 131))); // row in the middle: border only at col=10,130 assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 9))); assert!(terminal_pane.position_is_on_frame(&Position::new(15, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(15, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 131))); // last row: border for 10 <= col <= 130 assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 9))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 10))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 11))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 131))); // row below pane: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 131))); } #[test] pub fn pane_with_bottom_and_right_borders_position_is_on_frame() { let mut fake_win_size = PaneGeom { x: 10, y: 10, ..PaneGeom::default() }; fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index terminal_pane.set_content_offset(Offset::shift(1, 1)); // row above pane: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 129))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 131))); // first row: border only at col=130 assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 129))); assert!(terminal_pane.position_is_on_frame(&Position::new(10, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 131))); // second row: border only at col=130 assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(11, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 131))); // row in the middle: border only at col=130 assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(15, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 131))); // last row: border for 10 <= col <= 130 assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 9))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 10))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 11))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 70))); assert!(terminal_pane.position_is_on_frame(&Position::new(29, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 131))); // row below pane: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 131))); } #[test] pub fn frameless_pane_position_is_on_frame() { let mut fake_win_size = PaneGeom { x: 10, y: 10, ..PaneGeom::default() }; fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, terminal_emulator_colors, terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index terminal_pane.set_content_offset(Offset::default()); // row above pane: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 129))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(9, 131))); // first row: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 129))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(10, 131))); // second row: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(11, 131))); // random row in the middle: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(15, 131))); // last row: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 9))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(29, 131))); // row below pane: no border assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 10))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 11))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 70))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 130))); assert!(!terminal_pane.position_is_on_frame(&Position::new(30, 131))); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/unit/search_in_pane_tests.rs
zellij-server/src/panes/unit/search_in_pane_tests.rs
use super::super::TerminalPane; use crate::panes::sixel::SixelImageStore; use crate::panes::LinkHandler; use crate::tab::Pane; use insta::assert_snapshot; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use zellij_utils::data::{Palette, Style}; use zellij_utils::pane_size::PaneGeom; fn read_fixture() -> Vec<u8> { let mut path_to_file = std::path::PathBuf::new(); path_to_file.push("../src"); path_to_file.push("tests"); path_to_file.push("fixtures"); path_to_file.push("grid_copy"); std::fs::read(path_to_file) .unwrap_or_else(|_| panic!("could not read fixture ../src/tests/fixtures/grid_copy")) } fn create_pane() -> TerminalPane { let mut fake_win_size = PaneGeom::default(); fake_win_size.cols.set_inner(121); fake_win_size.rows.set_inner(20); let pid = 1; let style = Style::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut terminal_pane = TerminalPane::new( pid, fake_win_size, style, 0, String::new(), Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, None, None, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); // 0 is the pane index let content = read_fixture(); terminal_pane.handle_pty_bytes(content); terminal_pane } #[test] pub fn searching_inside_a_viewport() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("tortor"); assert_snapshot!( "grid_copy_tortor_highlighted", format!("{:?}", terminal_pane.grid) ); terminal_pane.search_up(); // snapshot-size optimization: We use a named one here to de-duplicate assert_snapshot!( "grid_copy_search_cursor_at_bottom", format!("{:?}", terminal_pane.grid) ); terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_cursor_at_second", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_scroll_viewport() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("tortor"); terminal_pane.search_up(); // snapshot-size optimization: We use a named one here to de-duplicate assert_snapshot!( "grid_copy_search_cursor_at_bottom", format!("{:?}", terminal_pane.grid) ); terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_cursor_at_second", format!("{:?}", terminal_pane.grid) ); // Scroll away terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_scrolled_up", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_with_wrap() { let mut terminal_pane = create_pane(); // Searching for "tortor" terminal_pane.update_search_term("tortor"); // Selecting the last place tortor was found terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_cursor_at_bottom", format!("{:?}", terminal_pane.grid) ); // Search backwards again terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_cursor_at_second", format!("{:?}", terminal_pane.grid) ); terminal_pane.search_down(); assert_snapshot!( "grid_copy_search_cursor_at_bottom", format!("{:?}", terminal_pane.grid) ); // Searching forward again should do nothing here terminal_pane.search_down(); assert_snapshot!( "grid_copy_search_cursor_at_bottom", format!("{:?}", terminal_pane.grid) ); // Only after wrapping search is active, do we actually jump in the scroll buffer terminal_pane.toggle_search_wrap(); terminal_pane.search_down(); assert_snapshot!( "grid_copy_search_cursor_at_top", format!("{:?}", terminal_pane.grid) ); // Deactivate wrap again terminal_pane.toggle_search_wrap(); // Should be a no-op again terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_cursor_at_top", format!("{:?}", terminal_pane.grid) ); // Re-activate wrap again terminal_pane.toggle_search_wrap(); terminal_pane.search_up(); assert_snapshot!( "grid_copy_search_cursor_at_bottom", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_case_insensitive() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("quam"); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); // sensitivity off terminal_pane.toggle_search_case_sensitivity(); assert_snapshot!( "grid_copy_quam_insensitive_highlighted", format!("{:?}", terminal_pane.grid) ); // sensitivity on terminal_pane.toggle_search_case_sensitivity(); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); // Select one and check that we keep the current selection, // if it wasn't one that vanished terminal_pane.search_up(); assert_snapshot!( "grid_copy_quam_highlighted_cursor_bottom", format!("{:?}", terminal_pane.grid) ); // sensitivity off terminal_pane.toggle_search_case_sensitivity(); assert_snapshot!( "grid_copy_quam_insensitive_cursor_bottom", format!("{:?}", terminal_pane.grid) ); // sensitivity on terminal_pane.toggle_search_case_sensitivity(); assert_snapshot!( "grid_copy_quam_highlighted_cursor_bottom", format!("{:?}", terminal_pane.grid) ); // sensitivity off terminal_pane.toggle_search_case_sensitivity(); // Selecting the case insensitive result terminal_pane.search_up(); terminal_pane.search_up(); terminal_pane.search_up(); terminal_pane.search_up(); terminal_pane.search_up(); assert_snapshot!( "grid_copy_quam_insensitive_selection", format!("{:?}", terminal_pane.grid) ); // sensitivity on terminal_pane.toggle_search_case_sensitivity(); // Now the selected result vanished and we should be back at // the beginning assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); terminal_pane.search_up(); assert_snapshot!( "grid_copy_quam_highlighted_cursor_bottom", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_inside_and_scroll() { let fake_client_id = 1; let mut terminal_pane = create_pane(); terminal_pane.update_search_term("quam"); terminal_pane.search_up(); assert_snapshot!( "grid_copy_quam_highlighted_cursor_bottom", format!("{:?}", terminal_pane.grid) ); assert_eq!( terminal_pane.grid.search_results.active.as_ref(), terminal_pane.grid.search_results.selections.last() ); // Scrolling up until a new search result appears terminal_pane.scroll_up(4, fake_client_id); // Scrolling back down should give the same result as before terminal_pane.scroll_down(4, fake_client_id); assert_eq!( terminal_pane.grid.search_results.active.as_ref(), terminal_pane.grid.search_results.selections.last() ); assert_snapshot!( "grid_copy_quam_highlighted_cursor_bottom", format!("{:?}", terminal_pane.grid) ); // Scrolling up until a the active marker goes out of view terminal_pane.scroll_up(5, fake_client_id); assert_eq!(terminal_pane.grid.search_results.active, None); terminal_pane.scroll_down(5, fake_client_id); assert_eq!(terminal_pane.grid.search_results.active, None); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_and_resize() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("tortor"); assert_snapshot!( "grid_copy_tortor_highlighted", format!("{:?}", terminal_pane.grid) ); // Highlights should still be there, if pane gets resized terminal_pane.grid.change_size(20, 150); assert_snapshot!( "grid_copy_tortor_highlighted_wide", format!("{:?}", terminal_pane.grid) ); terminal_pane.grid.change_size(20, 80); assert_snapshot!( "grid_copy_tortor_highlighted_narrow", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_across_line_wrap() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("aliquam sem fringilla"); // Spread across two lines terminal_pane.grid.change_size(30, 60); assert_snapshot!( "grid_copy_multiline_highlighted", format!("{:?}", terminal_pane.grid) ); // Spread across 4 lines terminal_pane.grid.change_size(40, 4); assert_snapshot!( "grid_copy_multiline_highlighted_narrow", format!("{:?}", terminal_pane.grid) ); terminal_pane.search_up(); assert_snapshot!( "grid_copy_multiline_selected_narrow", format!("{:?}", terminal_pane.grid) ); // Wrap on terminal_pane.toggle_search_wrap(); terminal_pane.search_down(); assert_snapshot!( "grid_copy_multiline_selected_wrap_narrow", format!("{:?}", terminal_pane.grid) ); // Wrap off terminal_pane.toggle_search_wrap(); // Don't forget the current selection terminal_pane.search_up(); assert_snapshot!( "grid_copy_multiline_selected_wrap_narrow", format!("{:?}", terminal_pane.grid) ); // Wrap on terminal_pane.toggle_search_wrap(); terminal_pane.search_up(); assert_snapshot!( "grid_copy_multiline_selected_narrow", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_whole_word() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("quam"); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_whole_words(); assert_snapshot!( "grid_copy_quam_whole_word_only", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_whole_words(); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_whole_word_across_line_wrap() { let mut terminal_pane = create_pane(); terminal_pane.handle_pty_bytes( "a:--:aaaaaaaaa:--:--:--:aaaaaaaaaaa:--: :--: :--: aaa :--::--: aaa" .as_bytes() .to_vec(), ); terminal_pane.grid.change_size(20, 5); terminal_pane.update_search_term(":--:"); assert_snapshot!( "grid_copy_multiline_not_whole_word", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_whole_words(); assert_snapshot!( "grid_copy_multiline_whole_word", format!("{:?}", terminal_pane.grid) ); } #[test] pub fn searching_whole_word_case_insensitive() { let mut terminal_pane = create_pane(); terminal_pane.update_search_term("quam"); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_whole_words(); assert_snapshot!( "grid_copy_quam_whole_word_only", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_case_sensitivity(); assert_snapshot!( "grid_copy_quam_whole_word_case_insensitive", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_whole_words(); assert_snapshot!( "grid_copy_quam_insensitive_highlighted", format!("{:?}", terminal_pane.grid) ); terminal_pane.toggle_search_case_sensitivity(); assert_snapshot!( "grid_copy_quam_highlighted", format!("{:?}", terminal_pane.grid) ); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/unit/selection_tests.rs
zellij-server/src/panes/unit/selection_tests.rs
use super::*; #[test] fn selection_start() { let mut selection = Selection::default(); selection.start(Position::new(10, 10)); assert!(selection.active); assert_eq!(selection.start, Position::new(10, 10)); assert_eq!(selection.end, Position::new(10, 10)); } #[test] fn selection_to() { let mut selection = Selection::default(); selection.start(Position::new(10, 10)); let is_active = selection.active; selection.to(Position::new(20, 30)); assert_eq!(selection.active, is_active); assert_eq!(selection.end, Position::new(20, 30)); } #[test] fn selection_end() { let mut selection = Selection::default(); selection.start(Position::new(10, 10)); selection.end(Position::new(20, 30)); assert!(!selection.active); assert_eq!(selection.end, Position::new(20, 30)); } #[test] fn contains() { struct TestCase<'a> { selection: &'a Selection, position: Position, result: bool, } let selection = Selection { start: Position::new(10, 5), end: Position::new(40, 20), active: false, last_added_word_position: None, last_added_line_index: None, }; let test_cases = vec![ TestCase { selection: &selection, position: Position::new(10, 5), result: true, }, TestCase { selection: &selection, position: Position::new(10, 4), result: false, }, TestCase { selection: &selection, position: Position::new(20, 0), result: true, }, TestCase { selection: &selection, position: Position::new(20, 21), result: true, }, TestCase { selection: &selection, position: Position::new(40, 19), result: true, }, TestCase { selection: &selection, position: Position::new(40, 20), result: false, }, ]; for test_case in test_cases { let result = test_case.selection.contains( test_case.position.line.0 as usize, test_case.position.column.0, ); assert_eq!(result, test_case.result) } } #[test] fn sorted() { let selection = Selection { start: Position::new(1, 1), end: Position::new(10, 2), active: false, last_added_word_position: None, last_added_line_index: None, }; let sorted_selection = selection.sorted(); assert_eq!(selection.start, sorted_selection.start); assert_eq!(selection.end, sorted_selection.end); let selection = Selection { start: Position::new(10, 2), end: Position::new(1, 1), active: false, last_added_word_position: None, last_added_line_index: None, }; let sorted_selection = selection.sorted(); assert_eq!(selection.end, sorted_selection.start); assert_eq!(selection.start, sorted_selection.end); } #[test] fn line_indices() { let selection = Selection { start: Position::new(1, 1), end: Position::new(10, 2), active: false, last_added_word_position: None, last_added_line_index: None, }; assert_eq!(selection.line_indices(), (1..=10)) } #[test] fn move_up_inactive() { let start = Position::new(10, 1); let end = Position::new(20, 2); let mut inactive_selection = Selection { start, end, active: false, last_added_word_position: None, last_added_line_index: None, }; inactive_selection.move_up(2); assert_eq!(inactive_selection.start, Position::new(8, 1)); assert_eq!(inactive_selection.end, Position::new(18, 2)); inactive_selection.move_up(10); assert_eq!(inactive_selection.start, Position::new(-2, 1)); assert_eq!(inactive_selection.end, Position::new(8, 2)); } #[test] fn move_up_active() { let start = Position::new(10, 1); let end = Position::new(20, 2); let mut inactive_selection = Selection { start, end, active: true, last_added_word_position: None, last_added_line_index: None, }; inactive_selection.move_up(2); assert_eq!(inactive_selection.start, Position::new(8, 1)); assert_eq!(inactive_selection.end, end); } #[test] fn move_down_inactive() { let start = Position::new(10, 1); let end = Position::new(20, 2); let mut inactive_selection = Selection { start, end, active: false, last_added_word_position: None, last_added_line_index: None, }; inactive_selection.move_down(2); assert_eq!(inactive_selection.start, Position::new(12, 1)); assert_eq!(inactive_selection.end, Position::new(22, 2)); inactive_selection.move_down(10); assert_eq!(inactive_selection.start, Position::new(22, 1)); assert_eq!(inactive_selection.end, Position::new(32, 2)); } #[test] fn move_down_active() { let start = Position::new(10, 1); let end = Position::new(20, 2); let mut inactive_selection = Selection { start, end, active: true, last_added_word_position: None, last_added_line_index: None, }; inactive_selection.move_down(2); assert_eq!(inactive_selection.start, Position::new(12, 1)); assert_eq!(inactive_selection.end, end); } #[test] fn add_word_to_position_extend_line_above() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(10, 10); let last_word_end = Position::new(10, 15); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(9, 5); let word_end = Position::new(9, 6); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, word_start); assert_eq!(selection.end, selection_end); } #[test] fn add_word_to_position_extend_line_below() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(20, 15); let last_word_end = Position::new(20, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(21, 5); let word_end = Position::new(21, 6); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, selection_start); assert_eq!(selection.end, word_end); } #[test] fn add_word_to_position_reduce_from_above() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(10, 10); let last_word_end = Position::new(10, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(11, 5); let word_end = Position::new(11, 6); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, word_start); assert_eq!(selection.end, selection_end); } #[test] fn add_word_to_position_reduce_from_below() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(20, 10); let last_word_end = Position::new(20, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(19, 5); let word_end = Position::new(19, 6); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, selection_start); assert_eq!(selection.end, word_end); } #[test] fn add_word_to_position_extend_right() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(20, 10); let last_word_end = Position::new(20, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(20, 21); let word_end = Position::new(20, 23); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, selection_start); assert_eq!(selection.end, word_end); } #[test] fn add_word_to_position_extend_left() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(10, 10); let last_word_end = Position::new(10, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(10, 5); let word_end = Position::new(10, 9); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, word_start); assert_eq!(selection.end, selection_end); } #[test] fn add_word_to_position_reduce_from_left() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(10, 10); let last_word_end = Position::new(10, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(10, 20); let word_end = Position::new(10, 30); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, word_start); assert_eq!(selection.end, selection_end); } #[test] fn add_word_to_position_reduce_from_right() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_word_start = Position::new(20, 10); let last_word_end = Position::new(20, 20); let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: Some((last_word_start, last_word_end)), last_added_line_index: None, }; let word_start = Position::new(20, 5); let word_end = Position::new(20, 10); selection.add_word_to_position(word_start, word_end); assert_eq!(selection.start, selection_start); assert_eq!(selection.end, word_end); } #[test] fn add_line_to_position_extend_upwards() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_added_line_index = 10; let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: None, last_added_line_index: Some(last_added_line_index), }; let line_index_to_add = 9; let last_index_in_line = 21; selection.add_line_to_position(line_index_to_add, last_index_in_line); assert_eq!(selection.start, Position::new(line_index_to_add as i32, 0)); assert_eq!(selection.end, selection_end); } #[test] fn add_line_to_position_extend_downwards() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_added_line_index = 20; let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: None, last_added_line_index: Some(last_added_line_index), }; let line_index_to_add = 21; let last_index_in_line = 21; selection.add_line_to_position(line_index_to_add, last_index_in_line); assert_eq!(selection.start, selection_start); assert_eq!( selection.end, Position::new(line_index_to_add as i32, last_index_in_line as u16) ); } #[test] fn add_line_to_position_reduce_from_below() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_added_line_index = 20; let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: None, last_added_line_index: Some(last_added_line_index), }; let line_index_to_add = 19; let last_index_in_line = 21; selection.add_line_to_position(line_index_to_add, last_index_in_line); assert_eq!(selection.start, selection_start); assert_eq!( selection.end, Position::new(line_index_to_add as i32, last_index_in_line as u16) ); } #[test] fn add_line_to_position_reduce_from_above() { let selection_start = Position::new(10, 10); let selection_end = Position::new(20, 20); let last_added_line_index = 10; let mut selection = Selection { start: selection_start, end: selection_end, active: true, last_added_word_position: None, last_added_line_index: Some(last_added_line_index), }; let line_index_to_add = 9; let last_index_in_line = 21; selection.add_line_to_position(line_index_to_add, last_index_in_line); assert_eq!(selection.start, Position::new(line_index_to_add as i32, 0)); assert_eq!(selection.end, selection_end); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/unit/grid_tests.rs
zellij-server/src/panes/unit/grid_tests.rs
use super::super::Grid; use crate::panes::grid::SixelImageStore; use crate::panes::link_handler::LinkHandler; use ::insta::assert_snapshot; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use vte; use zellij_utils::{ data::{Palette, Style}, pane_size::SizeInPixels, position::Position, }; use std::fmt::Write; fn read_fixture(fixture_name: &str) -> Vec<u8> { let mut path_to_file = std::path::PathBuf::new(); path_to_file.push("../src"); path_to_file.push("tests"); path_to_file.push("fixtures"); path_to_file.push(fixture_name); std::fs::read(path_to_file) .unwrap_or_else(|_| panic!("could not read fixture {:?}", &fixture_name)) } #[test] fn vttest1_0() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest1-0"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest1_1() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest1-1"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest1_2() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest1-2"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest1_3() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest1-3"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest1_4() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest1-4"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest1_5() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest1-5"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_0() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-0"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_1() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-1"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_2() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-2"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_3() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-3"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_4() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-4"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_5() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-5"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_6() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-6"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_7() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-7"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_8() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-8"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_9() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-9"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_10() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-10"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_11() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-11"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_12() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-12"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_13() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-13"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest2_14() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest2-14"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest3_0() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 41, 110, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest3-0"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest8_0() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest8-0"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest8_1() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest8-1"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest8_2() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest8-2"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest8_3() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest8-3"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest8_4() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest8-4"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn vttest8_5() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "vttest8-5"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn csi_b() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "csi-b"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn csi_capital_i() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "csi-capital-i"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn csi_capital_z() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "csi-capital-z"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid)); } #[test] fn terminal_reports() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( 51, 97, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let fixture_name = "terminal_reports"; let content = read_fixture(fixture_name); for byte in content { vte_parser.advance(&mut grid, byte); } assert_snapshot!(format!("{:?}", grid.pending_messages_to_pty)); } #[test] fn wide_characters() { let mut vte_parser = vte::Parser::new(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/floating_panes/floating_pane_grid.rs
zellij-server/src/panes/floating_panes/floating_pane_grid.rs
use crate::tab::{MIN_TERMINAL_HEIGHT, MIN_TERMINAL_WIDTH}; use crate::{panes::PaneId, tab::Pane}; use std::cmp::Ordering; use std::collections::HashMap; use zellij_utils::data::{Direction, ResizeStrategy}; use zellij_utils::errors::prelude::*; use zellij_utils::pane_size::{Dimension, PaneGeom, Size, Viewport}; use std::cell::RefCell; use std::rc::Rc; const MOVE_INCREMENT_HORIZONTAL: usize = 10; const MOVE_INCREMENT_VERTICAL: usize = 5; const MAX_PANES: usize = 100; // For error reporting fn no_pane_id(pane_id: &PaneId) -> String { format!("no floating pane with ID {:?} found", pane_id) } pub struct FloatingPaneGrid<'a> { panes: Rc<RefCell<HashMap<PaneId, &'a mut Box<dyn Pane>>>>, desired_pane_positions: Rc<RefCell<&'a mut HashMap<PaneId, PaneGeom>>>, display_area: Size, // includes all panes (including eg. the status bar and tab bar in the default layout) viewport: Viewport, // includes all non-UI panes } impl<'a> FloatingPaneGrid<'a> { pub fn new( panes: impl IntoIterator<Item = (&'a PaneId, &'a mut Box<dyn Pane>)>, desired_pane_positions: &'a mut HashMap<PaneId, PaneGeom>, display_area: Size, viewport: Viewport, ) -> Self { let panes: HashMap<_, _> = panes.into_iter().map(|(p_id, p)| (*p_id, p)).collect(); FloatingPaneGrid { panes: Rc::new(RefCell::new(panes)), desired_pane_positions: Rc::new(RefCell::new(desired_pane_positions)), display_area, viewport, } } pub fn move_pane_by(&mut self, pane_id: PaneId, x: isize, y: isize) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} by ({x}, {y})"); // true => succeeded to move, false => failed to move let new_pane_position = { let mut panes = self.panes.borrow_mut(); let pane = panes .iter_mut() .find(|(p_id, _p)| **p_id == pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)? .1; let mut new_pane_position = pane.position_and_size(); let min_x = self.viewport.x as isize; let min_y = self.viewport.y as isize; let max_x = (self.viewport.cols + self.viewport.x) .saturating_sub(new_pane_position.cols.as_usize()); let max_y = (self.viewport.rows + self.viewport.y) .saturating_sub(new_pane_position.rows.as_usize()); let new_x = std::cmp::max(min_x, new_pane_position.x as isize + x); let new_x = std::cmp::min(new_x, max_x as isize); let new_y = std::cmp::max(min_y, new_pane_position.y as isize + y); let new_y = std::cmp::min(new_y, max_y as isize); new_pane_position.x = new_x as usize; new_pane_position.y = new_y as usize; new_pane_position }; self.set_pane_geom(pane_id, new_pane_position) .with_context(err_context) } fn set_pane_geom(&mut self, pane_id: PaneId, new_pane_geom: PaneGeom) -> Result<()> { let err_context = || { format!( "failed to set pane {pane_id:?} geometry to {:?}", new_pane_geom ) }; let mut panes = self.panes.borrow_mut(); let pane = panes .iter_mut() .find(|(p_id, _p)| **p_id == pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)? .1; pane.set_geom(new_pane_geom); let mut desired_pane_positions = self.desired_pane_positions.borrow_mut(); desired_pane_positions.insert(pane_id, new_pane_geom); Ok(()) } pub fn resize(&mut self, space: Size) -> Result<()> { let err_context = || { format!( "failed to resize from {:?} to {:?}", self.display_area, space ) }; let mut panes = self.panes.borrow_mut(); let desired_pane_positions = self.desired_pane_positions.borrow(); // account for the difference between the viewport (including non-ui pane items which we // do not want to override) and the display_area, which is the area we can go over let display_size_row_difference = self.display_area.rows.saturating_sub(self.viewport.rows); let display_size_column_difference = self.display_area.cols.saturating_sub(self.viewport.cols); let mut new_viewport = self.viewport; new_viewport.cols = space.cols.saturating_sub(display_size_column_difference); new_viewport.rows = space.rows.saturating_sub(display_size_row_difference); for (pane_id, pane) in panes.iter_mut() { let mut new_pane_geom = pane.current_geom(); let desired_pane_geom = desired_pane_positions .get(pane_id) .with_context(|| { format!( "failed to acquire desired pane geometry for pane {:?}", pane_id ) }) .with_context(err_context)?; let desired_pane_geom_is_inside_viewport = pane_geom_is_inside_viewport(&new_viewport, desired_pane_geom); let pane_is_in_desired_position = new_pane_geom == *desired_pane_geom; if pane_is_in_desired_position && desired_pane_geom_is_inside_viewport { continue; } else if desired_pane_geom_is_inside_viewport { pane.set_geom(*desired_pane_geom); } else { let pane_right_side = new_pane_geom.x + new_pane_geom.cols.as_usize(); let pane_bottom_side = new_pane_geom.y + new_pane_geom.rows.as_usize(); let viewport_right_side = new_viewport.x + new_viewport.cols; let viewport_bottom_side = new_viewport.y + new_viewport.rows; let excess_width = pane_right_side.saturating_sub(viewport_right_side); let excess_height = pane_bottom_side.saturating_sub(viewport_bottom_side); let extra_width = viewport_right_side.saturating_sub(pane_right_side); let extra_height = viewport_bottom_side.saturating_sub(pane_bottom_side); // handle shrink width if excess_width > 0 && new_pane_geom.x.saturating_sub(excess_width) > new_viewport.x { new_pane_geom.x = new_pane_geom.x.saturating_sub(excess_width); } else if excess_width > 0 && new_pane_geom.cols.as_usize().saturating_sub(excess_width) > MIN_TERMINAL_WIDTH { new_pane_geom .cols .set_inner(new_pane_geom.cols.as_usize().saturating_sub(excess_width)); } else if excess_width > 0 { let reduce_x_by = new_pane_geom.x.saturating_sub(new_viewport.x); let reduced_width = new_pane_geom .cols .as_usize() .saturating_sub(excess_width.saturating_sub(reduce_x_by)); new_pane_geom.x = new_viewport.x; new_pane_geom .cols .set_inner(std::cmp::max(reduced_width, MIN_TERMINAL_WIDTH)); } // handle shrink height if excess_height > 0 && new_pane_geom.y.saturating_sub(excess_height) > new_viewport.y { new_pane_geom.y = new_pane_geom.y.saturating_sub(excess_height); } else if excess_height > 0 && new_pane_geom.rows.as_usize().saturating_sub(excess_height) > MIN_TERMINAL_HEIGHT { new_pane_geom .rows .set_inner(new_pane_geom.rows.as_usize().saturating_sub(excess_height)); } else if excess_height > 0 { let reduce_y_by = new_pane_geom.y.saturating_sub(new_viewport.y); let reduced_height = new_pane_geom .rows .as_usize() .saturating_sub(excess_height.saturating_sub(reduce_y_by)); new_pane_geom.y = new_viewport.y; new_pane_geom .rows .set_inner(std::cmp::max(reduced_height, MIN_TERMINAL_HEIGHT)); } // handle expand width if extra_width > 0 { let max_right_coords = new_viewport.x + new_viewport.cols; if new_pane_geom.x < desired_pane_geom.x { if desired_pane_geom.x + new_pane_geom.cols.as_usize() <= max_right_coords { new_pane_geom.x = desired_pane_geom.x } else if new_pane_geom.x + new_pane_geom.cols.as_usize() + extra_width < max_right_coords { new_pane_geom.x += extra_width; } else { new_pane_geom.x = max_right_coords.saturating_sub(new_pane_geom.cols.as_usize()); } } if new_pane_geom.cols.as_usize() < desired_pane_geom.cols.as_usize() { if new_pane_geom.x + desired_pane_geom.cols.as_usize() <= max_right_coords { new_pane_geom .cols .set_inner(desired_pane_geom.cols.as_usize()); } else if new_pane_geom.x + new_pane_geom.cols.as_usize() + extra_width < max_right_coords { new_pane_geom .cols .set_inner(new_pane_geom.cols.as_usize() + extra_width); } else { new_pane_geom.cols.set_inner( new_pane_geom.cols.as_usize() + (max_right_coords - (new_pane_geom.x + new_pane_geom.cols.as_usize())), ); } } } // handle expand height if extra_height > 0 { let max_bottom_coords = new_viewport.y + new_viewport.rows; if new_pane_geom.y < desired_pane_geom.y { if desired_pane_geom.y + new_pane_geom.rows.as_usize() <= max_bottom_coords { new_pane_geom.y = desired_pane_geom.y } else if new_pane_geom.y + new_pane_geom.rows.as_usize() + extra_height < max_bottom_coords { new_pane_geom.y += extra_height; } else { new_pane_geom.y = max_bottom_coords.saturating_sub(new_pane_geom.rows.as_usize()); } } if new_pane_geom.rows.as_usize() < desired_pane_geom.rows.as_usize() { if new_pane_geom.y + desired_pane_geom.rows.as_usize() <= max_bottom_coords { new_pane_geom .rows .set_inner(desired_pane_geom.rows.as_usize()); } else if new_pane_geom.y + new_pane_geom.rows.as_usize() + extra_height < max_bottom_coords { new_pane_geom .rows .set_inner(new_pane_geom.rows.as_usize() + extra_height); } else { new_pane_geom.rows.set_inner( new_pane_geom.rows.as_usize() + (max_bottom_coords - (new_pane_geom.y + new_pane_geom.rows.as_usize())), ); } } } pane.set_geom(new_pane_geom); } } Ok(()) } pub fn move_pane_left(&mut self, pane_id: &PaneId) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} left"); if let Some(move_by) = self .can_move_pane_left(pane_id, MOVE_INCREMENT_HORIZONTAL) .with_context(err_context)? { self.move_pane_position_left(pane_id, move_by) .with_context(err_context)?; } Ok(()) } pub fn move_pane_right(&mut self, pane_id: &PaneId) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} right"); if let Some(move_by) = self .can_move_pane_right(pane_id, MOVE_INCREMENT_HORIZONTAL) .with_context(err_context)? { self.move_pane_position_right(pane_id, move_by) .with_context(err_context)?; } Ok(()) } pub fn move_pane_down(&mut self, pane_id: &PaneId) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} down"); if let Some(move_by) = self .can_move_pane_down(pane_id, MOVE_INCREMENT_VERTICAL) .with_context(err_context)? { self.move_pane_position_down(pane_id, move_by) .with_context(err_context)?; } Ok(()) } pub fn move_pane_up(&mut self, pane_id: &PaneId) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} up"); if let Some(move_by) = self .can_move_pane_up(pane_id, MOVE_INCREMENT_VERTICAL) .with_context(err_context)? { self.move_pane_position_up(pane_id, move_by) .with_context(err_context)?; } Ok(()) } fn can_move_pane_left(&self, pane_id: &PaneId, move_by: usize) -> Result<Option<usize>> { let err_context = || { format!( "failed to determine if pane {pane_id:?} can be moved left by {move_by} columns" ) }; let panes = self.panes.borrow(); let pane = panes .get(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let space_until_left_screen_edge = pane.x().saturating_sub(self.viewport.x); Ok(if space_until_left_screen_edge >= move_by { Some(move_by) } else if space_until_left_screen_edge > 0 { Some(space_until_left_screen_edge) } else { None }) } fn can_move_pane_right(&self, pane_id: &PaneId, move_by: usize) -> Result<Option<usize>> { let err_context = || { format!( "failed to determine if pane {pane_id:?} can be moved right by {move_by} columns" ) }; let panes = self.panes.borrow(); let pane = panes .get(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let space_until_right_screen_edge = (self.viewport.x + self.viewport.cols).saturating_sub(pane.x() + pane.cols()); Ok(if space_until_right_screen_edge >= move_by { Some(move_by) } else if space_until_right_screen_edge > 0 { Some(space_until_right_screen_edge) } else { None }) } fn can_move_pane_up(&self, pane_id: &PaneId, move_by: usize) -> Result<Option<usize>> { let err_context = || format!("failed to determine if pane {pane_id:?} can be moved up by {move_by} rows"); let panes = self.panes.borrow(); let pane = panes .get(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let space_until_top_screen_edge = pane.y().saturating_sub(self.viewport.y); Ok(if space_until_top_screen_edge >= move_by { Some(move_by) } else if space_until_top_screen_edge > 0 { Some(space_until_top_screen_edge) } else { None }) } fn can_move_pane_down(&self, pane_id: &PaneId, move_by: usize) -> Result<Option<usize>> { let err_context = || { format!("failed to determine if pane {pane_id:?} can be moved down by {move_by} rows") }; let panes = self.panes.borrow(); let pane = panes .get(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let space_until_bottom_screen_edge = (self.viewport.y + self.viewport.rows).saturating_sub(pane.y() + pane.rows()); Ok(if space_until_bottom_screen_edge >= move_by { Some(move_by) } else if space_until_bottom_screen_edge > 0 { Some(space_until_bottom_screen_edge) } else { None }) } fn move_pane_position_left(&mut self, pane_id: &PaneId, move_by: usize) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} left by {move_by}"); let new_pane_geom = { let mut panes = self.panes.borrow_mut(); let pane = panes .get_mut(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let mut current_geom = pane.position_and_size(); current_geom.x -= move_by; current_geom }; self.set_pane_geom(*pane_id, new_pane_geom) .with_context(err_context) } fn move_pane_position_right(&mut self, pane_id: &PaneId, move_by: usize) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} right by {move_by}"); let new_pane_geom = { let mut panes = self.panes.borrow_mut(); let pane = panes .get_mut(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let mut current_geom = pane.position_and_size(); current_geom.x += move_by; current_geom }; self.set_pane_geom(*pane_id, new_pane_geom) .with_context(err_context) } fn move_pane_position_down(&mut self, pane_id: &PaneId, move_by: usize) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} down by {move_by}"); let new_pane_geom = { let mut panes = self.panes.borrow_mut(); let pane = panes .get_mut(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let mut current_geom = pane.position_and_size(); current_geom.y += move_by; current_geom }; self.set_pane_geom(*pane_id, new_pane_geom) .with_context(err_context) } fn move_pane_position_up(&mut self, pane_id: &PaneId, move_by: usize) -> Result<()> { let err_context = || format!("failed to move pane {pane_id:?} up by {move_by}"); let new_pane_geom = { let mut panes = self.panes.borrow_mut(); let pane = panes .get_mut(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)?; let mut current_geom = pane.position_and_size(); current_geom.y -= move_by; current_geom }; self.set_pane_geom(*pane_id, new_pane_geom) .with_context(err_context) } pub fn change_pane_size( &mut self, pane_id: &PaneId, strategy: &ResizeStrategy, change_by: (usize, usize), // (x, y) ) -> Result<()> { let err_context = || format!("failed to {strategy} for pane {pane_id:?}"); let mut geometry = self .panes .borrow() .get(pane_id) .with_context(|| no_pane_id(&pane_id)) .with_context(err_context)? .position_and_size(); let change_by = if strategy.direction.is_none() { (change_by.0 / 2, change_by.1 / 2) } else { change_by }; // Move left border if strategy.move_left_border_left() || strategy.move_all_borders_out() { let increment = std::cmp::min(geometry.x.saturating_sub(self.viewport.x), change_by.0); // Invert if on boundary already if increment == 0 && strategy.direction.is_some() { return self.change_pane_size(pane_id, &strategy.invert(), change_by); } geometry.x -= increment; geometry .cols .set_inner(geometry.cols.as_usize() + increment); } else if strategy.move_left_border_right() || strategy.move_all_borders_in() { let increment = std::cmp::min( geometry.cols.as_usize().saturating_sub(MIN_TERMINAL_WIDTH), change_by.0, ); geometry.x += increment; geometry .cols .set_inner(geometry.cols.as_usize() - increment); }; // Move right border if strategy.move_right_border_right() || strategy.move_all_borders_out() { let increment = std::cmp::min( (self.viewport.x + self.viewport.cols) .saturating_sub(geometry.x + geometry.cols.as_usize()), change_by.0, ); // Invert if on boundary already if increment == 0 && strategy.direction.is_some() { return self.change_pane_size(pane_id, &strategy.invert(), change_by); } geometry .cols .set_inner(geometry.cols.as_usize() + increment); } else if strategy.move_right_border_left() || strategy.move_all_borders_in() { let increment = std::cmp::min( geometry.cols.as_usize().saturating_sub(MIN_TERMINAL_WIDTH), change_by.0, ); geometry .cols .set_inner(geometry.cols.as_usize() - increment); }; // Move upper border if strategy.move_upper_border_up() || strategy.move_all_borders_out() { let increment = std::cmp::min(geometry.y.saturating_sub(self.viewport.y), change_by.1); // Invert if on boundary already if increment == 0 && strategy.direction.is_some() { return self.change_pane_size(pane_id, &strategy.invert(), change_by); } geometry.y -= increment; geometry .rows .set_inner(geometry.rows.as_usize() + increment); } else if strategy.move_upper_border_down() || strategy.move_all_borders_in() { let increment = std::cmp::min( geometry.rows.as_usize().saturating_sub(MIN_TERMINAL_HEIGHT), change_by.1, ); geometry.y += increment; geometry .rows .set_inner(geometry.rows.as_usize() - increment); } // Move lower border if strategy.move_lower_border_down() || strategy.move_all_borders_out() { let increment = std::cmp::min( (self.viewport.y + self.viewport.rows) .saturating_sub(geometry.y + geometry.rows.as_usize()), change_by.1, ); // Invert if on boundary already if increment == 0 && strategy.direction.is_some() { return self.change_pane_size(pane_id, &strategy.invert(), change_by); } geometry .rows .set_inner(geometry.rows.as_usize() + increment); } else if strategy.move_lower_border_up() || strategy.move_all_borders_in() { let increment = std::cmp::min( geometry.rows.as_usize().saturating_sub(MIN_TERMINAL_HEIGHT), change_by.1, ); geometry .rows .set_inner(geometry.rows.as_usize() - increment); } self.set_pane_geom(*pane_id, geometry) .with_context(err_context) } pub fn next_selectable_pane_id_to_the_left(&self, current_pane_id: &PaneId) -> Option<PaneId> { let panes = self.panes.borrow(); let current_pane = panes.get(current_pane_id)?; let panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); let next_index = panes .iter() .enumerate() .filter(|(_, (_, c))| { c.is_left_of(Box::as_ref(current_pane)) && c.horizontally_overlaps_with(Box::as_ref(current_pane)) }) .max_by(|(_, (_, a)), (_, (_, b))| { let x_comparison = a.x().cmp(&b.x()); match x_comparison { Ordering::Equal => a.y().cmp(&b.y()), _ => x_comparison, } }) .map(|(_, (pid, _))| pid) .copied(); next_index } pub fn pane_id_on_edge(&self, direction: Direction) -> Option<PaneId> { let panes = self.panes.borrow(); let panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); let next_index = panes .iter() .enumerate() .max_by(|(_, (_, a)), (_, (_, b))| match direction { Direction::Left => { let x_comparison = a.x().cmp(&b.x()); match x_comparison { Ordering::Equal => a.y().cmp(&b.y()), _ => x_comparison, } }, Direction::Right => { let x_comparison = b.x().cmp(&a.x()); match x_comparison { Ordering::Equal => a.y().cmp(&b.y()), _ => x_comparison, } }, Direction::Up => { let y_comparison = a.y().cmp(&b.y()); match y_comparison { Ordering::Equal => a.x().cmp(&b.x()), _ => y_comparison, } }, Direction::Down => { let y_comparison = b.y().cmp(&a.y()); match y_comparison { Ordering::Equal => b.x().cmp(&a.x()), _ => y_comparison, } }, }) .map(|(_, (pid, _))| pid) .copied(); next_index } pub fn next_selectable_pane_id_below(&self, current_pane_id: &PaneId) -> Option<PaneId> { let panes = self.panes.borrow(); let current_pane = panes.get(current_pane_id)?; let panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); let next_index = panes .iter() .enumerate() .filter(|(_, (_, c))| { c.is_below(Box::as_ref(current_pane)) && c.vertically_overlaps_with(Box::as_ref(current_pane)) }) .min_by(|(_, (_, a)), (_, (_, b))| { let y_comparison = a.y().cmp(&b.y()); match y_comparison { Ordering::Equal => b.x().cmp(&a.x()), _ => y_comparison, } }) .map(|(_, (pid, _))| pid) .copied(); next_index } pub fn next_selectable_pane_id_above(&self, current_pane_id: &PaneId) -> Option<PaneId> { let panes = self.panes.borrow(); let current_pane = panes.get(current_pane_id)?; let panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); let next_index = panes .iter() .enumerate() .filter(|(_, (_, c))| { c.is_above(Box::as_ref(current_pane)) && c.vertically_overlaps_with(Box::as_ref(current_pane)) }) .max_by(|(_, (_, a)), (_, (_, b))| { let y_comparison = a.y().cmp(&b.y()); match y_comparison { Ordering::Equal => b.x().cmp(&a.x()), _ => y_comparison, } }) .map(|(_, (pid, _))| pid) .copied(); next_index } pub fn next_selectable_pane_id_to_the_right(&self, current_pane_id: &PaneId) -> Option<PaneId> { let panes = self.panes.borrow(); let current_pane = panes.get(current_pane_id)?; let panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); let next_index = panes .iter() .enumerate() .filter(|(_, (_, c))| { c.is_right_of(Box::as_ref(current_pane)) && c.horizontally_overlaps_with(Box::as_ref(current_pane)) }) .min_by(|(_, (_, a)), (_, (_, b))| { let x_comparison = a.x().cmp(&b.x()); match x_comparison { Ordering::Equal => a.y().cmp(&b.y()), _ => x_comparison, } }) .map(|(_, (pid, _))| pid) .copied(); next_index } pub fn next_selectable_pane_id(&self, current_pane_id: &PaneId) -> Option<PaneId> { let panes = self.panes.borrow(); let mut panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); panes.sort_by(|(_a_id, a_pane), (_b_id, b_pane)| { if a_pane.y() == b_pane.y() { a_pane.x().cmp(&b_pane.x()) } else { a_pane.y().cmp(&b_pane.y()) } }); let active_pane_position = panes.iter().position(|(id, _)| id == current_pane_id)?; let next_active_pane_id = panes .get(active_pane_position + 1) .or_else(|| panes.get(0)) .map(|p| p.0)?; Some(next_active_pane_id) } pub fn previous_selectable_pane_id(&self, current_pane_id: &PaneId) -> Option<PaneId> { let panes = self.panes.borrow(); let mut panes: Vec<(PaneId, &&mut Box<dyn Pane>)> = panes .iter() .filter(|(_, p)| p.selectable()) .map(|(p_id, p)| (*p_id, p)) .collect(); panes.sort_by(|(_a_id, a_pane), (_b_id, b_pane)| { if a_pane.y() == b_pane.y() { a_pane.x().cmp(&b_pane.x()) } else { a_pane.y().cmp(&b_pane.y()) } }); let active_pane_position = panes.iter().position(|(id, _)| id == current_pane_id)?; let last_pane = panes.last()?; let previous_active_pane_id = if active_pane_position == 0 { last_pane.0 } else { panes.get(active_pane_position - 1)?.0 }; Some(previous_active_pane_id) } pub fn find_room_for_new_pane(&self) -> Option<PaneGeom> { let panes = self.panes.borrow(); let pane_geoms: Vec<PaneGeom> = panes.values().map(|p| p.position_and_size()).collect(); macro_rules! find_unoccupied_offset { ($get_geom_with_offset:expr, $viewport:expr, $other_geoms:expr) => { let mut offset = 0; loop {
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/floating_panes/mod.rs
zellij-server/src/panes/floating_panes/mod.rs
pub mod floating_pane_grid; use zellij_utils::{ data::{Direction, FloatingPaneCoordinates, PaneInfo, ResizeStrategy}, position::Position, }; use crate::resize_pty; use crate::tab::{pane_info_for_pane, Pane}; use floating_pane_grid::FloatingPaneGrid; use crate::{ os_input_output::ServerOsApi, output::{FloatingPanesStack, Output}, panes::{ActivePanes, PaneId}, plugins::PluginInstruction, thread_bus::ThreadSenders, ui::pane_contents_and_ui::PaneContentsAndUi, ClientId, }; use std::cell::RefCell; use std::cmp::Ordering; use std::collections::{BTreeMap, HashMap, HashSet}; use std::rc::Rc; use std::time::Instant; use zellij_utils::{ data::{ModeInfo, Style, Styling}, errors::prelude::*, input::command::RunCommand, input::layout::{FloatingPaneLayout, Run, RunPluginOrAlias}, pane_size::{Dimension, Offset, PaneGeom, Size, SizeInPixels, Viewport}, }; const RESIZE_INCREMENT_WIDTH: usize = 5; const RESIZE_INCREMENT_HEIGHT: usize = 2; pub struct FloatingPanes { panes: BTreeMap<PaneId, Box<dyn Pane>>, display_area: Rc<RefCell<Size>>, viewport: Rc<RefCell<Viewport>>, connected_clients: Rc<RefCell<HashSet<ClientId>>>, connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client mode_info: Rc<RefCell<HashMap<ClientId, ModeInfo>>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, default_mode_info: ModeInfo, style: Style, session_is_mirrored: bool, desired_pane_positions: HashMap<PaneId, PaneGeom>, // this represents the positions of panes the user moved with intention, rather than by resizing the terminal window z_indices: Vec<PaneId>, active_panes: ActivePanes, show_panes: bool, pane_being_moved_with_mouse: Option<(PaneId, Position)>, senders: ThreadSenders, window_title: Option<String>, } #[allow(clippy::borrowed_box)] #[allow(clippy::too_many_arguments)] impl FloatingPanes { pub fn new( display_area: Rc<RefCell<Size>>, viewport: Rc<RefCell<Viewport>>, connected_clients: Rc<RefCell<HashSet<ClientId>>>, connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client mode_info: Rc<RefCell<HashMap<ClientId, ModeInfo>>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, session_is_mirrored: bool, default_mode_info: ModeInfo, style: Style, os_input: Box<dyn ServerOsApi>, senders: ThreadSenders, ) -> Self { FloatingPanes { panes: BTreeMap::new(), display_area, viewport, connected_clients, connected_clients_in_app, mode_info, character_cell_size, session_is_mirrored, default_mode_info, style, desired_pane_positions: HashMap::new(), z_indices: vec![], show_panes: false, active_panes: ActivePanes::new(&os_input), pane_being_moved_with_mouse: None, senders, window_title: None, } } pub fn stack(&self) -> Option<FloatingPanesStack> { if self.panes_are_visible() { let layers: Vec<PaneGeom> = self .z_indices .iter() .filter_map(|pane_id| self.panes.get(pane_id).map(|p| p.position_and_size())) .collect(); if layers.is_empty() { None } else { Some(FloatingPanesStack { layers }) } } else if self.has_pinned_panes() { let layers = self .z_indices .iter() .filter_map(|pane_id| { self.panes .get(pane_id) .map(|p| p.position_and_size()) .and_then(|p| if p.is_pinned { Some(p) } else { None }) }) .collect(); Some(FloatingPanesStack { layers }) } else { None } } pub fn has_pinned_panes(&self) -> bool { self.panes .iter() .any(|(_, p)| p.position_and_size().is_pinned) } pub fn pane_ids(&self) -> impl Iterator<Item = &PaneId> { self.panes.keys() } pub fn add_pane(&mut self, pane_id: PaneId, pane: Box<dyn Pane>) { self.desired_pane_positions .insert(pane_id, pane.position_and_size()); self.panes.insert(pane_id, pane); self.z_indices.push(pane_id); self.make_sure_pinned_panes_are_on_top(); } pub fn replace_active_pane( &mut self, pane: Box<dyn Pane>, client_id: ClientId, ) -> Result<Box<dyn Pane>> { self.active_panes .get(&client_id) .with_context(|| format!("failed to determine active pane for client {client_id}")) .copied() .and_then(|active_pane_id| self.replace_pane(active_pane_id, pane)) .with_context(|| format!("failed to replace active pane for client {client_id}")) } pub fn replace_pane( &mut self, pane_id: PaneId, mut with_pane: Box<dyn Pane>, ) -> Result<Box<dyn Pane>> { let err_context = || format!("failed to replace pane {pane_id:?} with pane"); let with_pane_id = with_pane.pid(); with_pane.set_content_offset(Offset::frame(1)); let removed_pane = self .panes .remove(&pane_id) .with_context(|| format!("failed to remove unknown pane with ID {pane_id:?}")) .and_then(|removed_pane| { let removed_pane_id = removed_pane.pid(); let with_pane_id = with_pane.pid(); let removed_pane_geom = removed_pane.current_geom(); with_pane.set_geom(removed_pane_geom); self.panes.insert(with_pane_id, with_pane); let z_index = self .z_indices .iter() .position(|pane_id| pane_id == &removed_pane_id) .context("no z-index found for pane to be removed with ID {removed_pane_id:?}") .with_context(err_context)?; self.z_indices.remove(z_index); self.z_indices.insert(z_index, with_pane_id); self.make_sure_pinned_panes_are_on_top(); Ok(removed_pane) }); // update the desired_pane_positions to relate to the new pane if let Some(desired_pane_position) = self.desired_pane_positions.remove(&pane_id) { self.desired_pane_positions .insert(with_pane_id, desired_pane_position); } // move clients from the previously active pane to the new pane we just inserted self.move_clients_between_panes(pane_id, with_pane_id); let _ = self.set_pane_frames(); removed_pane } pub fn remove_pane(&mut self, pane_id: PaneId) -> Option<Box<dyn Pane>> { self.z_indices.retain(|p_id| *p_id != pane_id); self.desired_pane_positions.remove(&pane_id); self.panes.remove(&pane_id) } pub fn hold_pane( &mut self, pane_id: PaneId, exit_status: Option<i32>, is_first_run: bool, run_command: RunCommand, ) { self.panes .get_mut(&pane_id) .map(|p| p.hold(exit_status, is_first_run, run_command)); } pub fn get(&self, pane_id: &PaneId) -> Option<&Box<dyn Pane>> { self.panes.get(pane_id) } pub fn get_mut(&mut self, pane_id: &PaneId) -> Option<&mut Box<dyn Pane>> { self.panes.get_mut(pane_id) } pub fn get_active_pane(&self, client_id: ClientId) -> Option<&Box<dyn Pane>> { self.active_panes .get(&client_id) .and_then(|active_pane_id| self.panes.get(active_pane_id)) } pub fn get_active_pane_mut(&mut self, client_id: ClientId) -> Option<&mut Box<dyn Pane>> { self.active_panes .get(&client_id) .and_then(|active_pane_id| self.panes.get_mut(active_pane_id)) } pub fn panes_are_visible(&self) -> bool { self.show_panes } pub fn has_active_panes(&self) -> bool { !self.active_panes.is_empty() } pub fn has_panes(&self) -> bool { !self.panes.is_empty() } pub fn active_pane_id(&self, client_id: ClientId) -> Option<PaneId> { self.active_panes.get(&client_id).copied() } pub fn active_pane_id_or_focused_pane_id(&self, client_id: Option<ClientId>) -> Option<PaneId> { // returns the focused pane of any client_id - should be safe because the way things are // set up at the time of writing, all clients are focused on the same floating pane due to // z_index issues client_id .and_then(|client_id| self.active_panes.get(&client_id).copied()) .or_else(|| self.panes.keys().next().copied()) } pub fn toggle_show_panes(&mut self, should_show_floating_panes: bool) { self.window_title = None; // clear so that it will be re-rendered once we toggle back self.show_panes = should_show_floating_panes; if should_show_floating_panes { self.active_panes.focus_all_panes(&mut self.panes); } else { self.active_panes.unfocus_all_panes(&mut self.panes); } } pub fn active_panes_contain(&self, client_id: &ClientId) -> bool { self.active_panes.contains_key(client_id) } pub fn panes_contain(&self, pane_id: &PaneId) -> bool { self.panes.contains_key(pane_id) } pub fn find_room_for_new_pane(&mut self) -> Option<PaneGeom> { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid.find_room_for_new_pane() } pub fn move_client_focus_to_existing_panes(&mut self) { let existing_pane_ids: Vec<PaneId> = self.panes.keys().copied().collect(); let nonexisting_panes_that_are_focused = self .active_panes .values() .filter(|pane_id| !existing_pane_ids.contains(pane_id)) .copied() .collect::<Vec<_>>(); for pane_id in nonexisting_panes_that_are_focused { self.move_clients_out_of_pane(pane_id); } } pub fn position_floating_pane_layout( &mut self, floating_pane_layout: &FloatingPaneLayout, ) -> Result<PaneGeom> { let err_context = || format!("failed to find position for floating pane"); let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); let mut position = floating_pane_grid .find_room_for_new_pane() .with_context(err_context)?; if let Some(x) = &floating_pane_layout.x { position.x = x.to_position(viewport.cols); } if let Some(y) = &floating_pane_layout.y { position.y = y.to_position(viewport.rows); } if let Some(width) = &floating_pane_layout.width { position.cols = Dimension::fixed(width.to_position(viewport.cols)); } if let Some(height) = &floating_pane_layout.height { position.rows = Dimension::fixed(height.to_position(viewport.rows)); } if let Some(is_pinned) = &floating_pane_layout.pinned { position.is_pinned = *is_pinned; } if let Some(logical_position) = &floating_pane_layout.logical_position { position.logical_position = Some(*logical_position); } if position.cols.as_usize() > viewport.cols { position.cols = Dimension::fixed(viewport.cols); } if position.rows.as_usize() > viewport.rows { position.rows = Dimension::fixed(viewport.rows); } if position.x + position.cols.as_usize() > viewport.cols { position.x = position .x .saturating_sub((position.x + position.cols.as_usize()) - viewport.cols); } if position.y + position.rows.as_usize() > viewport.rows { position.y = position .y .saturating_sub((position.y + position.rows.as_usize()) - viewport.rows); } Ok(position) } pub fn first_floating_pane_id(&self) -> Option<PaneId> { self.panes.keys().next().copied() } pub fn last_floating_pane_id(&self) -> Option<PaneId> { self.panes.keys().last().copied() } pub fn last_selectable_floating_pane_id(&self) -> Option<PaneId> { self.panes .iter() .filter(|(_p_id, p)| p.selectable()) .last() .map(|(p_id, _p)| *p_id) } pub fn has_selectable_panes(&self) -> bool { self.panes .iter() .filter(|(_p_id, p)| p.selectable()) .last() .is_some() } pub fn first_active_floating_pane_id(&self) -> Option<PaneId> { self.active_panes.values().next().copied() } pub fn set_force_render(&mut self) { for pane in self.panes.values_mut() { pane.set_should_render(true); pane.set_should_render_boundaries(true); pane.render_full_viewport(); } } pub fn set_pane_frames(&mut self) -> Result<()> { let err_context = |pane_id: &PaneId| format!("failed to activate frame on pane {pane_id:?}"); for pane in self.panes.values_mut() { // floating panes should always have a frame unless explicitly set otherwise if !pane.borderless() { pane.set_frame(true); pane.set_content_offset(Offset::frame(1)); } else { pane.set_content_offset(Offset::default()); } resize_pty!(pane, os_api, self.senders, self.character_cell_size) .with_context(|| err_context(&pane.pid()))?; } Ok(()) } pub fn render( &mut self, output: &mut Output, mouse_hover_pane_id: &HashMap<ClientId, PaneId>, current_pane_group: HashMap<ClientId, Vec<PaneId>>, client_id_override: Option<ClientId>, ) -> Result<()> { let err_context = || "failed to render output"; let mut connected_clients: HashSet<ClientId> = { self.connected_clients.borrow().iter().copied().collect() }; // If we have a client_id_override (for watcher rendering), add it temporarily if let Some(override_id) = client_id_override { connected_clients.insert(override_id); } let connected_clients: Vec<ClientId> = connected_clients.into_iter().collect(); let active_panes = if self.panes_are_visible() { self.active_panes.clone_active_panes() } else { Default::default() }; for (kind, pane) in &self.panes { match kind { PaneId::Terminal(_) => { output.add_pane_contents( &connected_clients, pane.pid(), pane.pane_contents(None, false), ); }, PaneId::Plugin(_) => { for client_id in &connected_clients { output.add_pane_contents( &[*client_id], pane.pid(), pane.pane_contents(Some(*client_id), false), ); } }, } } let mut floating_panes: Vec<_> = if self.panes_are_visible() { self.panes.iter_mut().collect() } else if self.has_pinned_panes() { self.panes .iter_mut() .filter(|(_, p)| p.position_and_size().is_pinned) .collect() } else { vec![] }; floating_panes.sort_by(|(a_id, _a_pane), (b_id, _b_pane)| { let a_pos = self.z_indices.iter().position(|id| id == *a_id); let b_pos = self.z_indices.iter().position(|id| id == *b_id); a_pos.cmp(&b_pos) }); for (z_index, (kind, pane)) in floating_panes.iter_mut().enumerate() { let mut active_panes = active_panes.clone(); let multiple_users_exist_in_session = { self.connected_clients_in_app.borrow().len() > 1 }; active_panes.retain(|c_id, _| self.connected_clients.borrow().contains(c_id)); let pane_is_selectable = pane.selectable(); let mut pane_contents_and_ui = PaneContentsAndUi::new( pane, output, self.style, &active_panes, multiple_users_exist_in_session, Some(z_index + 1), // +1 because 0 is reserved for non-floating panes false, false, true, mouse_hover_pane_id, current_pane_group.clone(), ); for client_id in &connected_clients { let client_mode = self .mode_info .borrow() .get(client_id) .unwrap_or(&self.default_mode_info) .mode; let is_floating = true; pane_contents_and_ui .render_pane_frame( *client_id, client_mode, self.session_is_mirrored, is_floating, pane_is_selectable, ) .with_context(err_context)?; if let PaneId::Plugin(..) = kind { pane_contents_and_ui .render_pane_contents_for_client(*client_id) .with_context(err_context)?; } pane_contents_and_ui.render_terminal_title_if_needed( *client_id, client_mode, &mut self.window_title, ); // this is done for panes that don't have their own cursor (eg. panes of // another user) pane_contents_and_ui .render_fake_cursor_if_needed(*client_id) .with_context(err_context)?; } if let PaneId::Terminal(..) = kind { pane_contents_and_ui .render_pane_contents_to_multiple_clients(connected_clients.iter().copied()) .with_context(err_context)?; } } Ok(()) } pub fn resize(&mut self, new_screen_size: Size) { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let mut floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid.resize(new_screen_size).non_fatal(); self.set_force_render(); } pub fn resize_pty_all_panes(&mut self, _os_api: &mut Box<dyn ServerOsApi>) -> Result<()> { for pane in self.panes.values_mut() { resize_pty!(pane, os_api, self.senders, self.character_cell_size) .with_context(|| format!("failed to resize PTY in pane {:?}", pane.pid()))?; } Ok(()) } pub fn resize_active_pane( &mut self, client_id: ClientId, _os_api: &mut Box<dyn ServerOsApi>, strategy: &ResizeStrategy, ) -> Result<bool> { // true => successfully resized if let Some(active_floating_pane_id) = self.active_panes.get(&client_id) { return self.resize_pane_with_id(*strategy, *active_floating_pane_id); } Ok(false) } pub fn resize_pane_with_id( &mut self, strategy: ResizeStrategy, pane_id: PaneId, ) -> Result<bool> { // true => successfully resized let err_context = || format!("Failed to resize pane with id: {:?}", pane_id); let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let mut floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid .change_pane_size( &pane_id, &strategy, (RESIZE_INCREMENT_WIDTH, RESIZE_INCREMENT_HEIGHT), ) .with_context(err_context)?; for pane in self.panes.values_mut() { resize_pty!(pane, os_api, self.senders, self.character_cell_size) .with_context(err_context)?; } self.set_force_render(); Ok(true) } fn set_pane_active_at(&mut self, pane_id: PaneId) { if let Some(pane) = self.panes.get_mut(&pane_id) { pane.set_active_at(Instant::now()); } } pub fn move_focus( &mut self, client_id: ClientId, connected_clients: &HashSet<ClientId>, direction: &Direction, ) -> Result<bool> { // true => successfully moved let _err_context = || { format!("failed to move focus of floating pane {direction:?} for client {client_id}") }; let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let active_pane_id = self.active_panes.get(&client_id).copied(); let updated_active_pane = if let Some(active_pane_id) = active_pane_id { let floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); let next_index = match direction { Direction::Left => { floating_pane_grid.next_selectable_pane_id_to_the_left(&active_pane_id) }, Direction::Down => { floating_pane_grid.next_selectable_pane_id_below(&active_pane_id) }, Direction::Up => floating_pane_grid.next_selectable_pane_id_above(&active_pane_id), Direction::Right => { floating_pane_grid.next_selectable_pane_id_to_the_right(&active_pane_id) }, }; match next_index { Some(p) => { // render previously active pane so that its frame does not remain actively // colored let Some(previously_active_pane) = self.get_active_pane_mut(client_id) else { log::error!("Failed to get active pane"); return Ok(false); }; previously_active_pane.set_should_render(true); // we render the full viewport to remove any ui elements that might have been // there before (eg. another user's cursor) previously_active_pane.render_full_viewport(); let Some(next_active_pane) = self.get_pane_mut(p) else { log::error!("Failed to get next active pane"); return Ok(false); }; next_active_pane.set_should_render(true); // we render the full viewport to remove any ui elements that might have been // there before (eg. another user's cursor) next_active_pane.render_full_viewport(); // move all clients let connected_clients: Vec<ClientId> = connected_clients.iter().copied().collect(); for client_id in connected_clients { self.focus_pane(p, client_id); } self.set_pane_active_at(p); self.set_force_render(); return Ok(true); }, None => Some(active_pane_id), } } else { active_pane_id }; match updated_active_pane { Some(updated_active_pane) => { let connected_clients: Vec<ClientId> = connected_clients.iter().copied().collect(); for client_id in connected_clients { self.focus_pane(updated_active_pane, client_id); } self.set_pane_active_at(updated_active_pane); self.set_force_render(); }, None => { // TODO: can this happen? self.active_panes.clear(&mut self.panes); self.z_indices.clear(); }, } Ok(false) } pub fn focus_pane_on_edge(&mut self, direction: Direction, client_id: ClientId) { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); if let Some(pane_id) = floating_pane_grid.pane_id_on_edge(direction) { self.focus_pane(pane_id, client_id); self.set_force_render(); } } pub fn move_active_pane_down(&mut self, client_id: ClientId) { if let Some(active_pane_id) = self.active_panes.get(&client_id) { self.move_pane_down(*active_pane_id); } } pub fn move_pane_down(&mut self, pane_id: PaneId) { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let mut floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid.move_pane_down(&pane_id).non_fatal(); self.set_force_render(); } pub fn move_active_pane_up(&mut self, client_id: ClientId) { if let Some(active_pane_id) = self.active_panes.get(&client_id) { self.move_pane_up(*active_pane_id); } } pub fn move_pane_up(&mut self, pane_id: PaneId) { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let mut floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid.move_pane_up(&pane_id).non_fatal(); self.set_force_render(); } pub fn move_active_pane_left(&mut self, client_id: ClientId) { if let Some(active_pane_id) = self.active_panes.get(&client_id) { self.move_pane_left(*active_pane_id); } } pub fn move_pane_left(&mut self, pane_id: PaneId) { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let mut floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid.move_pane_left(&pane_id).non_fatal(); self.set_force_render(); } pub fn move_active_pane_right(&mut self, client_id: ClientId) { if let Some(active_pane_id) = self.active_panes.get(&client_id) { self.move_pane_right(*active_pane_id); } } pub fn move_pane_right(&mut self, pane_id: PaneId) { let display_area = *self.display_area.borrow(); let viewport = *self.viewport.borrow(); let mut floating_pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, display_area, viewport, ); floating_pane_grid.move_pane_right(&pane_id).non_fatal(); self.set_force_render(); } pub fn move_active_pane( &mut self, search_backwards: bool, _os_api: &mut Box<dyn ServerOsApi>, client_id: ClientId, ) { if let Some(active_pane_id) = self.get_active_pane_id(client_id) { self.move_pane(search_backwards, active_pane_id) } } pub fn move_pane(&mut self, search_backwards: bool, pane_id: PaneId) { let new_position_id = { let pane_grid = FloatingPaneGrid::new( &mut self.panes, &mut self.desired_pane_positions, *self.display_area.borrow(), *self.viewport.borrow(), ); if search_backwards { pane_grid.previous_selectable_pane_id(&pane_id) } else { pane_grid.next_selectable_pane_id(&pane_id) } }; if let Some(new_position_id) = new_position_id { let Some(current_position) = self.panes.get(&pane_id) else { log::error!("Failed to find current position"); return; }; let prev_geom = current_position.position_and_size(); let prev_geom_override = current_position.geom_override(); let Some(new_position) = self.panes.get_mut(&new_position_id) else { log::error!("Failed to find new position"); return; }; let next_geom = new_position.position_and_size(); let next_geom_override = new_position.geom_override(); new_position.set_geom(prev_geom); if let Some(geom) = prev_geom_override { new_position.set_geom_override(geom); } new_position.set_should_render(true); let Some(current_position) = self.panes.get_mut(&pane_id) else { log::error!("Failed to find current position"); return; }; current_position.set_geom(next_geom); if let Some(geom) = next_geom_override { current_position.set_geom_override(geom); } current_position.set_should_render(true); let _ = self.set_pane_frames(); } } pub fn change_pane_coordinates( &mut self, pane_id: PaneId, new_coordinates: FloatingPaneCoordinates, ) -> Result<()> { let err_context = || format!("Failed to change_pane_coordinates"); { let viewport = { self.viewport.borrow().clone() }; let pane = self.get_pane_mut(pane_id).with_context(err_context)?; let mut pane_geom = pane.position_and_size(); if let Some(pinned) = new_coordinates.pinned.as_ref() { pane.set_pinned(*pinned); } pane_geom.adjust_coordinates(new_coordinates, viewport); pane.set_geom(pane_geom); pane.set_should_render(true); // we do this in case this moves the pane under another pane so that the pane user's // are focused on will always be on top let is_focused = self.active_panes.pane_id_is_focused(&pane_id); if is_focused { self.z_indices.retain(|p_id| *p_id != pane_id); self.z_indices.push(pane_id); self.make_sure_pinned_panes_are_on_top(); } self.desired_pane_positions.insert(pane_id, pane_geom); } let _ = self.set_pane_frames(); Ok(()) } pub fn move_clients_out_of_pane(&mut self, pane_id: PaneId) { let active_panes: Vec<(ClientId, PaneId)> = self .active_panes .iter() .map(|(cid, pid)| (*cid, *pid)) .collect(); // find the most recently active pane let mut next_active_pane_candidates: Vec<(&PaneId, &Box<dyn Pane>)> = self .panes .iter() .filter(|(_p_id, p)| p.selectable()) .collect();
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/unit/os_input_output_tests.rs
zellij-server/src/unit/os_input_output_tests.rs
use super::*; use nix::{pty::openpty, unistd::close}; struct TestTerminal { openpty: OpenptyResult, } impl TestTerminal { pub fn new() -> TestTerminal { let openpty = openpty(None, None).expect("Could not create openpty"); TestTerminal { openpty } } #[allow(dead_code)] pub fn master(&self) -> RawFd { self.openpty.master } pub fn slave(&self) -> RawFd { self.openpty.slave } } impl Drop for TestTerminal { fn drop(&mut self) { close(self.openpty.master).expect("Failed to close the master"); close(self.openpty.slave).expect("Failed to close the slave"); } } #[test] fn get_cwd() { let test_terminal = TestTerminal::new(); let test_termios = termios::tcgetattr(test_terminal.slave()).expect("Could not configure the termios"); let server = ServerOsInputOutput { orig_termios: Arc::new(Mutex::new(Some(test_termios))), client_senders: Arc::default(), terminal_id_to_raw_fd: Arc::default(), cached_resizes: Arc::default(), }; let pid = nix::unistd::getpid(); assert!( server.get_cwd(pid).is_some(), "Get current working directory from PID {}", pid ); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/unit/screen_tests.rs
zellij-server/src/unit/screen_tests.rs
use super::{screen_thread_main, CopyOptions, Screen, ScreenInstruction}; use crate::panes::PaneId; use crate::{ channels::SenderWithContext, os_input_output::{AsyncReader, Pid, ServerOsApi}, route::route_action, thread_bus::Bus, ClientId, ServerInstruction, SessionMetaData, ThreadSenders, }; use insta::assert_snapshot; use std::net::{IpAddr, Ipv4Addr}; use std::path::PathBuf; use zellij_utils::cli::CliAction; use zellij_utils::data::{Event, Resize, Style, WebSharing}; use zellij_utils::errors::{prelude::*, ErrorContext}; use zellij_utils::input::actions::Action; use zellij_utils::input::command::{RunCommand, TerminalAction}; use zellij_utils::input::config::Config; use zellij_utils::input::layout::{ FloatingPaneLayout, Layout, PluginAlias, PluginUserConfiguration, Run, RunPlugin, RunPluginLocation, RunPluginOrAlias, SplitDirection, SplitSize, TiledPaneLayout, }; use zellij_utils::input::mouse::MouseEvent; use zellij_utils::input::options::Options; use zellij_utils::ipc::IpcReceiverWithContext; use zellij_utils::pane_size::{Size, SizeInPixels}; use zellij_utils::position::Position; use crate::background_jobs::BackgroundJob; use crate::pty_writer::PtyWriteInstruction; use std::env::set_var; use std::os::unix::io::RawFd; use std::sync::{Arc, Mutex}; use crate::{ plugins::PluginInstruction, pty::{ClientTabIndexOrPaneId, PtyInstruction}, }; use zellij_utils::ipc::PixelDimensions; use interprocess::local_socket::LocalSocketStream; use zellij_utils::{ channels::{self, ChannelWithContext, Receiver}, data::{ Direction, FloatingPaneCoordinates, InputMode, ModeInfo, NewPanePlacement, Palette, PluginCapabilities, }, ipc::{ClientAttributes, ClientToServerMsg, ServerToClientMsg}, }; use crate::panes::grid::Grid; use crate::panes::link_handler::LinkHandler; use crate::panes::sixel::SixelImageStore; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; fn take_snapshot_and_cursor_coordinates( ansi_instructions: &str, grid: &mut Grid, ) -> (Option<(usize, usize)>, String) { let mut vte_parser = vte::Parser::new(); for &byte in ansi_instructions.as_bytes() { vte_parser.advance(grid, byte); } (grid.cursor_coordinates(), format!("{:?}", grid)) } fn take_snapshots_and_cursor_coordinates_from_render_events<'a>( all_events: impl Iterator<Item = &'a ServerInstruction>, screen_size: Size, ) -> Vec<(Option<(usize, usize)>, String)> { let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( screen_size.rows, screen_size.cols, Rc::new(RefCell::new(Palette::default())), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let snapshots: Vec<(Option<(usize, usize)>, String)> = all_events .filter_map(|server_instruction| { match server_instruction { ServerInstruction::Render(output) => { if let Some(output) = output { // note this only takes a snapshot of the first client! let raw_snapshot = output.get(&1).unwrap(); let snapshot = take_snapshot_and_cursor_coordinates(raw_snapshot, &mut grid); Some(snapshot) } else { None } }, _ => None, } }) .collect(); snapshots } fn send_cli_action_to_server( session_metadata: &SessionMetaData, cli_action: CliAction, client_id: ClientId, ) { let get_current_dir = || PathBuf::from("."); let actions = Action::actions_from_cli(cli_action, Box::new(get_current_dir), None).unwrap(); let senders = session_metadata.senders.clone(); let capabilities = PluginCapabilities::default(); let client_attributes = ClientAttributes::default(); let default_shell = None; let default_layout = Box::new(Layout::default()); let default_mode = session_metadata .session_configuration .get_client_configuration(&client_id) .options .default_mode .unwrap_or(InputMode::Normal); let client_keybinds = session_metadata .session_configuration .get_client_keybinds(&client_id) .clone(); for action in actions { route_action( action, client_id, None, None, senders.clone(), capabilities, client_attributes.clone(), default_shell.clone(), default_layout.clone(), None, client_keybinds.clone(), default_mode, None, ) .unwrap(); } } #[derive(Clone, Default)] struct FakeInputOutput { fake_filesystem: Arc<Mutex<HashMap<String, String>>>, server_to_client_messages: Arc<Mutex<HashMap<ClientId, Vec<ServerToClientMsg>>>>, } impl ServerOsApi for FakeInputOutput { fn set_terminal_size_using_terminal_id( &self, _terminal_id: u32, _cols: u16, _rows: u16, _width_in_pixels: Option<u16>, _height_in_pixels: Option<u16>, ) -> Result<()> { // noop Ok(()) } fn spawn_terminal( &self, _file_to_open: TerminalAction, _quit_db: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, _default_editor: Option<PathBuf>, ) -> Result<(u32, RawFd, RawFd)> { unimplemented!() } fn read_from_tty_stdout(&self, _fd: RawFd, _buf: &mut [u8]) -> Result<usize> { unimplemented!() } fn async_file_reader(&self, _fd: RawFd) -> Box<dyn AsyncReader> { unimplemented!() } fn write_to_tty_stdin(&self, _id: u32, _buf: &[u8]) -> Result<usize> { unimplemented!() } fn tcdrain(&self, _id: u32) -> Result<()> { unimplemented!() } fn kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn force_kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn box_clone(&self) -> Box<dyn ServerOsApi> { Box::new((*self).clone()) } fn send_to_client(&self, client_id: ClientId, msg: ServerToClientMsg) -> Result<()> { self.server_to_client_messages .lock() .unwrap() .entry(client_id) .or_insert_with(Vec::new) .push(msg); Ok(()) } fn new_client( &mut self, _client_id: ClientId, _stream: LocalSocketStream, ) -> Result<IpcReceiverWithContext<ClientToServerMsg>> { unimplemented!() } fn remove_client(&mut self, _client_id: ClientId) -> Result<()> { unimplemented!() } fn load_palette(&self) -> Palette { unimplemented!() } fn get_cwd(&self, _pid: Pid) -> Option<PathBuf> { unimplemented!() } fn write_to_file(&mut self, contents: String, filename: Option<String>) -> Result<()> { if let Some(filename) = filename { self.fake_filesystem .lock() .unwrap() .insert(filename, contents); } Ok(()) } fn re_run_command_in_terminal( &self, _terminal_id: u32, _run_command: RunCommand, _quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status ) -> Result<(RawFd, RawFd)> { unimplemented!() } fn clear_terminal_id(&self, _terminal_id: u32) -> Result<()> { unimplemented!() } fn send_sigint(&self, pid: Pid) -> Result<()> { unimplemented!() } } fn create_new_screen(size: Size, advanced_mouse_actions: bool) -> Screen { let mut bus: Bus<ScreenInstruction> = Bus::empty(); let fake_os_input = FakeInputOutput::default(); bus.os_input = Some(Box::new(fake_os_input)); let client_attributes = ClientAttributes { size, ..Default::default() }; let max_panes = None; let mut mode_info = ModeInfo::default(); mode_info.session_name = Some("zellij-test".into()); let draw_pane_frames = false; let auto_layout = true; let session_is_mirrored = true; let copy_options = CopyOptions::default(); let default_layout = Box::new(Layout::default()); let default_layout_name = None; let default_shell = PathBuf::from("my_default_shell"); let session_serialization = true; let serialize_pane_viewport = false; let scrollback_lines_to_serialize = None; let layout_dir = None; let debug = false; let styled_underlines = true; let arrow_fonts = true; let explicitly_disable_kitty_keyboard_protocol = false; let stacked_resize = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let screen = Screen::new( bus, &client_attributes, max_panes, mode_info, draw_pane_frames, auto_layout, session_is_mirrored, copy_options, debug, default_layout, default_layout_name, default_shell, session_serialization, serialize_pane_viewport, scrollback_lines_to_serialize, styled_underlines, arrow_fonts, layout_dir, explicitly_disable_kitty_keyboard_protocol, stacked_resize, None, false, web_sharing, advanced_mouse_actions, web_server_ip, web_server_port, ); screen } struct MockScreen { pub main_client_id: u16, pub pty_receiver: Option<Receiver<(PtyInstruction, ErrorContext)>>, pub pty_writer_receiver: Option<Receiver<(PtyWriteInstruction, ErrorContext)>>, pub background_jobs_receiver: Option<Receiver<(BackgroundJob, ErrorContext)>>, pub screen_receiver: Option<Receiver<(ScreenInstruction, ErrorContext)>>, pub server_receiver: Option<Receiver<(ServerInstruction, ErrorContext)>>, pub plugin_receiver: Option<Receiver<(PluginInstruction, ErrorContext)>>, pub to_screen: SenderWithContext<ScreenInstruction>, pub to_pty: SenderWithContext<PtyInstruction>, pub to_plugin: SenderWithContext<PluginInstruction>, pub to_server: SenderWithContext<ServerInstruction>, pub to_pty_writer: SenderWithContext<PtyWriteInstruction>, pub to_background_jobs: SenderWithContext<BackgroundJob>, pub os_input: FakeInputOutput, pub client_attributes: ClientAttributes, pub config_options: Options, pub session_metadata: SessionMetaData, pub config: Config, advanced_mouse_actions: bool, last_opened_tab_index: Option<usize>, } impl MockScreen { pub fn run( &mut self, initial_layout: Option<TiledPaneLayout>, initial_floating_panes_layout: Vec<FloatingPaneLayout>, ) -> std::thread::JoinHandle<()> { std::thread::sleep(std::time::Duration::from_millis(100)); // give time for the async render let mut config = self.config.clone(); config.options.advanced_mouse_actions = Some(self.advanced_mouse_actions); let client_attributes = self.client_attributes.clone(); let screen_bus = Bus::new( vec![self.screen_receiver.take().unwrap()], None, Some(&self.to_pty.clone()), Some(&self.to_plugin.clone()), Some(&self.to_server.clone()), Some(&self.to_pty_writer.clone()), Some(&self.to_background_jobs.clone()), Some(Box::new(self.os_input.clone())), ) .should_silently_fail(); let debug = false; let screen_thread = std::thread::Builder::new() .name("screen_thread".to_string()) .spawn(move || { set_var("ZELLIJ_SESSION_NAME", "zellij-test"); screen_thread_main( screen_bus, None, client_attributes, config, debug, Box::new(Layout::default()), ) .expect("TEST") }) .unwrap(); let pane_layout = initial_layout.unwrap_or_default(); let pane_count = pane_layout.extract_run_instructions().len(); let floating_pane_count = initial_floating_panes_layout.len(); let mut pane_ids = vec![]; let mut floating_pane_ids = vec![]; let mut plugin_ids = HashMap::new(); plugin_ids.insert( RunPluginOrAlias::from_url("file:/path/to/fake/plugin", &None, None, None).unwrap(), vec![1], ); for i in 0..pane_count { pane_ids.push((i as u32, None)); } for i in 0..floating_pane_count { floating_pane_ids.push((i as u32, None)); } let default_shell = None; let tab_name = None; let tab_index = self.last_opened_tab_index.map(|l| l + 1).unwrap_or(0); let should_change_focus_to_new_tab = true; std::thread::sleep(std::time::Duration::from_millis(100)); // give time for the async // render let _ = self.to_screen.send(ScreenInstruction::NewTab( None, default_shell, Some(pane_layout.clone()), initial_floating_panes_layout.clone(), tab_name, (vec![], vec![]), // swap layouts None, // initial_panes false, should_change_focus_to_new_tab, (self.main_client_id, false), None, )); let _ = self.to_screen.send(ScreenInstruction::ApplyLayout( pane_layout, initial_floating_panes_layout, pane_ids, floating_pane_ids, plugin_ids, tab_index, true, (self.main_client_id, false), None, None, )); self.last_opened_tab_index = Some(tab_index); std::thread::sleep(std::time::Duration::from_millis(100)); // give time for the async render screen_thread } // same as the above function, but starts a plugin with a plugin alias pub fn run_with_alias( &mut self, initial_layout: Option<TiledPaneLayout>, initial_floating_panes_layout: Vec<FloatingPaneLayout>, ) -> std::thread::JoinHandle<()> { let config = self.config.clone(); let client_attributes = self.client_attributes.clone(); let screen_bus = Bus::new( vec![self.screen_receiver.take().unwrap()], None, Some(&self.to_pty.clone()), Some(&self.to_plugin.clone()), Some(&self.to_server.clone()), Some(&self.to_pty_writer.clone()), Some(&self.to_background_jobs.clone()), Some(Box::new(self.os_input.clone())), ) .should_silently_fail(); let debug = false; let screen_thread = std::thread::Builder::new() .name("screen_thread".to_string()) .spawn(move || { set_var("ZELLIJ_SESSION_NAME", "zellij-test"); screen_thread_main( screen_bus, None, client_attributes, config, debug, Box::new(Layout::default()), ) .expect("TEST") }) .unwrap(); let pane_layout = initial_layout.unwrap_or_default(); let pane_count = pane_layout.extract_run_instructions().len(); let floating_pane_count = initial_floating_panes_layout.len(); let mut pane_ids = vec![]; let mut floating_pane_ids = vec![]; let mut plugin_ids = HashMap::new(); plugin_ids.insert( RunPluginOrAlias::Alias(PluginAlias { name: "fixture_plugin_for_tests".to_owned(), configuration: Some(Default::default()), run_plugin: Some(RunPlugin { location: RunPluginLocation::parse("file:/path/to/fake/plugin", None).unwrap(), configuration: PluginUserConfiguration::default(), ..Default::default() }), ..Default::default() }), vec![1], ); for i in 0..pane_count { pane_ids.push((i as u32, None)); } for i in 0..floating_pane_count { floating_pane_ids.push((i as u32, None)); } let default_shell = None; let tab_name = None; let tab_index = self.last_opened_tab_index.map(|l| l + 1).unwrap_or(0); let should_change_focus_to_new_tab = true; let _ = self.to_screen.send(ScreenInstruction::NewTab( None, default_shell, Some(pane_layout.clone()), initial_floating_panes_layout.clone(), tab_name, (vec![], vec![]), // swap layouts None, // initial_panes false, should_change_focus_to_new_tab, (self.main_client_id, false), None, )); let _ = self.to_screen.send(ScreenInstruction::ApplyLayout( pane_layout, initial_floating_panes_layout, pane_ids, floating_pane_ids, plugin_ids, tab_index, true, (self.main_client_id, false), None, None, )); self.last_opened_tab_index = Some(tab_index); screen_thread } pub fn new_tab(&mut self, tab_layout: TiledPaneLayout) { let pane_count = tab_layout.extract_run_instructions().len(); let mut pane_ids = vec![]; let plugin_ids = HashMap::new(); let default_shell = None; let tab_name = None; let tab_index = self.last_opened_tab_index.map(|l| l + 1).unwrap_or(0); for i in 0..pane_count { pane_ids.push((i as u32, None)); } let should_change_focus_to_new_tab = true; let _ = self.to_screen.send(ScreenInstruction::NewTab( None, default_shell, Some(tab_layout.clone()), vec![], // floating_panes_layout tab_name, (vec![], vec![]), // swap layouts None, // initial_panes false, should_change_focus_to_new_tab, (self.main_client_id, false), None, )); let _ = self.to_screen.send(ScreenInstruction::ApplyLayout( tab_layout, vec![], // floating_panes_layout pane_ids, vec![], // floating panes ids plugin_ids, 0, true, (self.main_client_id, false), None, None, )); self.last_opened_tab_index = Some(tab_index); } pub fn teardown(&mut self, threads: Vec<std::thread::JoinHandle<()>>) { let _ = self.to_pty.send(PtyInstruction::Exit); let _ = self.to_pty_writer.send(PtyWriteInstruction::Exit); let _ = self.to_screen.send(ScreenInstruction::Exit); let _ = self.to_server.send(ServerInstruction::KillSession); let _ = self.to_plugin.send(PluginInstruction::Exit); let _ = self.to_background_jobs.send(BackgroundJob::Exit); for thread in threads { let _ = thread.join(); } } pub fn clone_session_metadata(&self) -> SessionMetaData { // hack that only clones the clonable parts of SessionMetaData let layout = Box::new(Layout::default()); // this is not actually correct!! SessionMetaData { senders: self.session_metadata.senders.clone(), capabilities: self.session_metadata.capabilities.clone(), client_attributes: self.session_metadata.client_attributes.clone(), default_shell: self.session_metadata.default_shell.clone(), screen_thread: None, pty_thread: None, plugin_thread: None, pty_writer_thread: None, background_jobs_thread: None, session_configuration: self.session_metadata.session_configuration.clone(), layout, current_input_modes: self.session_metadata.current_input_modes.clone(), web_sharing: WebSharing::Off, config_file_path: self.session_metadata.config_file_path.clone(), } } } impl MockScreen { pub fn new(size: Size) -> Self { let (to_server, server_receiver): ChannelWithContext<ServerInstruction> = channels::bounded(50); let to_server = SenderWithContext::new(to_server); let (to_screen, screen_receiver): ChannelWithContext<ScreenInstruction> = channels::unbounded(); let to_screen = SenderWithContext::new(to_screen); let (to_plugin, plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded(); let to_plugin = SenderWithContext::new(to_plugin); let (to_pty, pty_receiver): ChannelWithContext<PtyInstruction> = channels::unbounded(); let to_pty = SenderWithContext::new(to_pty); let (to_pty_writer, pty_writer_receiver): ChannelWithContext<PtyWriteInstruction> = channels::unbounded(); let to_pty_writer = SenderWithContext::new(to_pty_writer); let (to_background_jobs, background_jobs_receiver): ChannelWithContext<BackgroundJob> = channels::unbounded(); let to_background_jobs = SenderWithContext::new(to_background_jobs); let client_attributes = ClientAttributes { size, ..Default::default() }; let capabilities = PluginCapabilities { arrow_fonts: Default::default(), }; let layout = Box::new(Layout::default()); // this is not actually correct!! let session_metadata = SessionMetaData { senders: ThreadSenders { to_screen: Some(to_screen.clone()), to_pty: Some(to_pty.clone()), to_plugin: Some(to_plugin.clone()), to_pty_writer: Some(to_pty_writer.clone()), to_background_jobs: Some(to_background_jobs.clone()), to_server: Some(to_server.clone()), should_silently_fail: true, }, capabilities, default_shell: None, client_attributes: client_attributes.clone(), screen_thread: None, pty_thread: None, plugin_thread: None, pty_writer_thread: None, background_jobs_thread: None, layout, session_configuration: Default::default(), current_input_modes: HashMap::new(), web_sharing: WebSharing::Off, config_file_path: None, }; let os_input = FakeInputOutput::default(); let config_options = Options::default(); let main_client_id = 1; std::thread::Builder::new() .name("background_jobs_thread".to_string()) .spawn({ let to_screen = to_screen.clone(); move || loop { let (event, _err_ctx) = background_jobs_receiver .recv() .expect("failed to receive event on channel"); match event { BackgroundJob::RenderToClients => { let _ = to_screen.send(ScreenInstruction::RenderToClients); }, BackgroundJob::Exit => { break; }, _ => {}, } } }) .unwrap(); MockScreen { main_client_id, pty_receiver: Some(pty_receiver), pty_writer_receiver: Some(pty_writer_receiver), background_jobs_receiver: None, screen_receiver: Some(screen_receiver), server_receiver: Some(server_receiver), plugin_receiver: Some(plugin_receiver), to_screen, to_pty, to_plugin, to_server, to_pty_writer, to_background_jobs, os_input, client_attributes, config_options, session_metadata, last_opened_tab_index: None, config: Config::default(), advanced_mouse_actions: true, } } pub fn set_advanced_hover_effects(&mut self, advanced_mouse_actions: bool) { self.advanced_mouse_actions = advanced_mouse_actions; } pub fn drop_all_pty_messages(&mut self) { let pty_receiver = self.pty_receiver.take(); std::thread::Builder::new() .name("pty_thread".to_string()) .spawn({ move || { if let Some(pty_receiver) = pty_receiver { loop { let (event, _err_ctx) = pty_receiver .recv() .expect("failed to receive event on channel"); match event { PtyInstruction::Exit => { break; }, _ => { // here the event will be dropped - we do this so that the completion_tx will drop and release the // test actions }, } } } } }) .unwrap(); } } macro_rules! log_actions_in_thread { ( $arc_mutex_log:expr, $exit_event:path, $receiver:expr ) => { std::thread::Builder::new() .name("pty_writer_thread".to_string()) .spawn({ let log = $arc_mutex_log.clone(); move || loop { let (event, _err_ctx) = $receiver .recv() .expect("failed to receive event on channel"); match event { $exit_event => { log.lock().unwrap().push(event.clone()); break; }, _ => { log.lock().unwrap().push(event.clone()); }, } } }) .unwrap() }; } fn new_tab(screen: &mut Screen, pid: u32, tab_index: usize) { let client_id = 1; let new_terminal_ids = vec![(pid, None)]; let new_plugin_ids = HashMap::new(); screen .new_tab(tab_index, (vec![], vec![]), None, Some(client_id)) .expect("TEST"); screen .apply_layout( TiledPaneLayout::default(), vec![], // floating panes layout new_terminal_ids, vec![], // new floating terminal ids new_plugin_ids, tab_index, true, (client_id, false), None, ) .expect("TEST"); } #[test] fn open_new_tab() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 0); new_tab(&mut screen, 2, 1); assert_eq!(screen.tabs.len(), 2, "Screen now has two tabs"); assert_eq!( screen.get_active_tab(1).unwrap().position, 1, "Active tab switched to new tab" ); } #[test] pub fn switch_to_prev_tab() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 1); new_tab(&mut screen, 2, 2); screen.switch_tab_prev(None, true, 1).expect("TEST"); assert_eq!( screen.get_active_tab(1).unwrap().position, 0, "Active tab switched to previous tab" ); } #[test] pub fn switch_to_next_tab() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 1); new_tab(&mut screen, 2, 2); screen.switch_tab_prev(None, true, 1).expect("TEST"); screen.switch_tab_next(None, true, 1).expect("TEST"); assert_eq!( screen.get_active_tab(1).unwrap().position, 1, "Active tab switched to next tab" ); } #[test] pub fn switch_to_tab_name() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 1); new_tab(&mut screen, 2, 2); assert_eq!( screen .switch_active_tab_name("Tab #1".to_string(), 1) .expect("TEST"), false, "Active tab switched to tab by name" ); assert_eq!( screen .switch_active_tab_name("Tab #2".to_string(), 1) .expect("TEST"), true, "Active tab switched to tab by name" ); assert_eq!( screen .switch_active_tab_name("Tab #3".to_string(), 1) .expect("TEST"), true, "Active tab switched to tab by name" ); } #[test] pub fn close_tab() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 1); new_tab(&mut screen, 2, 2); screen.close_tab(1).expect("TEST"); assert_eq!(screen.tabs.len(), 1, "Only one tab left"); assert_eq!( screen.get_active_tab(1).unwrap().position, 0, "Active tab switched to previous tab" ); } #[test] pub fn close_the_middle_tab() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 1); new_tab(&mut screen, 2, 2); new_tab(&mut screen, 3, 3); screen.switch_tab_prev(None, true, 1).expect("TEST"); screen.close_tab(1).expect("TEST"); assert_eq!(screen.tabs.len(), 2, "Two tabs left"); assert_eq!( screen.get_active_tab(1).unwrap().position, 1, "Active tab switched to previous tab" ); } #[test] fn move_focus_left_at_left_screen_edge_changes_tab() { let size = Size { cols: 121, rows: 20, }; let mut screen = create_new_screen(size, true); new_tab(&mut screen, 1, 1); new_tab(&mut screen, 2, 2); new_tab(&mut screen, 3, 3); screen.switch_tab_prev(None, true, 1).expect("TEST"); screen.move_focus_left_or_previous_tab(1).expect("TEST"); assert_eq!( screen.get_active_tab(1).unwrap().position, 0, "Active tab switched to previous" ); } #[test] fn basic_move_of_active_tab_to_left() { let mut screen = create_fixed_size_screen(); new_tab(&mut screen, 1, 0); new_tab(&mut screen, 2, 1); assert_eq!(screen.get_active_tab(1).unwrap().position, 1); screen.move_active_tab_to_left(1).expect("TEST"); assert_eq!( screen.get_active_tab(1).unwrap().position, 0, "Active tab moved to left" ); } fn create_fixed_size_screen() -> Screen { create_new_screen( Size { cols: 121, rows: 20, }, true, ) } #[test] fn move_of_active_tab_to_left_when_there_is_only_one_tab() { let mut screen = create_fixed_size_screen(); new_tab(&mut screen, 1, 0); assert_eq!(screen.get_active_tab(1).unwrap().position, 0); screen.move_active_tab_to_left(1).expect("TEST"); assert_eq!( screen.get_active_tab(1).unwrap().position, 0, "Active tab moved to left" ); } #[test] fn move_of_active_tab_to_left_multiple_times() { let mut screen = create_fixed_size_screen(); new_tab(&mut screen, 1, 0);
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/swap_layouts.rs
zellij-server/src/tab/swap_layouts.rs
use crate::panes::{FloatingPanes, TiledPanes}; use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use zellij_utils::{ input::layout::{ FloatingPaneLayout, LayoutConstraint, SwapFloatingLayout, SwapTiledLayout, TiledPaneLayout, }, pane_size::{PaneGeom, Size}, }; #[derive(Clone, Debug, Default)] pub struct SwapLayouts { swap_tiled_layouts: Vec<SwapTiledLayout>, swap_floating_layouts: Vec<SwapFloatingLayout>, current_floating_layout_position: usize, current_tiled_layout_position: usize, is_floating_damaged: bool, is_tiled_damaged: bool, display_area: Rc<RefCell<Size>>, // includes all panes (including eg. the status bar and tab bar in the default layout) } impl SwapLayouts { pub fn new( swap_layouts: (Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), display_area: Rc<RefCell<Size>>, ) -> Self { let display_area = display_area.clone(); SwapLayouts { swap_tiled_layouts: swap_layouts.0, swap_floating_layouts: swap_layouts.1, is_floating_damaged: false, is_tiled_damaged: false, display_area, ..Default::default() } } pub fn set_base_layout(&mut self, layout: (TiledPaneLayout, Vec<FloatingPaneLayout>)) { let mut base_swap_tiled_layout = BTreeMap::new(); let mut base_swap_floating_layout = BTreeMap::new(); let tiled_panes_count = layout.0.pane_count(); let floating_panes_count = layout.1.len(); // we set ExactPanes to the current panes in the layout, because the base layout is not // intended to be progressive - i.e. to have additional panes added to it // we also don't want it to be applied for less than the expected amount of panes, because // then unintended things can happen // we still want to keep it around in case we'd like to swap layouts without adding panes base_swap_tiled_layout.insert(LayoutConstraint::ExactPanes(tiled_panes_count), layout.0); base_swap_floating_layout .insert(LayoutConstraint::ExactPanes(floating_panes_count), layout.1); self.swap_tiled_layouts .insert(0, (base_swap_tiled_layout, Some("BASE".into()))); self.swap_floating_layouts .insert(0, (base_swap_floating_layout, Some("BASE".into()))); self.current_tiled_layout_position = 0; self.current_floating_layout_position = 0; } pub fn set_swap_tiled_layouts(&mut self, new_swap_tiled_layouts: Vec<SwapTiledLayout>) { self.swap_tiled_layouts = new_swap_tiled_layouts; self.current_tiled_layout_position = 0; } pub fn set_swap_floating_layouts( &mut self, new_swap_floating_layouts: Vec<SwapFloatingLayout>, ) { self.swap_floating_layouts = new_swap_floating_layouts; self.current_floating_layout_position = 0; } pub fn set_is_floating_damaged(&mut self) { self.is_floating_damaged = true; } pub fn set_is_tiled_damaged(&mut self) { self.is_tiled_damaged = true; } pub fn reset_floating_damage(&mut self) { self.is_floating_damaged = false; } pub fn is_floating_damaged(&self) -> bool { self.is_floating_damaged } pub fn is_tiled_damaged(&self) -> bool { self.is_tiled_damaged } pub fn tiled_layout_info(&self) -> (Option<String>, bool) { // (swap_layout_name, is_swap_layout_dirty) match self .swap_tiled_layouts .iter() .nth(self.current_tiled_layout_position) { Some(current_tiled_layout) => ( current_tiled_layout.1.clone().or_else(|| { Some(format!( "Layout #{}", self.current_tiled_layout_position + 1 )) }), self.is_tiled_damaged, ), None => (None, self.is_tiled_damaged), } } pub fn floating_layout_info(&self) -> (Option<String>, bool) { // (swap_layout_name, is_swap_layout_dirty) match self .swap_floating_layouts .iter() .nth(self.current_floating_layout_position) { Some(current_floating_layout) => ( current_floating_layout.1.clone().or_else(|| { Some(format!( "Layout #{}", self.current_floating_layout_position + 1 )) }), self.is_floating_damaged, ), None => (None, self.is_floating_damaged), } } pub fn swap_floating_panes( &mut self, floating_panes: &FloatingPanes, search_backwards: bool, ) -> Option<Vec<FloatingPaneLayout>> { if self.swap_floating_layouts.is_empty() { return None; } let initial_position = self.current_floating_layout_position; macro_rules! progress_layout { () => {{ if search_backwards { if self.current_floating_layout_position == 0 { self.current_floating_layout_position = self.swap_floating_layouts.len().saturating_sub(1); } else { self.current_floating_layout_position -= 1; } } else { self.current_floating_layout_position += 1; } }}; } if !self.is_floating_damaged && self .swap_floating_layouts .iter() .nth(self.current_floating_layout_position) .is_some() { progress_layout!(); } self.is_floating_damaged = false; loop { match self .swap_floating_layouts .iter() .nth(self.current_floating_layout_position) { Some(swap_layout) => { for (constraint, layout) in swap_layout.0.iter() { if self.state_fits_floating_panes_constraint(constraint, floating_panes) { return Some(layout.clone()); }; } progress_layout!(); }, None => { self.current_floating_layout_position = 0; }, }; if self.current_floating_layout_position == initial_position { break; } } None } fn state_fits_tiled_panes_constraint( &self, constraint: &LayoutConstraint, tiled_panes: &TiledPanes, ) -> bool { match constraint { LayoutConstraint::MaxPanes(max_panes) => { tiled_panes.visible_panes_count() <= *max_panes }, LayoutConstraint::MinPanes(min_panes) => { tiled_panes.visible_panes_count() >= *min_panes }, LayoutConstraint::ExactPanes(pane_count) => { tiled_panes.visible_panes_count() == *pane_count }, LayoutConstraint::NoConstraint => true, } } fn state_fits_floating_panes_constraint( &self, constraint: &LayoutConstraint, floating_panes: &FloatingPanes, ) -> bool { match constraint { LayoutConstraint::MaxPanes(max_panes) => { floating_panes.visible_panes_count() <= *max_panes }, LayoutConstraint::MinPanes(min_panes) => { floating_panes.visible_panes_count() >= *min_panes }, LayoutConstraint::ExactPanes(pane_count) => { floating_panes.visible_panes_count() == *pane_count }, LayoutConstraint::NoConstraint => true, } } pub fn swap_tiled_panes( &mut self, tiled_panes: &TiledPanes, search_backwards: bool, ) -> Option<TiledPaneLayout> { if self.swap_tiled_layouts.is_empty() { return None; } macro_rules! progress_layout { () => {{ if search_backwards { if self.current_tiled_layout_position == 0 { self.current_tiled_layout_position = self.swap_tiled_layouts.len().saturating_sub(1); } else { self.current_tiled_layout_position -= 1; } } else { self.current_tiled_layout_position += 1; } }}; } let initial_position = self.current_tiled_layout_position; if !self.is_tiled_damaged && self .swap_tiled_layouts .iter() .nth(self.current_tiled_layout_position) .is_some() { progress_layout!(); } self.is_tiled_damaged = false; loop { match self .swap_tiled_layouts .iter() .nth(self.current_tiled_layout_position) { Some(swap_layout) => { for (constraint, layout) in swap_layout.0.iter() { if self.state_fits_tiled_panes_constraint(constraint, tiled_panes) { let focus_layout_if_not_focused = true; let display_area = self.display_area.borrow(); // TODO: reuse the assets from position_panes_in_space here? let pane_count = tiled_panes.visible_panes_count(); let display_area = PaneGeom::from(&*display_area); if layout .position_panes_in_space( &display_area, Some(pane_count), false, focus_layout_if_not_focused, ) .is_ok() { return Some(layout.clone()); } }; } progress_layout!(); }, None => { self.current_tiled_layout_position = 0; }, }; if self.current_tiled_layout_position == initial_position { break; } } None } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/clipboard.rs
zellij-server/src/tab/clipboard.rs
use anyhow::Result; use zellij_utils::{data::CopyDestination, input::options::Clipboard}; use crate::ClientId; use super::{copy_command::CopyCommand, Output}; pub(crate) enum ClipboardProvider { Command(CopyCommand), Osc52(Clipboard), } impl ClipboardProvider { pub(crate) fn set_content( &self, content: &str, output: &mut Output, client_ids: impl Iterator<Item = ClientId>, ) -> Result<()> { match &self { ClipboardProvider::Command(command) => { command.set(content.to_string())?; }, ClipboardProvider::Osc52(clipboard) => { let dest = match clipboard { #[cfg(not(target_os = "macos"))] Clipboard::Primary => 'p', #[cfg(target_os = "macos")] // primary selection does not exist on macos Clipboard::Primary => 'c', Clipboard::System => 'c', }; output.add_pre_vte_instruction_to_multiple_clients( client_ids, &format!("\u{1b}]52;{};{}\u{1b}\\", dest, base64::encode(content)), ); }, }; Ok(()) } pub(crate) fn as_copy_destination(&self) -> CopyDestination { match self { ClipboardProvider::Command(_) => CopyDestination::Command, ClipboardProvider::Osc52(clipboard) => match clipboard { Clipboard::Primary => CopyDestination::Primary, Clipboard::System => CopyDestination::System, }, } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/copy_command.rs
zellij-server/src/tab/copy_command.rs
use std::io::prelude::*; use std::process::{Command, Stdio}; use anyhow::{Context, Result}; pub struct CopyCommand { command: String, args: Vec<String>, } impl CopyCommand { pub fn new(command: String) -> Self { let mut command_with_args = command.split(' ').map(String::from); Self { command: command_with_args.next().expect("missing command"), args: command_with_args.collect(), } } pub fn set(&self, value: String) -> Result<()> { let mut process = Command::new(self.command.clone()) .args(self.args.clone()) .stdin(Stdio::piped()) .spawn() .with_context(|| format!("couldn't spawn {}", self.command))?; process .stdin .take() .context("could not get stdin")? .write_all(value.as_bytes()) .with_context(|| format!("couldn't write to {} stdin", self.command))?; // reap process with a 1 second timeout std::thread::spawn(move || { let timeout = std::time::Duration::from_secs(1); let start = std::time::Instant::now(); loop { match process.try_wait() { Ok(Some(_)) => { return; // Process finished normally }, Ok(None) => { if start.elapsed() > timeout { let _ = process.kill(); log::error!("Copy operation times out after 1 second"); return; } std::thread::sleep(std::time::Duration::from_millis(50)); }, Err(e) => { log::error!("Clipboard failure: {}", e); return; }, } } }); Ok(()) } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/mod.rs
zellij-server/src/tab/mod.rs
//! `Tab`s holds multiple panes. It tracks their coordinates (x/y) and size, //! as well as how they should be resized mod clipboard; mod copy_command; mod layout_applier; mod swap_layouts; use copy_command::CopyCommand; use std::env::temp_dir; use std::net::IpAddr; use std::path::PathBuf; use uuid::Uuid; use zellij_utils::data::PaneContents; use zellij_utils::data::{ Direction, KeyWithModifier, NewPanePlacement, PaneInfo, PermissionStatus, PermissionType, PluginPermission, ResizeStrategy, WebSharing, }; use zellij_utils::errors::prelude::*; use zellij_utils::input::command::RunCommand; use zellij_utils::input::mouse::{MouseEvent, MouseEventType}; use zellij_utils::position::Position; use zellij_utils::position::{Column, Line}; use zellij_utils::shared::clean_string_from_control_and_linebreak; use crate::background_jobs::BackgroundJob; use crate::pane_groups::PaneGroups; use crate::pty_writer::PtyWriteInstruction; use crate::screen::CopyOptions; use crate::ui::{loading_indication::LoadingIndication, pane_boundaries_frame::FrameParams}; use layout_applier::LayoutApplier; use swap_layouts::SwapLayouts; use self::clipboard::ClipboardProvider; use crate::route::NotificationEnd; use crate::{ os_input_output::ServerOsApi, output::{CharacterChunk, Output, SixelImageChunk}, panes::floating_panes::floating_pane_grid::half_size_middle_geom, panes::sixel::SixelImageStore, panes::{FloatingPanes, TiledPanes}, panes::{LinkHandler, PaneId, PluginPane, TerminalPane}, plugins::PluginInstruction, pty::{ClientTabIndexOrPaneId, PtyInstruction, VteBytes}, thread_bus::ThreadSenders, ClientId, ServerInstruction, }; use std::cell::RefCell; use std::rc::Rc; use std::time::Instant; use std::{ collections::{BTreeMap, HashMap, HashSet}, str, }; use zellij_utils::{ data::{ Event, FloatingPaneCoordinates, InputMode, ModeInfo, Palette, PaletteColor, Style, Styling, }, input::{ command::TerminalAction, layout::{ FloatingPaneLayout, Run, RunPluginOrAlias, SwapFloatingLayout, SwapTiledLayout, TiledPaneLayout, }, parse_keys, }, pane_size::{Offset, PaneGeom, Size, SizeInPixels, Viewport}, }; #[macro_export] macro_rules! resize_pty { ($pane:expr, $os_input:expr, $senders:expr) => {{ match $pane.pid() { PaneId::Terminal(ref pid) => { $senders .send_to_pty_writer(PtyWriteInstruction::ResizePty( *pid, $pane.get_content_columns() as u16, $pane.get_content_rows() as u16, None, None, )) .with_context(err_context); }, PaneId::Plugin(ref pid) => { let err_context = || format!("failed to resize plugin {pid}"); $senders .send_to_plugin(PluginInstruction::Resize( *pid, $pane.get_content_columns(), $pane.get_content_rows(), )) .with_context(err_context) }, } }}; ($pane:expr, $os_input:expr, $senders:expr, $character_cell_size:expr) => {{ let (width_in_pixels, height_in_pixels) = { let character_cell_size = $character_cell_size.borrow(); match *character_cell_size { Some(size_in_pixels) => { let width_in_pixels = (size_in_pixels.width * $pane.get_content_columns()) as u16; let height_in_pixels = (size_in_pixels.height * $pane.get_content_rows()) as u16; (Some(width_in_pixels), Some(height_in_pixels)) }, None => (None, None), } }; match $pane.pid() { PaneId::Terminal(ref pid) => { use crate::PtyWriteInstruction; let err_context = || format!("Failed to send resize pty instruction"); $senders .send_to_pty_writer(PtyWriteInstruction::ResizePty( *pid, $pane.get_content_columns() as u16, $pane.get_content_rows() as u16, width_in_pixels, height_in_pixels, )) .with_context(err_context) }, PaneId::Plugin(ref pid) => { let err_context = || format!("failed to resize plugin {pid}"); $senders .send_to_plugin(PluginInstruction::Resize( *pid, $pane.get_content_columns(), $pane.get_content_rows(), )) .with_context(err_context) }, } }}; } // FIXME: This should be replaced by `RESIZE_PERCENT` at some point pub const MIN_TERMINAL_HEIGHT: usize = 5; pub const MIN_TERMINAL_WIDTH: usize = 5; const MAX_PENDING_VTE_EVENTS: usize = 7000; type HoldForCommand = Option<RunCommand>; pub type SuppressedPanes = HashMap<PaneId, (bool, Box<dyn Pane>)>; // bool => is scrollback editor enum BufferedTabInstruction { SetPaneSelectable(PaneId, bool), HandlePtyBytes(u32, VteBytes), HoldPane(PaneId, Option<i32>, bool, RunCommand), // Option<i32> is the exit status, bool is is_first_run } #[derive(Debug, Default, Copy, Clone)] pub struct MouseEffect { pub state_changed: bool, pub leave_clipboard_message: bool, pub group_toggle: Option<PaneId>, pub group_add: Option<PaneId>, pub ungroup: bool, } impl MouseEffect { pub fn state_changed() -> Self { MouseEffect { state_changed: true, leave_clipboard_message: false, group_toggle: None, group_add: None, ungroup: false, } } pub fn leave_clipboard_message() -> Self { MouseEffect { state_changed: false, leave_clipboard_message: true, group_toggle: None, group_add: None, ungroup: false, } } pub fn state_changed_and_leave_clipboard_message() -> Self { MouseEffect { state_changed: true, leave_clipboard_message: true, group_toggle: None, group_add: None, ungroup: false, } } pub fn group_toggle(pane_id: PaneId) -> Self { MouseEffect { state_changed: true, leave_clipboard_message: false, group_toggle: Some(pane_id), group_add: None, ungroup: false, } } pub fn group_add(pane_id: PaneId) -> Self { MouseEffect { state_changed: true, leave_clipboard_message: false, group_toggle: None, group_add: Some(pane_id), ungroup: false, } } pub fn ungroup() -> Self { MouseEffect { state_changed: true, leave_clipboard_message: false, group_toggle: None, group_add: None, ungroup: true, } } } pub(crate) struct Tab { pub index: usize, pub position: usize, pub name: String, pub prev_name: String, tiled_panes: TiledPanes, floating_panes: FloatingPanes, suppressed_panes: SuppressedPanes, max_panes: Option<usize>, viewport: Rc<RefCell<Viewport>>, // includes all non-UI panes display_area: Rc<RefCell<Size>>, // includes all panes (including eg. the status bar and tab bar in the default layout) character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, sixel_image_store: Rc<RefCell<SixelImageStore>>, os_api: Box<dyn ServerOsApi>, pub senders: ThreadSenders, synchronize_is_active: bool, should_clear_display_before_rendering: bool, mode_info: Rc<RefCell<HashMap<ClientId, ModeInfo>>>, default_mode_info: ModeInfo, pub style: Style, connected_clients: Rc<RefCell<HashSet<ClientId>>>, draw_pane_frames: bool, auto_layout: bool, pending_vte_events: HashMap<u32, Vec<VteBytes>>, pub selecting_with_mouse_in_pane: Option<PaneId>, // this is only pub for the tests link_handler: Rc<RefCell<LinkHandler>>, clipboard_provider: ClipboardProvider, // TODO: used only to focus the pane when the layout is loaded // it seems that optimization is possible using `active_panes` focus_pane_id: Option<PaneId>, copy_on_select: bool, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, pids_waiting_resize: HashSet<u32>, // u32 is the terminal_id cursor_positions_and_shape: HashMap<ClientId, (usize, usize, String)>, // (x_position, // y_position, // cursor_shape_csi) is_pending: bool, // a pending tab is one that is still being loaded or otherwise waiting pending_instructions: Vec<BufferedTabInstruction>, // instructions that came while the tab was // pending and need to be re-applied swap_layouts: SwapLayouts, default_shell: PathBuf, default_editor: Option<PathBuf>, debug: bool, arrow_fonts: bool, styled_underlines: bool, explicitly_disable_kitty_keyboard_protocol: bool, web_clients_allowed: bool, web_sharing: WebSharing, mouse_hover_pane_id: HashMap<ClientId, PaneId>, current_pane_group: Rc<RefCell<PaneGroups>>, advanced_mouse_actions: bool, currently_marking_pane_group: Rc<RefCell<HashMap<ClientId, bool>>>, connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client // the below are the configured values - the ones that will be set if and when the web server // is brought online web_server_ip: IpAddr, web_server_port: u16, } // FIXME: Use a struct that has a pane_type enum, to reduce all of the duplication pub trait Pane { fn x(&self) -> usize; fn y(&self) -> usize; fn rows(&self) -> usize; fn cols(&self) -> usize; fn get_content_x(&self) -> usize; fn get_content_y(&self) -> usize; fn get_content_columns(&self) -> usize; fn get_content_rows(&self) -> usize; fn reset_size_and_position_override(&mut self); fn set_geom(&mut self, position_and_size: PaneGeom); fn set_geom_override(&mut self, pane_geom: PaneGeom); fn handle_pty_bytes(&mut self, _bytes: VteBytes) {} fn handle_plugin_bytes(&mut self, _client_id: ClientId, _bytes: VteBytes) {} fn show_cursor(&mut self, _client_id: ClientId, _cursor_position: Option<(usize, usize)>) {} fn cursor_coordinates(&self, _client_id: Option<ClientId>) -> Option<(usize, usize)>; fn is_mid_frame(&self) -> bool { false } fn adjust_input_to_terminal( &mut self, _key_with_modifier: &Option<KeyWithModifier>, _raw_input_bytes: Vec<u8>, _raw_input_bytes_are_kitty: bool, _client_id: Option<ClientId>, ) -> Option<AdjustedInput> { None } fn position_and_size(&self) -> PaneGeom; fn current_geom(&self) -> PaneGeom; fn geom_override(&self) -> Option<PaneGeom>; fn should_render(&self) -> bool; fn set_should_render(&mut self, should_render: bool); fn set_should_render_boundaries(&mut self, _should_render: bool) {} fn selectable(&self) -> bool; fn set_selectable(&mut self, selectable: bool); fn request_permissions_from_user(&mut self, _permissions: Option<PluginPermission>) {} fn render( &mut self, client_id: Option<ClientId>, ) -> Result<Option<(Vec<CharacterChunk>, Option<String>, Vec<SixelImageChunk>)>>; // TODO: better fn render_frame( &mut self, client_id: ClientId, frame_params: FrameParams, input_mode: InputMode, ) -> Result<Option<(Vec<CharacterChunk>, Option<String>)>>; // TODO: better fn render_fake_cursor( &mut self, cursor_color: PaletteColor, text_color: PaletteColor, ) -> Option<String>; fn render_terminal_title(&mut self, _input_mode: InputMode) -> String; fn update_name(&mut self, name: &str); fn pid(&self) -> PaneId; fn reduce_height(&mut self, percent: f64); fn increase_height(&mut self, percent: f64); fn reduce_width(&mut self, percent: f64); fn increase_width(&mut self, percent: f64); fn push_down(&mut self, count: usize); fn push_right(&mut self, count: usize); fn pull_left(&mut self, count: usize); fn pull_up(&mut self, count: usize); fn clear_screen(&mut self); fn dump_screen(&self, _full: bool, _client_id: Option<ClientId>) -> String { "".to_owned() } fn scroll_up(&mut self, count: usize, client_id: ClientId); fn scroll_down(&mut self, count: usize, client_id: ClientId); fn clear_scroll(&mut self); fn is_scrolled(&self) -> bool; fn active_at(&self) -> Instant; fn set_active_at(&mut self, instant: Instant); fn set_frame(&mut self, frame: bool); fn set_content_offset(&mut self, offset: Offset); fn get_content_offset(&self) -> Offset { Offset::default() } fn cursor_shape_csi(&self) -> String { "\u{1b}[0 q".to_string() // default to non blinking block } fn contains(&self, position: &Position) -> bool { match self.geom_override() { Some(position_and_size) => position_and_size.contains(position), None => self.position_and_size().contains(position), } } fn start_selection(&mut self, _start: &Position, _client_id: ClientId) {} fn update_selection(&mut self, _position: &Position, _client_id: ClientId) {} fn end_selection(&mut self, _end: &Position, _client_id: ClientId) {} fn reset_selection(&mut self, _client_id: Option<ClientId>) {} fn supports_mouse_selection(&self) -> bool { true } fn get_selected_text(&self, _client_id: ClientId) -> Option<String> { None } fn right_boundary_x_coords(&self) -> usize { self.x() + self.cols() } fn right_boundary_x_content_coords(&self) -> usize { self.get_content_x() + self.get_content_columns() } fn bottom_boundary_y_coords(&self) -> usize { self.y() + self.rows() } fn bottom_boundary_y_content_coords(&self) -> usize { self.get_content_y() + self.get_content_rows() } fn is_right_of(&self, other: &dyn Pane) -> bool { self.x() > other.x() } fn is_directly_right_of(&self, other: &dyn Pane) -> bool { self.x() == other.x() + other.cols() } fn is_left_of(&self, other: &dyn Pane) -> bool { self.x() < other.x() } fn is_directly_left_of(&self, other: &dyn Pane) -> bool { self.x() + self.cols() == other.x() } fn is_below(&self, other: &dyn Pane) -> bool { self.y() > other.y() } fn is_directly_below(&self, other: &dyn Pane) -> bool { self.y() == other.y() + other.rows() } fn is_above(&self, other: &dyn Pane) -> bool { self.y() < other.y() } fn is_directly_above(&self, other: &dyn Pane) -> bool { self.y() + self.rows() == other.y() } fn horizontally_overlaps_with(&self, other: &dyn Pane) -> bool { (self.y() >= other.y() && self.y() < (other.y() + other.rows())) || ((self.y() + self.rows()) <= (other.y() + other.rows()) && (self.y() + self.rows()) > other.y()) || (self.y() <= other.y() && (self.y() + self.rows() >= (other.y() + other.rows()))) || (other.y() <= self.y() && (other.y() + other.rows() >= (self.y() + self.rows()))) } fn get_horizontal_overlap_with(&self, other: &dyn Pane) -> usize { std::cmp::min(self.y() + self.rows(), other.y() + other.rows()) - std::cmp::max(self.y(), other.y()) } fn vertically_overlaps_with(&self, other: &dyn Pane) -> bool { (self.x() >= other.x() && self.x() < (other.x() + other.cols())) || ((self.x() + self.cols()) <= (other.x() + other.cols()) && (self.x() + self.cols()) > other.x()) || (self.x() <= other.x() && (self.x() + self.cols() >= (other.x() + other.cols()))) || (other.x() <= self.x() && (other.x() + other.cols() >= (self.x() + self.cols()))) } fn get_vertical_overlap_with(&self, other: &dyn Pane) -> usize { std::cmp::min(self.x() + self.cols(), other.x() + other.cols()) - std::cmp::max(self.x(), other.x()) } fn can_reduce_height_by(&self, reduce_by: usize) -> bool { self.rows() > reduce_by && self.rows() - reduce_by >= self.min_height() } fn can_reduce_width_by(&self, reduce_by: usize) -> bool { self.cols() > reduce_by && self.cols() - reduce_by >= self.min_width() } fn min_width(&self) -> usize { MIN_TERMINAL_WIDTH } fn min_height(&self) -> usize { MIN_TERMINAL_HEIGHT } fn drain_messages_to_pty(&mut self) -> Vec<Vec<u8>> { // TODO: this is only relevant to terminal panes // we should probably refactor away from this trait at some point vec![] } fn drain_clipboard_update(&mut self) -> Option<String> { None } fn render_full_viewport(&mut self) {} fn relative_position(&self, position_on_screen: &Position) -> Position { position_on_screen.relative_to(self.get_content_y(), self.get_content_x()) } fn position_is_on_frame(&self, position: &Position) -> bool { if !self.contains(position) { return false; } if (self.x()..self.get_content_x()).contains(&position.column()) { // position is on left border return true; } if (self.get_content_x() + self.get_content_columns()..(self.x() + self.cols())) .contains(&position.column()) { // position is on right border return true; } if (self.y() as isize..self.get_content_y() as isize).contains(&position.line()) { // position is on top border return true; } if ((self.get_content_y() + self.get_content_rows()) as isize ..(self.y() + self.rows()) as isize) .contains(&position.line()) { // position is on bottom border return true; } false } // TODO: get rid of this in favor of intercept_mouse_event_on_frame fn intercept_left_mouse_click(&mut self, _position: &Position, _client_id: ClientId) -> bool { let intercepted = false; intercepted } fn intercept_mouse_event_on_frame( &mut self, _event: &MouseEvent, _client_id: ClientId, ) -> bool { let intercepted = false; intercepted } fn store_pane_name(&mut self); fn load_pane_name(&mut self); fn set_borderless(&mut self, borderless: bool); fn borderless(&self) -> bool; fn set_exclude_from_sync(&mut self, exclude_from_sync: bool); fn exclude_from_sync(&self) -> bool; // TODO: this should probably be merged with the mouse_right_click fn handle_right_click(&mut self, _to: &Position, _client_id: ClientId) {} fn mouse_event(&self, _event: &MouseEvent, _client_id: ClientId) -> Option<String> { None } fn mouse_left_click(&self, _position: &Position, _is_held: bool) -> Option<String> { None } fn mouse_left_click_release(&self, _position: &Position) -> Option<String> { None } fn mouse_right_click(&self, _position: &Position, _is_held: bool) -> Option<String> { None } fn mouse_right_click_release(&self, _position: &Position) -> Option<String> { None } fn mouse_middle_click(&self, _position: &Position, _is_held: bool) -> Option<String> { None } fn mouse_middle_click_release(&self, _position: &Position) -> Option<String> { None } fn mouse_scroll_up(&self, _position: &Position) -> Option<String> { None } fn mouse_scroll_down(&self, _position: &Position) -> Option<String> { None } fn focus_event(&self) -> Option<String> { None } fn unfocus_event(&self) -> Option<String> { None } fn get_line_number(&self) -> Option<usize> { None } fn update_search_term(&mut self, _needle: &str) { // No-op by default (only terminal-panes currently have search capability) } fn search_down(&mut self) { // No-op by default (only terminal-panes currently have search capability) } fn search_up(&mut self) { // No-op by default (only terminal-panes currently have search capability) } fn toggle_search_case_sensitivity(&mut self) { // No-op by default (only terminal-panes currently have search capability) } fn toggle_search_whole_words(&mut self) { // No-op by default (only terminal-panes currently have search capability) } fn toggle_search_wrap(&mut self) { // No-op by default (only terminal-panes currently have search capability) } fn clear_search(&mut self) { // No-op by default (only terminal-panes currently have search capability) } fn is_alternate_mode_active(&self) -> bool { // False by default (only terminal-panes support alternate mode) false } fn hold(&mut self, _exit_status: Option<i32>, _is_first_run: bool, _run_command: RunCommand) { // No-op by default, only terminal panes support holding } fn add_red_pane_frame_color_override(&mut self, _error_text: Option<String>); fn add_highlight_pane_frame_color_override( &mut self, _text: Option<String>, _client_id: Option<ClientId>, ) { } fn clear_pane_frame_color_override(&mut self, _client_id: Option<ClientId>); fn frame_color_override(&self) -> Option<PaletteColor>; fn invoked_with(&self) -> &Option<Run>; fn set_title(&mut self, title: String); fn update_loading_indication(&mut self, _loading_indication: LoadingIndication) {} // only relevant for plugins fn start_loading_indication(&mut self, _loading_indication: LoadingIndication) {} // only relevant for plugins fn progress_animation_offset(&mut self) {} // only relevant for plugins fn current_title(&self) -> String; fn custom_title(&self) -> Option<String>; fn is_held(&self) -> bool { false } fn exited(&self) -> bool { false } fn exit_status(&self) -> Option<i32> { None } fn rename(&mut self, _buf: Vec<u8>) {} fn serialize(&self, _scrollback_lines_to_serialize: Option<usize>) -> Option<String> { None } fn rerun(&mut self) -> Option<RunCommand> { None } // only relevant to terminal panes fn update_theme(&mut self, _theme: Styling) {} fn update_arrow_fonts(&mut self, _should_support_arrow_fonts: bool) {} fn update_rounded_corners(&mut self, _rounded_corners: bool) {} fn set_should_be_suppressed(&mut self, _should_be_suppressed: bool) {} fn query_should_be_suppressed(&self) -> bool { false } fn drain_fake_cursors(&mut self) -> Option<HashSet<(usize, usize)>> { None } fn toggle_pinned(&mut self) {} fn set_pinned(&mut self, _should_be_pinned: bool) {} fn reset_logical_position(&mut self) {} fn set_mouse_selection_support(&mut self, _selection_support: bool) {} fn pane_contents( &self, client_id: Option<ClientId>, _get_full_scrollback: bool, ) -> PaneContents; fn update_exit_status(&mut self, _exit_status: i32) {} } #[derive(Clone, Debug)] pub enum AdjustedInput { WriteBytesToTerminal(Vec<u8>), ReRunCommandInThisPane(RunCommand), PermissionRequestResult(Vec<PermissionType>, PermissionStatus), CloseThisPane, DropToShellInThisPane { working_dir: Option<PathBuf> }, WriteKeyToPlugin(KeyWithModifier), } pub fn get_next_terminal_position( tiled_panes: &TiledPanes, floating_panes: &FloatingPanes, ) -> usize { let tiled_panes_count = tiled_panes .get_panes() .filter(|(k, _)| match k { PaneId::Plugin(_) => false, PaneId::Terminal(_) => true, }) .count(); let floating_panes_count = floating_panes .get_panes() .filter(|(k, _)| match k { PaneId::Plugin(_) => false, PaneId::Terminal(_) => true, }) .count(); tiled_panes_count + floating_panes_count + 1 } impl Tab { // FIXME: Still too many arguments for clippy to be happy... #[allow(clippy::too_many_arguments)] pub fn new( index: usize, position: usize, name: String, display_area: Size, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, stacked_resize: Rc<RefCell<bool>>, sixel_image_store: Rc<RefCell<SixelImageStore>>, os_api: Box<dyn ServerOsApi>, senders: ThreadSenders, max_panes: Option<usize>, style: Style, default_mode_info: ModeInfo, draw_pane_frames: bool, auto_layout: bool, connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client session_is_mirrored: bool, client_id: Option<ClientId>, copy_options: CopyOptions, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, swap_layouts: (Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), default_shell: PathBuf, debug: bool, arrow_fonts: bool, styled_underlines: bool, explicitly_disable_kitty_keyboard_protocol: bool, default_editor: Option<PathBuf>, web_clients_allowed: bool, web_sharing: WebSharing, current_pane_group: Rc<RefCell<PaneGroups>>, currently_marking_pane_group: Rc<RefCell<HashMap<ClientId, bool>>>, advanced_mouse_actions: bool, web_server_ip: IpAddr, web_server_port: u16, ) -> Self { let name = if name.is_empty() { format!("Tab #{}", index + 1) } else { name }; let mut connected_clients = HashSet::new(); if let Some(client_id) = client_id { connected_clients.insert(client_id); } let viewport: Viewport = display_area.into(); let viewport = Rc::new(RefCell::new(viewport)); let display_area = Rc::new(RefCell::new(display_area)); let connected_clients = Rc::new(RefCell::new(connected_clients)); let mode_info = Rc::new(RefCell::new(HashMap::new())); let tiled_panes = TiledPanes::new( display_area.clone(), viewport.clone(), connected_clients.clone(), connected_clients_in_app.clone(), mode_info.clone(), character_cell_size.clone(), stacked_resize.clone(), session_is_mirrored, draw_pane_frames, default_mode_info.clone(), style, os_api.clone(), senders.clone(), ); let floating_panes = FloatingPanes::new( display_area.clone(), viewport.clone(), connected_clients.clone(), connected_clients_in_app.clone(), mode_info.clone(), character_cell_size.clone(), session_is_mirrored, default_mode_info.clone(), style, os_api.clone(), senders.clone(), ); let clipboard_provider = match copy_options.command { Some(command) => ClipboardProvider::Command(CopyCommand::new(command)), None => ClipboardProvider::Osc52(copy_options.clipboard), }; let swap_layouts = SwapLayouts::new(swap_layouts, display_area.clone()); Tab { index, position, tiled_panes, floating_panes, suppressed_panes: HashMap::new(), name: name.clone(), prev_name: name, max_panes, viewport, display_area, character_cell_size, sixel_image_store, synchronize_is_active: false, os_api, senders, should_clear_display_before_rendering: false, style, mode_info, default_mode_info, draw_pane_frames, auto_layout, pending_vte_events: HashMap::new(), connected_clients, selecting_with_mouse_in_pane: None, link_handler: Rc::new(RefCell::new(LinkHandler::new())), clipboard_provider, focus_pane_id: None, copy_on_select: copy_options.copy_on_select, terminal_emulator_colors, terminal_emulator_color_codes, pids_waiting_resize: HashSet::new(), cursor_positions_and_shape: HashMap::new(), is_pending: true, // will be switched to false once the layout is applied pending_instructions: vec![], swap_layouts, default_shell, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, default_editor, web_clients_allowed, web_sharing, mouse_hover_pane_id: HashMap::new(), current_pane_group, currently_marking_pane_group, advanced_mouse_actions, connected_clients_in_app, web_server_ip, web_server_port, } } pub fn apply_layout( &mut self, layout: TiledPaneLayout, floating_panes_layout: Vec<FloatingPaneLayout>, new_terminal_ids: Vec<(u32, HoldForCommand)>, new_floating_terminal_ids: Vec<(u32, HoldForCommand)>, new_plugin_ids: HashMap<RunPluginOrAlias, Vec<u32>>, client_id: ClientId, blocking_terminal: Option<(u32, NotificationEnd)>, ) -> Result<()> { self.swap_layouts .set_base_layout((layout.clone(), floating_panes_layout.clone())); match LayoutApplier::new( &self.viewport, &self.senders, &self.sixel_image_store, &self.link_handler, &self.terminal_emulator_colors, &self.terminal_emulator_color_codes, &self.character_cell_size, &self.connected_clients_in_app, &self.style, &self.display_area, &mut self.tiled_panes, &mut self.floating_panes, self.draw_pane_frames, &mut self.focus_pane_id, &self.os_api, self.debug, self.arrow_fonts, self.styled_underlines, self.explicitly_disable_kitty_keyboard_protocol, blocking_terminal, ) .apply_layout( layout, floating_panes_layout, new_terminal_ids, new_floating_terminal_ids, new_plugin_ids, client_id, ) { Ok(should_show_floating_panes) => { if should_show_floating_panes && !self.floating_panes.panes_are_visible() { self.toggle_floating_panes(Some(client_id), None, None) .non_fatal(); } else if !should_show_floating_panes && self.floating_panes.panes_are_visible() { self.toggle_floating_panes(Some(client_id), None, None) .non_fatal(); } self.tiled_panes.reapply_pane_frames(); self.is_pending = false; self.apply_buffered_instructions().non_fatal(); }, Err(e) => { // TODO: this should only happen due to an erroneous layout created by user // configuration that was somehow not caught in our KDL layout parser // we should still be able to properly recover from this with a useful error // message though log::error!("Failed to apply layout: {}", e); self.tiled_panes.reapply_pane_frames(); self.is_pending = false; self.apply_buffered_instructions().non_fatal(); }, } Ok(()) } pub fn override_layout( &mut self, layout: TiledPaneLayout, floating_panes_layout: Vec<FloatingPaneLayout>,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/layout_applier.rs
zellij-server/src/tab/layout_applier.rs
use zellij_utils::errors::prelude::*; use crate::resize_pty; use crate::tab::{get_next_terminal_position, HoldForCommand, Pane}; use crate::{ os_input_output::ServerOsApi, panes::sixel::SixelImageStore, panes::{FloatingPanes, TiledPanes}, panes::{LinkHandler, PaneId, PluginPane, TerminalPane}, plugins::PluginInstruction, pty::PtyInstruction, thread_bus::ThreadSenders, ClientId, NotificationEnd, }; use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::rc::Rc; use zellij_utils::{ data::{Palette, Style}, input::layout::{FloatingPaneLayout, Run, RunPluginOrAlias, TiledPaneLayout}, pane_size::{Offset, PaneGeom, Size, SizeInPixels, Viewport}, }; pub struct LayoutApplier<'a> { viewport: Rc<RefCell<Viewport>>, // includes all non-UI panes senders: ThreadSenders, sixel_image_store: Rc<RefCell<SixelImageStore>>, link_handler: Rc<RefCell<LinkHandler>>, terminal_emulator_colors: Rc<RefCell<Palette>>, terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, connected_clients: Rc<RefCell<HashMap<ClientId, bool>>>, style: Style, display_area: Rc<RefCell<Size>>, // includes all panes (including eg. the status bar and tab bar in the default layout) tiled_panes: &'a mut TiledPanes, floating_panes: &'a mut FloatingPanes, draw_pane_frames: bool, focus_pane_id: &'a mut Option<PaneId>, os_api: Box<dyn ServerOsApi>, debug: bool, arrow_fonts: bool, styled_underlines: bool, explicitly_disable_kitty_keyboard_protocol: bool, blocking_terminal: Option<(u32, NotificationEnd)>, } impl<'a> LayoutApplier<'a> { pub fn new( viewport: &Rc<RefCell<Viewport>>, senders: &ThreadSenders, sixel_image_store: &Rc<RefCell<SixelImageStore>>, link_handler: &Rc<RefCell<LinkHandler>>, terminal_emulator_colors: &Rc<RefCell<Palette>>, terminal_emulator_color_codes: &Rc<RefCell<HashMap<usize, String>>>, character_cell_size: &Rc<RefCell<Option<SizeInPixels>>>, connected_clients: &Rc<RefCell<HashMap<ClientId, bool>>>, style: &Style, display_area: &Rc<RefCell<Size>>, // includes all panes (including eg. the status bar and tab bar in the default layout) tiled_panes: &'a mut TiledPanes, floating_panes: &'a mut FloatingPanes, draw_pane_frames: bool, focus_pane_id: &'a mut Option<PaneId>, os_api: &Box<dyn ServerOsApi>, debug: bool, arrow_fonts: bool, styled_underlines: bool, explicitly_disable_kitty_keyboard_protocol: bool, blocking_terminal: Option<(u32, NotificationEnd)>, ) -> Self { let viewport = viewport.clone(); let senders = senders.clone(); let sixel_image_store = sixel_image_store.clone(); let link_handler = link_handler.clone(); let terminal_emulator_colors = terminal_emulator_colors.clone(); let terminal_emulator_color_codes = terminal_emulator_color_codes.clone(); let character_cell_size = character_cell_size.clone(); let connected_clients = connected_clients.clone(); let style = style.clone(); let display_area = display_area.clone(); let os_api = os_api.clone(); LayoutApplier { viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, tiled_panes, floating_panes, draw_pane_frames, focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, blocking_terminal, } } pub fn apply_layout( &mut self, layout: TiledPaneLayout, floating_panes_layout: Vec<FloatingPaneLayout>, new_terminal_ids: Vec<(u32, HoldForCommand)>, new_floating_terminal_ids: Vec<(u32, HoldForCommand)>, mut new_plugin_ids: HashMap<RunPluginOrAlias, Vec<u32>>, client_id: ClientId, ) -> Result<bool> { // true => should_show_floating_panes let hide_floating_panes = layout.hide_floating_panes; self.apply_tiled_panes_layout(layout, new_terminal_ids, &mut new_plugin_ids, client_id)?; let layout_has_floating_panes = self.apply_floating_panes_layout( floating_panes_layout, new_floating_terminal_ids, &mut new_plugin_ids, )?; let should_show_floating_panes = layout_has_floating_panes && !hide_floating_panes; return Ok(should_show_floating_panes); } pub fn override_layout( &mut self, tiled_panes_layout: TiledPaneLayout, floating_panes_layout: Vec<FloatingPaneLayout>, new_terminal_ids: Vec<(u32, HoldForCommand)>, new_floating_terminal_ids: Vec<(u32, HoldForCommand)>, mut new_plugin_ids: HashMap<RunPluginOrAlias, Vec<u32>>, retain_existing_terminal_panes: bool, retain_existing_plugin_panes: bool, client_id: ClientId, ) -> Result<bool> { // true => should_show_floating_panes let hide_floating_panes = tiled_panes_layout.hide_floating_panes; self.override_tiled_panes_layout_for_existing_panes( &tiled_panes_layout, new_terminal_ids, &mut new_plugin_ids, retain_existing_terminal_panes, retain_existing_plugin_panes, client_id, )?; let layout_has_floating_panes = self.override_floating_panes_layout_for_existing_panes( &floating_panes_layout, new_floating_terminal_ids, &mut new_plugin_ids, retain_existing_terminal_panes, retain_existing_plugin_panes, )?; let should_show_floating_panes = layout_has_floating_panes && !hide_floating_panes; return Ok(should_show_floating_panes); } pub fn apply_tiled_panes_layout_to_existing_panes( &mut self, layout: &TiledPaneLayout, ) -> Result<()> { let positions_in_layout = self.flatten_layout(layout, true)?; let mut existing_tab_state = ExistingTabState::new(self.tiled_panes.drain()); let mut pane_applier = PaneApplier::new( &mut self.tiled_panes, &mut self.floating_panes, &self.senders, &self.character_cell_size, ); let mut positions_left_without_exact_matches = vec![]; // look for exact matches (eg. panes that expect a specific command or plugin to run in them) for (layout, position_and_size) in positions_in_layout { match existing_tab_state .find_and_extract_exact_match_pane(&layout.run, position_and_size.logical_position) { Some(pane) => { pane_applier.apply_position_and_size_to_tiled_pane( pane, position_and_size, layout, ); }, None => { positions_left_without_exact_matches.push((layout, position_and_size)); }, } } // look for matches according to the logical position in the layout let mut positions_left = vec![]; for (layout, position_and_size) in positions_left_without_exact_matches { if let Some(pane) = existing_tab_state.find_and_extract_pane_with_same_logical_position( position_and_size.logical_position, ) { pane_applier.apply_position_and_size_to_tiled_pane(pane, position_and_size, layout); } else { positions_left.push((layout, position_and_size)); } } // fill the remaining panes by order of their logical position for (layout, position_and_size) in positions_left { // now let's try to find panes on a best-effort basis if let Some(pane) = existing_tab_state.find_and_extract_pane(position_and_size.logical_position) { pane_applier.apply_position_and_size_to_tiled_pane(pane, position_and_size, layout); } } // add the rest of the panes where tiled_panes finds room for them (eg. if the layout had // less panes than we've got in our state) let remaining_pane_ids: Vec<PaneId> = existing_tab_state.pane_ids(); pane_applier.handle_remaining_tiled_pane_ids( remaining_pane_ids, existing_tab_state, None, None, ); pane_applier.finalize_tiled_state(); LayoutApplier::offset_viewport( self.viewport.clone(), self.display_area.clone(), self.tiled_panes, self.draw_pane_frames, ); Ok(()) } pub fn override_tiled_panes_layout_for_existing_panes( &mut self, tiled_panes_layout: &TiledPaneLayout, mut new_terminal_ids: Vec<(u32, HoldForCommand)>, mut new_plugin_ids: &mut HashMap<RunPluginOrAlias, Vec<u32>>, retain_existing_terminal_panes: bool, retain_existing_plugin_panes: bool, client_id: ClientId, ) -> Result<()> { let positions_in_layout = self.flatten_layout(tiled_panes_layout, false)?; let mut existing_tab_state = ExistingTabState::new(self.tiled_panes.drain()); let mut pane_applier = PaneApplier::new( &mut self.tiled_panes, &mut self.floating_panes, &self.senders, &self.character_cell_size, ); let mut positions_left_without_exact_matches = vec![]; // look for exact matches (eg. panes that expect a specific command or plugin to run in them) let mut last_logical_position = None; for (layout, position_and_size) in positions_in_layout { match existing_tab_state.find_and_extract_exact_pane_with_same_run(&layout.run) { Some(pane) => { last_logical_position = position_and_size.logical_position; pane_applier.apply_position_and_size_to_tiled_pane( pane, position_and_size, layout, ); }, None => { last_logical_position = position_and_size.logical_position; positions_left_without_exact_matches.push((layout, position_and_size)); }, } } let remaining_pane_ids: Vec<PaneId> = existing_tab_state.pane_ids(); self.close_non_retained_panes( &mut existing_tab_state, &remaining_pane_ids, retain_existing_terminal_panes, retain_existing_plugin_panes, ); let (focus_pane_id, pane_ids_expanded_in_stack) = self.position_new_panes( &mut new_terminal_ids, &mut new_plugin_ids, &mut positions_left_without_exact_matches, )?; // we do this because we have to add the remaining tiled pane ids ONLY AFTER positioning // the new panes, otherwise the layout might get borked let mut pane_applier = PaneApplier::new( &mut self.tiled_panes, &mut self.floating_panes, &self.senders, &self.character_cell_size, ); if retain_existing_terminal_panes || retain_existing_plugin_panes { pane_applier.handle_remaining_tiled_pane_ids( remaining_pane_ids, existing_tab_state, last_logical_position, Some(client_id), ); } pane_applier.finalize_tiled_state(); if let Some(pane_id) = focus_pane_id { *self.focus_pane_id = Some(pane_id); self.tiled_panes.focus_pane(pane_id, client_id); } // in case focused panes were closed by the override self.tiled_panes.move_client_focus_to_existing_panes(); for pane_id in &pane_ids_expanded_in_stack { self.tiled_panes.expand_pane_in_stack(*pane_id); } LayoutApplier::offset_viewport( self.viewport.clone(), self.display_area.clone(), self.tiled_panes, self.draw_pane_frames, ); Ok(()) } fn close_non_retained_panes( &self, existing_tab_state: &mut ExistingTabState, remaining_pane_ids: &[PaneId], retain_existing_terminal_panes: bool, retain_existing_plugin_panes: bool, ) { for pane_id in remaining_pane_ids { if retain_existing_terminal_panes && matches!(pane_id, PaneId::Terminal(_)) { continue; } if retain_existing_plugin_panes && matches!(pane_id, PaneId::Plugin(_)) { continue; } existing_tab_state.remove_pane(pane_id); match pane_id { PaneId::Terminal(_) => { let _ = self .senders .send_to_pty(PtyInstruction::ClosePane(*pane_id, None)); }, PaneId::Plugin(plugin_id) => { let _ = self .senders .send_to_plugin(PluginInstruction::Unload(*plugin_id)); }, } } } fn flatten_layout( &self, layout: &TiledPaneLayout, has_existing_panes: bool, ) -> Result<Vec<(TiledPaneLayout, PaneGeom)>> { let free_space = self.total_space_for_tiled_panes(); let tiled_panes_count = if has_existing_panes { Some(self.tiled_panes.visible_panes_count()) } else { None }; let focus_layout_if_not_focused = if has_existing_panes { false } else { true }; let mut positions_in_layout = layout .position_panes_in_space( &free_space, tiled_panes_count, false, focus_layout_if_not_focused, ) .or_else(|_e| { // in the error branch, we try to recover by positioning the panes in the space but // ignoring the percentage sizes (passing true as the third argument), this is a hack // around some issues with the constraint system that should be addressed in a systemic // manner layout.position_panes_in_space( &free_space, tiled_panes_count, true, focus_layout_if_not_focused, ) }) .map_err(|e| anyhow!(e))?; let mut logical_position = 0; for (_layout, position_and_size) in positions_in_layout.iter_mut() { position_and_size.logical_position = Some(logical_position); logical_position += 1; } Ok(positions_in_layout) } fn apply_tiled_panes_layout( &mut self, layout: TiledPaneLayout, mut new_terminal_ids: Vec<(u32, HoldForCommand)>, mut new_plugin_ids: &mut HashMap<RunPluginOrAlias, Vec<u32>>, client_id: ClientId, ) -> Result<()> { let err_context = || format!("failed to apply tiled panes layout"); let mut positions_in_layout = self.flatten_layout(&layout, false)?; let run_instructions_without_a_location = self.position_run_instructions_to_ignore( &layout.run_instructions_to_ignore, &mut positions_in_layout, ); let (focus_pane_id, pane_ids_expanded_in_stack) = self.position_new_panes( &mut new_terminal_ids, &mut new_plugin_ids, &mut positions_in_layout, )?; self.handle_run_instructions_without_a_location( run_instructions_without_a_location, &mut new_terminal_ids, ); for pane_id in &pane_ids_expanded_in_stack { self.tiled_panes.expand_pane_in_stack(*pane_id); } self.adjust_viewport().with_context(err_context)?; self.set_focused_tiled_pane(focus_pane_id, client_id); Ok(()) } fn position_run_instructions_to_ignore( &mut self, run_instructions_to_ignore: &Vec<Option<Run>>, positions_in_layout: &mut Vec<(TiledPaneLayout, PaneGeom)>, ) -> Vec<Option<Run>> { // here we try to find rooms for the panes that are already running (represented by // run_instructions_to_ignore), we try to either find an explicit position (the new // layout has a pane with the exact run instruction) or an otherwise free position // (the new layout has a pane with None as its run instruction, eg. just `pane` in the // layout) let mut run_instructions_without_a_location = vec![]; for run_instruction in run_instructions_to_ignore.clone().drain(..) { if self .place_running_pane_in_exact_match_location(&run_instruction, positions_in_layout) { // found exact match } else if self .place_running_pane_in_empty_location(&run_instruction, positions_in_layout) { // found empty location } else { // no room! we'll add it below after we place everything else run_instructions_without_a_location.push(run_instruction); } } run_instructions_without_a_location } fn position_new_panes( &mut self, new_terminal_ids: &mut Vec<(u32, HoldForCommand)>, new_plugin_ids: &mut HashMap<RunPluginOrAlias, Vec<u32>>, positions_in_layout: &mut Vec<(TiledPaneLayout, PaneGeom)>, ) -> Result<(Option<PaneId>, Vec<PaneId>)> { // returns: optional pane id to focus, pane ids // expanded in stack // here we open new panes for each run instruction in the layout with the details // we got from the plugin thread and pty thread let mut pane_ids_expanded_in_stack = vec![]; let mut focus_pane_id: Option<PaneId> = None; let mut set_focus_pane_id = |layout: &TiledPaneLayout, pane_id: PaneId| { if layout.focus.unwrap_or(false) && focus_pane_id.is_none() { focus_pane_id = Some(pane_id); } }; for (layout, position_and_size) in positions_in_layout { if let Some(Run::Plugin(run)) = layout.run.clone() { let pid = self.new_tiled_plugin_pane(run, new_plugin_ids, &position_and_size, &layout)?; if layout.is_expanded_in_stack { pane_ids_expanded_in_stack.push(PaneId::Terminal(pid)); } set_focus_pane_id(&layout, PaneId::Plugin(pid)); } else if !new_terminal_ids.is_empty() { // there are still panes left to fill, use the pids we received in this method let (pid, hold_for_command) = new_terminal_ids.remove(0); self.new_terminal_pane(pid, &hold_for_command, &position_and_size, &layout)?; if layout.is_expanded_in_stack { pane_ids_expanded_in_stack.push(PaneId::Terminal(pid)); } set_focus_pane_id(&layout, PaneId::Terminal(pid)); } } Ok((focus_pane_id, pane_ids_expanded_in_stack)) } fn handle_run_instructions_without_a_location( &mut self, run_instructions_without_a_location: Vec<Option<Run>>, new_terminal_ids: &mut Vec<(u32, HoldForCommand)>, ) { for run_instruction in run_instructions_without_a_location { self.tiled_panes .assign_geom_for_pane_with_run(run_instruction); } for (unused_pid, _) in new_terminal_ids { let _ = self.senders.send_to_pty(PtyInstruction::ClosePane( PaneId::Terminal(*unused_pid), None, )); } } fn new_tiled_plugin_pane( &mut self, run: RunPluginOrAlias, new_plugin_ids: &mut HashMap<RunPluginOrAlias, Vec<u32>>, position_and_size: &PaneGeom, layout: &TiledPaneLayout, ) -> Result<u32> { let err_context = || format!("Failed to start new plugin pane"); let pane_title = run.location_string(); let pid = new_plugin_ids .get_mut(&run) .and_then(|ids| ids.pop()) .with_context(err_context)?; let mut new_plugin = PluginPane::new( pid, *position_and_size, self.senders .to_plugin .as_ref() .with_context(err_context)? .clone(), pane_title, layout.name.clone().unwrap_or_default(), self.sixel_image_store.clone(), self.terminal_emulator_colors.clone(), self.terminal_emulator_color_codes.clone(), self.link_handler.clone(), self.character_cell_size.clone(), self.connected_clients.borrow().keys().copied().collect(), self.style, layout.run.clone(), self.debug, self.arrow_fonts, self.styled_underlines, ); if let Some(pane_initial_contents) = &layout.pane_initial_contents { new_plugin.handle_pty_bytes(pane_initial_contents.as_bytes().into()); new_plugin.handle_pty_bytes("\n\r".as_bytes().into()); } new_plugin.set_borderless(layout.borderless); if let Some(exclude_from_sync) = layout.exclude_from_sync { new_plugin.set_exclude_from_sync(exclude_from_sync); } self.tiled_panes .add_pane_with_existing_geom(PaneId::Plugin(pid), Box::new(new_plugin)); Ok(pid) } fn new_floating_plugin_pane( &mut self, run: RunPluginOrAlias, new_plugin_ids: &mut HashMap<RunPluginOrAlias, Vec<u32>>, position_and_size: PaneGeom, floating_pane_layout: &FloatingPaneLayout, ) -> Result<Option<PaneId>> { let mut pid_to_focus = None; let err_context = || format!("Failed to create new floating plugin pane"); let pane_title = run.location_string(); let pid = new_plugin_ids .get_mut(&run) .and_then(|ids| ids.pop()) .with_context(err_context)?; let mut new_pane = PluginPane::new( pid, position_and_size, self.senders .to_plugin .as_ref() .with_context(err_context)? .clone(), pane_title, floating_pane_layout.name.clone().unwrap_or_default(), self.sixel_image_store.clone(), self.terminal_emulator_colors.clone(), self.terminal_emulator_color_codes.clone(), self.link_handler.clone(), self.character_cell_size.clone(), self.connected_clients.borrow().keys().copied().collect(), self.style, floating_pane_layout.run.clone(), self.debug, self.arrow_fonts, self.styled_underlines, ); if let Some(pane_initial_contents) = &floating_pane_layout.pane_initial_contents { new_pane.handle_pty_bytes(pane_initial_contents.as_bytes().into()); new_pane.handle_pty_bytes("\n\r".as_bytes().into()); } new_pane.set_borderless(false); new_pane.set_content_offset(Offset::frame(1)); resize_pty!( new_pane, self.os_api, self.senders, self.character_cell_size )?; self.floating_panes .add_pane(PaneId::Plugin(pid), Box::new(new_pane)); if floating_pane_layout.focus.unwrap_or(false) { pid_to_focus = Some(PaneId::Plugin(pid)); } Ok(pid_to_focus) } fn new_floating_terminal_pane( &mut self, pid: &u32, hold_for_command: &HoldForCommand, position_and_size: PaneGeom, floating_pane_layout: &FloatingPaneLayout, ) -> Result<Option<PaneId>> { let mut pane_id_to_focus = None; let next_terminal_position = get_next_terminal_position(&self.tiled_panes, &self.floating_panes); let initial_title = match &floating_pane_layout.run { Some(Run::Command(run_command)) => Some(run_command.to_string()), _ => None, }; let mut new_pane = TerminalPane::new( *pid, position_and_size, self.style, next_terminal_position, floating_pane_layout.name.clone().unwrap_or_default(), self.link_handler.clone(), self.character_cell_size.clone(), self.sixel_image_store.clone(), self.terminal_emulator_colors.clone(), self.terminal_emulator_color_codes.clone(), initial_title, floating_pane_layout.run.clone(), self.debug, self.arrow_fonts, self.styled_underlines, self.explicitly_disable_kitty_keyboard_protocol, None, ); if let Some(pane_initial_contents) = &floating_pane_layout.pane_initial_contents { new_pane.handle_pty_bytes(pane_initial_contents.as_bytes().into()); new_pane.handle_pty_bytes("\n\r".as_bytes().into()); } new_pane.set_borderless(false); new_pane.set_content_offset(Offset::frame(1)); if let Some(held_command) = hold_for_command { new_pane.hold(None, true, held_command.clone()); } resize_pty!( new_pane, self.os_api, self.senders, self.character_cell_size )?; self.floating_panes .add_pane(PaneId::Terminal(*pid), Box::new(new_pane)); if floating_pane_layout.focus.unwrap_or(false) { pane_id_to_focus = Some(PaneId::Terminal(*pid)); } Ok(pane_id_to_focus) } fn new_terminal_pane( &mut self, pid: u32, hold_for_command: &HoldForCommand, position_and_size: &PaneGeom, layout: &TiledPaneLayout, ) -> Result<()> { let next_terminal_position = get_next_terminal_position(&self.tiled_panes, &self.floating_panes); let initial_title = match &layout.run { Some(Run::Command(run_command)) => Some(run_command.to_string()), _ => None, }; // Check if this terminal should receive the blocking completion_tx let notification_end = if let Some((blocking_pid, _)) = &self.blocking_terminal { if *blocking_pid == pid { self.blocking_terminal.take().map(|(_, tx)| tx) } else { None } } else { None }; let mut new_pane = TerminalPane::new( pid, *position_and_size, self.style, next_terminal_position, layout.name.clone().unwrap_or_default(), self.link_handler.clone(), self.character_cell_size.clone(), self.sixel_image_store.clone(), self.terminal_emulator_colors.clone(), self.terminal_emulator_color_codes.clone(), initial_title, layout.run.clone(), self.debug, self.arrow_fonts, self.styled_underlines, self.explicitly_disable_kitty_keyboard_protocol, notification_end, ); if let Some(pane_initial_contents) = &layout.pane_initial_contents { new_pane.handle_pty_bytes(pane_initial_contents.as_bytes().into()); new_pane.handle_pty_bytes("\n\r".as_bytes().into()); } new_pane.set_borderless(layout.borderless); if let Some(exclude_from_sync) = layout.exclude_from_sync { new_pane.set_exclude_from_sync(exclude_from_sync); } if let Some(held_command) = hold_for_command { new_pane.hold(None, true, held_command.clone()); } self.tiled_panes .add_pane_with_existing_geom(PaneId::Terminal(pid), Box::new(new_pane)); Ok(()) } fn place_running_pane_in_exact_match_location( &mut self, run_instruction: &Option<Run>, positions_in_layout: &mut Vec<(TiledPaneLayout, PaneGeom)>, ) -> bool { let mut found_exact_match = false; if let Some(position) = positions_in_layout .iter() .position(|(layout, _position_and_size)| &layout.run == run_instruction) { let (layout, position_and_size) = positions_in_layout.remove(position); self.tiled_panes.set_geom_for_pane_with_run( layout.run, position_and_size, layout.borderless, ); found_exact_match = true; } found_exact_match } fn place_running_pane_in_empty_location( &mut self, run_instruction: &Option<Run>, positions_in_layout: &mut Vec<(TiledPaneLayout, PaneGeom)>, ) -> bool { let mut found_empty_location = false; if let Some(position) = positions_in_layout .iter() .position(|(layout, _position_and_size)| layout.run.is_none()) { let (layout, position_and_size) = positions_in_layout.remove(position); self.tiled_panes.set_geom_for_pane_with_run( run_instruction.clone(), position_and_size, layout.borderless, ); found_empty_location = true; } found_empty_location } fn apply_floating_panes_layout( &mut self, mut floating_panes_layout: Vec<FloatingPaneLayout>, new_floating_terminal_ids: Vec<(u32, HoldForCommand)>, mut new_plugin_ids: &mut HashMap<RunPluginOrAlias, Vec<u32>>, ) -> Result<bool> { let layout_has_floating_panes = !floating_panes_layout.is_empty(); let mut logical_position = 0; for floating_pane_layout in floating_panes_layout.iter_mut() { floating_pane_layout.logical_position = Some(logical_position); logical_position += 1; } let floating_panes_layout = floating_panes_layout.iter(); let mut focused_floating_pane = None; let mut new_floating_terminal_ids = new_floating_terminal_ids.iter(); for floating_pane_layout in floating_panes_layout { let position_and_size = self .floating_panes .position_floating_pane_layout(&floating_pane_layout)?; let pid_to_focus = if floating_pane_layout.already_running { self.floating_panes.set_geom_for_pane_with_run( floating_pane_layout.run.clone(), position_and_size, ); None } else if let Some(Run::Plugin(run)) = floating_pane_layout.run.clone() { self.new_floating_plugin_pane( run, &mut new_plugin_ids, position_and_size, &floating_pane_layout, )? } else if let Some((pid, hold_for_command)) = new_floating_terminal_ids.next() { self.new_floating_terminal_pane( pid, hold_for_command, position_and_size, floating_pane_layout, )? } else { None }; if let Some(pid_to_focus) = pid_to_focus { focused_floating_pane = Some(pid_to_focus); } } if let Some(focused_floating_pane) = focused_floating_pane { self.floating_panes .focus_pane_for_all_clients(focused_floating_pane); } if layout_has_floating_panes { Ok(true) } else { Ok(false) } } pub fn apply_floating_panes_layout_to_existing_panes( &mut self, floating_panes_layout: &Vec<FloatingPaneLayout>,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/unit/tab_integration_tests.rs
zellij-server/src/tab/unit/tab_integration_tests.rs
use super::{Output, Tab}; use crate::panes::sixel::SixelImageStore; use crate::screen::CopyOptions; use crate::Arc; use crate::{ os_input_output::{AsyncReader, Pid, ServerOsApi}, pane_groups::PaneGroups, panes::PaneId, plugins::PluginInstruction, thread_bus::ThreadSenders, ClientId, }; use std::net::{IpAddr, Ipv4Addr}; use std::path::PathBuf; use std::sync::Mutex; use zellij_utils::channels::Receiver; use zellij_utils::data::Direction; use zellij_utils::data::Resize; use zellij_utils::data::ResizeStrategy; use zellij_utils::data::WebSharing; use zellij_utils::envs::set_session_name; use zellij_utils::errors::{prelude::*, ErrorContext}; use zellij_utils::input::layout::{ FloatingPaneLayout, Layout, PluginUserConfiguration, RunPluginLocation, RunPluginOrAlias, SwapFloatingLayout, SwapTiledLayout, TiledPaneLayout, }; use zellij_utils::input::mouse::MouseEvent; use zellij_utils::input::plugins::PluginTag; use zellij_utils::ipc::IpcReceiverWithContext; use zellij_utils::pane_size::{Size, SizeInPixels}; use zellij_utils::position::Position; use crate::pty_writer::PtyWriteInstruction; use zellij_utils::channels::{self, ChannelWithContext, SenderWithContext}; use std::cell::RefCell; use std::collections::{BTreeMap, HashMap, HashSet}; use std::os::unix::io::RawFd; use std::rc::Rc; use interprocess::local_socket::LocalSocketStream; use zellij_utils::{ data::{InputMode, ModeInfo, NewPanePlacement, Palette, Style}, input::command::{RunCommand, TerminalAction}, ipc::{ClientToServerMsg, ServerToClientMsg}, }; #[derive(Clone, Default)] struct FakeInputOutput { file_dumps: Arc<Mutex<HashMap<String, String>>>, pub tty_stdin_bytes: Arc<Mutex<BTreeMap<u32, Vec<u8>>>>, } impl ServerOsApi for FakeInputOutput { fn set_terminal_size_using_terminal_id( &self, _id: u32, _cols: u16, _rows: u16, _width_in_pixels: Option<u16>, _height_in_pixels: Option<u16>, ) -> Result<()> { // noop Ok(()) } fn spawn_terminal( &self, _file_to_open: TerminalAction, _quit_db: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, _default_editor: Option<PathBuf>, ) -> Result<(u32, RawFd, RawFd)> { unimplemented!() } fn read_from_tty_stdout(&self, _fd: RawFd, _buf: &mut [u8]) -> Result<usize> { unimplemented!() } fn async_file_reader(&self, _fd: RawFd) -> Box<dyn AsyncReader> { unimplemented!() } fn write_to_tty_stdin(&self, id: u32, buf: &[u8]) -> Result<usize> { self.tty_stdin_bytes .lock() .unwrap() .entry(id) .or_insert_with(|| vec![]) .extend_from_slice(buf); Ok(buf.len()) } fn tcdrain(&self, _id: u32) -> Result<()> { unimplemented!() } fn kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn force_kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn box_clone(&self) -> Box<dyn ServerOsApi> { Box::new((*self).clone()) } fn send_to_client(&self, _client_id: ClientId, _msg: ServerToClientMsg) -> Result<()> { unimplemented!() } fn new_client( &mut self, _client_id: ClientId, _stream: LocalSocketStream, ) -> Result<IpcReceiverWithContext<ClientToServerMsg>> { unimplemented!() } fn remove_client(&mut self, _client_id: ClientId) -> Result<()> { unimplemented!() } fn load_palette(&self) -> Palette { unimplemented!() } fn get_cwd(&self, _pid: Pid) -> Option<PathBuf> { unimplemented!() } fn write_to_file(&mut self, buf: String, name: Option<String>) -> Result<()> { let f: String = match name { Some(x) => x, None => "tmp-name".to_owned(), }; self.file_dumps.lock().to_anyhow()?.insert(f, buf); Ok(()) } fn re_run_command_in_terminal( &self, _terminal_id: u32, _run_command: RunCommand, _quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status ) -> Result<(RawFd, RawFd)> { unimplemented!() } fn clear_terminal_id(&self, _terminal_id: u32) -> Result<()> { unimplemented!() } fn send_sigint(&self, pid: Pid) -> Result<()> { unimplemented!() } } struct MockPtyInstructionBus { output: Arc<Mutex<Vec<String>>>, pty_writer_sender: SenderWithContext<PtyWriteInstruction>, pty_writer_receiver: Arc<Receiver<(PtyWriteInstruction, ErrorContext)>>, handle: Option<std::thread::JoinHandle<()>>, } impl MockPtyInstructionBus { fn new() -> Self { let output = Arc::new(Mutex::new(vec![])); let (pty_writer_sender, pty_writer_receiver): ChannelWithContext<PtyWriteInstruction> = channels::unbounded(); let pty_writer_sender = SenderWithContext::new(pty_writer_sender); let pty_writer_receiver = Arc::new(pty_writer_receiver); Self { output, pty_writer_sender, pty_writer_receiver, handle: None, } } fn start(&mut self) { let output = self.output.clone(); let pty_writer_receiver = self.pty_writer_receiver.clone(); let handle = std::thread::Builder::new() .name("pty_writer".to_string()) .spawn({ move || loop { let (event, _err_ctx) = pty_writer_receiver .recv() .expect("failed to receive event on channel"); match event { PtyWriteInstruction::Write(msg, _) => output .lock() .unwrap() .push(String::from_utf8_lossy(&msg).to_string()), PtyWriteInstruction::Exit => break, _ => {}, } } }) .unwrap(); self.handle = Some(handle); } fn exit(&mut self) { self.pty_writer_sender .send(PtyWriteInstruction::Exit) .unwrap(); let handle = self.handle.take().unwrap(); handle.join().unwrap(); } fn pty_write_sender(&self) -> SenderWithContext<PtyWriteInstruction> { self.pty_writer_sender.clone() } fn clone_output(&self) -> Vec<String> { self.output.lock().unwrap().clone() } } fn create_new_tab(size: Size, default_mode: ModeInfo) -> Tab { set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput::default()); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = default_mode; let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(true)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_without_pane_frames(size: Size, default_mode: ModeInfo) -> Tab { set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput::default()); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = default_mode; let style = Style::default(); let draw_pane_frames = false; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(true)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_with_swap_layouts( size: Size, default_mode: ModeInfo, swap_layouts: (Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), base_layout_and_ids: Option<( TiledPaneLayout, Vec<FloatingPaneLayout>, Vec<(u32, Option<RunCommand>)>, Vec<(u32, Option<RunCommand>)>, HashMap<RunPluginOrAlias, Vec<u32>>, )>, draw_pane_frames: bool, stacked_resize: bool, ) -> Tab { set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput::default()); let mut senders = ThreadSenders::default().silently_fail_on_send(); let (mock_plugin_sender, _mock_plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded(); senders.replace_to_plugin(SenderWithContext::new(mock_plugin_sender)); let max_panes = None; let mode_info = default_mode; let style = Style::default(); let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(stacked_resize)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, swap_layouts, PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); let ( base_layout, base_floating_layout, new_terminal_ids, new_floating_terminal_ids, new_plugin_ids, ) = base_layout_and_ids.unwrap_or_default(); let new_terminal_ids = if new_terminal_ids.is_empty() { vec![(1, None)] } else { new_terminal_ids }; tab.apply_layout( base_layout, base_floating_layout, new_terminal_ids, new_floating_terminal_ids, new_plugin_ids, client_id, None, ) .unwrap(); tab } fn create_new_tab_with_os_api( size: Size, default_mode: ModeInfo, os_api: &Box<FakeInputOutput>, ) -> Tab { set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = os_api.clone(); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = default_mode; let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(true)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_with_layout(size: Size, default_mode: ModeInfo, layout: &str) -> Tab { set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput::default()); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = default_mode; let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(true)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let layout = Layout::from_str(layout, "layout_file_name".into(), None, None).unwrap(); let (tab_layout, floating_panes_layout) = layout.new_tab(); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); let pane_ids = tab_layout .extract_run_instructions() .iter() .enumerate() .map(|(i, _)| (i as u32, None)) .collect(); let floating_pane_ids = floating_panes_layout .iter() .enumerate() .map(|(i, _)| (i as u32, None)) .collect(); tab.apply_layout( tab_layout, floating_panes_layout, pane_ids, floating_pane_ids, HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_with_mock_pty_writer( size: Size, default_mode: ModeInfo, mock_pty_writer: SenderWithContext<PtyWriteInstruction>, ) -> Tab { set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput::default()); let mut senders = ThreadSenders::default().silently_fail_on_send(); senders.replace_to_pty_writer(mock_pty_writer); let max_panes = None; let mode_info = default_mode; let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(true)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_with_sixel_support( size: Size, sixel_image_store: Rc<RefCell<SixelImageStore>>, ) -> Tab { // this is like the create_new_tab function but includes stuff needed for sixel, // eg. character_cell_size set_session_name("test".into()); let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput::default()); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = ModeInfo::default(); let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let stacked_resize = Rc::new(RefCell::new(true)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let current_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_size, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn read_fixture(fixture_name: &str) -> Vec<u8> { let mut path_to_file = std::path::PathBuf::new(); path_to_file.push("../src"); path_to_file.push("tests"); path_to_file.push("fixtures"); path_to_file.push(fixture_name); std::fs::read(path_to_file) .unwrap_or_else(|_| panic!("could not read fixture {:?}", &fixture_name)) } use crate::panes::grid::Grid; use crate::panes::link_handler::LinkHandler; use insta::assert_snapshot; use vte; fn take_snapshot(ansi_instructions: &str, rows: usize, columns: usize, palette: Palette) -> String { let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( rows, columns, Rc::new(RefCell::new(palette)), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let mut vte_parser = vte::Parser::new(); for &byte in ansi_instructions.as_bytes() { vte_parser.advance(&mut grid, byte); } format!("{:?}", grid) } fn take_snapshot_with_sixel( ansi_instructions: &str, rows: usize, columns: usize, palette: Palette, sixel_image_store: Rc<RefCell<SixelImageStore>>, ) -> String { let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { width: 8, height: 21, }))); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( rows, columns, Rc::new(RefCell::new(palette)), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), character_cell_size, sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let mut vte_parser = vte::Parser::new(); for &byte in ansi_instructions.as_bytes() { vte_parser.advance(&mut grid, byte); } format!("{:?}", grid) } fn take_snapshot_and_cursor_position( ansi_instructions: &str, rows: usize, columns: usize, palette: Palette, ) -> (String, Option<(usize, usize)>) { // snapshot, x_coordinates, y_coordinates let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let mut grid = Grid::new( rows, columns, Rc::new(RefCell::new(palette)), terminal_emulator_color_codes, Rc::new(RefCell::new(LinkHandler::new())), Rc::new(RefCell::new(None)), sixel_image_store, Style::default(), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ); let mut vte_parser = vte::Parser::new(); for &byte in ansi_instructions.as_bytes() { vte_parser.advance(&mut grid, byte); } (format!("{:?}", grid), grid.cursor_coordinates()) } #[test] fn increase_tiled_pane_sizes_with_stacked_resizes() { // this is the default resizing algorithm let size = Size { cols: 200, rows: 40, }; let client_id = 1; let mut tab = create_new_tab(size, ModeInfo::default()); let mut output = Output::default(); for i in 2..5 { let new_pane_id_1 = PaneId::Terminal(i); tab.new_pane( new_pane_id_1, None, None, false, true, NewPanePlacement::default(), Some(client_id), None, ) .unwrap(); } // first we increase until fullscreen and once more to make sure we don't increase beyond it for _ in 0..=6 { tab.resize(client_id, ResizeStrategy::new(Resize::Increase, None)) .unwrap(); tab.render(&mut output, None).unwrap(); let snapshot = take_snapshot( output.serialize().unwrap().get(&client_id).unwrap(), size.rows, size.cols, Palette::default(), ); assert_snapshot!(snapshot); } // then we decrease until the original position for _ in 0..=5 { tab.resize(client_id, ResizeStrategy::new(Resize::Decrease, None)) .unwrap(); tab.render(&mut output, None).unwrap(); let snapshot = take_snapshot( output.serialize().unwrap().get(&client_id).unwrap(), size.rows, size.cols, Palette::default(), ); assert_snapshot!(snapshot); } } #[test] fn increase_tiled_pane_sizes_with_stacked_resizes_into_uneven_panes() { // this is the default resizing algorithm let size = Size { cols: 200, rows: 40, }; let client_id = 1; let mut tab = create_new_tab(size, ModeInfo::default()); let mut output = Output::default(); for i in 2..4 { let new_pane_id_1 = PaneId::Terminal(i); tab.new_pane( new_pane_id_1, None, None, false, true, NewPanePlacement::default(), Some(client_id), None, ) .unwrap(); } tab.move_focus_up(client_id).unwrap();
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/unit/tab_tests.rs
zellij-server/src/tab/unit/tab_tests.rs
use super::Tab; use crate::pane_groups::PaneGroups; use crate::panes::sixel::SixelImageStore; use crate::screen::CopyOptions; use crate::{ os_input_output::{AsyncReader, Pid, ServerOsApi}, panes::PaneId, thread_bus::ThreadSenders, ClientId, }; use std::net::{IpAddr, Ipv4Addr}; use std::path::PathBuf; use zellij_utils::data::{Direction, NewPanePlacement, Resize, ResizeStrategy, WebSharing}; use zellij_utils::errors::prelude::*; use zellij_utils::input::layout::{SplitDirection, SplitSize, TiledPaneLayout}; use zellij_utils::ipc::IpcReceiverWithContext; use zellij_utils::pane_size::{Size, SizeInPixels}; use std::cell::RefCell; use std::collections::HashMap; use std::os::unix::io::RawFd; use std::rc::Rc; use interprocess::local_socket::LocalSocketStream; use zellij_utils::{ data::{ModeInfo, Palette, Style}, input::command::{RunCommand, TerminalAction}, ipc::{ClientToServerMsg, ServerToClientMsg}, }; #[derive(Clone)] struct FakeInputOutput {} impl ServerOsApi for FakeInputOutput { fn set_terminal_size_using_terminal_id( &self, _id: u32, _cols: u16, _rows: u16, _width_in_pixels: Option<u16>, _height_in_pixels: Option<u16>, ) -> Result<()> { // noop Ok(()) } fn spawn_terminal( &self, _file_to_open: TerminalAction, _quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, _default_editor: Option<PathBuf>, ) -> Result<(u32, RawFd, RawFd)> { unimplemented!() } fn read_from_tty_stdout(&self, _fd: RawFd, _buf: &mut [u8]) -> Result<usize> { unimplemented!() } fn async_file_reader(&self, _fd: RawFd) -> Box<dyn AsyncReader> { unimplemented!() } fn write_to_tty_stdin(&self, _id: u32, _buf: &[u8]) -> Result<usize> { unimplemented!() } fn tcdrain(&self, _id: u32) -> Result<()> { unimplemented!() } fn kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn force_kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn box_clone(&self) -> Box<dyn ServerOsApi> { Box::new((*self).clone()) } fn send_to_client(&self, _client_id: ClientId, _msg: ServerToClientMsg) -> Result<()> { unimplemented!() } fn new_client( &mut self, _client_id: ClientId, _stream: LocalSocketStream, ) -> Result<IpcReceiverWithContext<ClientToServerMsg>> { unimplemented!() } fn remove_client(&mut self, _client_id: ClientId) -> Result<()> { unimplemented!() } fn load_palette(&self) -> Palette { unimplemented!() } fn get_cwd(&self, _pid: Pid) -> Option<PathBuf> { unimplemented!() } fn write_to_file(&mut self, _buf: String, _name: Option<String>) -> Result<()> { unimplemented!() } fn re_run_command_in_terminal( &self, _terminal_id: u32, _run_command: RunCommand, _quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status ) -> Result<(RawFd, RawFd)> { unimplemented!() } fn clear_terminal_id(&self, _terminal_id: u32) -> Result<()> { unimplemented!() } fn send_sigint(&self, pid: Pid) -> Result<()> { unimplemented!() } } fn tab_resize_increase(tab: &mut Tab, id: ClientId) { tab.resize(id, ResizeStrategy::new(Resize::Increase, None)) .unwrap(); } fn tab_resize_left(tab: &mut Tab, id: ClientId) { tab.resize( id, ResizeStrategy::new(Resize::Increase, Some(Direction::Left)), ) .unwrap(); } fn tab_resize_down(tab: &mut Tab, id: ClientId) { tab.resize( id, ResizeStrategy::new(Resize::Increase, Some(Direction::Down)), ) .unwrap(); } fn tab_resize_up(tab: &mut Tab, id: ClientId) { tab.resize( id, ResizeStrategy::new(Resize::Increase, Some(Direction::Up)), ) .unwrap(); } fn tab_resize_right(tab: &mut Tab, id: ClientId) { tab.resize( id, ResizeStrategy::new(Resize::Increase, Some(Direction::Right)), ) .unwrap(); } fn create_new_tab(size: Size, stacked_resize: bool) -> Tab { let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput {}); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = ModeInfo::default(); let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(stacked_resize)); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let current_pane_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_pane_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_with_layout(size: Size, layout: TiledPaneLayout) -> Tab { let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput {}); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = ModeInfo::default(); let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); let character_cell_info = Rc::new(RefCell::new(None)); let stacked_resize = Rc::new(RefCell::new(true)); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let current_pane_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_info, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_pane_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); let mut new_terminal_ids = vec![]; for i in 0..layout.extract_run_instructions().len() { new_terminal_ids.push((i as u32, None)); } tab.apply_layout( layout, vec![], new_terminal_ids, vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } fn create_new_tab_with_cell_size( size: Size, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, ) -> Tab { let index = 0; let position = 0; let name = String::new(); let os_api = Box::new(FakeInputOutput {}); let senders = ThreadSenders::default().silently_fail_on_send(); let max_panes = None; let mode_info = ModeInfo::default(); let style = Style::default(); let draw_pane_frames = true; let auto_layout = true; let client_id = 1; let session_is_mirrored = true; let mut connected_clients = HashMap::new(); connected_clients.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients)); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let copy_options = CopyOptions::default(); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let stacked_resize = Rc::new(RefCell::new(true)); let current_pane_group = Rc::new(RefCell::new(PaneGroups::new(ThreadSenders::default()))); let currently_marking_pane_group = Rc::new(RefCell::new(HashMap::new())); let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; let advanced_mouse_actions = true; let web_sharing = WebSharing::Off; let web_server_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let web_server_port = 8080; let mut tab = Tab::new( index, position, name, size, character_cell_size, stacked_resize, sixel_image_store, os_api, senders, max_panes, style, mode_info, draw_pane_frames, auto_layout, connected_clients, session_is_mirrored, Some(client_id), copy_options, terminal_emulator_colors, terminal_emulator_color_codes, (vec![], vec![]), // swap layouts PathBuf::from("my_default_shell"), debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, false, web_sharing, current_pane_group, currently_marking_pane_group, advanced_mouse_actions, web_server_ip, web_server_port, ); tab.apply_layout( TiledPaneLayout::default(), vec![], vec![(1, None)], vec![], HashMap::new(), client_id, None, ) .unwrap(); tab } #[test] fn write_to_suppressed_pane() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); tab.vertical_split(PaneId::Terminal(2), None, 1, None) .unwrap(); // Suppress pane 2 and remove it from active panes tab.replace_active_pane_with_editor_pane(PaneId::Terminal(2), 1) .unwrap(); tab.tiled_panes.remove_pane(PaneId::Terminal(2)); // Make sure it's suppressed now tab.suppressed_panes.get(&PaneId::Terminal(2)).unwrap(); // Write content to it tab.write_to_pane_id( &None, vec![34, 127, 31, 82, 17, 182], false, PaneId::Terminal(2), None, None, ) .unwrap(); } #[test] fn split_panes_vertically() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); let new_pane_id = PaneId::Terminal(2); tab.vertical_split(new_pane_id, None, 1, None).unwrap(); assert_eq!(tab.tiled_panes.panes.len(), 2, "The tab has two panes"); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .x, 0, "first pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .y, 0, "first pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .cols .as_usize(), 61, "first pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .rows .as_usize(), 20, "first pane row count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .x, 61, "second pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .y, 0, "second pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .cols .as_usize(), 60, "second pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .rows .as_usize(), 20, "second pane row count" ); } #[test] fn split_panes_horizontally() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); let new_pane_id = PaneId::Terminal(2); tab.horizontal_split(new_pane_id, None, 1, None).unwrap(); assert_eq!(tab.tiled_panes.panes.len(), 2, "The tab has two panes"); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .x, 0, "first pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .y, 0, "first pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .cols .as_usize(), 121, "first pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .rows .as_usize(), 10, "first pane row count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .x, 0, "second pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .y, 10, "second pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .cols .as_usize(), 121, "second pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .rows .as_usize(), 10, "second pane row count" ); } #[test] fn split_largest_pane() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = false; // note - this is not the default let mut tab = create_new_tab(size, stacked_resize); for i in 2..5 { let new_pane_id = PaneId::Terminal(i); tab.new_pane( new_pane_id, None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); } assert_eq!(tab.tiled_panes.panes.len(), 4, "The tab has four panes"); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .x, 0, "first pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .y, 0, "first pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .cols .as_usize(), 61, "first pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(1)) .unwrap() .position_and_size() .rows .as_usize(), 10, "first pane row count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .x, 61, "second pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .y, 0, "second pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .cols .as_usize(), 60, "second pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(2)) .unwrap() .position_and_size() .rows .as_usize(), 10, "second pane row count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(3)) .unwrap() .position_and_size() .x, 0, "third pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(3)) .unwrap() .position_and_size() .y, 10, "third pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(3)) .unwrap() .position_and_size() .cols .as_usize(), 61, "third pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(3)) .unwrap() .position_and_size() .rows .as_usize(), 10, "third pane row count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .position_and_size() .x, 61, "fourth pane x position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .position_and_size() .y, 10, "fourth pane y position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .position_and_size() .cols .as_usize(), 60, "fourth pane column count" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .position_and_size() .rows .as_usize(), 10, "fourth pane row count" ); } #[test] pub fn cannot_split_panes_vertically_when_active_pane_is_too_small() { let size = Size { cols: 8, rows: 20 }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); tab.vertical_split(PaneId::Terminal(2), None, 1, None) .unwrap(); assert_eq!( tab.tiled_panes.panes.len(), 1, "Tab still has only one pane" ); } #[test] pub fn cannot_split_panes_horizontally_when_active_pane_is_too_small() { let size = Size { cols: 121, rows: 4 }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); tab.horizontal_split(PaneId::Terminal(2), None, 1, None) .unwrap(); assert_eq!( tab.tiled_panes.panes.len(), 1, "Tab still has only one pane" ); } #[test] pub fn cannot_split_largest_pane_when_there_is_no_room() { let size = Size { cols: 8, rows: 4 }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); tab.new_pane( PaneId::Terminal(2), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); assert_eq!( tab.tiled_panes.panes.len(), 1, "Tab still has only one pane" ); } #[test] pub fn cannot_split_panes_vertically_when_active_pane_has_fixed_columns() { let size = Size { cols: 50, rows: 20 }; let mut initial_layout = TiledPaneLayout::default(); initial_layout.children_split_direction = SplitDirection::Vertical; let mut fixed_child = TiledPaneLayout::default(); fixed_child.split_size = Some(SplitSize::Fixed(30)); initial_layout.children = vec![fixed_child, TiledPaneLayout::default()]; let mut tab = create_new_tab_with_layout(size, initial_layout); tab.vertical_split(PaneId::Terminal(3), None, 1, None) .unwrap(); assert_eq!(tab.tiled_panes.panes.len(), 2, "Tab still has two panes"); } #[test] pub fn cannot_split_panes_horizontally_when_active_pane_has_fixed_rows() { let size = Size { cols: 50, rows: 20 }; let mut initial_layout = TiledPaneLayout::default(); initial_layout.children_split_direction = SplitDirection::Horizontal; let mut fixed_child = TiledPaneLayout::default(); fixed_child.split_size = Some(SplitSize::Fixed(12)); initial_layout.children = vec![fixed_child, TiledPaneLayout::default()]; let mut tab = create_new_tab_with_layout(size, initial_layout); tab.horizontal_split(PaneId::Terminal(3), None, 1, None) .unwrap(); assert_eq!(tab.tiled_panes.panes.len(), 2, "Tab still has two panes"); } #[test] pub fn toggle_focused_pane_fullscreen() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = false; // note - this is not the default let mut tab = create_new_tab(size, stacked_resize); for i in 2..5 { let new_pane_id = PaneId::Terminal(i); tab.new_pane( new_pane_id, None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); } tab.toggle_active_pane_fullscreen(1); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().x(), 0, "Pane x is on screen edge" ); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().y(), 0, "Pane y is on screen edge" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .cols(), 121, "Pane cols match fullscreen cols" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .rows(), 20, "Pane rows match fullscreen rows" ); tab.toggle_active_pane_fullscreen(1); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().x(), 61, "Pane x is on screen edge" ); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().y(), 10, "Pane y is on screen edge" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .cols(), 60, "Pane cols match fullscreen cols" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .rows(), 10, "Pane rows match fullscreen rows" ); // we don't test if all other panes are hidden because this logic is done in the render // function and we already test that in the e2e tests } #[test] pub fn toggle_focused_pane_fullscreen_with_stacked_resizes() { // note - this is the default let size = Size { cols: 121, rows: 20, }; let stacked_resize = true; let mut tab = create_new_tab(size, stacked_resize); for i in 2..5 { let new_pane_id = PaneId::Terminal(i); tab.new_pane( new_pane_id, None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); } tab.toggle_active_pane_fullscreen(1); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().x(), 0, "Pane x is on screen edge" ); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().y(), 0, "Pane y is on screen edge" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .cols(), 121, "Pane cols match fullscreen cols" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .rows(), 20, "Pane rows match fullscreen rows" ); tab.toggle_active_pane_fullscreen(1); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().x(), 61, "Pane x is back to its original position" ); assert_eq!( tab.tiled_panes.panes.get(&PaneId::Terminal(4)).unwrap().y(), 2, "Pane y is back to its original position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .cols(), 60, "Pane cols are back at their original position" ); assert_eq!( tab.tiled_panes .panes .get(&PaneId::Terminal(4)) .unwrap() .rows(), 18, "Pane rows are back at their original position" ); // we don't test if all other panes are hidden because this logic is done in the render // function and we already test that in the e2e tests } #[test] fn switch_to_next_pane_fullscreen() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = true; let mut active_tab = create_new_tab(size, stacked_resize); active_tab .new_pane( PaneId::Terminal(1), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab .new_pane( PaneId::Terminal(2), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab .new_pane( PaneId::Terminal(3), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab .new_pane( PaneId::Terminal(4), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab.toggle_active_pane_fullscreen(1); // order is now 1 ->2 -> 3 -> 4 due to how new panes are inserted active_tab.switch_next_pane_fullscreen(1); active_tab.switch_next_pane_fullscreen(1); active_tab.switch_next_pane_fullscreen(1); active_tab.switch_next_pane_fullscreen(1); // position should now be back in terminal 4. assert_eq!( active_tab.get_active_pane_id(1).unwrap(), PaneId::Terminal(4), "Active pane did not switch in fullscreen mode" ); } #[test] fn switch_to_prev_pane_fullscreen() { let size = Size { cols: 121, rows: 20, }; let stacked_resize = true; let mut active_tab = create_new_tab(size, stacked_resize); //testing four consecutive switches in fullscreen mode active_tab .new_pane( PaneId::Terminal(1), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab .new_pane( PaneId::Terminal(2), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab .new_pane( PaneId::Terminal(3), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab .new_pane( PaneId::Terminal(4), None, None, false, true, NewPanePlacement::default(), Some(1), None, ) .unwrap(); active_tab.toggle_active_pane_fullscreen(1); // order is now 1 2 3 4 active_tab.switch_prev_pane_fullscreen(1); active_tab.switch_prev_pane_fullscreen(1); active_tab.switch_prev_pane_fullscreen(1); active_tab.switch_prev_pane_fullscreen(1); // the position should now be in Terminal 4. assert_eq!( active_tab.get_active_pane_id(1).unwrap(), PaneId::Terminal(4), "Active pane did not switch in fullscreen mode" ); } #[test] pub fn close_pane_with_another_pane_above_it() { // ┌───────────┐ ┌───────────┐ // │xxxxxxxxxxx│ │xxxxxxxxxxx│ // │xxxxxxxxxxx│ │xxxxxxxxxxx│ // ├───────────┤ ==close==> │xxxxxxxxxxx│ // │███████████│ │xxxxxxxxxxx│ // │███████████│ │xxxxxxxxxxx│
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/tab/unit/layout_applier_tests.rs
zellij-server/src/tab/unit/layout_applier_tests.rs
use crate::panes::sixel::SixelImageStore; use crate::panes::{FloatingPanes, TiledPanes}; use crate::panes::{LinkHandler, PaneId}; use crate::plugins::PluginInstruction; use crate::pty::PtyInstruction; use crate::tab::layout_applier::LayoutApplier; use crate::{ os_input_output::{AsyncReader, Pid, ServerOsApi}, thread_bus::ThreadSenders, ClientId, }; use insta::assert_snapshot; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::fmt::Write; use std::os::unix::io::RawFd; use std::path::PathBuf; use std::rc::Rc; use interprocess::local_socket::LocalSocketStream; use zellij_utils::{ channels::{self, ChannelWithContext, Receiver, SenderWithContext}, data::{ModeInfo, Palette, Style}, errors::prelude::*, input::command::{RunCommand, TerminalAction}, input::layout::RunPluginOrAlias, input::layout::{FloatingPaneLayout, Layout, Run, TiledPaneLayout}, ipc::{ClientToServerMsg, IpcReceiverWithContext, ServerToClientMsg}, pane_size::{Size, SizeInPixels, Viewport}, }; #[derive(Clone)] struct FakeInputOutput {} impl ServerOsApi for FakeInputOutput { fn set_terminal_size_using_terminal_id( &self, _id: u32, _cols: u16, _rows: u16, _width_in_pixels: Option<u16>, _height_in_pixels: Option<u16>, ) -> Result<()> { Ok(()) } fn spawn_terminal( &self, _file_to_open: TerminalAction, _quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, _default_editor: Option<PathBuf>, ) -> Result<(u32, RawFd, RawFd)> { unimplemented!() } fn read_from_tty_stdout(&self, _fd: RawFd, _buf: &mut [u8]) -> Result<usize> { unimplemented!() } fn async_file_reader(&self, _fd: RawFd) -> Box<dyn AsyncReader> { unimplemented!() } fn write_to_tty_stdin(&self, _id: u32, _buf: &[u8]) -> Result<usize> { unimplemented!() } fn tcdrain(&self, _id: u32) -> Result<()> { unimplemented!() } fn kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn force_kill(&self, _pid: Pid) -> Result<()> { unimplemented!() } fn box_clone(&self) -> Box<dyn ServerOsApi> { Box::new((*self).clone()) } fn send_to_client(&self, _client_id: ClientId, _msg: ServerToClientMsg) -> Result<()> { unimplemented!() } fn new_client( &mut self, _client_id: ClientId, _stream: LocalSocketStream, ) -> Result<IpcReceiverWithContext<ClientToServerMsg>> { unimplemented!() } fn remove_client(&mut self, _client_id: ClientId) -> Result<()> { unimplemented!() } fn load_palette(&self) -> Palette { unimplemented!() } fn get_cwd(&self, _pid: Pid) -> Option<PathBuf> { unimplemented!() } fn write_to_file(&mut self, _buf: String, _name: Option<String>) -> Result<()> { unimplemented!() } fn re_run_command_in_terminal( &self, _terminal_id: u32, _run_command: RunCommand, _quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, ) -> Result<(RawFd, RawFd)> { unimplemented!() } fn clear_terminal_id(&self, _terminal_id: u32) -> Result<()> { unimplemented!() } fn send_sigint(&self, _pid: Pid) -> Result<()> { unimplemented!() } } /// Parse KDL layout string and extract tiled and floating layouts fn parse_kdl_layout(kdl_str: &str) -> (TiledPaneLayout, Vec<FloatingPaneLayout>) { let layout = Layout::from_kdl(kdl_str, Some("test_layout".into()), None, None) .expect("Failed to parse KDL layout"); layout.new_tab() } /// Creates all the fixtures needed for LayoutApplier tests #[allow(clippy::type_complexity)] fn create_layout_applier_fixtures( size: Size, ) -> ( Rc<RefCell<Viewport>>, ThreadSenders, Rc<RefCell<SixelImageStore>>, Rc<RefCell<LinkHandler>>, Rc<RefCell<Palette>>, Rc<RefCell<HashMap<usize, String>>>, Rc<RefCell<Option<SizeInPixels>>>, Rc<RefCell<HashMap<ClientId, bool>>>, Style, Rc<RefCell<Size>>, TiledPanes, FloatingPanes, bool, Option<PaneId>, Box<dyn ServerOsApi>, bool, bool, bool, bool, ) { let viewport = Rc::new(RefCell::new(Viewport { x: 0, y: 0, rows: size.rows, cols: size.cols, })); let (mock_plugin_sender, _mock_plugin_receiver) = channels::unbounded(); let mut senders = ThreadSenders::default().silently_fail_on_send(); senders.replace_to_plugin(SenderWithContext::new(mock_plugin_sender)); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(None)); let client_id = 1; let mut connected_clients_map = HashMap::new(); connected_clients_map.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients_map)); let style = Style::default(); let display_area = Rc::new(RefCell::new(size)); let os_api = Box::new(FakeInputOutput {}); // Create TiledPanes let connected_clients_set = Rc::new(RefCell::new(HashSet::from([client_id]))); let mode_info = Rc::new(RefCell::new(HashMap::new())); let stacked_resize = Rc::new(RefCell::new(false)); let session_is_mirrored = true; let draw_pane_frames = true; let default_mode_info = ModeInfo::default(); let tiled_panes = TiledPanes::new( display_area.clone(), viewport.clone(), connected_clients_set.clone(), connected_clients.clone(), mode_info.clone(), character_cell_size.clone(), stacked_resize, session_is_mirrored, draw_pane_frames, default_mode_info.clone(), style.clone(), os_api.box_clone(), senders.clone(), ); // Create FloatingPanes let floating_panes = FloatingPanes::new( display_area.clone(), viewport.clone(), connected_clients_set, connected_clients.clone(), mode_info, character_cell_size.clone(), session_is_mirrored, default_mode_info, style.clone(), os_api.box_clone(), senders.clone(), ); let focus_pane_id = None; let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, tiled_panes, floating_panes, draw_pane_frames, focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) } /// Creates fixtures with receivers for verifying messages sent to pty and plugin threads #[allow(clippy::type_complexity)] fn create_layout_applier_fixtures_with_receivers( size: Size, ) -> ( Rc<RefCell<Viewport>>, ThreadSenders, Rc<RefCell<SixelImageStore>>, Rc<RefCell<LinkHandler>>, Rc<RefCell<Palette>>, Rc<RefCell<HashMap<usize, String>>>, Rc<RefCell<Option<SizeInPixels>>>, Rc<RefCell<HashMap<ClientId, bool>>>, Style, Rc<RefCell<Size>>, TiledPanes, FloatingPanes, bool, Option<PaneId>, Box<dyn ServerOsApi>, bool, bool, bool, bool, Receiver<(PtyInstruction, zellij_utils::errors::ErrorContext)>, Receiver<(PluginInstruction, zellij_utils::errors::ErrorContext)>, ) { let viewport = Rc::new(RefCell::new(Viewport { x: 0, y: 0, rows: size.rows, cols: size.cols, })); let (mock_pty_sender, mock_pty_receiver): ChannelWithContext<PtyInstruction> = channels::unbounded(); let (mock_plugin_sender, mock_plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded(); let mut senders = ThreadSenders::default().silently_fail_on_send(); senders.replace_to_pty(SenderWithContext::new(mock_pty_sender)); senders.replace_to_plugin(SenderWithContext::new(mock_plugin_sender)); let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); let terminal_emulator_colors = Rc::new(RefCell::new(Palette::default())); let terminal_emulator_color_codes = Rc::new(RefCell::new(HashMap::new())); let character_cell_size = Rc::new(RefCell::new(None)); let client_id = 1; let mut connected_clients_map = HashMap::new(); connected_clients_map.insert(client_id, false); let connected_clients = Rc::new(RefCell::new(connected_clients_map)); let style = Style::default(); let display_area = Rc::new(RefCell::new(size)); let os_api = Box::new(FakeInputOutput {}); // Create TiledPanes let connected_clients_set = Rc::new(RefCell::new(HashSet::from([client_id]))); let mode_info = Rc::new(RefCell::new(HashMap::new())); let stacked_resize = Rc::new(RefCell::new(false)); let session_is_mirrored = true; let draw_pane_frames = true; let default_mode_info = ModeInfo::default(); let tiled_panes = TiledPanes::new( display_area.clone(), viewport.clone(), connected_clients_set.clone(), connected_clients.clone(), mode_info.clone(), character_cell_size.clone(), stacked_resize, session_is_mirrored, draw_pane_frames, default_mode_info.clone(), style.clone(), os_api.box_clone(), senders.clone(), ); // Create FloatingPanes let floating_panes = FloatingPanes::new( display_area.clone(), viewport.clone(), connected_clients_set, connected_clients.clone(), mode_info, character_cell_size.clone(), session_is_mirrored, default_mode_info, style.clone(), os_api.box_clone(), senders.clone(), ); let focus_pane_id = None; let debug = false; let arrow_fonts = true; let styled_underlines = true; let explicitly_disable_kitty_keyboard_protocol = false; ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, tiled_panes, floating_panes, draw_pane_frames, focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, mock_pty_receiver, mock_plugin_receiver, ) } /// Takes a snapshot of the current pane state for assertion fn take_pane_state_snapshot( tiled_panes: &TiledPanes, floating_panes: &FloatingPanes, focus_pane_id: &Option<PaneId>, viewport: &Rc<RefCell<Viewport>>, display_area: &Rc<RefCell<Size>>, ) -> String { let mut output = String::new(); // Viewport info let viewport_state = viewport.borrow(); writeln!( &mut output, "VIEWPORT: x={}, y={}, cols={}, rows={}", viewport_state.x, viewport_state.y, viewport_state.cols, viewport_state.rows ) .unwrap(); let display_state = display_area.borrow(); writeln!( &mut output, "DISPLAY: cols={}, rows={}", display_state.cols, display_state.rows ) .unwrap(); // Focus state writeln!(&mut output, "FOCUS: {:?}", focus_pane_id).unwrap(); writeln!(&mut output).unwrap(); // Tiled panes writeln!(&mut output, "TILED PANES ({})", tiled_panes.panes.len()).unwrap(); let mut tiled_list: Vec<_> = tiled_panes.get_panes().collect(); tiled_list.sort_by_key(|(id, _)| **id); for (pane_id, pane) in tiled_list { let geom = pane.position_and_size(); let run = pane.invoked_with(); let selectable = pane.selectable(); writeln!(&mut output, " {:?}:", pane_id).unwrap(); writeln!( &mut output, " geom: x={}, y={}, cols={}, rows={}", geom.x, geom.y, geom.cols.as_usize(), geom.rows.as_usize() ) .unwrap(); if let Some(logical_pos) = geom.logical_position { writeln!(&mut output, " logical_position: {}", logical_pos).unwrap(); } if let Some(stack_id) = geom.stacked { writeln!(&mut output, " stacked: {}", stack_id).unwrap(); } writeln!(&mut output, " run: {}", format_run_instruction(run)).unwrap(); writeln!(&mut output, " selectable: {}", selectable).unwrap(); writeln!(&mut output, " title: {}", pane.current_title()).unwrap(); writeln!(&mut output, " borderless: {}", pane.borderless()).unwrap(); writeln!(&mut output).unwrap(); } // Floating panes if floating_panes.pane_ids().count() > 0 { writeln!( &mut output, "FLOATING PANES ({})", floating_panes.pane_ids().count() ) .unwrap(); let mut floating_list: Vec<_> = floating_panes.get_panes().collect(); floating_list.sort_by_key(|(id, _)| **id); for (pane_id, pane) in floating_list { let geom = pane.position_and_size(); let run = pane.invoked_with(); writeln!(&mut output, " {:?}:", pane_id).unwrap(); writeln!( &mut output, " geom: x={}, y={}, cols={}, rows={}", geom.x, geom.y, geom.cols.as_usize(), geom.rows.as_usize() ) .unwrap(); if let Some(logical_pos) = geom.logical_position { writeln!(&mut output, " logical_position: {}", logical_pos).unwrap(); } writeln!(&mut output, " run: {}", format_run_instruction(run)).unwrap(); writeln!(&mut output, " pinned: {}", geom.is_pinned).unwrap(); writeln!(&mut output, " selectable: {}", pane.selectable()).unwrap(); writeln!(&mut output, " title: {}", pane.current_title()).unwrap(); writeln!(&mut output, " borderless: {}", pane.borderless()).unwrap(); writeln!(&mut output).unwrap(); } } output } /// Format a Run instruction as a human-readable string fn format_run_instruction(run: &Option<Run>) -> String { match run { None => "None".to_string(), Some(Run::Command(cmd)) => { let mut s = format!("Command({})", cmd.command.display()); if !cmd.args.is_empty() { s.push_str(&format!(" args={:?}", cmd.args)); } if let Some(cwd) = &cmd.cwd { s.push_str(&format!(" cwd={:?}", cwd)); } s }, Some(Run::Plugin(plugin)) => { format!("Plugin({})", plugin.location_string()) }, Some(Run::Cwd(path)) => format!("Cwd({:?})", path), Some(Run::EditFile(path, line, cwd)) => { format!("EditFile({:?}, line={:?}, cwd={:?})", path, line, cwd) }, } } /// Collect all close pane messages from the pty receiver fn collect_close_pane_messages( pty_receiver: &Receiver<(PtyInstruction, zellij_utils::errors::ErrorContext)>, ) -> Vec<PaneId> { let mut closed_panes = Vec::new(); while let Ok((instruction, _)) = pty_receiver.try_recv() { if let PtyInstruction::ClosePane(pane_id, _) = instruction { closed_panes.push(pane_id); } } closed_panes } /// Collect all unload plugin messages from the plugin receiver fn collect_unload_plugin_messages( plugin_receiver: &Receiver<(PluginInstruction, zellij_utils::errors::ErrorContext)>, ) -> Vec<u32> { let mut unloaded_plugins = Vec::new(); while let Ok((instruction, _)) = plugin_receiver.try_recv() { if let PluginInstruction::Unload(plugin_id) = instruction { unloaded_plugins.push(plugin_id); } } unloaded_plugins } #[test] fn test_apply_empty_layout() { let kdl_layout = r#" layout { } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, // blocking_terminal ); let result = applier.apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], // new_floating_terminal_ids HashMap::new(), // new_plugin_ids 1, // client_id ); assert!(result.is_ok()); let snapshot = take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, ); assert_snapshot!(snapshot); } #[test] fn test_apply_simple_two_pane_layout() { let kdl_layout = r#" layout { pane pane } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); let snapshot = take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, ); assert_snapshot!(snapshot); } #[test] fn test_apply_three_pane_layout() { let kdl_layout = r#" layout { pane pane pane } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None), (3, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); assert_snapshot!(take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, )); } #[test] fn test_apply_horizontal_split_with_sizes() { let kdl_layout = r#" layout { pane split_direction="Horizontal" { pane size="30%" pane size="70%" } } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); assert_snapshot!(take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, )); } #[test] fn test_apply_vertical_split_with_sizes() { let kdl_layout = r#" layout { pane split_direction="Vertical" { pane size="60%" pane size="40%" } } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); assert_snapshot!(take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, )); } #[test] fn test_apply_nested_layout() { let kdl_layout = r#" layout { pane split_direction="Vertical" { pane size="60%" pane size="40%" split_direction="Horizontal" { pane pane } } } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None), (3, None)]; let size = Size { cols: 120, rows: 40, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); assert_snapshot!(take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, )); } #[test] fn test_apply_layout_with_focus() { let kdl_layout = r#" layout { pane pane focus=true pane } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None), (3, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); // Snapshot should show FOCUS: Some(Terminal(2)) assert_snapshot!(take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, )); } #[test] fn test_apply_layout_with_commands() { let kdl_layout = r#" layout { pane command="htop" pane command="tail" { args "-f" "/var/log/syslog" } pane } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None), (3, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, ) = create_layout_applier_fixtures(size); let mut applier = LayoutApplier::new( &viewport, &senders, &sixel_image_store, &link_handler, &terminal_emulator_colors, &terminal_emulator_color_codes, &character_cell_size, &connected_clients, &style, &display_area, &mut tiled_panes, &mut floating_panes, draw_pane_frames, &mut focus_pane_id, &os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol, None, ); applier .apply_layout( tiled_layout, floating_layout, terminal_ids, vec![], HashMap::new(), 1, ) .unwrap(); assert_snapshot!(take_pane_state_snapshot( &tiled_panes, &floating_panes, &focus_pane_id, &viewport, &display_area, )); } #[test] fn test_apply_layout_with_named_panes() { let kdl_layout = r#" layout { pane name="editor" pane name="terminal" pane name="logs" } "#; let (tiled_layout, floating_layout) = parse_kdl_layout(kdl_layout); let terminal_ids = vec![(1, None), (2, None), (3, None)]; let size = Size { cols: 100, rows: 50, }; let ( viewport, senders, sixel_image_store, link_handler, terminal_emulator_colors, terminal_emulator_color_codes, character_cell_size, connected_clients, style, display_area, mut tiled_panes, mut floating_panes, draw_pane_frames, mut focus_pane_id, os_api, debug, arrow_fonts, styled_underlines, explicitly_disable_kitty_keyboard_protocol,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/loading_indication.rs
zellij-server/src/ui/loading_indication.rs
use std::fmt::{Display, Error, Formatter}; use std::time::Instant; use zellij_utils::{ data::{PaletteColor, Styling}, errors::prelude::*, }; #[derive(Debug, Clone, Default)] pub struct LoadingIndication { pub ended: bool, error: Option<String>, animation_offset: usize, plugin_name: String, terminal_emulator_colors: Option<Styling>, override_previous_error: bool, started_at: Option<Instant>, } impl LoadingIndication { pub fn new(plugin_name: String) -> Self { let started_at = Some(Instant::now()); LoadingIndication { plugin_name, animation_offset: 0, started_at, ..Default::default() } } pub fn set_name(&mut self, plugin_name: String) { self.plugin_name = plugin_name; } pub fn with_colors(mut self, terminal_emulator_colors: Styling) -> Self { self.terminal_emulator_colors = Some(terminal_emulator_colors); self } pub fn merge(&mut self, other: LoadingIndication) { let current_animation_offset = self.animation_offset; let current_terminal_emulator_colors = self.terminal_emulator_colors.take(); let mut current_error = self.error.take(); let override_previous_error = other.override_previous_error; drop(std::mem::replace(self, other)); self.animation_offset = current_animation_offset; self.terminal_emulator_colors = current_terminal_emulator_colors; if let Some(current_error) = current_error.take() { // we do this so that only the first error (usually the root cause) will be shown // when plugins support scrolling, we might want to do an append here if !override_previous_error { self.error = Some(current_error); } } } pub fn progress_animation_offset(&mut self) { if self.animation_offset == 3 { self.animation_offset = 0; } else { self.animation_offset += 1; } } pub fn indicate_loading_error(&mut self, error_text: String) { self.error = Some(error_text); } pub fn is_error(&self) -> bool { self.error.is_some() } pub fn override_previous_error(&mut self) { self.override_previous_error = true; } } macro_rules! style { ($fg:expr) => { ansi_term::Style::new().fg(match $fg { PaletteColor::Rgb((r, g, b)) => ansi_term::Color::RGB(r, g, b), PaletteColor::EightBit(color) => ansi_term::Color::Fixed(color), }) }; } impl Display for LoadingIndication { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { let cyan = match self.terminal_emulator_colors { Some(terminal_emulator_colors) => { style!(terminal_emulator_colors.exit_code_success.emphasis_0).bold() }, None => ansi_term::Style::new(), }; let red = match self.terminal_emulator_colors { Some(terminal_emulator_colors) => { style!(terminal_emulator_colors.exit_code_error.base).bold() }, None => ansi_term::Style::new(), }; let plugin_name = &self.plugin_name; let add_dots = |stringified: &mut String| { for _ in 0..self.animation_offset { stringified.push('.'); } stringified.push(' '); }; let mut stringified = String::new(); if let Some(error_text) = &self.error { stringified.push_str(&format!( "\n\r{} {}", red.bold().paint("ERROR: "), error_text.replace('\n', "\n\r") )); // we add this additional line explicitly to make it easier to realize when something // is wrong in very small plugins (eg. the tab-bar and status-bar) stringified.push_str(&format!( "\n\r{}", red.bold() .paint("ERROR IN PLUGIN - check logs for more info") )); } else { let loading_text = "Loading"; stringified.push_str(&format!("{} {}", loading_text, cyan.paint(plugin_name))); add_dots(&mut stringified); } if self .started_at .map(|s| s.elapsed() > std::time::Duration::from_millis(400)) .unwrap_or(true) || self.error.is_some() { write!(f, "{}", stringified) } else { Ok(()) } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/pane_boundaries_frame.rs
zellij-server/src/ui/pane_boundaries_frame.rs
use crate::output::CharacterChunk; use crate::panes::{AnsiCode, RcCharacterStyles, TerminalCharacter, EMPTY_TERMINAL_CHARACTER}; use crate::ui::boundaries::boundary_type; use crate::ClientId; use zellij_utils::data::{client_id_to_colors, PaletteColor, Style}; use zellij_utils::errors::prelude::*; use zellij_utils::pane_size::{Offset, Viewport}; use zellij_utils::position::Position; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; fn foreground_color(characters: &str, color: Option<PaletteColor>) -> Vec<TerminalCharacter> { let mut colored_string = Vec::new(); for character in characters.chars() { let mut styles = RcCharacterStyles::reset(); styles.update(|styles| { styles.bold = Some(AnsiCode::On); match color { Some(palette_color) => { styles.foreground = Some(AnsiCode::from(palette_color)); }, None => {}, } }); let terminal_character = TerminalCharacter::new_styled(character, styles); colored_string.push(terminal_character); } colored_string } fn background_color(characters: &str, color: Option<PaletteColor>) -> Vec<TerminalCharacter> { let mut colored_string = Vec::new(); for character in characters.chars() { let mut styles = RcCharacterStyles::reset(); styles.update(|styles| match color { Some(palette_color) => { styles.background = Some(AnsiCode::from(palette_color)); styles.bold(Some(AnsiCode::On)); }, None => {}, }); let terminal_character = TerminalCharacter::new_styled(character, styles); colored_string.push(terminal_character); } colored_string } #[derive(Debug, Clone, Copy, PartialEq)] enum ExitStatus { Code(i32), Exited, } pub struct FrameParams { pub focused_client: Option<ClientId>, pub is_main_client: bool, // more accurately: is_focused_for_main_client pub other_focused_clients: Vec<ClientId>, pub style: Style, pub color: Option<PaletteColor>, pub other_cursors_exist_in_session: bool, pub pane_is_stacked_under: bool, pub pane_is_stacked_over: bool, pub should_draw_pane_frames: bool, pub pane_is_floating: bool, pub content_offset: Offset, pub mouse_is_hovering_over_pane: bool, pub pane_is_selectable: bool, } #[derive(Default, PartialEq)] pub struct PaneFrame { pub geom: Viewport, pub title: String, pub scroll_position: (usize, usize), // (position, length) pub style: Style, pub color: Option<PaletteColor>, pub focused_client: Option<ClientId>, pub is_main_client: bool, pub other_cursors_exist_in_session: bool, pub other_focused_clients: Vec<ClientId>, exit_status: Option<ExitStatus>, is_first_run: bool, pane_is_stacked_over: bool, pane_is_stacked_under: bool, should_draw_pane_frames: bool, is_pinned: bool, is_floating: bool, content_offset: Offset, mouse_is_hovering_over_pane: bool, is_selectable: bool, } impl PaneFrame { pub fn new( geom: Viewport, scroll_position: (usize, usize), main_title: String, frame_params: FrameParams, ) -> Self { PaneFrame { geom, title: main_title, scroll_position, style: frame_params.style, color: frame_params.color, focused_client: frame_params.focused_client, is_main_client: frame_params.is_main_client, other_focused_clients: frame_params.other_focused_clients, other_cursors_exist_in_session: frame_params.other_cursors_exist_in_session, exit_status: None, is_first_run: false, pane_is_stacked_over: frame_params.pane_is_stacked_over, pane_is_stacked_under: frame_params.pane_is_stacked_under, should_draw_pane_frames: frame_params.should_draw_pane_frames, is_pinned: false, is_floating: frame_params.pane_is_floating, content_offset: frame_params.content_offset, mouse_is_hovering_over_pane: frame_params.mouse_is_hovering_over_pane, is_selectable: frame_params.pane_is_selectable, } } pub fn is_pinned(mut self, is_pinned: bool) -> Self { self.is_pinned = is_pinned; self } pub fn add_exit_status(&mut self, exit_status: Option<i32>) { self.exit_status = match exit_status { Some(exit_status) => Some(ExitStatus::Code(exit_status)), None => Some(ExitStatus::Exited), }; } pub fn indicate_first_run(&mut self) { self.is_first_run = true; } pub fn override_color(&mut self, color: PaletteColor) { self.color = Some(color); } fn client_cursor(&self, client_id: ClientId) -> Vec<TerminalCharacter> { let color = client_id_to_colors(client_id, self.style.colors.multiplayer_user_colors); background_color(" ", color.map(|c| c.0)) } fn get_corner(&self, corner: &'static str) -> &'static str { let corner = if !self.should_draw_pane_frames && (corner == boundary_type::TOP_LEFT || corner == boundary_type::TOP_RIGHT) { boundary_type::HORIZONTAL } else if self.pane_is_stacked_under && corner == boundary_type::TOP_RIGHT { boundary_type::BOTTOM_RIGHT } else if self.pane_is_stacked_under && corner == boundary_type::TOP_LEFT { boundary_type::BOTTOM_LEFT } else { corner }; if self.style.rounded_corners { match corner { boundary_type::TOP_RIGHT => boundary_type::TOP_RIGHT_ROUND, boundary_type::TOP_LEFT => boundary_type::TOP_LEFT_ROUND, boundary_type::BOTTOM_RIGHT => boundary_type::BOTTOM_RIGHT_ROUND, boundary_type::BOTTOM_LEFT => boundary_type::BOTTOM_LEFT_ROUND, _ => corner, } } else { corner } } fn render_title_right_side( &self, max_length: usize, ) -> Option<(Vec<TerminalCharacter>, usize)> { // string and length because of color let has_scroll = self.scroll_position.0 > 0 || self.scroll_position.1 > 0; if has_scroll && self.is_selectable { // TODO: don't show SCROLL at all for plugins let pin_indication = if self.is_floating && self.is_selectable { self.render_pinned_indication(max_length) } else { None }; // no pin indication for tiled panes let space_for_scroll_indication = pin_indication .as_ref() .map(|(_, length)| max_length.saturating_sub(*length + 1)) .unwrap_or(max_length); let scroll_indication = self.render_scroll_indication(space_for_scroll_indication); match (pin_indication, scroll_indication) { ( Some((mut pin_indication, pin_indication_len)), Some((mut scroll_indication, scroll_indication_len)), ) => { let mut characters: Vec<_> = scroll_indication.drain(..).collect(); let mut separator = foreground_color(&format!("|"), self.color); characters.append(&mut separator); characters.append(&mut pin_indication); Some((characters, pin_indication_len + scroll_indication_len + 1)) }, (Some(pin_indication), None) => Some(pin_indication), (None, Some(scroll_indication)) => Some(scroll_indication), _ => None, } } else if self.is_floating && self.is_selectable { self.render_pinned_indication(max_length) } else { None } } fn render_scroll_indication( &self, max_length: usize, ) -> Option<(Vec<TerminalCharacter>, usize)> { let prefix = " SCROLL: "; let full_indication = format!(" {}/{} ", self.scroll_position.0, self.scroll_position.1); let short_indication = format!(" {} ", self.scroll_position.0); let full_indication_len = full_indication.chars().count(); let short_indication_len = short_indication.chars().count(); let prefix_len = prefix.chars().count(); if prefix_len + full_indication_len <= max_length { Some(( foreground_color(&format!("{}{}", prefix, full_indication), self.color), prefix_len + full_indication_len, )) } else if full_indication_len <= max_length { Some(( foreground_color(&full_indication, self.color), full_indication_len, )) } else if short_indication_len <= max_length { Some(( foreground_color(&short_indication, self.color), short_indication_len, )) } else { None } } fn render_pinned_indication( &self, max_length: usize, ) -> Option<(Vec<TerminalCharacter>, usize)> { let is_checked = if self.is_pinned { '+' } else { ' ' }; let full_indication = format!(" PIN [{}] ", is_checked); let full_indication_len = full_indication.chars().count(); if full_indication_len <= max_length { Some(( foreground_color(&full_indication, self.color), full_indication_len, )) } else { None } } fn render_my_focus(&self, max_length: usize) -> Option<(Vec<TerminalCharacter>, usize)> { let mut left_separator = foreground_color(boundary_type::VERTICAL_LEFT, self.color); let mut right_separator = foreground_color(boundary_type::VERTICAL_RIGHT, self.color); let full_indication_text = "MY FOCUS"; let mut full_indication = vec![]; full_indication.append(&mut left_separator); full_indication.push(EMPTY_TERMINAL_CHARACTER); full_indication.append(&mut foreground_color(full_indication_text, self.color)); full_indication.push(EMPTY_TERMINAL_CHARACTER); full_indication.append(&mut right_separator); let full_indication_len = full_indication_text.width() + 4; // 2 for separators 2 for padding let short_indication_text = "ME"; let mut short_indication = vec![]; short_indication.append(&mut left_separator); short_indication.push(EMPTY_TERMINAL_CHARACTER); short_indication.append(&mut foreground_color(short_indication_text, self.color)); short_indication.push(EMPTY_TERMINAL_CHARACTER); short_indication.append(&mut right_separator); let short_indication_len = short_indication_text.width() + 4; // 2 for separators 2 for padding if full_indication_len <= max_length { Some((full_indication, full_indication_len)) } else if short_indication_len <= max_length { Some((short_indication, short_indication_len)) } else { None } } fn render_my_and_others_focus( &self, max_length: usize, ) -> Option<(Vec<TerminalCharacter>, usize)> { let mut left_separator = foreground_color(boundary_type::VERTICAL_LEFT, self.color); let mut right_separator = foreground_color(boundary_type::VERTICAL_RIGHT, self.color); let full_indication_text = "MY FOCUS AND:"; let short_indication_text = "+"; let mut full_indication = foreground_color(full_indication_text, self.color); let mut full_indication_len = full_indication_text.width(); let mut short_indication = foreground_color(short_indication_text, self.color); let mut short_indication_len = short_indication_text.width(); for client_id in &self.other_focused_clients { let mut text = self.client_cursor(*client_id); full_indication_len += 2; full_indication.push(EMPTY_TERMINAL_CHARACTER); full_indication.append(&mut text.clone()); short_indication_len += 2; short_indication.push(EMPTY_TERMINAL_CHARACTER); short_indication.append(&mut text); } if full_indication_len + 4 <= max_length { // 2 for separators, 2 for padding let mut ret = vec![]; ret.append(&mut left_separator); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut full_indication); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut right_separator); Some((ret, full_indication_len + 4)) } else if short_indication_len + 4 <= max_length { // 2 for separators, 2 for padding let mut ret = vec![]; ret.append(&mut left_separator); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut short_indication); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut right_separator); Some((ret, short_indication_len + 4)) } else { None } } fn render_other_focused_users( &self, max_length: usize, ) -> Option<(Vec<TerminalCharacter>, usize)> { let mut left_separator = foreground_color(boundary_type::VERTICAL_LEFT, self.color); let mut right_separator = foreground_color(boundary_type::VERTICAL_RIGHT, self.color); let full_indication_text = if self.other_focused_clients.len() == 1 { "FOCUSED USER:" } else { "FOCUSED USERS:" }; let middle_indication_text = "U:"; let mut full_indication = foreground_color(full_indication_text, self.color); let mut full_indication_len = full_indication_text.width(); let mut middle_indication = foreground_color(middle_indication_text, self.color); let mut middle_indication_len = middle_indication_text.width(); let mut short_indication = vec![]; let mut short_indication_len = 0; for client_id in &self.other_focused_clients { let mut text = self.client_cursor(*client_id); full_indication_len += 2; full_indication.push(EMPTY_TERMINAL_CHARACTER); full_indication.append(&mut text.clone()); middle_indication_len += 2; middle_indication.push(EMPTY_TERMINAL_CHARACTER); middle_indication.append(&mut text.clone()); short_indication_len += 2; short_indication.push(EMPTY_TERMINAL_CHARACTER); short_indication.append(&mut text); } if full_indication_len + 4 <= max_length { // 2 for separators, 2 for padding let mut ret = vec![]; ret.append(&mut left_separator); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut full_indication); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut right_separator); Some((ret, full_indication_len + 4)) } else if middle_indication_len + 4 <= max_length { // 2 for separators, 2 for padding let mut ret = vec![]; ret.append(&mut left_separator); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut middle_indication); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut right_separator); Some((ret, middle_indication_len + 4)) } else if short_indication_len + 3 <= max_length { // 2 for separators, 1 for padding let mut ret = vec![]; ret.append(&mut left_separator); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut short_indication); ret.push(EMPTY_TERMINAL_CHARACTER); ret.append(&mut right_separator); Some((ret, short_indication_len + 3)) } else { None } } fn render_title_middle(&self, max_length: usize) -> Option<(Vec<TerminalCharacter>, usize)> { // string and length because of color if self.is_main_client && self.other_focused_clients.is_empty() && !self.other_cursors_exist_in_session { None } else if self.is_main_client && self.other_focused_clients.is_empty() && self.other_cursors_exist_in_session { self.render_my_focus(max_length) } else if self.is_main_client && !self.other_focused_clients.is_empty() { self.render_my_and_others_focus(max_length) } else if !self.other_focused_clients.is_empty() { self.render_other_focused_users(max_length) } else if (self.pane_is_stacked_under || self.pane_is_stacked_over) && self.exit_status.is_some() { let (first_part, first_part_len) = self.first_exited_held_title_part_full(); if first_part_len <= max_length { Some((first_part, first_part_len)) } else { None } } else { None } } fn render_title_left_side(&self, max_length: usize) -> Option<(Vec<TerminalCharacter>, usize)> { let middle_truncated_sign = "[..]"; let middle_truncated_sign_long = "[...]"; let full_text = format!(" {} ", &self.title); if max_length <= 6 || self.title.is_empty() { None } else if full_text.width() <= max_length { Some((foreground_color(&full_text, self.color), full_text.width())) } else { let length_of_each_half = (max_length - middle_truncated_sign.width()) / 2; let mut first_part: String = String::new(); for char in full_text.chars() { if first_part.width() + char.width().unwrap_or(0) > length_of_each_half { break; } else { first_part.push(char); } } let mut second_part: String = String::new(); for char in full_text.chars().rev() { if second_part.width() + char.width().unwrap_or(0) > length_of_each_half { break; } else { second_part.insert(0, char); } } let (title_left_side, title_length) = if first_part.width() + middle_truncated_sign.width() + second_part.width() < max_length { // this means we lost 1 character when dividing the total length into halves ( format!( "{}{}{}", first_part, middle_truncated_sign_long, second_part ), first_part.width() + middle_truncated_sign_long.width() + second_part.width(), ) } else { ( format!("{}{}{}", first_part, middle_truncated_sign, second_part), first_part.width() + middle_truncated_sign.width() + second_part.width(), ) }; Some((foreground_color(&title_left_side, self.color), title_length)) } } fn three_part_title_line( &self, mut left_side: Vec<TerminalCharacter>, left_side_len: &usize, mut middle: Vec<TerminalCharacter>, middle_len: &usize, mut right_side: Vec<TerminalCharacter>, right_side_len: &usize, ) -> Vec<TerminalCharacter> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let mut title_line = vec![]; let left_side_start_position = self.geom.x + 1; let middle_start_position = self.geom.x + (total_title_length / 2) - (middle_len / 2) + 1; let right_side_start_position = (self.geom.x + self.geom.cols - 1).saturating_sub(*right_side_len); let mut col = self.geom.x; loop { if col == self.geom.x { title_line.append(&mut foreground_color( self.get_corner(boundary_type::TOP_LEFT), self.color, )); } else if col == self.geom.x + self.geom.cols - 1 { title_line.append(&mut foreground_color( self.get_corner(boundary_type::TOP_RIGHT), self.color, )); } else if col == left_side_start_position { title_line.append(&mut left_side); col += left_side_len; continue; } else if col == middle_start_position { title_line.append(&mut middle); col += middle_len; continue; } else if col == right_side_start_position { title_line.append(&mut right_side); col += right_side_len; continue; } else { title_line.append(&mut foreground_color(boundary_type::HORIZONTAL, self.color)); } if col == self.geom.x + self.geom.cols - 1 { break; } col += 1; } title_line } fn left_and_middle_title_line( &self, mut left_side: Vec<TerminalCharacter>, left_side_len: &usize, mut middle: Vec<TerminalCharacter>, middle_len: &usize, ) -> Vec<TerminalCharacter> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let mut title_line = vec![]; let left_side_start_position = self.geom.x + 1; let middle_start_position = self.geom.x + (total_title_length / 2) - (*middle_len / 2) + 1; let mut col = self.geom.x; loop { if col == self.geom.x { title_line.append(&mut foreground_color( self.get_corner(boundary_type::TOP_LEFT), self.color, )); } else if col == self.geom.x + self.geom.cols - 1 { title_line.append(&mut foreground_color( self.get_corner(boundary_type::TOP_RIGHT), self.color, )); } else if col == left_side_start_position { title_line.append(&mut left_side); col += *left_side_len; continue; } else if col == middle_start_position { title_line.append(&mut middle); col += *middle_len; continue; } else { title_line.append(&mut foreground_color(boundary_type::HORIZONTAL, self.color)); } if col == self.geom.x + self.geom.cols - 1 { break; } col += 1; } title_line } fn middle_only_title_line( &self, mut middle: Vec<TerminalCharacter>, middle_len: &usize, ) -> Vec<TerminalCharacter> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let mut title_line = vec![]; let middle_start_position = self.geom.x + (total_title_length / 2) - (*middle_len / 2) + 1; let mut col = self.geom.x; loop { if col == self.geom.x { title_line.append(&mut foreground_color( self.get_corner(boundary_type::TOP_LEFT), self.color, )); } else if col == self.geom.x + self.geom.cols - 1 { title_line.append(&mut foreground_color( self.get_corner(boundary_type::TOP_RIGHT), self.color, )); } else if col == middle_start_position { title_line.append(&mut middle); col += *middle_len; continue; } else { title_line.append(&mut foreground_color(boundary_type::HORIZONTAL, self.color)); } if col == self.geom.x + self.geom.cols - 1 { break; } col += 1; } title_line } fn two_part_title_line( &self, mut left_side: Vec<TerminalCharacter>, left_side_len: &usize, mut right_side: Vec<TerminalCharacter>, right_side_len: &usize, ) -> Vec<TerminalCharacter> { let mut left_boundary = foreground_color(self.get_corner(boundary_type::TOP_LEFT), self.color); let mut right_boundary = foreground_color(self.get_corner(boundary_type::TOP_RIGHT), self.color); let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let mut middle = String::new(); for _ in (left_side_len + right_side_len)..total_title_length { middle.push_str(boundary_type::HORIZONTAL); } let mut ret = vec![]; ret.append(&mut left_boundary); ret.append(&mut left_side); ret.append(&mut foreground_color(&middle, self.color)); ret.append(&mut right_side); ret.append(&mut right_boundary); ret } fn left_only_title_line( &self, mut left_side: Vec<TerminalCharacter>, left_side_len: &usize, ) -> Vec<TerminalCharacter> { let mut left_boundary = foreground_color(self.get_corner(boundary_type::TOP_LEFT), self.color); let mut right_boundary = foreground_color(self.get_corner(boundary_type::TOP_RIGHT), self.color); let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let mut middle_padding = String::new(); for _ in *left_side_len..total_title_length { middle_padding.push_str(boundary_type::HORIZONTAL); } let mut ret = vec![]; ret.append(&mut left_boundary); ret.append(&mut left_side); ret.append(&mut foreground_color(&middle_padding, self.color)); ret.append(&mut right_boundary); ret } fn empty_title_line(&self) -> Vec<TerminalCharacter> { let mut left_boundary = foreground_color(self.get_corner(boundary_type::TOP_LEFT), self.color); let mut right_boundary = foreground_color(self.get_corner(boundary_type::TOP_RIGHT), self.color); let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let mut middle_padding = String::new(); for _ in 0..total_title_length { middle_padding.push_str(boundary_type::HORIZONTAL); } let mut ret = vec![]; ret.append(&mut left_boundary); ret.append(&mut foreground_color(&middle_padding, self.color)); ret.append(&mut right_boundary); ret } fn title_line_with_middle( &self, middle: Vec<TerminalCharacter>, middle_len: &usize, ) -> Vec<TerminalCharacter> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let length_of_each_side = total_title_length.saturating_sub(*middle_len + 2) / 2; let left_side = self.render_title_left_side(length_of_each_side); let right_side = self.render_title_right_side(length_of_each_side); match (left_side, right_side) { (Some((left_side, left_side_len)), Some((right_side, right_side_len))) => self .three_part_title_line( left_side, &left_side_len, middle, middle_len, right_side, &right_side_len, ), (Some((left_side, left_side_len)), None) => { self.left_and_middle_title_line(left_side, &left_side_len, middle, middle_len) }, _ => self.middle_only_title_line(middle, middle_len), } } fn title_line_without_middle(&self) -> Vec<TerminalCharacter> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let left_side = self.render_title_left_side(total_title_length); let right_side = left_side.as_ref().and_then(|(_left_side, left_side_len)| { let space_left = total_title_length.saturating_sub(*left_side_len + 1); // 1 for a middle separator self.render_title_right_side(space_left) }); match (left_side, right_side) { (Some((left_side, left_side_len)), Some((right_side, right_side_len))) => { self.two_part_title_line(left_side, &left_side_len, right_side, &right_side_len) }, (Some((left_side, left_side_len)), None) => { self.left_only_title_line(left_side, &left_side_len) }, _ => self.empty_title_line(), } } fn render_title(&self) -> Result<Vec<TerminalCharacter>> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners self.render_title_middle(total_title_length) .map(|(middle, middle_length)| self.title_line_with_middle(middle, &middle_length)) .or_else(|| Some(self.title_line_without_middle())) .with_context(|| format!("failed to render title '{}'", self.title)) } fn render_one_line_title(&self) -> Result<Vec<TerminalCharacter>> { let total_title_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners self.render_title_middle(total_title_length) .map(|(middle, middle_length)| self.title_line_with_middle(middle, &middle_length)) .or_else(|| Some(self.title_line_without_middle())) .with_context(|| format!("failed to render title '{}'", self.title)) } fn render_held_undertitle(&self) -> Result<Vec<TerminalCharacter>> { let max_undertitle_length = self.geom.cols.saturating_sub(2); // 2 for the left and right corners let (mut first_part, first_part_len) = self.first_exited_held_title_part_full(); let mut left_boundary = foreground_color(self.get_corner(boundary_type::BOTTOM_LEFT), self.color); let mut right_boundary = foreground_color(self.get_corner(boundary_type::BOTTOM_RIGHT), self.color); let res = if self.is_main_client { let (mut second_part, second_part_len) = self.second_held_title_part_full(); let full_text_len = first_part_len + second_part_len; if full_text_len <= max_undertitle_length { // render exit status and tips let mut padding = String::new(); for _ in full_text_len..max_undertitle_length { padding.push_str(boundary_type::HORIZONTAL); } let mut ret = vec![]; ret.append(&mut left_boundary); ret.append(&mut first_part); ret.append(&mut second_part); ret.append(&mut foreground_color(&padding, self.color)); ret.append(&mut right_boundary); ret } else if first_part_len <= max_undertitle_length { // render only exit status let mut padding = String::new(); for _ in first_part_len..max_undertitle_length { padding.push_str(boundary_type::HORIZONTAL); } let mut ret = vec![]; ret.append(&mut left_boundary); ret.append(&mut first_part); ret.append(&mut foreground_color(&padding, self.color)); ret.append(&mut right_boundary); ret } else { self.empty_undertitle(max_undertitle_length) } } else { if first_part_len <= max_undertitle_length { // render first part let full_text_len = first_part_len; let mut padding = String::new(); for _ in full_text_len..max_undertitle_length { padding.push_str(boundary_type::HORIZONTAL); } let mut ret = vec![]; ret.append(&mut left_boundary); ret.append(&mut first_part); ret.append(&mut foreground_color(&padding, self.color)); ret.append(&mut right_boundary); ret
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/mod.rs
zellij-server/src/ui/mod.rs
pub mod boundaries; pub mod components; pub mod loading_indication; pub mod pane_boundaries_frame; pub mod pane_contents_and_ui;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/pane_contents_and_ui.rs
zellij-server/src/ui/pane_contents_and_ui.rs
use crate::output::Output; use crate::panes::PaneId; use crate::tab::Pane; use crate::ui::boundaries::Boundaries; use crate::ui::pane_boundaries_frame::FrameParams; use crate::ClientId; use std::collections::{HashMap, HashSet}; use zellij_utils::data::{client_id_to_colors, InputMode, PaletteColor, Style}; use zellij_utils::errors::prelude::*; pub struct PaneContentsAndUi<'a> { pane: &'a mut Box<dyn Pane>, output: &'a mut Output, style: Style, focused_clients: Vec<ClientId>, multiple_users_exist_in_session: bool, z_index: Option<usize>, pane_is_stacked_under: bool, pane_is_stacked_over: bool, should_draw_pane_frames: bool, mouse_is_hovering_over_pane_for_clients: HashSet<ClientId>, current_pane_group: HashMap<ClientId, Vec<PaneId>>, } impl<'a> PaneContentsAndUi<'a> { pub fn new( pane: &'a mut Box<dyn Pane>, output: &'a mut Output, style: Style, active_panes: &HashMap<ClientId, PaneId>, multiple_users_exist_in_session: bool, z_index: Option<usize>, pane_is_stacked_under: bool, pane_is_stacked_over: bool, should_draw_pane_frames: bool, mouse_hover_pane_id: &HashMap<ClientId, PaneId>, current_pane_group: HashMap<ClientId, Vec<PaneId>>, ) -> Self { let mut focused_clients: Vec<ClientId> = active_panes .iter() .filter(|(_c_id, p_id)| **p_id == pane.pid()) .map(|(c_id, _p_id)| *c_id) .collect(); focused_clients.sort_unstable(); let mouse_is_hovering_over_pane_for_clients = mouse_hover_pane_id .iter() .filter_map(|(client_id, pane_id)| { if pane_id == &pane.pid() { Some(*client_id) } else { None } }) .collect(); PaneContentsAndUi { pane, output, style, focused_clients, multiple_users_exist_in_session, z_index, pane_is_stacked_under, pane_is_stacked_over, should_draw_pane_frames, mouse_is_hovering_over_pane_for_clients, current_pane_group, } } pub fn render_pane_contents_to_multiple_clients( &mut self, clients: impl Iterator<Item = ClientId>, ) -> Result<()> { let err_context = "failed to render pane contents to multiple clients"; // here we drop the fake cursors so that their lines will be updated // and we can clear them from the UI below drop(self.pane.drain_fake_cursors()); if let Some((character_chunks, raw_vte_output, sixel_image_chunks)) = self.pane.render(None).context(err_context)? { let clients: Vec<ClientId> = clients.collect(); self.output .add_character_chunks_to_multiple_clients( character_chunks, clients.iter().copied(), self.z_index, ) .context(err_context)?; self.output.add_sixel_image_chunks_to_multiple_clients( sixel_image_chunks, clients.iter().copied(), self.z_index, ); if let Some(raw_vte_output) = raw_vte_output { if !raw_vte_output.is_empty() { self.output.add_post_vte_instruction_to_multiple_clients( clients.iter().copied(), &format!( "\u{1b}[{};{}H\u{1b}[m{}", self.pane.y() + 1, self.pane.x() + 1, raw_vte_output ), ); } } } Ok(()) } pub fn render_pane_contents_for_client(&mut self, client_id: ClientId) -> Result<()> { let err_context = || format!("failed to render pane contents for client {client_id}"); if let Some((character_chunks, raw_vte_output, sixel_image_chunks)) = self .pane .render(Some(client_id)) .with_context(err_context)? { self.output .add_character_chunks_to_client(client_id, character_chunks, self.z_index) .with_context(err_context)?; self.output.add_sixel_image_chunks_to_client( client_id, sixel_image_chunks, self.z_index, ); if let Some(raw_vte_output) = raw_vte_output { self.output.add_post_vte_instruction_to_client( client_id, &format!( "\u{1b}[{};{}H\u{1b}[m{}", self.pane.y() + 1, self.pane.x() + 1, raw_vte_output ), ); } } Ok(()) } pub fn render_fake_cursor_if_needed(&mut self, client_id: ClientId) -> Result<()> { let pane_focused_for_client_id = self.focused_clients.contains(&client_id); let pane_focused_for_different_client = self .focused_clients .iter() .filter(|&&c_id| c_id != client_id) .count() > 0; if pane_focused_for_different_client && !pane_focused_for_client_id { let fake_cursor_client_id = self .focused_clients .iter() .find(|&&c_id| c_id != client_id) .with_context(|| { format!("failed to render fake cursor if needed for client {client_id}") })?; if let Some(colors) = client_id_to_colors( *fake_cursor_client_id, self.style.colors.multiplayer_user_colors, ) { let cursor_is_visible = self .pane .cursor_coordinates(Some(*fake_cursor_client_id)) .map(|(x, y)| { self.output .cursor_is_visible(self.pane.x() + x, self.pane.y() + y) }) .unwrap_or(false); if cursor_is_visible { if let Some(vte_output) = self.pane.render_fake_cursor(colors.0, colors.1) { self.output.add_post_vte_instruction_to_client( client_id, &format!( "\u{1b}[{};{}H\u{1b}[m{}", self.pane.y() + 1, self.pane.x() + 1, vte_output ), ); } } } } Ok(()) } pub fn render_terminal_title_if_needed( &mut self, client_id: ClientId, client_mode: InputMode, previous_title: &mut Option<String>, ) { if !self.focused_clients.contains(&client_id) { return; } let vte_output = self.pane.render_terminal_title(client_mode); if let Some(previous_title) = previous_title { if *previous_title == vte_output { return; } } *previous_title = Some(vte_output.clone()); self.output .add_post_vte_instruction_to_client(client_id, &vte_output); } pub fn render_pane_frame( &mut self, client_id: ClientId, client_mode: InputMode, session_is_mirrored: bool, pane_is_floating: bool, pane_is_selectable: bool, ) -> Result<()> { let err_context = || format!("failed to render pane frame for client {client_id}"); let pane_focused_for_client_id = self.focused_clients.contains(&client_id); let other_focused_clients: Vec<ClientId> = self .focused_clients .iter() .filter(|&&c_id| c_id != client_id) .copied() .collect(); let pane_focused_for_differet_client = !other_focused_clients.is_empty(); let frame_color = self.frame_color(client_id, client_mode, session_is_mirrored); let focused_client = if pane_focused_for_client_id { Some(client_id) } else if pane_focused_for_differet_client { Some(*other_focused_clients.first().with_context(err_context)?) } else { None }; let frame_params = if session_is_mirrored { FrameParams { focused_client, is_main_client: pane_focused_for_client_id, other_focused_clients: vec![], style: self.style, color: frame_color.map(|c| c.0), other_cursors_exist_in_session: false, pane_is_stacked_over: self.pane_is_stacked_over, pane_is_stacked_under: self.pane_is_stacked_under, should_draw_pane_frames: self.should_draw_pane_frames, pane_is_floating, content_offset: self.pane.get_content_offset(), mouse_is_hovering_over_pane: self .mouse_is_hovering_over_pane_for_clients .contains(&client_id), pane_is_selectable, } } else { FrameParams { focused_client, is_main_client: pane_focused_for_client_id, other_focused_clients, style: self.style, color: frame_color.map(|c| c.0), other_cursors_exist_in_session: self.multiple_users_exist_in_session, pane_is_stacked_over: self.pane_is_stacked_over, pane_is_stacked_under: self.pane_is_stacked_under, should_draw_pane_frames: self.should_draw_pane_frames, pane_is_floating, content_offset: self.pane.get_content_offset(), mouse_is_hovering_over_pane: self .mouse_is_hovering_over_pane_for_clients .contains(&client_id), pane_is_selectable, } }; if let Some((frame_terminal_characters, vte_output)) = self .pane .render_frame(client_id, frame_params, client_mode) .with_context(err_context)? { self.output .add_character_chunks_to_client(client_id, frame_terminal_characters, self.z_index) .with_context(err_context)?; if let Some(vte_output) = vte_output { self.output .add_post_vte_instruction_to_client(client_id, &vte_output); } } Ok(()) } pub fn render_pane_boundaries( &self, client_id: ClientId, client_mode: InputMode, boundaries: &mut Boundaries, session_is_mirrored: bool, pane_is_on_top_of_stack: bool, pane_is_on_bottom_of_stack: bool, ) { let color = self.frame_color(client_id, client_mode, session_is_mirrored); boundaries.add_rect( self.pane.as_ref(), color, pane_is_on_top_of_stack, pane_is_on_bottom_of_stack, self.pane_is_stacked_under, ); } fn frame_color( &self, client_id: ClientId, mode: InputMode, session_is_mirrored: bool, ) -> Option<(PaletteColor, usize)> { // (color, color_precedence) (the color_precedence is used // for the no-pane-frames mode) let pane_focused_for_client_id = self.focused_clients.contains(&client_id); let pane_is_in_group = self .current_pane_group .get(&client_id) .map(|p| p.contains(&self.pane.pid())) .unwrap_or(false); if self.pane.frame_color_override().is_some() && !pane_is_in_group { self.pane .frame_color_override() .map(|override_color| (override_color, 4)) } else if pane_is_in_group && !pane_focused_for_client_id { Some((self.style.colors.frame_highlight.emphasis_0, 2)) } else if pane_is_in_group && pane_focused_for_client_id { Some((self.style.colors.frame_highlight.emphasis_1, 3)) } else if pane_focused_for_client_id { match mode { InputMode::Normal | InputMode::Locked => { if session_is_mirrored || !self.multiple_users_exist_in_session { Some((self.style.colors.frame_selected.base, 3)) } else { let colors = client_id_to_colors( client_id, self.style.colors.multiplayer_user_colors, ); colors.map(|colors| (colors.0, 3)) } }, _ => Some((self.style.colors.frame_highlight.base, 3)), } } else if self .mouse_is_hovering_over_pane_for_clients .contains(&client_id) { Some((self.style.colors.frame_highlight.base, 1)) } else { self.style .colors .frame_unselected .map(|frame| (frame.base, 0)) } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/boundaries.rs
zellij-server/src/ui/boundaries.rs
use zellij_utils::pane_size::{Offset, Viewport}; use crate::output::CharacterChunk; use crate::panes::terminal_character::{TerminalCharacter, EMPTY_TERMINAL_CHARACTER, RESET_STYLES}; use crate::tab::Pane; use ansi_term::Colour::{Fixed, RGB}; use std::collections::HashMap; use zellij_utils::errors::prelude::*; use zellij_utils::{data::PaletteColor, shared::colors}; use std::fmt::{Display, Error, Formatter}; pub mod boundary_type { pub const TOP_RIGHT: &str = "┐"; pub const TOP_RIGHT_ROUND: &str = "╮"; pub const VERTICAL: &str = "│"; pub const HORIZONTAL: &str = "─"; pub const TOP_LEFT: &str = "┌"; pub const TOP_LEFT_ROUND: &str = "╭"; pub const BOTTOM_RIGHT: &str = "┘"; pub const BOTTOM_RIGHT_ROUND: &str = "╯"; pub const BOTTOM_LEFT: &str = "└"; pub const BOTTOM_LEFT_ROUND: &str = "╰"; pub const VERTICAL_LEFT: &str = "┤"; pub const VERTICAL_RIGHT: &str = "├"; pub const HORIZONTAL_DOWN: &str = "┬"; pub const HORIZONTAL_UP: &str = "┴"; pub const CROSS: &str = "┼"; } pub type BoundaryType = &'static str; // easy way to refer to boundary_type above #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BoundarySymbol { boundary_type: BoundaryType, invisible: bool, color: Option<(PaletteColor, usize)>, // (color, color_precedence) } impl BoundarySymbol { pub fn new(boundary_type: BoundaryType) -> Self { BoundarySymbol { boundary_type, invisible: false, color: Some((PaletteColor::EightBit(colors::GRAY), 0)), } } pub fn color(&mut self, color: Option<(PaletteColor, usize)>) -> Self { self.color = color; *self } pub fn as_terminal_character(&self) -> Result<TerminalCharacter> { let tc = if self.invisible { EMPTY_TERMINAL_CHARACTER } else { let character = self .boundary_type .chars() .next() .context("no boundary symbols defined") .with_context(|| { format!( "failed to convert boundary symbol {} into terminal character", self.boundary_type ) })?; TerminalCharacter::new_singlewidth_styled( character, RESET_STYLES .foreground(self.color.map(|palette_color| palette_color.0.into())) .into(), ) }; Ok(tc) } } impl Display for BoundarySymbol { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match self.invisible { true => write!(f, " "), false => match self.color { Some(color) => match color.0 { PaletteColor::Rgb((r, g, b)) => { write!(f, "{}", RGB(r, g, b).paint(self.boundary_type)) }, PaletteColor::EightBit(color) => { write!(f, "{}", Fixed(color).paint(self.boundary_type)) }, }, None => write!(f, "{}", self.boundary_type), }, } } } fn combine_symbols( current_symbol: BoundarySymbol, next_symbol: BoundarySymbol, ) -> Option<BoundarySymbol> { use boundary_type::*; let invisible = current_symbol.invisible || next_symbol.invisible; let color = match (current_symbol.color, next_symbol.color) { (Some(current_symbol_color), Some(next_symbol_color)) => { let ret = if current_symbol_color.1 >= next_symbol_color.1 { Some(current_symbol_color) } else { Some(next_symbol_color) }; ret }, _ => current_symbol.color.or(next_symbol.color), }; match (current_symbol.boundary_type, next_symbol.boundary_type) { (CROSS, _) | (_, CROSS) => { // (┼, *) or (*, ┼) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_RIGHT, TOP_RIGHT) => { // (┐, ┐) => Some(┐) let boundary_type = TOP_RIGHT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_RIGHT, VERTICAL) | (TOP_RIGHT, BOTTOM_RIGHT) | (TOP_RIGHT, VERTICAL_LEFT) => { // (┐, │) => Some(┤) // (┐, ┘) => Some(┤) // (─, ┤) => Some(┤) let boundary_type = VERTICAL_LEFT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_RIGHT, HORIZONTAL) | (TOP_RIGHT, TOP_LEFT) | (TOP_RIGHT, HORIZONTAL_DOWN) => { // (┐, ─) => Some(┬) // (┐, ┌) => Some(┬) // (┐, ┬) => Some(┬) let boundary_type = HORIZONTAL_DOWN; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_RIGHT, BOTTOM_LEFT) | (TOP_RIGHT, VERTICAL_RIGHT) | (TOP_RIGHT, HORIZONTAL_UP) => { // (┐, └) => Some(┼) // (┐, ├) => Some(┼) // (┐, ┴) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL, HORIZONTAL) => { // (─, ─) => Some(─) let boundary_type = HORIZONTAL; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL, VERTICAL) | (HORIZONTAL, VERTICAL_LEFT) | (HORIZONTAL, VERTICAL_RIGHT) => { // (─, │) => Some(┼) // (─, ┤) => Some(┼) // (─, ├) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL, TOP_LEFT) | (HORIZONTAL, HORIZONTAL_DOWN) => { // (─, ┌) => Some(┬) // (─, ┬) => Some(┬) let boundary_type = HORIZONTAL_DOWN; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL, BOTTOM_RIGHT) | (HORIZONTAL, BOTTOM_LEFT) | (HORIZONTAL, HORIZONTAL_UP) => { // (─, ┘) => Some(┴) // (─, └) => Some(┴) // (─, ┴) => Some(┴) let boundary_type = HORIZONTAL_UP; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL, VERTICAL) => { // (│, │) => Some(│) let boundary_type = VERTICAL; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL, TOP_LEFT) | (VERTICAL, BOTTOM_LEFT) | (VERTICAL, VERTICAL_RIGHT) => { // (│, ┌) => Some(├) // (│, └) => Some(├) // (│, ├) => Some(├) let boundary_type = VERTICAL_RIGHT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL, BOTTOM_RIGHT) | (VERTICAL, VERTICAL_LEFT) => { // (│, ┘) => Some(┤) // (│, ┤) => Some(┤) let boundary_type = VERTICAL_LEFT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL, HORIZONTAL_DOWN) | (VERTICAL, HORIZONTAL_UP) => { // (│, ┬) => Some(┼) // (│, ┴) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_LEFT, TOP_LEFT) => { // (┌, ┌) => Some(┌) let boundary_type = TOP_LEFT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_LEFT, BOTTOM_RIGHT) | (TOP_LEFT, VERTICAL_LEFT) | (TOP_LEFT, HORIZONTAL_UP) => { // (┌, ┘) => Some(┼) // (┌, ┤) => Some(┼) // (┌, ┴) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_LEFT, BOTTOM_LEFT) | (TOP_LEFT, VERTICAL_RIGHT) => { // (┌, └) => Some(├) // (┌, ├) => Some(├) let boundary_type = VERTICAL_RIGHT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (TOP_LEFT, HORIZONTAL_DOWN) => { // (┌, ┬) => Some(┬) let boundary_type = HORIZONTAL_DOWN; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_RIGHT, BOTTOM_RIGHT) => { // (┘, ┘) => Some(┘) let boundary_type = BOTTOM_RIGHT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_RIGHT, BOTTOM_LEFT) | (BOTTOM_RIGHT, HORIZONTAL_UP) => { // (┘, └) => Some(┴) // (┘, ┴) => Some(┴) let boundary_type = HORIZONTAL_UP; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_RIGHT, VERTICAL_LEFT) => { // (┘, ┤) => Some(┤) let boundary_type = VERTICAL_LEFT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_RIGHT, VERTICAL_RIGHT) | (BOTTOM_RIGHT, HORIZONTAL_DOWN) => { // (┘, ├) => Some(┼) // (┘, ┬) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_LEFT, BOTTOM_LEFT) => { // (└, └) => Some(└) let boundary_type = BOTTOM_LEFT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_LEFT, VERTICAL_LEFT) | (BOTTOM_LEFT, HORIZONTAL_DOWN) => { // (└, ┤) => Some(┼) // (└, ┬) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_LEFT, VERTICAL_RIGHT) => { // (└, ├) => Some(├) let boundary_type = VERTICAL_RIGHT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (BOTTOM_LEFT, HORIZONTAL_UP) => { // (└, ┴) => Some(┴) let boundary_type = HORIZONTAL_UP; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL_LEFT, VERTICAL_LEFT) => { // (┤, ┤) => Some(┤) let boundary_type = VERTICAL_LEFT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL_LEFT, VERTICAL_RIGHT) | (VERTICAL_LEFT, HORIZONTAL_DOWN) | (VERTICAL_LEFT, HORIZONTAL_UP) => { // (┤, ├) => Some(┼) // (┤, ┬) => Some(┼) // (┤, ┴) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL_RIGHT, VERTICAL_RIGHT) => { // (├, ├) => Some(├) let boundary_type = VERTICAL_RIGHT; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (VERTICAL_RIGHT, HORIZONTAL_DOWN) | (VERTICAL_RIGHT, HORIZONTAL_UP) => { // (├, ┬) => Some(┼) // (├, ┴) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL_DOWN, HORIZONTAL_DOWN) => { // (┬, ┬) => Some(┬) let boundary_type = HORIZONTAL_DOWN; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL_DOWN, HORIZONTAL_UP) => { // (┬, ┴) => Some(┼) let boundary_type = CROSS; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (HORIZONTAL_UP, HORIZONTAL_UP) => { // (┴, ┴) => Some(┴) let boundary_type = HORIZONTAL_UP; Some(BoundarySymbol { boundary_type, invisible, color, }) }, (_, _) => combine_symbols(next_symbol, current_symbol), } } #[derive(PartialEq, Eq, Hash, Debug)] pub struct Coordinates { x: usize, y: usize, } impl Coordinates { pub fn new(x: usize, y: usize) -> Self { Coordinates { x, y } } } pub struct Boundaries { viewport: Viewport, pub boundary_characters: HashMap<Coordinates, BoundarySymbol>, } #[allow(clippy::if_same_then_else)] impl Boundaries { pub fn new(viewport: Viewport) -> Self { Boundaries { viewport, boundary_characters: HashMap::new(), } } pub fn add_rect( &mut self, rect: &dyn Pane, color: Option<(PaletteColor, usize)>, // (color, color_precedence) pane_is_on_top_of_stack: bool, pane_is_on_bottom_of_stack: bool, pane_is_stacked_under: bool, ) { let pane_is_stacked = rect.current_geom().is_stacked(); let should_skip_top_boundary = pane_is_stacked && !pane_is_on_top_of_stack; let should_skip_bottom_boundary = pane_is_stacked && !pane_is_on_bottom_of_stack; let content_offset = rect.get_content_offset(); if !self.is_fully_inside_screen(rect) { return; } if rect.x() > self.viewport.x { // left boundary let boundary_x_coords = rect.x() - 1; let first_row_coordinates = self.rect_right_boundary_row_start(rect, pane_is_stacked_under, content_offset); let last_row_coordinates = self.rect_right_boundary_row_end(rect); for row in first_row_coordinates..last_row_coordinates { let coordinates = Coordinates::new(boundary_x_coords, row); let symbol_to_add = if row == first_row_coordinates && row != self.viewport.y { if pane_is_stacked { BoundarySymbol::new(boundary_type::VERTICAL_RIGHT).color(color) } else { BoundarySymbol::new(boundary_type::TOP_LEFT).color(color) } } else if row == first_row_coordinates && pane_is_stacked { BoundarySymbol::new(boundary_type::TOP_LEFT).color(color) } else if row == last_row_coordinates - 1 && row != self.viewport.y + self.viewport.rows - 1 && content_offset.bottom > 0 { BoundarySymbol::new(boundary_type::BOTTOM_LEFT).color(color) } else { BoundarySymbol::new(boundary_type::VERTICAL).color(color) }; let next_symbol = self .boundary_characters .remove(&coordinates) .and_then(|current_symbol| combine_symbols(current_symbol, symbol_to_add)) .unwrap_or(symbol_to_add); self.boundary_characters.insert(coordinates, next_symbol); } } if rect.y() > self.viewport.y && !should_skip_top_boundary { // top boundary let boundary_y_coords = rect.y() - 1; let first_col_coordinates = self.rect_bottom_boundary_col_start(rect); let last_col_coordinates = self.rect_bottom_boundary_col_end(rect); for col in first_col_coordinates..last_col_coordinates { let coordinates = Coordinates::new(col, boundary_y_coords); let symbol_to_add = if col == first_col_coordinates && col != self.viewport.x { BoundarySymbol::new(boundary_type::TOP_LEFT).color(color) } else if col == last_col_coordinates - 1 && col != self.viewport.cols - 1 { BoundarySymbol::new(boundary_type::TOP_RIGHT).color(color) } else { BoundarySymbol::new(boundary_type::HORIZONTAL).color(color) }; let next_symbol = self .boundary_characters .remove(&coordinates) .and_then(|current_symbol| combine_symbols(current_symbol, symbol_to_add)) .unwrap_or(symbol_to_add); self.boundary_characters.insert(coordinates, next_symbol); } } if self.rect_right_boundary_is_before_screen_edge(rect) { // right boundary let boundary_x_coords = rect.right_boundary_x_coords() - 1; let first_row_coordinates = self.rect_right_boundary_row_start(rect, pane_is_stacked_under, content_offset); let last_row_coordinates = self.rect_right_boundary_row_end(rect); for row in first_row_coordinates..last_row_coordinates { let coordinates = Coordinates::new(boundary_x_coords, row); let symbol_to_add = if row == first_row_coordinates && pane_is_stacked { BoundarySymbol::new(boundary_type::VERTICAL_LEFT).color(color) } else if row == first_row_coordinates && row != self.viewport.y { if pane_is_stacked { BoundarySymbol::new(boundary_type::VERTICAL_LEFT).color(color) } else { BoundarySymbol::new(boundary_type::TOP_RIGHT).color(color) } } else if row == last_row_coordinates - 1 && row != self.viewport.y + self.viewport.rows - 1 && content_offset.bottom > 0 { BoundarySymbol::new(boundary_type::BOTTOM_RIGHT).color(color) } else { BoundarySymbol::new(boundary_type::VERTICAL).color(color) }; let next_symbol = self .boundary_characters .remove(&coordinates) .and_then(|current_symbol| combine_symbols(current_symbol, symbol_to_add)) .unwrap_or(symbol_to_add); self.boundary_characters.insert(coordinates, next_symbol); } } if self.rect_bottom_boundary_is_before_screen_edge(rect) && !should_skip_bottom_boundary { // bottom boundary let boundary_y_coords = rect.bottom_boundary_y_coords() - 1; let first_col_coordinates = self.rect_bottom_boundary_col_start(rect); let last_col_coordinates = self.rect_bottom_boundary_col_end(rect); for col in first_col_coordinates..last_col_coordinates { let coordinates = Coordinates::new(col, boundary_y_coords); let symbol_to_add = if col == first_col_coordinates && col != self.viewport.x { BoundarySymbol::new(boundary_type::BOTTOM_LEFT).color(color) } else if col == last_col_coordinates - 1 && col != self.viewport.cols - 1 { BoundarySymbol::new(boundary_type::BOTTOM_RIGHT).color(color) } else { BoundarySymbol::new(boundary_type::HORIZONTAL).color(color) }; let next_symbol = self .boundary_characters .remove(&coordinates) .and_then(|current_symbol| combine_symbols(current_symbol, symbol_to_add)) .unwrap_or(symbol_to_add); self.boundary_characters.insert(coordinates, next_symbol); } } } pub fn render( &self, existing_boundaries_on_screen: Option<&Boundaries>, ) -> Result<Vec<CharacterChunk>> { let mut character_chunks = vec![]; for (coordinates, boundary_character) in &self.boundary_characters { let already_on_screen = existing_boundaries_on_screen .and_then(|e| e.boundary_characters.get(coordinates)) .map(|e| e == boundary_character) .unwrap_or(false); if already_on_screen { continue; } character_chunks.push(CharacterChunk::new( vec![boundary_character .as_terminal_character() .context("failed to render as terminal character")?], coordinates.x, coordinates.y, )); } Ok(character_chunks) } fn rect_right_boundary_is_before_screen_edge(&self, rect: &dyn Pane) -> bool { rect.x() + rect.cols() < self.viewport.cols } fn rect_bottom_boundary_is_before_screen_edge(&self, rect: &dyn Pane) -> bool { rect.y() + rect.rows() < self.viewport.y + self.viewport.rows } fn rect_right_boundary_row_start( &self, rect: &dyn Pane, pane_is_stacked_under: bool, content_offset: Offset, ) -> usize { let pane_is_stacked = rect.current_geom().is_stacked(); let horizontal_frame_offset = if pane_is_stacked_under { // these panes - panes that are in a stack below the flexible pane - need to have their // content offset taken into account when rendering them (i.e. they are rendered // one line above their actual y coordinates, since they are only 1 line) // as opposed to panes that are in a stack above the flexible pane who do not because // they are rendered in place (the content offset of the stack is "absorbed" by the // flexible pane below them) content_offset.bottom } else if pane_is_stacked { 0 } else { 1 }; if rect.y() > self.viewport.y { rect.y().saturating_sub(horizontal_frame_offset) } else { self.viewport.y } } fn rect_right_boundary_row_end(&self, rect: &dyn Pane) -> usize { rect.y() + rect.rows() } fn rect_bottom_boundary_col_start(&self, rect: &dyn Pane) -> usize { if rect.x() == 0 { 0 } else { rect.x() - 1 } } fn rect_bottom_boundary_col_end(&self, rect: &dyn Pane) -> usize { rect.x() + rect.cols() } fn is_fully_inside_screen(&self, rect: &dyn Pane) -> bool { rect.x() >= self.viewport.x && rect.x() + rect.cols() <= self.viewport.x + self.viewport.cols && rect.y() >= self.viewport.y && rect.y() + rect.rows() <= self.viewport.y + self.viewport.rows } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/components/component_coordinates.rs
zellij-server/src/ui/components/component_coordinates.rs
use std::fmt::{self, Display, Formatter}; #[derive(Debug, Clone)] pub struct Coordinates { pub x: usize, pub y: usize, pub width: Option<usize>, pub height: Option<usize>, } impl Coordinates { pub fn stringify_with_y_offset(&self, y_offset: usize) -> String { format!("\u{1b}[{};{}H", self.y + y_offset + 1, self.x + 1) } } impl Display for Coordinates { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "\u{1b}[{};{}H", self.y + 1, self.x + 1) } } pub fn is_too_wide( character_width: usize, current_width: usize, component_coordinates: &Option<Coordinates>, ) -> bool { if let Some(max_width) = component_coordinates.as_ref().and_then(|p| p.width) { if current_width + character_width > max_width { return true; } } false } pub fn is_too_high(current_height: usize, component_coordinates: &Option<Coordinates>) -> bool { if let Some(max_height) = component_coordinates.as_ref().and_then(|p| p.height) { if current_height > max_height { return true; } } false }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/components/table.rs
zellij-server/src/ui/components/table.rs
use super::{is_too_high, is_too_wide, stringify_text, Coordinates, Text}; use crate::panes::{ terminal_character::{AnsiCode, RESET_STYLES}, CharacterStyles, }; use std::collections::BTreeMap; use zellij_utils::{data::Style, shared::ansi_len}; pub fn table( columns: usize, _rows: usize, contents: Vec<Text>, style: &Style, coordinates: Option<Coordinates>, ) -> Vec<u8> { let mut stringified = String::new(); // we first arrange the data by columns so that we can pad them by the widest one let stringified_columns = stringify_table_columns(contents, columns); let stringified_rows = stringify_table_rows(stringified_columns, &coordinates); for (row_index, (_, row)) in stringified_rows.into_iter().enumerate() { let is_title_row = row_index == 0; if is_too_high(row_index + 1, &coordinates) { break; } let cell_count = row.iter().len(); for (cell_index, cell) in row.into_iter().enumerate() { let declaration = if is_title_row { style.colors.table_title } else { if cell.selected { style.colors.table_cell_selected } else { style.colors.table_cell_unselected } }; let text_style = if cell.opaque || cell.selected { CharacterStyles::from(declaration).background(Some(declaration.background.into())) } else { CharacterStyles::from(declaration) }; // Default: bold let text_style = text_style.bold(Some(AnsiCode::On)); // here we intentionally don't pass our coordinates even if we have them, because // these cells have already been padded and truncated let (text, _text_width) = stringify_text(&cell, None, &None, &declaration, &style.colors, text_style); if cell_index == cell_count.saturating_sub(1) { // do not add padding between columns for the last cell stringified.push_str(&format!("{}{}{}", text_style, text, RESET_STYLES)); } else { // add padding between columns stringified.push_str(&format!("{}{} {}", text_style, text, RESET_STYLES)); } } let next_row_instruction = coordinates .as_ref() .map(|c| c.stringify_with_y_offset(row_index + 1)) .unwrap_or_else(|| format!("\n\r")); stringified.push_str(&next_row_instruction); } if let Some(coordinates) = coordinates { format!("{}{}", coordinates, stringified) .as_bytes() .to_vec() } else { stringified.as_bytes().to_vec() } } fn stringify_table_columns(contents: Vec<Text>, columns: usize) -> BTreeMap<usize, Vec<Text>> { let mut stringified_columns: BTreeMap<usize, Vec<Text>> = BTreeMap::new(); for (i, cell) in contents.into_iter().enumerate() { let column_index = i % columns; stringified_columns .entry(column_index) .or_insert_with(Vec::new) .push(cell); } stringified_columns } fn max_table_column_width(column: &Vec<Text>) -> usize { let mut max_column_width = 0; for cell in column { let cell_width = ansi_len(&cell.text); if cell_width > max_column_width { max_column_width = cell_width; } } max_column_width } fn stringify_table_rows( stringified_columns: BTreeMap<usize, Vec<Text>>, coordinates: &Option<Coordinates>, ) -> BTreeMap<usize, Vec<Text>> { let mut stringified_rows: BTreeMap<usize, Vec<Text>> = BTreeMap::new(); let mut row_width = 0; for (_, column) in stringified_columns.into_iter() { let max_column_width = max_table_column_width(&column); if is_too_wide(max_column_width + 1, row_width, &coordinates) { break; } row_width += max_column_width + 1; for (row_index, mut cell) in column.into_iter().enumerate() { cell.pad_text(max_column_width); stringified_rows .entry(row_index) .or_insert_with(Vec::new) .push(cell); } } stringified_rows }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/components/text.rs
zellij-server/src/ui/components/text.rs
use super::{is_too_wide, parse_indices, parse_opaque, parse_selected, Coordinates}; use crate::panes::{terminal_character::CharacterStyles, AnsiCode}; use zellij_utils::{ data::{PaletteColor, Style, StyleDeclaration}, shared::ansi_len, }; use unicode_width::UnicodeWidthChar; use zellij_utils::errors::prelude::*; pub fn text(content: Text, style: &Style, component_coordinates: Option<Coordinates>) -> Vec<u8> { let declaration = if content.selected { style.colors.text_selected } else { style.colors.text_unselected }; // Start with base style from declaration let base_text_style = CharacterStyles::from(declaration).bold(Some(AnsiCode::On)); let (text, _text_width) = stringify_text( &content, None, &component_coordinates, &declaration, &style.colors, base_text_style, ); match component_coordinates { Some(component_coordinates) => { format!("{}{}{}", component_coordinates, base_text_style, text) .as_bytes() .to_vec() }, None => format!("{}{}", base_text_style, text).as_bytes().to_vec(), } } pub fn stringify_text( text: &Text, left_padding: Option<usize>, coordinates: &Option<Coordinates>, style: &StyleDeclaration, styling: &zellij_utils::data::Styling, component_text_style: CharacterStyles, ) -> (String, usize) { let mut text_width = 0; let mut stringified = String::new(); let base_text_style = if text.opaque || text.selected { component_text_style.background(Some(style.background.into())) } else { component_text_style }; stringified.push_str(&format!("{}", base_text_style)); for (i, character) in text.text.chars().enumerate() { let character_width = character.width().unwrap_or(0); if is_too_wide( character_width, left_padding.unwrap_or(0) + text_width, &coordinates, ) { break; } text_width += character_width; if text.selected || text.opaque { // we do this so that selected text will appear selected // even if it does not have color indices stringified.push_str(&format!("{}", base_text_style)); } if !text.indices.is_empty() || text.selected || text.opaque { let character_with_styling = color_index_character(character, i, &text, style, styling, base_text_style); stringified.push_str(&character_with_styling); } else { stringified.push(character) } } let coordinates_width = coordinates.as_ref().and_then(|c| c.width); match (coordinates_width, base_text_style.background) { (Some(coordinates_width), Some(_background_style)) => { let text_width_with_left_padding = text_width + left_padding.unwrap_or(0); let background_padding_length = coordinates_width.saturating_sub(text_width_with_left_padding); if text_width_with_left_padding < coordinates_width { // here we pad the string with whitespace until the end so that the background // style will apply the whole length of the coordinates stringified.push_str(&format!( "{:width$}", " ", width = background_padding_length )); } text_width += background_padding_length; }, _ => {}, } (stringified, text_width) } pub fn color_index_character( character: char, index: usize, text: &Text, declaration: &StyleDeclaration, styling: &zellij_utils::data::Styling, base_text_style: CharacterStyles, ) -> String { let mut character_style = text .style_of_index(index, declaration, styling) .map(|foreground_style| base_text_style.foreground(Some(foreground_style.into()))) .unwrap_or(base_text_style); // Apply dim and unbold per-character based on index levels 4 and 5 if text.is_unbold_at(index) { // Remove bold for this character character_style = character_style.bold(Some(AnsiCode::Reset)); } else if text.is_dimmed_at(index) { // Apply dim for this character character_style = character_style .foreground(Some(AnsiCode::Reset)) // some terminals (eg. alacritty) do not support dimming non 16 // colors, so we have to defer to the terminal's default here .dim(Some(AnsiCode::On)); } else { character_style = character_style .bold(Some(AnsiCode::On)) .dim(Some(AnsiCode::Reset)); // default, to reset any // possible dim/bold values // from previous indices } format!("{}{}{}", character_style, character, base_text_style) } pub fn parse_text_params<'a>(params_iter: impl Iterator<Item = &'a mut String>) -> Vec<Text> { params_iter .flat_map(|mut stringified| { let selected = parse_selected(&mut stringified); let opaque = parse_opaque(&mut stringified); let indices = parse_indices(&mut stringified); let text = parse_text(&mut stringified).map_err(|e| e.to_string())?; Ok::<Text, String>(Text { text, opaque, selected, indices, }) }) .collect::<Vec<Text>>() } #[derive(Debug, Clone)] pub struct Text { pub text: String, pub selected: bool, pub opaque: bool, pub indices: Vec<Vec<usize>>, } impl Text { pub fn pad_text(&mut self, max_column_width: usize) { for _ in ansi_len(&self.text)..max_column_width { self.text.push(' '); } } pub fn is_dimmed_at(&self, index: usize) -> bool { const DIM_LEVEL: usize = 4; self.indices .get(DIM_LEVEL) .map(|indices| indices.contains(&index)) .unwrap_or(false) } pub fn is_unbold_at(&self, index: usize) -> bool { const UNBOLD_LEVEL: usize = 5; self.indices .get(UNBOLD_LEVEL) .map(|indices| indices.contains(&index)) .unwrap_or(false) } pub fn style_of_index( &self, index: usize, style: &StyleDeclaration, styling: &zellij_utils::data::Styling, ) -> Option<PaletteColor> { const ERROR_COLOR_LEVEL: usize = 6; const SUCCESS_COLOR_LEVEL: usize = 7; // Check error color first (highest precedence) if let Some(indices) = self.indices.get(ERROR_COLOR_LEVEL) { if indices.contains(&index) { return Some(styling.exit_code_error.base); } } // Check success color (second highest precedence) if let Some(indices) = self.indices.get(SUCCESS_COLOR_LEVEL) { if indices.contains(&index) { return Some(styling.exit_code_success.base); } } // Check regular emphasis levels (existing code) let index_variant_styles = [ style.emphasis_0, style.emphasis_1, style.emphasis_2, style.emphasis_3, ]; for i in (0..=3).rev() { // we do this in reverse to give precedence to the last applied // style if let Some(indices) = self.indices.get(i) { if indices.contains(&index) { return Some(index_variant_styles[i]); } } } Some(style.base) } } pub fn parse_text(stringified: &mut String) -> Result<String> { let mut utf8 = vec![]; for stringified_character in stringified.split(',') { utf8.push( stringified_character .to_string() .parse::<u8>() .with_context(|| format!("Failed to parse utf8"))?, ); } Ok(String::from_utf8_lossy(&utf8).to_string()) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/components/mod.rs
zellij-server/src/ui/components/mod.rs
mod component_coordinates; mod nested_list; mod ribbon; mod table; mod text; use crate::panes::grid::Grid; use lazy_static::lazy_static; use regex::Regex; use vte; use zellij_utils::data::Style; use zellij_utils::errors::prelude::*; use component_coordinates::{is_too_high, is_too_wide, Coordinates}; use nested_list::{nested_list, parse_nested_list_items}; use ribbon::ribbon; use table::table; use text::{parse_text, parse_text_params, stringify_text, text, Text}; macro_rules! parse_next_param { ($next_param:expr, $type:ident, $component_name:expr, $item_name:expr) => {{ $next_param .and_then(|stringified_param| stringified_param.parse::<$type>().ok()) .with_context(|| format!("{} must have {}", $component_name, $item_name))? }}; } macro_rules! parse_vte_bytes { ($self:expr, $encoded_component:expr) => {{ let mut vte_parser = vte::Parser::new(); for &byte in &$encoded_component { vte_parser.advance($self.grid, byte); } }}; } #[derive(Debug)] pub struct UiComponentParser<'a> { grid: &'a mut Grid, style: Style, arrow_fonts: bool, } impl<'a> UiComponentParser<'a> { pub fn new(grid: &'a mut Grid, style: Style, arrow_fonts: bool) -> Self { UiComponentParser { grid, style, arrow_fonts, } } pub fn parse(&mut self, bytes: Vec<u8>) -> Result<()> { // The stages of parsing: // 1. We decode the bytes to utf8 and get something like (as a String): `component_name;111;222;333` // 2. We split this string by `;` to get at the parameters themselves // 3. We extract the component name, and then behave according to the component // 4. Some components interpret their parameters as bytes, and so have another layer of // utf8 decoding, others would take them verbatim, some will act depending on their // placement (eg. the `table` component treats the first two parameters as integers for // the columns/rows of the table, and then treats the rest of the component as utf8 // encoded bytes, each one representing one cell in the table) // 5. Each component parses its parameters, creating a String of ANSI instructions of its // own representing instructions to create the component // 6. Finally, we take this string, encode it back into bytes and pass it back through the ANSI // parser (our `Grid`) in order to create a representation of it on screen let mut params: Vec<String> = String::from_utf8_lossy(&bytes) .to_string() .split(';') .map(|c| c.to_owned()) .collect(); let mut params_iter = params.iter_mut().peekable(); let component_name = params_iter .next() .with_context(|| format!("ui component must have a name"))?; // parse coordinates let mut component_coordinates = None; if let Some(coordinates) = params_iter.peek() { component_coordinates = self.parse_coordinates(coordinates)?; if component_coordinates.is_some() { let _ = params_iter.next(); // we just peeked, let's consume the coords now } } if component_name == &"table" { let columns = parse_next_param!(params_iter.next(), usize, "table", "columns"); let rows = parse_next_param!(params_iter.next(), usize, "table", "rows"); let stringified_params = parse_text_params(params_iter); let encoded_table = table( columns, rows, stringified_params, &self.style, component_coordinates, ); parse_vte_bytes!(self, encoded_table); Ok(()) } else if component_name == &"ribbon" { let stringified_params = parse_text_params(params_iter) .into_iter() .next() .with_context(|| format!("a ribbon must have text"))?; let encoded_text = ribbon( stringified_params, &self.style, self.arrow_fonts, component_coordinates, ); parse_vte_bytes!(self, encoded_text); Ok(()) } else if component_name == &"nested_list" { let nested_list_items = parse_nested_list_items(params_iter); let encoded_nested_list = nested_list(nested_list_items, &self.style, component_coordinates); parse_vte_bytes!(self, encoded_nested_list); Ok(()) } else if component_name == &"text" { let stringified_params = parse_text_params(params_iter) .into_iter() .next() .with_context(|| format!("text must have, well, text..."))?; let encoded_text = text(stringified_params, &self.style, component_coordinates); parse_vte_bytes!(self, encoded_text); Ok(()) } else { Err(anyhow!("Unknown component: {}", component_name)) } } fn parse_coordinates(&self, coordinates: &str) -> Result<Option<Coordinates>> { lazy_static! { static ref RE: Regex = Regex::new(r"(\d*)/(\d*)/(\d*)/(\d*)").unwrap(); } if let Some(captures) = RE.captures_iter(&coordinates).next() { let x = captures[1].parse::<usize>().with_context(|| { format!( "Failed to parse x coordinates for string: {:?}", coordinates ) })?; let y = captures[2].parse::<usize>().with_context(|| { format!( "Failed to parse y coordinates for string: {:?}", coordinates ) })?; let width = captures[3].parse::<usize>().ok(); let height = captures[4].parse::<usize>().ok(); Ok(Some(Coordinates { x, y, width, height, })) } else { Ok(None) } } } fn parse_selected(stringified: &mut String) -> bool { let mut selected = false; if stringified.chars().next() == Some('x') { selected = true; stringified.remove(0); } selected } fn parse_opaque(stringified: &mut String) -> bool { let mut opaque = false; if stringified.chars().next() == Some('z') { opaque = true; stringified.remove(0); } opaque } fn parse_indices(stringified: &mut String) -> Vec<Vec<usize>> { stringified .chars() .collect::<Vec<_>>() .iter() .rposition(|c| c == &'$') .map(|last_position| stringified.drain(0..=last_position).collect::<String>()) .map(|indices_string| { let mut all_indices = vec![]; let raw_indices_for_each_variant = indices_string.split('$'); for index_string in raw_indices_for_each_variant { let indices_for_variant = index_string .split(',') .filter_map(|s| s.parse::<usize>().ok()) .collect(); all_indices.push(indices_for_variant) } all_indices }) .unwrap_or_default() }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/components/nested_list.rs
zellij-server/src/ui/components/nested_list.rs
use super::{ is_too_high, parse_indices, parse_opaque, parse_selected, parse_text, stringify_text, Coordinates, Text, }; use crate::panes::terminal_character::{AnsiCode, CharacterStyles, RESET_STYLES}; use zellij_utils::data::Style; use unicode_width::UnicodeWidthChar; #[derive(Debug, Clone)] pub struct NestedListItem { pub text: Text, pub indentation_level: usize, } pub fn nested_list( mut contents: Vec<NestedListItem>, style: &Style, coordinates: Option<Coordinates>, ) -> Vec<u8> { let mut stringified = String::new(); let max_width = coordinates .as_ref() .and_then(|c| c.width) .unwrap_or_else(|| max_nested_item_width(&contents)); for (line_index, line_item) in contents.drain(..).enumerate() { if is_too_high(line_index + 1, &coordinates) { break; } let style_declaration = if line_item.text.selected { style.colors.list_selected } else { style.colors.list_unselected }; let padding = line_item.indentation_level * 2 + 1; let bulletin = if line_item.indentation_level % 2 == 0 { "> " } else { "- " }; let text_style = if line_item.text.opaque || line_item.text.selected { CharacterStyles::from(style_declaration) .background(Some(style_declaration.background.into())) } else { CharacterStyles::from(style_declaration) }; let (mut text, text_width) = stringify_text( &line_item.text, Some(padding + bulletin.len()), &coordinates, &style_declaration, &style.colors, text_style.bold(Some(AnsiCode::On)), ); text = pad_line(text, max_width, padding, text_width); let go_to_row_instruction = coordinates .as_ref() .map(|c| c.stringify_with_y_offset(line_index)) .unwrap_or_else(|| { if line_index != 0 { format!("\n\r") } else { "".to_owned() } }); stringified.push_str(&format!( "{}{}{:padding$}{bulletin}{}{text}{}", go_to_row_instruction, text_style, " ", text_style.bold(Some(AnsiCode::On)), RESET_STYLES )); } stringified.as_bytes().to_vec() } pub fn parse_nested_list_items<'a>( params_iter: impl Iterator<Item = &'a mut String>, ) -> Vec<NestedListItem> { params_iter .flat_map(|mut stringified| { let indentation_level = parse_indentation_level(&mut stringified); let selected = parse_selected(&mut stringified); let opaque = parse_opaque(&mut stringified); let indices = parse_indices(&mut stringified); let text = parse_text(&mut stringified).map_err(|e| e.to_string())?; let text = Text { text, opaque, selected, indices, }; Ok::<NestedListItem, String>(NestedListItem { text, indentation_level, }) }) .collect::<Vec<NestedListItem>>() } fn parse_indentation_level(stringified: &mut String) -> usize { let mut indentation_level = 0; loop { if stringified.is_empty() { break; } if stringified.chars().next() == Some('|') { stringified.remove(0); indentation_level += 1; } else { break; } } indentation_level } fn max_nested_item_width(contents: &Vec<NestedListItem>) -> usize { let mut width_of_longest_line = 0; for line_item in contents.iter() { let mut line_item_text_width = 0; for character in line_item.text.text.chars() { let character_width = character.width().unwrap_or(0); line_item_text_width += character_width; } let bulletin_width = 2; let padding = line_item.indentation_level * 2 + 1; let total_width = line_item_text_width + bulletin_width + padding; if width_of_longest_line < total_width { width_of_longest_line = total_width; } } width_of_longest_line } fn pad_line(text: String, max_width: usize, padding: usize, text_width: usize) -> String { if max_width > text_width + padding + 2 { // 2 is the bulletin let end_padding = max_width.saturating_sub(text_width + padding + 2); return format!("{}{:end_padding$}", text, " "); } text }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/ui/components/ribbon.rs
zellij-server/src/ui/components/ribbon.rs
use super::{text::stringify_text, Coordinates, Text}; use crate::panes::terminal_character::{AnsiCode, CharacterStyles, RESET_STYLES}; use zellij_utils::data::{PaletteColor, Style}; static ARROW_SEPARATOR: &str = ""; pub fn ribbon( content: Text, style: &Style, arrow_fonts: bool, component_coordinates: Option<Coordinates>, ) -> Vec<u8> { let colors = style.colors; let background = colors.text_unselected.background; let declaration = if content.selected { colors.ribbon_selected } else { colors.ribbon_unselected }; let (first_arrow_styles, text_style, last_arrow_styles) = ( character_style(background, declaration.background), character_style(declaration.base, declaration.background), character_style(declaration.background, background), ); let (arrow, padding) = if arrow_fonts { (ARROW_SEPARATOR, Some(4)) } else { ("", None) }; let (text, _text_width) = stringify_text( &content, padding, &component_coordinates, &declaration, &colors, text_style, ); let mut stringified = component_coordinates .map(|c| c.to_string()) .unwrap_or_else(|| String::new()); stringified.push_str(&format!( "{}{}{}{} {} {}{}{}", RESET_STYLES, first_arrow_styles, arrow, text_style, text, last_arrow_styles, arrow, RESET_STYLES )); stringified.as_bytes().to_vec() } fn character_style(foreground: PaletteColor, background: PaletteColor) -> CharacterStyles { RESET_STYLES .foreground(Some(foreground.into())) .background(Some(background.into())) .bold(Some(AnsiCode::On)) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/output/mod.rs
zellij-server/src/output/mod.rs
use std::collections::VecDeque; use crate::panes::Row; use crate::panes::Selection; use crate::{ panes::sixel::SixelImageStore, panes::terminal_character::{AnsiCode, CharacterStyles}, panes::{LinkHandler, PaneId, TerminalCharacter, DEFAULT_STYLES, EMPTY_TERMINAL_CHARACTER}, ClientId, }; use std::cell::RefCell; use std::fmt::Write; use std::rc::Rc; use std::{ collections::{HashMap, HashSet}, str, }; use zellij_utils::data::{PaneContents, PaneRenderReport}; use zellij_utils::errors::prelude::*; use zellij_utils::pane_size::SizeInPixels; use zellij_utils::pane_size::{PaneGeom, Size}; fn vte_goto_instruction(x_coords: usize, y_coords: usize, vte_output: &mut String) -> Result<()> { write!( vte_output, "\u{1b}[{};{}H\u{1b}[m", y_coords + 1, // + 1 because VTE is 1 indexed x_coords + 1, ) .with_context(|| { format!( "failed to execute VTE instruction to go to ({}, {})", x_coords, y_coords ) }) } fn vte_hide_cursor_instruction(vte_output: &mut String) -> Result<()> { write!(vte_output, "\u{1b}[?25l").context("failed to execute VTE instruction to hide cursor") } fn adjust_styles_for_possible_selection( chunk_selection_and_colors: Vec<(Selection, AnsiCode, Option<AnsiCode>)>, character_styles: CharacterStyles, chunk_y: usize, chunk_width: usize, ) -> CharacterStyles { chunk_selection_and_colors .iter() .find(|(selection, _background_color, _foreground_color)| { selection.contains(chunk_y, chunk_width) }) .map(|(_selection, background_color, foreground_color)| { let mut character_styles = character_styles.background(Some(*background_color)); if let Some(foreground_color) = foreground_color { character_styles = character_styles.foreground(Some(*foreground_color)); } character_styles }) .unwrap_or(character_styles) } fn write_changed_styles( character_styles: &mut CharacterStyles, current_character_styles: CharacterStyles, chunk_changed_colors: Option<[Option<AnsiCode>; 256]>, link_handler: Option<&std::cell::Ref<LinkHandler>>, vte_output: &mut String, ) -> Result<()> { let err_context = "failed to format changed styles to VTE string"; if let Some(new_styles) = character_styles.update_and_return_diff(&current_character_styles, chunk_changed_colors) { if let Some(osc8_link) = link_handler.and_then(|l_h| l_h.output_osc8(new_styles.link_anchor)) { write!(vte_output, "{}{}", new_styles, osc8_link).context(err_context)?; } else { write!(vte_output, "{}", new_styles).context(err_context)?; } } Ok(()) } fn serialize_chunks_with_newlines( character_chunks: Vec<CharacterChunk>, _sixel_chunks: Option<&Vec<SixelImageChunk>>, // TODO: fix this sometime link_handler: Option<&mut Rc<RefCell<LinkHandler>>>, styled_underlines: bool, max_size: Option<Size>, ) -> Result<String> { let err_context = || "failed to serialize input chunks".to_string(); let mut vte_output = String::new(); let link_handler = link_handler.map(|l_h| l_h.borrow()); for character_chunk in character_chunks { // Skip chunks that are completely outside the size bounds if let Some(size) = max_size { if character_chunk.y >= size.rows { continue; // Chunk is below visible area } if character_chunk.x >= size.cols { continue; // Chunk starts outside visible area } } let chunk_changed_colors = character_chunk.changed_colors(); let mut character_styles = DEFAULT_STYLES.enable_styled_underlines(styled_underlines); vte_output.push_str("\n\r"); let mut chunk_width = character_chunk.x; for t_character in character_chunk.terminal_characters.iter() { // Stop rendering if the next character would exceed max_size.cols if let Some(size) = max_size { if chunk_width + t_character.width() > size.cols { break; // Stop rendering this chunk } } let current_character_styles = adjust_styles_for_possible_selection( character_chunk.selection_and_colors(), *t_character.styles, character_chunk.y, chunk_width, ); write_changed_styles( &mut character_styles, current_character_styles, chunk_changed_colors, link_handler.as_ref(), &mut vte_output, ) .with_context(err_context)?; chunk_width += t_character.width(); vte_output.push(t_character.character); } } Ok(vte_output) } fn serialize_chunks( character_chunks: Vec<CharacterChunk>, sixel_chunks: Option<&Vec<SixelImageChunk>>, link_handler: Option<&mut Rc<RefCell<LinkHandler>>>, sixel_image_store: Option<&mut SixelImageStore>, styled_underlines: bool, max_size: Option<Size>, ) -> Result<String> { let err_context = || "failed to serialize input chunks".to_string(); let mut vte_output = String::new(); let mut sixel_vte: Option<String> = None; let link_handler = link_handler.map(|l_h| l_h.borrow()); for character_chunk in character_chunks { // Skip chunks that are completely outside the size bounds if let Some(size) = max_size { if character_chunk.y >= size.rows { continue; // Chunk is below visible area } if character_chunk.x >= size.cols { continue; // Chunk starts outside visible area } } let chunk_changed_colors = character_chunk.changed_colors(); let mut character_styles = DEFAULT_STYLES.enable_styled_underlines(styled_underlines); vte_goto_instruction(character_chunk.x, character_chunk.y, &mut vte_output) .with_context(err_context)?; let mut chunk_width = character_chunk.x; for t_character in character_chunk.terminal_characters.iter() { // Stop rendering if the next character would exceed max_size.cols if let Some(size) = max_size { if chunk_width + t_character.width() > size.cols { break; // Stop rendering this chunk } } let current_character_styles = adjust_styles_for_possible_selection( character_chunk.selection_and_colors(), *t_character.styles, character_chunk.y, chunk_width, ); write_changed_styles( &mut character_styles, current_character_styles, chunk_changed_colors, link_handler.as_ref(), &mut vte_output, ) .with_context(err_context)?; chunk_width += t_character.width(); vte_output.push(t_character.character); } } if let Some(sixel_image_store) = sixel_image_store { if let Some(sixel_chunks) = sixel_chunks { for sixel_chunk in sixel_chunks { // Skip sixel chunks that are completely outside the size bounds if let Some(size) = max_size { if sixel_chunk.cell_y >= size.rows { continue; // Sixel chunk is below visible area } if sixel_chunk.cell_x >= size.cols { continue; // Sixel chunk starts outside visible area } } let serialized_sixel_image = sixel_image_store.serialize_image( sixel_chunk.sixel_image_id, sixel_chunk.sixel_image_pixel_x, sixel_chunk.sixel_image_pixel_y, sixel_chunk.sixel_image_pixel_width, sixel_chunk.sixel_image_pixel_height, ); if let Some(serialized_sixel_image) = serialized_sixel_image { let sixel_vte = sixel_vte.get_or_insert_with(String::new); vte_goto_instruction(sixel_chunk.cell_x, sixel_chunk.cell_y, sixel_vte) .with_context(err_context)?; sixel_vte.push_str(&serialized_sixel_image); } } } } if let Some(ref sixel_vte) = sixel_vte { // we do this at the end because of the implied z-index, // images should be above text unless the text was explicitly inserted after them (the // latter being a case we handle in our own internal state and not in the output) let save_cursor_position = "\u{1b}[s"; let restore_cursor_position = "\u{1b}[u"; vte_output.push_str(save_cursor_position); vte_output.push_str(sixel_vte); vte_output.push_str(restore_cursor_position); } Ok(vte_output) } type AbsoluteMiddleStart = usize; type AbsoluteMiddleEnd = usize; type PadLeftEndBy = usize; type PadRightStartBy = usize; fn adjust_middle_segment_for_wide_chars( middle_start: usize, middle_end: usize, terminal_characters: &[TerminalCharacter], ) -> Result<( AbsoluteMiddleStart, AbsoluteMiddleEnd, PadLeftEndBy, PadRightStartBy, )> { let err_context = || { format!( "failed to adjust middle segment (from {} to {}) for wide chars: '{:?}'", middle_start, middle_end, terminal_characters ) }; let mut absolute_middle_start_index = None; let mut absolute_middle_end_index = None; let mut current_x = 0; let mut pad_left_end_by = 0; let mut pad_right_start_by = 0; for (absolute_index, t_character) in terminal_characters.iter().enumerate() { current_x += t_character.width(); if current_x >= middle_start && absolute_middle_start_index.is_none() { if current_x > middle_start { pad_left_end_by = current_x - middle_start; absolute_middle_start_index = Some(absolute_index); } else { absolute_middle_start_index = Some(absolute_index + 1); } } if current_x >= middle_end && absolute_middle_end_index.is_none() { absolute_middle_end_index = Some(absolute_index + 1); if current_x > middle_end { pad_right_start_by = current_x - middle_end; } } } Ok(( absolute_middle_start_index.with_context(err_context)?, absolute_middle_end_index.with_context(err_context)?, pad_left_end_by, pad_right_start_by, )) } #[derive(Clone, Debug, Default)] pub struct Output { pre_vte_instructions: HashMap<ClientId, Vec<String>>, post_vte_instructions: HashMap<ClientId, Vec<String>>, client_character_chunks: HashMap<ClientId, Vec<CharacterChunk>>, sixel_chunks: HashMap<ClientId, Vec<SixelImageChunk>>, link_handler: Option<Rc<RefCell<LinkHandler>>>, sixel_image_store: Rc<RefCell<SixelImageStore>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, floating_panes_stack: Option<FloatingPanesStack>, styled_underlines: bool, pane_render_report: PaneRenderReport, cursor_coordinates: Option<(usize, usize)>, } impl Output { pub fn new( sixel_image_store: Rc<RefCell<SixelImageStore>>, character_cell_size: Rc<RefCell<Option<SizeInPixels>>>, styled_underlines: bool, ) -> Self { Output { sixel_image_store, character_cell_size, styled_underlines, ..Default::default() } } pub fn add_clients( &mut self, client_ids: &HashSet<ClientId>, link_handler: Rc<RefCell<LinkHandler>>, floating_panes_stack: Option<FloatingPanesStack>, ) { self.link_handler = Some(link_handler); self.floating_panes_stack = floating_panes_stack; for client_id in client_ids { self.client_character_chunks.insert(*client_id, vec![]); } } pub fn add_character_chunks_to_client( &mut self, client_id: ClientId, mut character_chunks: Vec<CharacterChunk>, z_index: Option<usize>, ) -> Result<()> { if let Some(client_character_chunks) = self.client_character_chunks.get_mut(&client_id) { if let Some(floating_panes_stack) = &self.floating_panes_stack { let mut visible_character_chunks = floating_panes_stack .visible_character_chunks(character_chunks, z_index) .with_context(|| { format!("failed to add character chunks for client {}", client_id) })?; client_character_chunks.append(&mut visible_character_chunks); } else { client_character_chunks.append(&mut character_chunks); } } Ok(()) } pub fn add_character_chunks_to_multiple_clients( &mut self, character_chunks: Vec<CharacterChunk>, client_ids: impl Iterator<Item = ClientId>, z_index: Option<usize>, ) -> Result<()> { for client_id in client_ids { self.add_character_chunks_to_client(client_id, character_chunks.clone(), z_index) .context("failed to add character chunks for multiple clients")?; // TODO: forgo clone by adding an all_clients thing? } Ok(()) } pub fn add_post_vte_instruction_to_multiple_clients( &mut self, client_ids: impl Iterator<Item = ClientId>, vte_instruction: &str, ) { for client_id in client_ids { let entry = self .post_vte_instructions .entry(client_id) .or_insert_with(Vec::new); entry.push(String::from(vte_instruction)); } } pub fn add_pre_vte_instruction_to_multiple_clients( &mut self, client_ids: impl Iterator<Item = ClientId>, vte_instruction: &str, ) { for client_id in client_ids { let entry = self .pre_vte_instructions .entry(client_id) .or_insert_with(Vec::new); entry.push(String::from(vte_instruction)); } } pub fn add_post_vte_instruction_to_client( &mut self, client_id: ClientId, vte_instruction: &str, ) { let entry = self .post_vte_instructions .entry(client_id) .or_insert_with(Vec::new); entry.push(String::from(vte_instruction)); } pub fn add_pre_vte_instruction_to_client( &mut self, client_id: ClientId, vte_instruction: &str, ) { let entry = self .pre_vte_instructions .entry(client_id) .or_insert_with(Vec::new); entry.push(String::from(vte_instruction)); } pub fn add_sixel_image_chunks_to_client( &mut self, client_id: ClientId, sixel_image_chunks: Vec<SixelImageChunk>, z_index: Option<usize>, ) { if let Some(character_cell_size) = *self.character_cell_size.borrow() { let mut sixel_chunks = if let Some(floating_panes_stack) = &self.floating_panes_stack { floating_panes_stack.visible_sixel_image_chunks( sixel_image_chunks, z_index, &character_cell_size, ) } else { sixel_image_chunks }; let entry = self.sixel_chunks.entry(client_id).or_insert_with(Vec::new); entry.append(&mut sixel_chunks); } } pub fn add_sixel_image_chunks_to_multiple_clients( &mut self, sixel_image_chunks: Vec<SixelImageChunk>, client_ids: impl Iterator<Item = ClientId>, z_index: Option<usize>, ) { if let Some(character_cell_size) = *self.character_cell_size.borrow() { let sixel_chunks = if let Some(floating_panes_stack) = &self.floating_panes_stack { floating_panes_stack.visible_sixel_image_chunks( sixel_image_chunks, z_index, &character_cell_size, ) } else { sixel_image_chunks }; for client_id in client_ids { let entry = self.sixel_chunks.entry(client_id).or_insert_with(Vec::new); entry.append(&mut sixel_chunks.clone()); } } } pub fn serialize(&mut self) -> Result<HashMap<ClientId, String>> { let err_context = || "failed to serialize output to clients".to_string(); let mut serialized_render_instructions = HashMap::new(); for (client_id, client_character_chunks) in self.client_character_chunks.drain() { let mut client_serialized_render_instructions = String::new(); // append pre-vte instructions for this client if let Some(pre_vte_instructions_for_client) = self.pre_vte_instructions.remove(&client_id) { for vte_instruction in pre_vte_instructions_for_client { client_serialized_render_instructions.push_str(&vte_instruction); } } // append the actual vte client_serialized_render_instructions.push_str( &serialize_chunks( client_character_chunks, self.sixel_chunks.get(&client_id), self.link_handler.as_mut(), Some(&mut self.sixel_image_store.borrow_mut()), self.styled_underlines, None, // No size constraints for regular rendering ) .with_context(err_context)?, ); // TODO: less allocations? // append post-vte instructions for this client if let Some(post_vte_instructions_for_client) = self.post_vte_instructions.remove(&client_id) { for vte_instruction in post_vte_instructions_for_client { client_serialized_render_instructions.push_str(&vte_instruction); } } serialized_render_instructions.insert(client_id, client_serialized_render_instructions); } Ok(serialized_render_instructions) } pub fn serialize_with_size( &mut self, max_size: Option<Size>, content_size: Option<Size>, ) -> Result<HashMap<ClientId, String>> { let err_context = || "failed to serialize output to clients with size constraints".to_string(); let mut serialized_render_instructions = HashMap::new(); for (client_id, client_character_chunks) in self.client_character_chunks.drain() { let mut client_serialized_render_instructions = String::new(); // append pre-vte instructions for this client if let Some(pre_vte_instructions_for_client) = self.pre_vte_instructions.remove(&client_id) { for vte_instruction in pre_vte_instructions_for_client { client_serialized_render_instructions.push_str(&vte_instruction); } } // Add padding instructions if max_size is larger than content_size if let (Some(max_size), Some(content_size)) = (max_size, content_size) { if max_size.rows > content_size.rows || max_size.cols > content_size.cols { // Clear each line from the end of rendered content to the end of the watcher's line for y in 0..content_size.rows { let padding_instruction = format!( "\u{1b}[{};{}H\u{1b}[m\u{1b}[K", y + 1, content_size.cols + 1 ); client_serialized_render_instructions.push_str(&padding_instruction); } // Clear all content below the last rendered line let clear_below_instruction = format!("\u{1b}[{};{}H\u{1b}[m\u{1b}[J", content_size.rows + 1, 1); client_serialized_render_instructions.push_str(&clear_below_instruction); } } // append the actual vte with size constraints client_serialized_render_instructions.push_str( &serialize_chunks( client_character_chunks, self.sixel_chunks.get(&client_id), self.link_handler.as_mut(), Some(&mut self.sixel_image_store.borrow_mut()), self.styled_underlines, max_size, ) .with_context(err_context)?, ); // append post-vte instructions for this client if let Some(post_vte_instructions_for_client) = self.post_vte_instructions.remove(&client_id) { for vte_instruction in post_vte_instructions_for_client { client_serialized_render_instructions.push_str(&vte_instruction); } } // Check if cursor was cropped and hide it if necessary if let (Some(max_size), Some((cursor_x, cursor_y))) = (max_size, self.cursor_coordinates) { let cursor_was_cropped = cursor_y >= max_size.rows || cursor_x >= max_size.cols; if cursor_was_cropped { vte_hide_cursor_instruction(&mut client_serialized_render_instructions) .with_context(err_context)?; } } serialized_render_instructions.insert(client_id, client_serialized_render_instructions); } Ok(serialized_render_instructions) } pub fn is_dirty(&self) -> bool { !self.pre_vte_instructions.is_empty() || !self.post_vte_instructions.is_empty() || self.client_character_chunks.values().any(|c| !c.is_empty()) || self.sixel_chunks.values().any(|c| !c.is_empty()) } pub fn has_rendered_assets(&self) -> bool { // pre_vte and post_vte are not considered rendered assets as they should not be visible self.client_character_chunks.values().any(|c| !c.is_empty()) || self.sixel_chunks.values().any(|c| !c.is_empty()) } pub fn cursor_is_visible(&mut self, cursor_x: usize, cursor_y: usize) -> bool { self.cursor_coordinates = Some((cursor_x, cursor_y)); self.floating_panes_stack .as_ref() .map(|s| s.cursor_is_visible(cursor_x, cursor_y)) .unwrap_or(true) } pub fn add_pane_contents( &mut self, client_ids: &[ClientId], pane_id: PaneId, pane_contents: PaneContents, ) { self.pane_render_report .add_pane_contents(client_ids, pane_id.into(), pane_contents); } pub fn drain_pane_render_report(&mut self) -> PaneRenderReport { let empty_pane_render_report = PaneRenderReport::default(); std::mem::replace(&mut self.pane_render_report, empty_pane_render_report) } } // this struct represents the geometry of a group of floating panes // we use it to filter out CharacterChunks who are behind these geometries // and so would not be visible. If a chunk is partially covered, it is adjusted // to include only the non-covered parts #[derive(Debug, Clone, Default)] pub struct FloatingPanesStack { pub layers: Vec<PaneGeom>, } impl FloatingPanesStack { pub fn visible_character_chunks( &self, mut character_chunks: Vec<CharacterChunk>, z_index: Option<usize>, ) -> Result<Vec<CharacterChunk>> { let err_context = || { format!( "failed to determine visible character chunks at z-index {:?}", z_index ) }; let z_index = z_index.unwrap_or(0); let mut chunks_to_check: Vec<CharacterChunk> = character_chunks.drain(..).collect(); let mut visible_chunks = vec![]; 'chunk_loop: loop { match chunks_to_check.pop() { Some(mut c_chunk) => { let panes_to_check = self.layers.iter().skip(z_index); for pane_geom in panes_to_check { let new_chunk_to_check = self .remove_covered_parts(pane_geom, &mut c_chunk) .with_context(err_context)?; if let Some(new_chunk_to_check) = new_chunk_to_check { // this happens when the pane covers the middle of the chunk, and so we // end up with an extra chunk we need to check (eg. against panes above // this one) chunks_to_check.push(new_chunk_to_check); } if c_chunk.terminal_characters.is_empty() { continue 'chunk_loop; } } visible_chunks.push(c_chunk); }, None => { break 'chunk_loop; }, } } Ok(visible_chunks) } pub fn visible_sixel_image_chunks( &self, mut sixel_image_chunks: Vec<SixelImageChunk>, z_index: Option<usize>, character_cell_size: &SizeInPixels, ) -> Vec<SixelImageChunk> { let z_index = z_index.unwrap_or(0); let mut chunks_to_check: Vec<SixelImageChunk> = sixel_image_chunks.drain(..).collect(); let panes_to_check = self.layers.iter().skip(z_index); for pane_geom in panes_to_check { let chunks_to_check_against_this_pane: Vec<SixelImageChunk> = chunks_to_check.drain(..).collect(); for s_chunk in chunks_to_check_against_this_pane { let mut uncovered_chunks = self.remove_covered_sixel_parts(pane_geom, &s_chunk, character_cell_size); chunks_to_check.append(&mut uncovered_chunks); } } chunks_to_check } fn remove_covered_parts( &self, pane_geom: &PaneGeom, c_chunk: &mut CharacterChunk, ) -> Result<Option<CharacterChunk>> { let err_context = || { format!( "failed to remove covered parts from floating panes: {:#?}", self ) }; let pane_top_edge = pane_geom.y; let pane_left_edge = pane_geom.x; let pane_bottom_edge = pane_geom.y + pane_geom.rows.as_usize().saturating_sub(1); let pane_right_edge = pane_geom.x + pane_geom.cols.as_usize().saturating_sub(1); let c_chunk_left_side = c_chunk.x; let c_chunk_right_side = c_chunk.x + (c_chunk.width()).saturating_sub(1); if pane_top_edge <= c_chunk.y && pane_bottom_edge >= c_chunk.y { if pane_left_edge <= c_chunk_left_side && pane_right_edge >= c_chunk_right_side { // pane covers chunk completely drop(c_chunk.terminal_characters.drain(..)); return Ok(None); } else if pane_right_edge > c_chunk_left_side && pane_right_edge < c_chunk_right_side && pane_left_edge <= c_chunk_left_side { // pane covers chunk partially to the left let covered_part = c_chunk.drain_by_width(pane_right_edge + 1 - c_chunk_left_side); drop(covered_part); c_chunk.x = pane_right_edge + 1; return Ok(None); } else if pane_left_edge > c_chunk_left_side && pane_left_edge < c_chunk_right_side && pane_right_edge >= c_chunk_right_side { // pane covers chunk partially to the right c_chunk.retain_by_width(pane_left_edge - c_chunk_left_side); return Ok(None); } else if pane_left_edge >= c_chunk_left_side && pane_right_edge <= c_chunk_right_side { // pane covers chunk middle let (left_chunk_characters, right_chunk_characters) = c_chunk .cut_middle_out( pane_left_edge - c_chunk_left_side, (pane_right_edge + 1) - c_chunk_left_side, ) .with_context(err_context)?; let left_chunk_x = c_chunk_left_side; let right_chunk_x = pane_right_edge + 1; let mut left_chunk = CharacterChunk::new(left_chunk_characters, left_chunk_x, c_chunk.y); if !c_chunk.selection_and_colors.is_empty() { left_chunk.selection_and_colors = c_chunk.selection_and_colors.clone(); } c_chunk.x = right_chunk_x; c_chunk.terminal_characters = right_chunk_characters; return Ok(Some(left_chunk)); } }; Ok(None) } fn remove_covered_sixel_parts( &self, pane_geom: &PaneGeom, s_chunk: &SixelImageChunk, character_cell_size: &SizeInPixels, ) -> Vec<SixelImageChunk> { // round these up to the nearest cell edge let rounded_sixel_image_pixel_height = if s_chunk.sixel_image_pixel_height % character_cell_size.height > 0 { let modulus = s_chunk.sixel_image_pixel_height % character_cell_size.height; s_chunk.sixel_image_pixel_height + (character_cell_size.height - modulus) } else { s_chunk.sixel_image_pixel_height }; let rounded_sixel_image_pixel_width = if s_chunk.sixel_image_pixel_width % character_cell_size.width > 0 { let modulus = s_chunk.sixel_image_pixel_width % character_cell_size.width; s_chunk.sixel_image_pixel_width + (character_cell_size.width - modulus) } else { s_chunk.sixel_image_pixel_width }; let pane_top_edge = pane_geom.y * character_cell_size.height; let pane_left_edge = pane_geom.x * character_cell_size.width; let pane_bottom_edge = (pane_geom.y + pane_geom.rows.as_usize().saturating_sub(1)) * character_cell_size.height; let pane_right_edge = (pane_geom.x + pane_geom.cols.as_usize().saturating_sub(1)) * character_cell_size.width; let s_chunk_top_edge = s_chunk.cell_y * character_cell_size.height; let s_chunk_bottom_edge = s_chunk_top_edge + rounded_sixel_image_pixel_height; let s_chunk_left_edge = s_chunk.cell_x * character_cell_size.width; let s_chunk_right_edge = s_chunk_left_edge + rounded_sixel_image_pixel_width; let mut uncovered_chunks = vec![]; let pane_covers_chunk_completely = pane_top_edge <= s_chunk_top_edge && pane_bottom_edge >= s_chunk_bottom_edge && pane_left_edge <= s_chunk_left_edge && pane_right_edge >= s_chunk_right_edge; let pane_intersects_with_chunk_vertically = (pane_left_edge >= s_chunk_left_edge && pane_left_edge <= s_chunk_right_edge) || (pane_right_edge >= s_chunk_left_edge && pane_right_edge <= s_chunk_right_edge) || (pane_left_edge <= s_chunk_left_edge && pane_right_edge >= s_chunk_right_edge); let pane_intersects_with_chunk_horizontally = (pane_top_edge >= s_chunk_top_edge && pane_top_edge <= s_chunk_bottom_edge) || (pane_bottom_edge >= s_chunk_top_edge && pane_bottom_edge <= s_chunk_bottom_edge) || (pane_top_edge <= s_chunk_top_edge && pane_bottom_edge >= s_chunk_bottom_edge); if pane_covers_chunk_completely { return uncovered_chunks; } if pane_top_edge >= s_chunk_top_edge && pane_top_edge <= s_chunk_bottom_edge && pane_intersects_with_chunk_vertically { // pane covers image bottom let top_image_chunk = SixelImageChunk { cell_x: s_chunk.cell_x,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/output/unit/mod.rs
zellij-server/src/output/unit/mod.rs
mod output_tests;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/output/unit/output_tests.rs
zellij-server/src/output/unit/output_tests.rs
use super::super::{CharacterChunk, FloatingPanesStack, Output, OutputBuffer, SixelImageChunk}; use crate::panes::sixel::SixelImageStore; use crate::panes::{LinkHandler, Row, TerminalCharacter}; use crate::ClientId; use std::cell::RefCell; use std::collections::{HashSet, VecDeque}; use std::rc::Rc; use zellij_utils::pane_size::{Dimension, PaneGeom, Size, SizeInPixels}; /// Helper to create a simple Output instance for testing fn create_test_output() -> Output { let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default())); let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels { height: 20, width: 10, }))); let styled_underlines = true; Output::new(sixel_image_store, character_cell_size, styled_underlines) } /// Helper to create a simple CharacterChunk with text fn create_character_chunk_from_str(text: &str, x: usize, y: usize) -> CharacterChunk { let terminal_chars: Vec<TerminalCharacter> = text.chars().map(|c| TerminalCharacter::new(c)).collect(); CharacterChunk::new(terminal_chars, x, y) } /// Helper to create test clients fn create_test_clients(count: usize) -> HashSet<ClientId> { (1..=count).map(|i| i as ClientId).collect() } /// Helper to create PaneGeom for FloatingPanesStack tests fn create_pane_geom(x: usize, y: usize, cols: usize, rows: usize) -> PaneGeom { PaneGeom { x, y, cols: Dimension::fixed(cols), rows: Dimension::fixed(rows), stacked: None, is_pinned: false, logical_position: None, } } #[test] fn test_output_new() { let output = create_test_output(); // Verify default state of all fields assert!(!output.is_dirty(), "New output should not be dirty"); assert!( !output.has_rendered_assets(), "New output should not have rendered assets" ); } #[test] fn test_add_clients() { let mut output = create_test_output(); let client_ids = create_test_clients(3); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); // Verify that client_character_chunks has entries for all clients assert!(!output.is_dirty(), "Should not be dirty until chunks added"); } #[test] fn test_is_dirty_with_empty_output() { let output = create_test_output(); assert!(!output.is_dirty(), "Empty output should not be dirty"); } #[test] fn test_is_dirty_with_character_chunks() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk = create_character_chunk_from_str("Hi", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); assert!( output.is_dirty(), "Output should be dirty after adding character chunks" ); } #[test] fn test_is_dirty_with_pre_vte_instructions() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); output.add_pre_vte_instruction_to_client(1, "\u{1b}[?1049h"); assert!( output.is_dirty(), "Output should be dirty after adding pre VTE instructions" ); } #[test] fn test_is_dirty_with_post_vte_instructions() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); output.add_post_vte_instruction_to_client(1, "\u{1b}[?25h"); assert!( output.is_dirty(), "Output should be dirty after adding post VTE instructions" ); } #[test] fn test_is_dirty_with_sixel_chunks() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let sixel_chunk = SixelImageChunk { cell_x: 0, cell_y: 0, sixel_image_pixel_x: 0, sixel_image_pixel_y: 0, sixel_image_pixel_width: 100, sixel_image_pixel_height: 100, sixel_image_id: 1, }; output.add_sixel_image_chunks_to_client(1, vec![sixel_chunk], None); assert!( output.is_dirty(), "Output should be dirty after adding sixel chunks" ); } #[test] fn test_has_rendered_assets_empty() { let output = create_test_output(); assert!( !output.has_rendered_assets(), "Empty output should not have rendered assets" ); } #[test] fn test_has_rendered_assets_only_vte_instructions() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); output.add_pre_vte_instruction_to_client(1, "\u{1b}[?25l"); output.add_post_vte_instruction_to_client(1, "\u{1b}[?25h"); assert!( !output.has_rendered_assets(), "VTE instructions alone should not count as rendered assets" ); } #[test] fn test_has_rendered_assets_with_character_chunks() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk = create_character_chunk_from_str("Hello", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); assert!( output.has_rendered_assets(), "Character chunks should count as rendered assets" ); } #[test] fn test_has_rendered_assets_with_sixel_chunks() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let sixel_chunk = SixelImageChunk { cell_x: 0, cell_y: 0, sixel_image_pixel_x: 0, sixel_image_pixel_y: 0, sixel_image_pixel_width: 100, sixel_image_pixel_height: 100, sixel_image_id: 1, }; output.add_sixel_image_chunks_to_client(1, vec![sixel_chunk], None); assert!( output.has_rendered_assets(), "Sixel chunks should count as rendered assets" ); } #[test] fn test_serialize_empty() { let mut output = create_test_output(); let result = output.serialize().unwrap(); assert!( result.is_empty(), "Serializing empty output should return empty HashMap" ); } #[test] fn test_serialize_single_client_simple_text() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk = create_character_chunk_from_str("Hello", 5, 10); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); let result = output.serialize().unwrap(); assert_eq!(result.len(), 1, "Should have one client in result"); let client_output = result.get(&1).unwrap(); // Verify contains goto instruction (y+1, x+1 for 1-indexed VTE) assert!( client_output.contains("\u{1b}[11;6H"), "Should contain goto instruction for position (5, 10)" ); // Verify contains reset styles assert!( client_output.contains("\u{1b}[m"), "Should contain reset styles" ); // Verify contains the text assert!(client_output.contains("Hello"), "Should contain the text"); } #[test] fn test_serialize_multiple_clients() { let mut output = create_test_output(); let client_ids = create_test_clients(2); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk1 = create_character_chunk_from_str("Hello", 0, 0); output .add_character_chunks_to_client(1, vec![chunk1], None) .unwrap(); let chunk2 = create_character_chunk_from_str("World", 10, 10); output .add_character_chunks_to_client(2, vec![chunk2], None) .unwrap(); let result = output.serialize().unwrap(); assert_eq!(result.len(), 2, "Should have two clients in result"); let client1_output = result.get(&1).unwrap(); assert!( client1_output.contains("Hello"), "Client 1 should contain 'Hello'" ); let client2_output = result.get(&2).unwrap(); assert!( client2_output.contains("World"), "Client 2 should contain 'World'" ); } #[test] fn test_serialize_with_pre_and_post_vte_instructions() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); output.add_pre_vte_instruction_to_client(1, "\u{1b}[?1049h"); let chunk = create_character_chunk_from_str("Test", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); output.add_post_vte_instruction_to_client(1, "\u{1b}[?25h"); let result = output.serialize().unwrap(); let client_output = result.get(&1).unwrap(); // Verify correct ordering let pre_vte_pos = client_output.find("\u{1b}[?1049h").unwrap(); let text_pos = client_output.find("Test").unwrap(); let post_vte_pos = client_output.find("\u{1b}[?25h").unwrap(); assert!( pre_vte_pos < text_pos && text_pos < post_vte_pos, "Instructions should be in correct order: pre, content, post" ); } #[test] fn test_serialize_drains_state() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk = create_character_chunk_from_str("Hello", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); assert!(output.is_dirty(), "Output should be dirty before serialize"); let result1 = output.serialize().unwrap(); assert_eq!(result1.len(), 1, "First serialize should return data"); assert!( !output.is_dirty(), "Output should not be dirty after serialize" ); let result2 = output.serialize().unwrap(); assert!( result2.is_empty(), "Second serialize should return empty HashMap" ); } #[test] fn test_serialize_with_size_no_constraints() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk = create_character_chunk_from_str("Hello", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); let result = output.serialize_with_size(None, None).unwrap(); assert_eq!(result.len(), 1, "Should have one client in result"); let client_output = result.get(&1).unwrap(); assert!(client_output.contains("Hello"), "Should contain the text"); } #[test] fn test_serialize_with_size_crops_chunks_below_visible_area() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let max_size = Some(Size { rows: 10, cols: 80 }); // Add chunk below visible area (should be cropped) let chunk_below = create_character_chunk_from_str("Hidden", 0, 15); output .add_character_chunks_to_client(1, vec![chunk_below], None) .unwrap(); // Add chunk within visible area (should be included) let chunk_visible = create_character_chunk_from_str("Visible", 0, 5); output .add_character_chunks_to_client(1, vec![chunk_visible], None) .unwrap(); let result = output.serialize_with_size(max_size, None).unwrap(); let client_output = result.get(&1).unwrap(); assert!( client_output.contains("Visible"), "Should contain visible chunk" ); assert!( !client_output.contains("Hidden"), "Should not contain chunk below visible area" ); } #[test] fn test_serialize_with_size_crops_chunks_outside_cols() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let max_size = Some(Size { rows: 10, cols: 20 }); // Add chunk outside visible columns (should be cropped) let chunk_outside = create_character_chunk_from_str("Hidden", 25, 5); output .add_character_chunks_to_client(1, vec![chunk_outside], None) .unwrap(); // Add chunk within visible area let chunk_visible = create_character_chunk_from_str("Visible", 5, 5); output .add_character_chunks_to_client(1, vec![chunk_visible], None) .unwrap(); let result = output.serialize_with_size(max_size, None).unwrap(); let client_output = result.get(&1).unwrap(); assert!( client_output.contains("Visible"), "Should contain visible chunk" ); assert!( !client_output.contains("Hidden"), "Should not contain chunk outside visible columns" ); } #[test] fn test_serialize_with_size_crops_characters_within_chunk() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let max_size = Some(Size { rows: 10, cols: 20 }); // Add chunk that starts at x=15 and would extend to x=25 (10 chars) let chunk = create_character_chunk_from_str("1234567890", 15, 5); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); let result = output.serialize_with_size(max_size, None).unwrap(); let client_output = result.get(&1).unwrap(); // Should only render first 5 characters (cols 15-19) assert!( client_output.contains("12345"), "Should contain first 5 characters" ); assert!( !client_output.contains("67890"), "Should not contain characters beyond max_size.cols" ); } #[test] fn test_serialize_with_size_adds_padding_instructions() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let max_size = Some(Size { rows: 30, cols: 100, }); let content_size = Some(Size { rows: 20, cols: 80 }); let chunk = create_character_chunk_from_str("Test", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); let result = output.serialize_with_size(max_size, content_size).unwrap(); let client_output = result.get(&1).unwrap(); // Verify padding/clearing instructions are present // Should contain clear line instructions: \u{1b}[y;xH\u{1b}[m\u{1b}[K assert!( client_output.contains("\u{1b}[K"), "Should contain clear line instructions" ); // Should contain clear below instruction: \u{1b}[21;1H\u{1b}[m\u{1b}[J assert!( client_output.contains("\u{1b}[21;1H\u{1b}[m\u{1b}[J"), "Should contain clear below instruction at line 21" ); } #[test] fn test_serialize_with_size_hides_cursor_when_cropped() { let mut output = create_test_output(); let client_ids = create_test_clients(1); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let max_size = Some(Size { rows: 10, cols: 20 }); // Set cursor outside max_size output.cursor_is_visible(25, 5); let chunk = create_character_chunk_from_str("Test", 0, 0); output .add_character_chunks_to_client(1, vec![chunk], None) .unwrap(); let result = output.serialize_with_size(max_size, None).unwrap(); let client_output = result.get(&1).unwrap(); // Verify hide cursor instruction is added assert!( client_output.contains("\u{1b}[?25l"), "Should contain hide cursor instruction when cursor is cropped" ); } #[test] fn test_add_character_chunks_to_multiple_clients() { let mut output = create_test_output(); let client_ids = create_test_clients(3); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let chunk = create_character_chunk_from_str("Test", 0, 0); output .add_character_chunks_to_multiple_clients(vec![chunk], client_ids.iter().copied(), None) .unwrap(); let result = output.serialize().unwrap(); assert_eq!(result.len(), 3, "Should have three clients in result"); for client_id in 1..=3 { let client_output = result.get(&client_id).unwrap(); assert!( client_output.contains("Test"), "Client {} should contain the text", client_id ); } } #[test] fn test_add_sixel_image_chunks_to_multiple_clients() { let mut output = create_test_output(); let client_ids = create_test_clients(2); let link_handler = Rc::new(RefCell::new(LinkHandler::new())); output.add_clients(&client_ids, link_handler, None); let sixel_chunk = SixelImageChunk { cell_x: 0, cell_y: 0, sixel_image_pixel_x: 0, sixel_image_pixel_y: 0, sixel_image_pixel_width: 100, sixel_image_pixel_height: 100, sixel_image_id: 1, }; output.add_sixel_image_chunks_to_multiple_clients( vec![sixel_chunk], client_ids.iter().copied(), None, ); assert!( output.has_rendered_assets(), "Output should have rendered assets" ); } #[test] fn test_character_chunk_new() { let terminal_chars: Vec<TerminalCharacter> = vec![TerminalCharacter::new('A')]; let chunk = CharacterChunk::new(terminal_chars, 5, 10); assert_eq!(chunk.x, 5, "x should be set correctly"); assert_eq!(chunk.y, 10, "y should be set correctly"); assert_eq!( chunk.terminal_characters.len(), 1, "Should have one character" ); } #[test] fn test_character_chunk_width() { let chunk = create_character_chunk_from_str("Hello", 0, 0); assert_eq!(chunk.width(), 5, "Width should be 5 for 'Hello'"); // Test with wide characters let terminal_chars: Vec<TerminalCharacter> = vec![ TerminalCharacter::new('a'), TerminalCharacter::new('中'), TerminalCharacter::new('b'), ]; let chunk_wide = CharacterChunk::new(terminal_chars, 0, 0); assert_eq!( chunk_wide.width(), 4, "Width should be 4 (1 + 2 + 1) for mixed characters" ); } #[test] fn test_character_chunk_drain_by_width() { let mut chunk = create_character_chunk_from_str("Hello World", 0, 0); assert_eq!(chunk.width(), 11, "Initial width should be 11"); // Drain first 5 characters let drained: Vec<TerminalCharacter> = chunk.drain_by_width(5).collect(); assert_eq!(drained.len(), 5, "Should drain 5 characters"); assert_eq!( chunk.terminal_characters.len(), 6, "Should have 6 characters remaining" ); let drained_text: String = drained.iter().map(|c| c.character).collect(); assert_eq!(drained_text, "Hello", "Drained part should be 'Hello'"); let remaining_text: String = chunk .terminal_characters .iter() .map(|c| c.character) .collect(); assert_eq!( remaining_text, " World", "Remaining part should be ' World'" ); } #[test] fn test_character_chunk_drain_by_width_with_wide_chars() { let terminal_chars: Vec<TerminalCharacter> = vec![ TerminalCharacter::new('a'), TerminalCharacter::new('中'), TerminalCharacter::new('b'), ]; let mut chunk = CharacterChunk::new(terminal_chars, 0, 0); // Drain 2 characters - this cuts in the middle of wide char let drained: Vec<TerminalCharacter> = chunk.drain_by_width(2).collect(); // Should have padding with EMPTY_TERMINAL_CHARACTER assert!( drained.len() >= 2, "Drained part should have at least 2 characters" ); } #[test] fn test_character_chunk_retain_by_width() { let mut chunk = create_character_chunk_from_str("Hello World", 0, 0); // Retain only first 5 characters chunk.retain_by_width(5); assert_eq!( chunk.terminal_characters.len(), 5, "Should have 5 characters" ); let text: String = chunk .terminal_characters .iter() .map(|c| c.character) .collect(); assert_eq!(text, "Hello", "Should retain 'Hello'"); } #[test] fn test_character_chunk_cut_middle_out() { let mut chunk = create_character_chunk_from_str("Hello World", 0, 0); // Cut middle (characters 5-8) let (left, right) = chunk.cut_middle_out(5, 8).unwrap(); let left_text: String = left.iter().map(|c| c.character).collect(); assert_eq!(left_text, "Hello", "Left chunk should be 'Hello'"); let right_text: String = right.iter().map(|c| c.character).collect(); assert_eq!(right_text, "rld", "Right chunk should be 'rld'"); } #[test] fn test_visible_character_chunks_no_panes() { let stack = FloatingPanesStack { layers: vec![] }; let chunks = vec![create_character_chunk_from_str("Test", 0, 0)]; let visible = stack.visible_character_chunks(chunks, None).unwrap(); assert_eq!(visible.len(), 1, "All chunks should be visible"); } #[test] fn test_visible_character_chunks_completely_covered() { let pane_geom = create_pane_geom(0, 0, 10, 10); let stack = FloatingPanesStack { layers: vec![pane_geom], }; // Chunk completely within pane bounds let chunks = vec![create_character_chunk_from_str("Test", 5, 5)]; let visible = stack.visible_character_chunks(chunks, Some(0)).unwrap(); assert_eq!( visible.len(), 0, "Completely covered chunk should not be visible" ); } #[test] fn test_visible_character_chunks_partially_covered_left() { let pane_geom = create_pane_geom(0, 5, 10, 1); let stack = FloatingPanesStack { layers: vec![pane_geom], }; // Chunk that spans x=5-15, pane covers x=0-9 let chunks = vec![create_character_chunk_from_str("HelloWorld", 5, 5)]; let visible = stack.visible_character_chunks(chunks, Some(0)).unwrap(); // Should retain the right part assert!(visible.len() > 0, "Should have visible chunks"); if !visible.is_empty() { assert!( visible[0].x >= 10, "Visible chunk should start after pane edge" ); } } #[test] fn test_visible_character_chunks_partially_covered_right() { let pane_geom = create_pane_geom(10, 5, 10, 1); let stack = FloatingPanesStack { layers: vec![pane_geom], }; // Chunk that spans x=5-15, pane covers x=10-19 let chunks = vec![create_character_chunk_from_str("HelloWorld", 5, 5)]; let visible = stack.visible_character_chunks(chunks, Some(0)).unwrap(); // Should retain the left part assert!(visible.len() > 0, "Should have visible chunks"); if !visible.is_empty() { assert_eq!(visible[0].x, 5, "Visible chunk should start at original x"); assert!( visible[0].width() < 10, "Visible chunk should be shorter than original" ); } } #[test] fn test_visible_character_chunks_middle_covered() { let pane_geom = create_pane_geom(5, 5, 3, 1); let stack = FloatingPanesStack { layers: vec![pane_geom], }; // Chunk spans x=0-10, pane covers x=5-7 let chunks = vec![create_character_chunk_from_str("0123456789", 0, 5)]; let visible = stack.visible_character_chunks(chunks, Some(0)).unwrap(); // Should return two chunks (left and right parts) assert!( visible.len() >= 1, "Should have at least one visible chunk when middle is covered" ); } #[test] fn test_cursor_is_visible_with_floating_panes() { let pane_geom = create_pane_geom(5, 5, 10, 10); let stack = FloatingPanesStack { layers: vec![pane_geom], }; // Cursor inside pane bounds assert!( !stack.cursor_is_visible(7, 7), "Cursor should not be visible when covered by pane" ); // Cursor outside pane bounds assert!( stack.cursor_is_visible(20, 20), "Cursor should be visible when not covered by pane" ); } #[test] fn test_output_buffer_update_line() { let mut buffer = OutputBuffer::default(); buffer.clear(); // Clear the initial "update all lines" state buffer.update_line(5); assert!( buffer.changed_lines.contains(&5), "Changed lines should contain line 5" ); } #[test] fn test_output_buffer_update_all_lines() { let mut buffer = OutputBuffer::default(); assert!( buffer.should_update_all_lines, "Should update all lines by default" ); buffer.clear(); assert!( !buffer.should_update_all_lines, "Should not update all lines after clear" ); buffer.update_all_lines(); assert!( buffer.should_update_all_lines, "Should update all lines after update_all_lines" ); } #[test] fn test_output_buffer_serialize() { let buffer = OutputBuffer::default(); // Create a simple viewport with Row data let mut columns = VecDeque::new(); columns.push_back(TerminalCharacter::new('A')); let row = Row::from_columns(columns); let viewport = vec![row]; let result = buffer.serialize(&viewport, None).unwrap(); // Should contain the character and newlines/carriage returns assert!(result.contains('A'), "Serialized output should contain 'A'"); assert!( result.contains("\n\r"), "Serialized output should contain newlines" ); } #[test] fn test_output_buffer_changed_chunks_in_viewport_when_all_dirty() { let buffer = OutputBuffer::default(); let mut columns = VecDeque::new(); columns.push_back(TerminalCharacter::new('A')); let row = Row::from_columns(columns); let viewport = vec![row]; let chunks = buffer.changed_chunks_in_viewport(&viewport, 10, 1, 0, 0); assert_eq!( chunks.len(), 1, "Should return all lines when should_update_all_lines is true" ); } #[test] fn test_output_buffer_changed_chunks_in_viewport_partial() { let mut buffer = OutputBuffer::default(); buffer.clear(); // Mark only specific lines as changed buffer.update_line(2); buffer.update_line(5); buffer.update_line(7); let rows: Vec<Row> = (0..10) .map(|_| { let mut columns = VecDeque::new(); columns.push_back(TerminalCharacter::new('A')); Row::from_columns(columns) }) .collect(); let chunks = buffer.changed_chunks_in_viewport(&rows, 10, 10, 0, 0); assert_eq!(chunks.len(), 3, "Should return only changed lines"); assert_eq!(chunks[0].y, 2, "First chunk should be at line 2"); assert_eq!(chunks[1].y, 5, "Second chunk should be at line 5"); assert_eq!(chunks[2].y, 7, "Third chunk should be at line 7"); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/share/src/main_screen.rs
default-plugins/share/src/main_screen.rs
use super::CoordinatesInLine; use crate::ui_components::{ hovering_on_line, render_text_with_underline, CurrentSessionSection, Usage, WebServerStatusSection, }; use zellij_tile::prelude::*; use std::collections::HashMap; use url::Url; pub struct MainScreenState { pub currently_hovering_over_link: bool, pub currently_hovering_over_unencrypted: bool, pub clickable_urls: HashMap<CoordinatesInLine, String>, } pub struct MainScreen<'a> { token_list_is_empty: bool, web_server_started: bool, web_server_error: &'a Option<String>, web_server_different_version_error: &'a Option<String>, web_server_base_url: &'a String, web_server_ip: Option<std::net::IpAddr>, web_server_port: Option<u16>, session_name: &'a Option<String>, web_sharing: WebSharing, hover_coordinates: Option<(usize, usize)>, info: &'a Option<String>, link_executable: &'a Option<&'a str>, } impl<'a> MainScreen<'a> { const TITLE_TEXT: &'static str = "Share Session Locally in the Browser"; const WARNING_TEXT: &'static str = "[*] Connection unencrypted. Consider using an SSL certificate."; const MORE_INFO_TEXT: &'static str = "More info: "; const SSL_URL: &'static str = "https://zellij.dev/documentation/web-client.html#https"; const HELP_TEXT_WITH_CLICK: &'static str = "Help: Click or Shift-Click to open in browser"; const HELP_TEXT_SHIFT_ONLY: &'static str = "Help: Shift-Click to open in browser"; pub fn new( token_list_is_empty: bool, web_server_started: bool, web_server_error: &'a Option<String>, web_server_different_version_error: &'a Option<String>, web_server_base_url: &'a String, web_server_ip: Option<std::net::IpAddr>, web_server_port: Option<u16>, session_name: &'a Option<String>, web_sharing: WebSharing, hover_coordinates: Option<(usize, usize)>, info: &'a Option<String>, link_executable: &'a Option<&'a str>, ) -> Self { Self { token_list_is_empty, web_server_started, web_server_error, web_server_different_version_error, web_server_base_url, web_server_ip, web_server_port, session_name, web_sharing, hover_coordinates, info, link_executable, } } pub fn render(self, rows: usize, cols: usize) -> MainScreenState { let mut state = MainScreenState { currently_hovering_over_link: false, currently_hovering_over_unencrypted: false, clickable_urls: HashMap::new(), }; let layout = self.calculate_layout(rows, cols); self.render_content(&layout, &mut state); state } fn calculate_layout<'b>(&'b self, rows: usize, cols: usize) -> Layout<'b> { let usage = Usage::new(!self.token_list_is_empty); let web_server_status_section = WebServerStatusSection::new( self.web_server_started, self.web_server_error.clone(), self.web_server_different_version_error.clone(), self.web_server_base_url.clone(), self.connection_is_unencrypted(), ); let current_session_section = CurrentSessionSection::new( self.web_server_started, self.web_server_ip, self.web_server_port, self.session_name.clone(), self.web_sharing, self.connection_is_unencrypted(), ); let title_width = Self::TITLE_TEXT.chars().count(); let (web_server_width, web_server_height) = web_server_status_section.web_server_status_width_and_height(); let (current_session_width, current_session_height) = current_session_section.current_session_status_width_and_height(); let (usage_width, usage_height) = usage.usage_width_and_height(cols); let mut max_width = title_width .max(web_server_width) .max(current_session_width) .max(usage_width); let mut total_height = 2 + web_server_height + 1 + current_session_height + 1 + usage_height; if self.connection_is_unencrypted() { let warning_width = self.unencrypted_warning_width(); max_width = max_width.max(warning_width); total_height += 3; } Layout { base_x: cols.saturating_sub(max_width) / 2, base_y: rows.saturating_sub(total_height) / 2, title_text: Self::TITLE_TEXT, web_server_height, usage_height, usage_width, } } fn render_content(&self, layout: &Layout, state: &mut MainScreenState) { let mut current_y = layout.base_y; self.render_title(layout, current_y); current_y += 2; current_y = self.render_web_server_section(layout, current_y, state); current_y = self.render_current_session_section(layout, current_y, state); current_y = self.render_usage_section(layout, current_y); current_y = self.render_warnings_and_help(layout, current_y, state); self.render_info(layout, current_y); } fn render_title(&self, layout: &Layout, y: usize) { let title = Text::new(layout.title_text).color_range(2, ..); print_text_with_coordinates(title, layout.base_x, y, None, None); } fn render_web_server_section( &self, layout: &Layout, y: usize, state: &mut MainScreenState, ) -> usize { let mut web_server_status_section = WebServerStatusSection::new( self.web_server_started, self.web_server_error.clone(), self.web_server_different_version_error.clone(), self.web_server_base_url.clone(), self.connection_is_unencrypted(), ); web_server_status_section.render_web_server_status( layout.base_x, y, self.hover_coordinates, ); state.currently_hovering_over_link |= web_server_status_section.currently_hovering_over_link; state.currently_hovering_over_unencrypted |= web_server_status_section.currently_hovering_over_unencrypted; for (coordinates, url) in web_server_status_section.clickable_urls { state.clickable_urls.insert(coordinates, url); } y + layout.web_server_height + 1 } fn render_current_session_section( &self, layout: &Layout, y: usize, state: &mut MainScreenState, ) -> usize { let mut current_session_section = CurrentSessionSection::new( self.web_server_started, self.web_server_ip, self.web_server_port, self.session_name.clone(), self.web_sharing, self.connection_is_unencrypted(), ); current_session_section.render_current_session_status( layout.base_x, y, self.hover_coordinates, ); state.currently_hovering_over_link |= current_session_section.currently_hovering_over_link; for (coordinates, url) in current_session_section.clickable_urls { state.clickable_urls.insert(coordinates, url); } y + layout.web_server_height + 1 } fn render_usage_section(&self, layout: &Layout, y: usize) -> usize { let usage = Usage::new(!self.token_list_is_empty); usage.render_usage(layout.base_x, y, layout.usage_width); y + layout.usage_height + 1 } fn render_warnings_and_help( &self, layout: &Layout, mut y: usize, state: &mut MainScreenState, ) -> usize { if self.connection_is_unencrypted() && self.web_server_started { self.render_unencrypted_warning(layout.base_x, y, state); y += 3; } if state.currently_hovering_over_link { self.render_link_help(layout.base_x, y); y += 3; } y } fn render_info(&self, layout: &Layout, y: usize) { if let Some(info) = self.info { let info_text = Text::new(info).color_range(1, ..); print_text_with_coordinates(info_text, layout.base_x, y, None, None); } } fn unencrypted_warning_width(&self) -> usize { let more_info_line = format!("{}{}", Self::MORE_INFO_TEXT, Self::SSL_URL); std::cmp::max( Self::WARNING_TEXT.chars().count(), more_info_line.chars().count(), ) } fn render_unencrypted_warning(&self, x: usize, y: usize, state: &mut MainScreenState) { let warning_text = Text::new(Self::WARNING_TEXT).color_range(1, ..3); let more_info_line = Text::new(format!("{}{}", Self::MORE_INFO_TEXT, Self::SSL_URL)); let url_x = x + Self::MORE_INFO_TEXT.chars().count(); let url_y = y + 1; let url_width = Self::SSL_URL.chars().count(); state.clickable_urls.insert( CoordinatesInLine::new(url_x, url_y, url_width), Self::SSL_URL.to_owned(), ); print_text_with_coordinates(warning_text, x, y, None, None); print_text_with_coordinates(more_info_line, x, y + 1, None, None); if hovering_on_line(url_x, url_y, url_width, self.hover_coordinates) { state.currently_hovering_over_link = true; render_text_with_underline(url_x, url_y, Self::SSL_URL); } } fn render_link_help(&self, x: usize, y: usize) { let help_text = if self.link_executable.is_some() { Text::new(Self::HELP_TEXT_WITH_CLICK) .color_range(3, 6..=10) .color_range(3, 15..=25) } else { Text::new(Self::HELP_TEXT_SHIFT_ONLY).color_range(3, 6..=16) }; print_text_with_coordinates(help_text, x, y, None, None); } pub fn connection_is_unencrypted(&self) -> bool { Url::parse(&self.web_server_base_url) .ok() .map(|b| b.scheme() == "http") .unwrap_or(false) } } struct Layout<'a> { base_x: usize, base_y: usize, title_text: &'a str, web_server_height: usize, usage_height: usize, usage_width: usize, }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/share/src/ui_components.rs
default-plugins/share/src/ui_components.rs
use std::net::IpAddr; use zellij_tile::prelude::*; use crate::CoordinatesInLine; use std::collections::HashMap; pub const USAGE_TITLE: &str = "How it works:"; pub const FIRST_TIME_USAGE_TITLE: &str = "Before logging in for the first time:"; pub const FIRST_TIME_BULLETIN_1: &str = "- Press <t> to generate a login token"; pub const BULLETIN_1_FULL: &str = "- Visit base URL to start a new session"; pub const BULLETIN_1_SHORT: &str = "- Base URL: new session"; pub const BULLETIN_2_FULL: &str = "- Follow base URL with a session name to attach to or create it"; pub const BULLETIN_2_SHORT: &str = "- Base URL + session name: attach or create"; pub const BULLETIN_3_FULL: &str = "- By default sessions not started from the web must be explicitly shared"; pub const BULLETIN_3_SHORT: &str = "- Sessions not started from the web must be explicitly shared"; pub const BULLETIN_4: &str = "- <t> manage login tokens"; pub const WEB_SERVER_TITLE: &str = "Web server: "; pub const WEB_SERVER_RUNNING: &str = "RUNNING "; pub const WEB_SERVER_NOT_RUNNING: &str = "NOT RUNNING"; pub const WEB_SERVER_INCOMPATIBLE_PREFIX: &str = "RUNNING INCOMPATIBLE VERSION "; pub const CTRL_C_STOP: &str = "(<Ctrl c> - Stop)"; pub const CTRL_C_STOP_OTHER: &str = "<Ctrl c> - Stop other server"; pub const PRESS_ENTER_START: &str = "Press <ENTER> to start"; pub const ERROR_PREFIX: &str = "ERROR: "; pub const URL_TITLE: &str = "URL: "; pub const UNENCRYPTED_MARKER: &str = " [*]"; pub const CURRENT_SESSION_TITLE: &str = "Current session: "; pub const SESSION_URL_TITLE: &str = "Session URL: "; pub const SHARING_STATUS: &str = "SHARING (<SPACE> - Stop Sharing)"; pub const SHARING_DISABLED: &str = "SHARING IS DISABLED"; pub const NOT_SHARING: &str = "NOT SHARING"; pub const PRESS_SPACE_SHARE: &str = "Press <SPACE> to share"; pub const WEB_SERVER_OFFLINE: &str = "...but web server is offline"; pub const COLOR_INDEX_0: usize = 0; pub const COLOR_INDEX_1: usize = 1; pub const COLOR_INDEX_2: usize = 2; pub const COLOR_HIGHLIGHT: usize = 3; #[derive(Debug, Clone)] pub struct ColorRange { pub start: usize, pub end: usize, pub color: usize, } // TODO: move this API to zellij-tile #[derive(Debug)] pub struct ColoredTextBuilder { text: String, ranges: Vec<ColorRange>, } impl ColoredTextBuilder { pub fn new(text: String) -> Self { Self { text, ranges: Vec::new(), } } pub fn highlight_substring(mut self, substring: &str, color: usize) -> Self { if let Some(start) = self.text.find(substring) { let end = start + substring.chars().count(); self.ranges.push(ColorRange { start, end, color }); } self } pub fn highlight_range(mut self, start: usize, end: usize, color: usize) -> Self { self.ranges.push(ColorRange { start, end, color }); self } pub fn highlight_from_start(mut self, start: usize, color: usize) -> Self { let end = self.text.chars().count(); self.ranges.push(ColorRange { start, end, color }); self } pub fn highlight_all(mut self, color: usize) -> Self { let end = self.text.chars().count(); self.ranges.push(ColorRange { start: 0, end, color, }); self } pub fn build(self) -> (Text, usize) { let length = self.text.chars().count(); let mut text_component = Text::new(self.text); for range in self.ranges { text_component = text_component.color_range(range.color, range.start..range.end); } (text_component, length) } } // create titled text with different colors for title and value fn create_titled_text( title: &str, value: &str, title_color: usize, value_color: usize, ) -> (Text, usize) { let full_text = format!("{}{}", title, value); ColoredTextBuilder::new(full_text) .highlight_range(0, title.chars().count(), title_color) .highlight_from_start(title.chars().count(), value_color) .build() } // to create text with a highlighted shortcut key fn create_highlighted_shortcut(text: &str, shortcut: &str, color: usize) -> (Text, usize) { ColoredTextBuilder::new(text.to_string()) .highlight_substring(shortcut, color) .build() } fn get_text_with_fallback( full_text: &'static str, short_text: &'static str, max_width: usize, ) -> &'static str { if full_text.chars().count() <= max_width { full_text } else { short_text } } fn calculate_max_length(texts: &[&str]) -> usize { texts .iter() .map(|text| text.chars().count()) .max() .unwrap_or(0) } fn format_url_with_encryption_marker(base_url: &str, is_unencrypted: bool) -> String { if is_unencrypted { format!("{}{}", base_url, UNENCRYPTED_MARKER) } else { base_url.to_string() } } #[derive(Debug)] pub struct Usage { has_login_tokens: bool, first_time_usage_title: &'static str, first_time_bulletin_1: &'static str, usage_title: &'static str, bulletin_1_full: &'static str, bulletin_1_short: &'static str, bulletin_2_full: &'static str, bulletin_2_short: &'static str, bulletin_3_full: &'static str, bulletin_3_short: &'static str, bulletin_4: &'static str, } impl Usage { pub fn new(has_login_tokens: bool) -> Self { Usage { has_login_tokens, usage_title: USAGE_TITLE, bulletin_1_full: BULLETIN_1_FULL, bulletin_1_short: BULLETIN_1_SHORT, bulletin_2_full: BULLETIN_2_FULL, bulletin_2_short: BULLETIN_2_SHORT, bulletin_3_full: BULLETIN_3_FULL, bulletin_3_short: BULLETIN_3_SHORT, bulletin_4: BULLETIN_4, first_time_usage_title: FIRST_TIME_USAGE_TITLE, first_time_bulletin_1: FIRST_TIME_BULLETIN_1, } } pub fn usage_width_and_height(&self, max_width: usize) -> (usize, usize) { if self.has_login_tokens { self.full_usage_width_and_height(max_width) } else { self.first_time_usage_width_and_height(max_width) } } pub fn full_usage_width_and_height(&self, max_width: usize) -> (usize, usize) { let bulletin_1 = get_text_with_fallback(self.bulletin_1_full, self.bulletin_1_short, max_width); let bulletin_2 = get_text_with_fallback(self.bulletin_2_full, self.bulletin_2_short, max_width); let bulletin_3 = get_text_with_fallback(self.bulletin_3_full, self.bulletin_3_short, max_width); let texts = &[ self.usage_title, bulletin_1, bulletin_2, bulletin_3, self.bulletin_4, ]; let width = calculate_max_length(texts); let height = 5; (width, height) } pub fn first_time_usage_width_and_height(&self, _max_width: usize) -> (usize, usize) { let texts = &[self.first_time_usage_title, self.first_time_bulletin_1]; let width = calculate_max_length(texts); let height = 2; (width, height) } pub fn render_usage(&self, x: usize, y: usize, max_width: usize) { if self.has_login_tokens { self.render_full_usage(x, y, max_width) } else { self.render_first_time_usage(x, y) } } pub fn render_full_usage(&self, x: usize, y: usize, max_width: usize) { let bulletin_1 = get_text_with_fallback(self.bulletin_1_full, self.bulletin_1_short, max_width); let bulletin_2 = get_text_with_fallback(self.bulletin_2_full, self.bulletin_2_short, max_width); let bulletin_3 = get_text_with_fallback(self.bulletin_3_full, self.bulletin_3_short, max_width); let usage_title = ColoredTextBuilder::new(self.usage_title.to_string()) .highlight_all(COLOR_INDEX_2) .build() .0; let bulletin_1_text = Text::new(bulletin_1); let bulletin_2_text = Text::new(bulletin_2); let bulletin_3_text = Text::new(bulletin_3); let bulletin_4_text = create_highlighted_shortcut(self.bulletin_4, "<t>", COLOR_HIGHLIGHT).0; let texts_and_positions = vec![ (usage_title, y), (bulletin_1_text, y + 1), (bulletin_2_text, y + 2), (bulletin_3_text, y + 3), (bulletin_4_text, y + 4), ]; for (text, y_pos) in texts_and_positions { print_text_with_coordinates(text, x, y_pos, None, None); } } pub fn render_first_time_usage(&self, x: usize, y: usize) { let usage_title = ColoredTextBuilder::new(self.first_time_usage_title.to_string()) .highlight_all(COLOR_INDEX_1) .build() .0; let bulletin_1 = create_highlighted_shortcut(self.first_time_bulletin_1, "<t>", COLOR_HIGHLIGHT).0; print_text_with_coordinates(usage_title, x, y, None, None); print_text_with_coordinates(bulletin_1, x, y + 1, None, None); } } #[derive(Debug)] pub struct WebServerStatusSection { web_server_started: bool, web_server_base_url: String, web_server_error: Option<String>, web_server_different_version_error: Option<String>, connection_is_unencrypted: bool, pub clickable_urls: HashMap<CoordinatesInLine, String>, pub currently_hovering_over_link: bool, pub currently_hovering_over_unencrypted: bool, } impl WebServerStatusSection { pub fn new( web_server_started: bool, web_server_error: Option<String>, web_server_different_version_error: Option<String>, web_server_base_url: String, connection_is_unencrypted: bool, ) -> Self { WebServerStatusSection { web_server_started, clickable_urls: HashMap::new(), currently_hovering_over_link: false, currently_hovering_over_unencrypted: false, web_server_error, web_server_different_version_error, web_server_base_url, connection_is_unencrypted, } } pub fn web_server_status_width_and_height(&self) -> (usize, usize) { let mut max_len = self.web_server_status_line().1; if let Some(error) = &self.web_server_error { max_len = std::cmp::max(max_len, self.web_server_error_component(error).1); } else if let Some(different_version) = &self.web_server_different_version_error { max_len = std::cmp::max( max_len, self.web_server_different_version_error_component(different_version) .1, ); } else if self.web_server_started { let url_display = format_url_with_encryption_marker( &self.web_server_base_url, self.connection_is_unencrypted, ); max_len = std::cmp::max( max_len, URL_TITLE.chars().count() + url_display.chars().count(), ); } else { max_len = std::cmp::max(max_len, self.start_server_line().1); } (max_len, 2) } pub fn render_web_server_status( &mut self, x: usize, y: usize, hover_coordinates: Option<(usize, usize)>, ) { let web_server_status_line = self.web_server_status_line().0; print_text_with_coordinates(web_server_status_line, x, y, None, None); if let Some(error) = &self.web_server_error { let error_component = self.web_server_error_component(error).0; print_text_with_coordinates(error_component, x, y + 1, None, None); } else if let Some(different_version) = &self.web_server_different_version_error { let version_error_component = self .web_server_different_version_error_component(different_version) .0; print_text_with_coordinates(version_error_component, x, y + 1, None, None); } else if self.web_server_started { self.render_server_url(x, y, hover_coordinates); } else { let info_line = self.start_server_line().0; print_text_with_coordinates(info_line, x, y + 1, None, None); } } fn render_server_url(&mut self, x: usize, y: usize, hover_coordinates: Option<(usize, usize)>) { let server_url = &self.web_server_base_url; let url_x = x + URL_TITLE.chars().count(); let url_width = server_url.chars().count(); let url_y = y + 1; self.clickable_urls.insert( CoordinatesInLine::new(url_x, url_y, url_width), server_url.clone(), ); let info_line = if self.connection_is_unencrypted { let full_text = format!("{}{}{}", URL_TITLE, server_url, UNENCRYPTED_MARKER); ColoredTextBuilder::new(full_text) .highlight_range(0, URL_TITLE.chars().count(), COLOR_INDEX_0) .highlight_substring(UNENCRYPTED_MARKER, COLOR_INDEX_1) .build() .0 } else { create_titled_text(URL_TITLE, server_url, COLOR_INDEX_0, COLOR_INDEX_1).0 }; print_text_with_coordinates(info_line, x, y + 1, None, None); if hovering_on_line(url_x, url_y, url_width, hover_coordinates) { self.currently_hovering_over_link = true; render_text_with_underline(url_x, url_y, server_url); } } fn web_server_status_line(&self) -> (Text, usize) { if self.web_server_started { self.create_running_status_line() } else if let Some(different_version) = &self.web_server_different_version_error { self.create_incompatible_version_line(different_version) } else { create_titled_text( WEB_SERVER_TITLE, WEB_SERVER_NOT_RUNNING, COLOR_INDEX_0, COLOR_HIGHLIGHT, ) } } fn create_running_status_line(&self) -> (Text, usize) { let full_text = format!("{}{}{}", WEB_SERVER_TITLE, WEB_SERVER_RUNNING, CTRL_C_STOP); ColoredTextBuilder::new(full_text) .highlight_range(0, WEB_SERVER_TITLE.chars().count(), COLOR_INDEX_0) .highlight_substring(WEB_SERVER_RUNNING.trim(), COLOR_HIGHLIGHT) .highlight_substring("<Ctrl c>", COLOR_HIGHLIGHT) .build() } fn create_incompatible_version_line(&self, different_version: &str) -> (Text, usize) { let value = format!("{}{}", WEB_SERVER_INCOMPATIBLE_PREFIX, different_version); create_titled_text(WEB_SERVER_TITLE, &value, COLOR_INDEX_0, COLOR_HIGHLIGHT) } fn start_server_line(&self) -> (Text, usize) { create_highlighted_shortcut(PRESS_ENTER_START, "<ENTER>", COLOR_HIGHLIGHT) } fn web_server_error_component(&self, error: &str) -> (Text, usize) { let text = format!("{}{}", ERROR_PREFIX, error); ColoredTextBuilder::new(text) .highlight_all(COLOR_HIGHLIGHT) .build() } fn web_server_different_version_error_component(&self, _version: &str) -> (Text, usize) { create_highlighted_shortcut(CTRL_C_STOP_OTHER, "<Ctrl c>", COLOR_HIGHLIGHT) } } #[derive(Debug)] pub struct CurrentSessionSection { web_server_started: bool, web_server_ip: Option<IpAddr>, web_server_port: Option<u16>, web_sharing: WebSharing, session_name: Option<String>, connection_is_unencrypted: bool, pub clickable_urls: HashMap<CoordinatesInLine, String>, pub currently_hovering_over_link: bool, } impl CurrentSessionSection { pub fn new( web_server_started: bool, web_server_ip: Option<IpAddr>, web_server_port: Option<u16>, session_name: Option<String>, web_sharing: WebSharing, connection_is_unencrypted: bool, ) -> Self { CurrentSessionSection { web_server_started, web_server_ip, web_server_port, session_name, web_sharing, clickable_urls: HashMap::new(), currently_hovering_over_link: false, connection_is_unencrypted, } } pub fn current_session_status_width_and_height(&self) -> (usize, usize) { let mut max_len = self.get_session_status_line_length(); if self.web_sharing.web_clients_allowed() && self.web_server_started { let url_display = format_url_with_encryption_marker( &self.session_url(), self.connection_is_unencrypted, ); max_len = std::cmp::max( max_len, SESSION_URL_TITLE.chars().count() + url_display.chars().count(), ); } else if self.web_sharing.web_clients_allowed() { max_len = std::cmp::max(max_len, WEB_SERVER_OFFLINE.chars().count()); } else { max_len = std::cmp::max(max_len, self.press_space_to_share().1); } (max_len, 2) } fn get_session_status_line_length(&self) -> usize { match self.web_sharing { WebSharing::On => self.render_current_session_sharing().1, WebSharing::Disabled => self.render_sharing_is_disabled().1, WebSharing::Off => self.render_not_sharing().1, } } pub fn render_current_session_status( &mut self, x: usize, y: usize, hover_coordinates: Option<(usize, usize)>, ) { let status_line = match self.web_sharing { WebSharing::On => self.render_current_session_sharing().0, WebSharing::Disabled => self.render_sharing_is_disabled().0, WebSharing::Off => self.render_not_sharing().0, }; print_text_with_coordinates(status_line, x, y, None, None); if self.web_sharing.web_clients_allowed() && self.web_server_started { self.render_session_url(x, y, hover_coordinates); } else if self.web_sharing.web_clients_allowed() { let info_line = Text::new(WEB_SERVER_OFFLINE); print_text_with_coordinates(info_line, x, y + 1, None, None); } else if !self.web_sharing.sharing_is_disabled() { let info_line = self.press_space_to_share().0; print_text_with_coordinates(info_line, x, y + 1, None, None); } } fn render_session_url( &mut self, x: usize, y: usize, hover_coordinates: Option<(usize, usize)>, ) { let session_url = self.session_url(); let url_x = x + SESSION_URL_TITLE.chars().count(); let url_width = session_url.chars().count(); let url_y = y + 1; self.clickable_urls.insert( CoordinatesInLine::new(url_x, url_y, url_width), session_url.clone(), ); let info_line = if self.connection_is_unencrypted { let full_text = format!("{}{}{}", SESSION_URL_TITLE, session_url, UNENCRYPTED_MARKER); ColoredTextBuilder::new(full_text) .highlight_range(0, SESSION_URL_TITLE.chars().count(), COLOR_INDEX_0) .highlight_substring(UNENCRYPTED_MARKER, COLOR_INDEX_1) .build() .0 } else { create_titled_text( SESSION_URL_TITLE, &session_url, COLOR_INDEX_0, COLOR_INDEX_1, ) .0 }; print_text_with_coordinates(info_line, x, y + 1, None, None); if hovering_on_line(url_x, url_y, url_width, hover_coordinates) { self.currently_hovering_over_link = true; render_text_with_underline(url_x, url_y, &session_url); } } fn render_current_session_sharing(&self) -> (Text, usize) { let full_text = format!("{}{}", CURRENT_SESSION_TITLE, SHARING_STATUS); ColoredTextBuilder::new(full_text) .highlight_range(0, CURRENT_SESSION_TITLE.chars().count(), COLOR_INDEX_0) .highlight_substring("SHARING", COLOR_HIGHLIGHT) .highlight_substring("<SPACE>", COLOR_HIGHLIGHT) .build() } fn render_sharing_is_disabled(&self) -> (Text, usize) { create_titled_text( CURRENT_SESSION_TITLE, SHARING_DISABLED, COLOR_INDEX_0, COLOR_HIGHLIGHT, ) } fn render_not_sharing(&self) -> (Text, usize) { create_titled_text( CURRENT_SESSION_TITLE, NOT_SHARING, COLOR_INDEX_0, COLOR_HIGHLIGHT, ) } fn session_url(&self) -> String { let web_server_ip = self .web_server_ip .map(|i| i.to_string()) .unwrap_or_else(|| "UNDEFINED".to_owned()); let web_server_port = self .web_server_port .map(|p| p.to_string()) .unwrap_or_else(|| "UNDEFINED".to_owned()); let prefix = if self.connection_is_unencrypted { "http" } else { "https" }; let session_name = self.session_name.as_deref().unwrap_or(""); format!( "{}://{}:{}/{}", prefix, web_server_ip, web_server_port, session_name ) } fn press_space_to_share(&self) -> (Text, usize) { create_highlighted_shortcut(PRESS_SPACE_SHARE, "<SPACE>", COLOR_HIGHLIGHT) } } pub fn hovering_on_line( x: usize, y: usize, width: usize, hover_coordinates: Option<(usize, usize)>, ) -> bool { match hover_coordinates { Some((hover_x, hover_y)) => hover_y == y && hover_x <= x + width && hover_x > x, None => false, } } pub fn render_text_with_underline(url_x: usize, url_y: usize, url_text: &str) { print!( "\u{1b}[{};{}H\u{1b}[m\u{1b}[1;4m{}", url_y + 1, url_x + 1, url_text, ); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/share/src/main.rs
default-plugins/share/src/main.rs
mod main_screen; mod token_management_screen; mod token_screen; mod ui_components; use std::net::IpAddr; use zellij_tile::prelude::*; use std::collections::{BTreeMap, HashMap}; use main_screen::MainScreen; use token_management_screen::TokenManagementScreen; use token_screen::TokenScreen; static WEB_SERVER_QUERY_DURATION: f64 = 0.4; // Doherty threshold #[derive(Debug, Default)] struct App { web_server: WebServerState, ui: UIState, tokens: TokenManager, state: AppState, } register_plugin!(App); impl ZellijPlugin for App { fn load(&mut self, _configuration: BTreeMap<String, String>) { self.initialize(); } fn update(&mut self, event: Event) -> bool { if !self.web_server.capability && !matches!(event, Event::ModeUpdate(_)) { return false; } match event { Event::Timer(_) => self.handle_timer(), Event::ModeUpdate(mode_info) => self.handle_mode_update(mode_info), Event::WebServerStatus(status) => self.handle_web_server_status(status), Event::Key(key) => self.handle_key_input(key), Event::Mouse(mouse_event) => self.handle_mouse_event(mouse_event), Event::RunCommandResult(exit_code, _stdout, _stderr, context) => { self.handle_command_result(exit_code, context) }, Event::FailedToStartWebServer(error) => self.handle_web_server_error(error), _ => false, } } fn render(&mut self, rows: usize, cols: usize) { if !self.web_server.capability { self.render_no_capability_message(rows, cols); return; } self.ui.reset_render_state(); match &self.state.current_screen { Screen::Main => self.render_main_screen(rows, cols), Screen::Token(token) => self.render_token_screen(rows, cols, token), Screen::ManageTokens => self.render_manage_tokens_screen(rows, cols), } } } impl App { fn initialize(&mut self) { self.subscribe_to_events(); self.state.own_plugin_id = Some(get_plugin_ids().plugin_id); self.retrieve_token_list(); self.query_link_executable(); self.set_plugin_title(); } fn subscribe_to_events(&self) { subscribe(&[ EventType::Key, EventType::ModeUpdate, EventType::WebServerStatus, EventType::Mouse, EventType::RunCommandResult, EventType::FailedToStartWebServer, EventType::Timer, ]); } fn set_plugin_title(&self) { if let Some(plugin_id) = self.state.own_plugin_id { rename_plugin_pane(plugin_id, "Share Session"); } } fn handle_timer(&mut self) -> bool { query_web_server_status(); self.retrieve_token_list(); set_timeout(WEB_SERVER_QUERY_DURATION); false } fn handle_mode_update(&mut self, mode_info: ModeInfo) -> bool { let mut should_render = false; self.state.session_name = mode_info.session_name; if let Some(web_clients_allowed) = mode_info.web_clients_allowed { self.web_server.clients_allowed = web_clients_allowed; should_render = true; } if let Some(web_sharing) = mode_info.web_sharing { self.web_server.sharing = web_sharing; should_render = true; } if let Some(web_server_ip) = mode_info.web_server_ip { self.web_server.ip = Some(web_server_ip); should_render = true; } if let Some(web_server_port) = mode_info.web_server_port { self.web_server.port = Some(web_server_port); should_render = true; } if let Some(web_server_capability) = mode_info.web_server_capability { self.web_server.capability = web_server_capability; if self.web_server.capability && !self.state.timer_running { self.state.timer_running = true; set_timeout(WEB_SERVER_QUERY_DURATION); } should_render = true; } should_render } fn handle_web_server_status(&mut self, status: WebServerStatus) -> bool { match status { WebServerStatus::Online(base_url) => { self.web_server.base_url = base_url; self.web_server.started = true; self.web_server.different_version_error = None; }, WebServerStatus::Offline => { self.web_server.started = false; self.web_server.different_version_error = None; }, WebServerStatus::DifferentVersion(version) => { self.web_server.started = false; self.web_server.different_version_error = Some(version); }, } true } fn handle_key_input(&mut self, key: KeyWithModifier) -> bool { if self.clear_error_or_info() { return true; } match self.state.current_screen { Screen::Main => self.handle_main_screen_keys(key), Screen::Token(_) => self.handle_token_screen_keys(key), Screen::ManageTokens => self.handle_manage_tokens_keys(key), } } fn clear_error_or_info(&mut self) -> bool { self.web_server.error.take().is_some() || self.state.info.take().is_some() } fn handle_main_screen_keys(&mut self, key: KeyWithModifier) -> bool { match key.bare_key { BareKey::Enter if key.has_no_modifiers() && !self.web_server.started => { start_web_server(); false }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Ctrl]) => { stop_web_server(); false }, BareKey::Char(' ') if key.has_no_modifiers() => { self.toggle_session_sharing(); false }, BareKey::Char('t') if key.has_no_modifiers() => { self.handle_token_action(); true }, BareKey::Esc if key.has_no_modifiers() => { close_self(); false }, _ => false, } } fn toggle_session_sharing(&self) { match self.web_server.sharing { WebSharing::Disabled => {}, WebSharing::On => stop_sharing_current_session(), WebSharing::Off => share_current_session(), } } fn handle_token_action(&mut self) { if self.tokens.list.is_empty() { self.generate_new_token(None, false); } else { self.change_to_manage_tokens_screen(); } } fn handle_token_screen_keys(&mut self, key: KeyWithModifier) -> bool { match key.bare_key { BareKey::Esc if key.has_no_modifiers() => { self.change_to_previous_screen(); true }, _ => false, } } fn handle_manage_tokens_keys(&mut self, key: KeyWithModifier) -> bool { if self.tokens.handle_text_input(&key) { return true; } match key.bare_key { BareKey::Esc if key.has_no_modifiers() => self.handle_escape_key(), BareKey::Down if key.has_no_modifiers() => self.tokens.navigate_down(), BareKey::Up if key.has_no_modifiers() => self.tokens.navigate_up(), BareKey::Char('n') if key.has_no_modifiers() => { self.tokens.start_new_token_input(); true }, BareKey::Char('o') if key.has_no_modifiers() => { self.tokens.start_new_read_only_token_input(); true }, BareKey::Enter if key.has_no_modifiers() => self.handle_enter_key(), BareKey::Char('r') if key.has_no_modifiers() => { self.tokens.start_rename_input(); true }, BareKey::Char('x') if key.has_no_modifiers() => self.revoke_selected_token(), BareKey::Char('x') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.revoke_all_tokens(); true }, _ => false, } } fn handle_escape_key(&mut self) -> bool { let was_editing = self.tokens.cancel_input(); if !was_editing { self.change_to_main_screen(); } true } fn handle_enter_key(&mut self) -> bool { if let Some(token_name) = self.tokens.finish_new_token_input() { self.generate_new_token(token_name, false); return true; } if let Some(token_name) = self.tokens.finish_new_read_only_token_input() { self.generate_new_token(token_name, true); return true; } if let Some(new_name) = self.tokens.finish_rename_input() { self.rename_current_token(new_name); return true; } false } fn generate_new_token(&mut self, name: Option<String>, read_only: bool) { match generate_web_login_token(name, read_only) { Ok(token) => self.change_to_token_screen(token), Err(e) => self.web_server.error = Some(e), } } fn rename_current_token(&mut self, new_name: String) { if let Some(current_token) = self.tokens.get_selected_token() { match rename_web_token(&current_token.0, &new_name) { Ok(_) => { self.retrieve_token_list(); if self.tokens.adjust_selection_after_list_change() { self.change_to_main_screen(); } }, Err(e) => self.web_server.error = Some(e), } } } fn revoke_selected_token(&mut self) -> bool { if let Some(token) = self.tokens.get_selected_token() { match revoke_web_login_token(&token.0) { Ok(_) => { self.retrieve_token_list(); if self.tokens.adjust_selection_after_list_change() { self.change_to_main_screen(); } self.state.info = Some("Revoked. Connected clients not affected.".to_owned()); }, Err(e) => self.web_server.error = Some(e), } return true; } false } fn revoke_all_tokens(&mut self) { match revoke_all_web_tokens() { Ok(_) => { self.retrieve_token_list(); if self.tokens.adjust_selection_after_list_change() { self.change_to_main_screen(); } self.state.info = Some("Revoked. Connected clients not affected.".to_owned()); }, Err(e) => self.web_server.error = Some(e), } } fn handle_mouse_event(&mut self, event: Mouse) -> bool { match event { Mouse::LeftClick(line, column) => self.handle_link_click(line, column), Mouse::Hover(line, column) => { self.ui.hover_coordinates = Some((column, line as usize)); true }, _ => false, } } fn handle_link_click(&mut self, line: isize, column: usize) -> bool { for (coordinates, url) in &self.ui.clickable_urls { if coordinates.contains(column, line as usize) { if let Some(executable) = self.ui.link_executable { run_command(&[executable, url], Default::default()); } return true; } } false } fn handle_command_result( &mut self, exit_code: Option<i32>, context: BTreeMap<String, String>, ) -> bool { if context.contains_key("xdg_open_cli") && exit_code == Some(0) { self.ui.link_executable = Some("xdg-open"); } else if context.contains_key("open_cli") && exit_code == Some(0) { self.ui.link_executable = Some("open"); } false } fn handle_web_server_error(&mut self, error: String) -> bool { self.web_server.error = Some(error); true } fn query_link_executable(&self) { let mut xdg_context = BTreeMap::new(); xdg_context.insert("xdg_open_cli".to_owned(), String::new()); run_command(&["xdg-open", "--help"], xdg_context); let mut open_context = BTreeMap::new(); open_context.insert("open_cli".to_owned(), String::new()); run_command(&["open", "--help"], open_context); } fn render_no_capability_message(&self, rows: usize, cols: usize) { let full_text = "This version of Zellij was compiled without web sharing capabilities"; let short_text = "No web server capabilities"; let text = if cols >= full_text.chars().count() { full_text } else { short_text }; let text_element = Text::new(text).color_range(3, ..); let text_x = cols.saturating_sub(text.chars().count()) / 2; let text_y = rows / 2; print_text_with_coordinates(text_element, text_x, text_y, None, None); } fn change_to_token_screen(&mut self, token: String) { self.retrieve_token_list(); set_self_mouse_selection_support(true); self.state.previous_screen = Some(self.state.current_screen.clone()); self.state.current_screen = Screen::Token(token); } fn change_to_manage_tokens_screen(&mut self) { self.retrieve_token_list(); set_self_mouse_selection_support(false); self.tokens.selected_index = Some(0); self.state.previous_screen = None; self.state.current_screen = Screen::ManageTokens; } fn change_to_main_screen(&mut self) { self.retrieve_token_list(); set_self_mouse_selection_support(false); self.state.previous_screen = None; self.state.current_screen = Screen::Main; } fn change_to_previous_screen(&mut self) { self.retrieve_token_list(); match self.state.previous_screen.take() { Some(Screen::ManageTokens) => self.change_to_manage_tokens_screen(), _ => self.change_to_main_screen(), } } fn render_main_screen(&mut self, rows: usize, cols: usize) { let state_changes = MainScreen::new( self.tokens.list.is_empty(), self.web_server.started, &self.web_server.error, &self.web_server.different_version_error, &self.web_server.base_url, self.web_server.ip, self.web_server.port, &self.state.session_name, self.web_server.sharing, self.ui.hover_coordinates, &self.state.info, &self.ui.link_executable, ) .render(rows, cols); self.ui.currently_hovering_over_link = state_changes.currently_hovering_over_link; self.ui.currently_hovering_over_unencrypted = state_changes.currently_hovering_over_unencrypted; self.ui.clickable_urls = state_changes.clickable_urls; } fn render_token_screen(&self, rows: usize, cols: usize, token: &str) { let token_screen = TokenScreen::new(token.to_string(), self.web_server.error.clone(), rows, cols); token_screen.render(); } fn render_manage_tokens_screen(&self, rows: usize, cols: usize) { // Pass whichever token input field is active (normal or read-only) let entering_new_token_name = if self.tokens.entering_new_name.is_some() { &self.tokens.entering_new_name } else { &self.tokens.entering_new_read_only_name }; TokenManagementScreen::new( &self.tokens.list, self.tokens.selected_index, &self.tokens.renaming_token, entering_new_token_name, &self.web_server.error, &self.state.info, rows, cols, ) .render(); } fn retrieve_token_list(&mut self) { if let Err(e) = self.tokens.retrieve_list() { self.web_server.error = Some(e); } } } #[derive(Debug, Default)] struct WebServerState { started: bool, sharing: WebSharing, clients_allowed: bool, error: Option<String>, different_version_error: Option<String>, ip: Option<IpAddr>, port: Option<u16>, base_url: String, capability: bool, } #[derive(Debug, Default)] struct UIState { hover_coordinates: Option<(usize, usize)>, clickable_urls: HashMap<CoordinatesInLine, String>, link_executable: Option<&'static str>, currently_hovering_over_link: bool, currently_hovering_over_unencrypted: bool, } impl UIState { fn reset_render_state(&mut self) { self.currently_hovering_over_link = false; self.clickable_urls.clear(); } } #[derive(Debug, Default)] struct TokenManager { list: Vec<(String, String, bool)>, // bool -> is_read_only selected_index: Option<usize>, entering_new_name: Option<String>, entering_new_read_only_name: Option<String>, renaming_token: Option<String>, } impl TokenManager { fn retrieve_list(&mut self) -> Result<(), String> { match list_web_login_tokens() { Ok(tokens) => { self.list = tokens; Ok(()) }, Err(e) => Err(format!("Failed to retrieve login tokens: {}", e)), } } fn get_selected_token(&self) -> Option<&(String, String, bool)> { self.selected_index.and_then(|i| self.list.get(i)) } fn adjust_selection_after_list_change(&mut self) -> bool { if self.list.is_empty() { self.selected_index = None; true // indicates should change to main screen } else if self.selected_index >= Some(self.list.len()) { self.selected_index = Some(self.list.len().saturating_sub(1)); false } else { false } } fn navigate_down(&mut self) -> bool { if let Some(ref mut index) = self.selected_index { *index = if *index < self.list.len().saturating_sub(1) { *index + 1 } else { 0 }; return true; } false } fn navigate_up(&mut self) -> bool { if let Some(ref mut index) = self.selected_index { *index = if *index == 0 { self.list.len().saturating_sub(1) } else { *index - 1 }; return true; } false } fn start_new_token_input(&mut self) { self.entering_new_name = Some(String::new()); } fn start_new_read_only_token_input(&mut self) { self.entering_new_read_only_name = Some(String::new()); } fn start_rename_input(&mut self) { self.renaming_token = Some(String::new()); } fn handle_text_input(&mut self, key: &KeyWithModifier) -> bool { match key.bare_key { BareKey::Char(c) if key.has_no_modifiers() => { if let Some(ref mut name) = self.entering_new_name { name.push(c); return true; } if let Some(ref mut name) = self.entering_new_read_only_name { name.push(c); return true; } if let Some(ref mut name) = self.renaming_token { name.push(c); return true; } }, BareKey::Backspace if key.has_no_modifiers() => { if let Some(ref mut name) = self.entering_new_name { name.pop(); return true; } if let Some(ref mut name) = self.entering_new_read_only_name { name.pop(); return true; } if let Some(ref mut name) = self.renaming_token { name.pop(); return true; } }, _ => {}, } false } fn finish_new_token_input(&mut self) -> Option<Option<String>> { self.entering_new_name .take() .map(|name| if name.is_empty() { None } else { Some(name) }) } fn finish_new_read_only_token_input(&mut self) -> Option<Option<String>> { self.entering_new_read_only_name .take() .map(|name| if name.is_empty() { None } else { Some(name) }) } fn finish_rename_input(&mut self) -> Option<String> { self.renaming_token.take() } fn cancel_input(&mut self) -> bool { self.entering_new_name.take().is_some() || self.entering_new_read_only_name.take().is_some() || self.renaming_token.take().is_some() } } #[derive(Debug, Default)] struct AppState { session_name: Option<String>, own_plugin_id: Option<u32>, timer_running: bool, current_screen: Screen, previous_screen: Option<Screen>, info: Option<String>, } #[derive(Debug, Clone)] enum Screen { Main, Token(String), ManageTokens, } impl Default for Screen { fn default() -> Self { Screen::Main } } #[derive(Debug, PartialEq, Eq, Hash)] pub struct CoordinatesInLine { x: usize, y: usize, width: usize, } impl CoordinatesInLine { pub fn new(x: usize, y: usize, width: usize) -> Self { CoordinatesInLine { x, y, width } } pub fn contains(&self, x: usize, y: usize) -> bool { x >= self.x && x <= self.x + self.width && self.y == y } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/share/src/token_management_screen.rs
default-plugins/share/src/token_management_screen.rs
use zellij_tile::prelude::*; #[derive(Debug)] struct ScreenContent { title: (String, Text), items: Vec<Vec<Text>>, help: (String, Text), status_message: Option<(String, Text)>, max_width: usize, new_token_line: Option<(String, Text)>, } #[derive(Debug)] struct Layout { base_x: usize, base_y: usize, title_x: usize, new_token_y: usize, help_y: usize, status_y: usize, } #[derive(Debug)] struct ScrollInfo { start_index: usize, end_index: usize, truncated_top: usize, truncated_bottom: usize, } #[derive(Debug)] struct ColumnWidths { token: usize, date: usize, read_only: usize, controls: usize, } pub struct TokenManagementScreen<'a> { token_list: &'a Vec<(String, String, bool)>, // bool -> is_read_only selected_list_index: Option<usize>, renaming_token: &'a Option<String>, entering_new_token_name: &'a Option<String>, error: &'a Option<String>, info: &'a Option<String>, rows: usize, cols: usize, } impl<'a> TokenManagementScreen<'a> { pub fn new( token_list: &'a Vec<(String, String, bool)>, selected_list_index: Option<usize>, renaming_token: &'a Option<String>, entering_new_token_name: &'a Option<String>, error: &'a Option<String>, info: &'a Option<String>, rows: usize, cols: usize, ) -> Self { Self { token_list, selected_list_index, renaming_token, entering_new_token_name, error, info, rows, cols, } } pub fn render(&self) { let content = self.build_screen_content(); let max_height = self.calculate_max_item_height(); let scrolled_content = self.apply_scroll_truncation(content, max_height); let layout = self.calculate_layout(&scrolled_content); self.print_items_to_screen(scrolled_content, layout); } fn calculate_column_widths(&self) -> ColumnWidths { let max_table_width = self.cols; const MIN_TOKEN_WIDTH: usize = 10; const MIN_DATE_WIDTH: usize = 10; // Minimum for just date "YYYY-MM-DD" const MIN_READ_ONLY_WIDTH: usize = 5; // Minimum for "RO/RW" const MIN_CONTROLS_WIDTH: usize = 6; // Minimum for "(<x>, <r>)" const COLUMN_SPACING: usize = 5; // Space between columns (4 columns with table padding) let min_total_width = MIN_TOKEN_WIDTH + MIN_DATE_WIDTH + MIN_READ_ONLY_WIDTH + MIN_CONTROLS_WIDTH + COLUMN_SPACING; if max_table_width <= min_total_width { return ColumnWidths { token: MIN_TOKEN_WIDTH, date: MIN_DATE_WIDTH, read_only: MIN_READ_ONLY_WIDTH, controls: MIN_CONTROLS_WIDTH, }; } const PREFERRED_DATE_WIDTH: usize = 29; // "issued on YYYY-MM-DD HH:MM:SS" const PREFERRED_READ_ONLY_WIDTH: usize = 10; // "read-write" const PREFERRED_CONTROLS_WIDTH: usize = 24; // "(<x> revoke, <r> rename)" let available_width = max_table_width.saturating_sub(COLUMN_SPACING); let preferred_fixed_width = PREFERRED_DATE_WIDTH + PREFERRED_READ_ONLY_WIDTH + PREFERRED_CONTROLS_WIDTH; if available_width >= preferred_fixed_width + MIN_TOKEN_WIDTH { // We can use preferred widths for date, read_only, and controls ColumnWidths { token: available_width.saturating_sub(preferred_fixed_width), date: PREFERRED_DATE_WIDTH, read_only: PREFERRED_READ_ONLY_WIDTH, controls: PREFERRED_CONTROLS_WIDTH, } } else { // Need to balance truncation across all columns // Priority: controls > read_only > date > token (token gets remaining space) let remaining_width = available_width .saturating_sub(MIN_TOKEN_WIDTH) .saturating_sub(MIN_DATE_WIDTH) .saturating_sub(MIN_READ_ONLY_WIDTH) .saturating_sub(MIN_CONTROLS_WIDTH); let extra_per_column = remaining_width / 4; ColumnWidths { token: MIN_TOKEN_WIDTH + extra_per_column, date: MIN_DATE_WIDTH + extra_per_column, read_only: MIN_READ_ONLY_WIDTH + extra_per_column, controls: MIN_CONTROLS_WIDTH + extra_per_column, } } } fn truncate_token_name(&self, token: &str, max_width: usize) -> String { if token.chars().count() <= max_width { return token.to_string(); } if max_width <= 6 { // Too small to show anything meaningful return "[...]".to_string(); } let truncator = if max_width <= 10 { "[..]" } else { "[...]" }; let truncator_len = truncator.chars().count(); let remaining_chars = max_width.saturating_sub(truncator_len); let start_chars = remaining_chars / 2; let end_chars = remaining_chars.saturating_sub(start_chars); let token_chars: Vec<char> = token.chars().collect(); let start_part: String = token_chars.iter().take(start_chars).collect(); let end_part: String = token_chars .iter() .rev() .take(end_chars) .collect::<String>() .chars() .rev() .collect(); format!("{}{}{}", start_part, truncator, end_part) } fn format_date( &self, created_at: &str, max_width: usize, include_issued_prefix: bool, ) -> String { let full_text = if include_issued_prefix { format!("issued on {}", created_at) } else { created_at.to_string() }; if full_text.chars().count() <= max_width { return full_text; } // If we can't fit "issued on", use the date if !include_issued_prefix || created_at.chars().count() <= max_width { if created_at.chars().count() <= max_width { return created_at.to_string(); } // Truncate the date itself if needed let chars: Vec<char> = created_at.chars().collect(); if max_width <= 3 { return "...".to_string(); } let truncated: String = chars.iter().take(max_width - 3).collect(); format!("{}...", truncated) } else { // Try without "issued on" prefix self.format_date(created_at, max_width, false) } } fn format_read_only(&self, is_read_only: bool, max_width: usize) -> String { let full_text = if is_read_only { "read-only" } else { "read-write" }; let short_text = if is_read_only { "RO" } else { "RW" }; let text = if full_text.chars().count() <= max_width { full_text } else { short_text }; // Center the text in the column let text_len = text.chars().count(); if text_len >= max_width { return text.to_string(); } let padding = max_width - text_len; let left_padding = padding / 2; let right_padding = padding - left_padding; format!( "{}{}{}", " ".repeat(left_padding), text, " ".repeat(right_padding) ) } fn format_controls(&self, max_width: usize, is_selected: bool) -> String { if !is_selected { return " ".repeat(max_width); } let full_controls = "(<x> revoke, <r> rename)"; let short_controls = "(<x>, <r>)"; if full_controls.chars().count() <= max_width { full_controls.to_string() } else if short_controls.chars().count() <= max_width { // Pad the short controls to fill the available width let padding = max_width - short_controls.chars().count(); format!("{}{}", short_controls, " ".repeat(padding)) } else { // Very constrained space " ".repeat(max_width) } } fn calculate_max_item_height(&self) -> usize { // Calculate fixed UI elements that are always present: // - 1 row for title // - 1 row for spacing after title (always preserved) // - 1 row for the "create new token" line (always visible) // - 1 row for spacing before help (always preserved) // - 1 row for help text (or status message - they're mutually exclusive) let fixed_rows = 4; // title + spacing + help/status + spacing before help let create_new_token_rows = 1; // "create new token" line let total_fixed_rows = fixed_rows + create_new_token_rows; // Calculate available rows for token items let available_for_items = self.rows.saturating_sub(total_fixed_rows); // Return at least 1 to avoid issues, but this will be the maximum height for token items only available_for_items.max(1) } fn build_screen_content(&self) -> ScreenContent { let mut max_width = 0; let max_table_width = self.cols; let column_widths = self.calculate_column_widths(); let title_text = "List of Login Tokens"; let title = Text::new(title_text).color_range(2, ..); max_width = std::cmp::max(max_width, title_text.len()); let mut items = vec![]; for (i, (token, created_at, read_only)) in self.token_list.iter().enumerate() { let is_selected = Some(i) == self.selected_list_index; let (row_text, row_items) = self.create_token_item(token, created_at, *read_only, is_selected, &column_widths); max_width = std::cmp::max(max_width, row_text.chars().count()); items.push(row_items); } let (new_token_text, new_token_line) = self.create_new_token_line(); max_width = std::cmp::max(max_width, new_token_text.chars().count()); let (help_text, help_line) = self.create_help_line(); max_width = std::cmp::max(max_width, help_text.chars().count()); let status_message = self.create_status_message(); if let Some((ref text, _)) = status_message { max_width = std::cmp::max(max_width, text.chars().count()); } max_width = std::cmp::min(max_width, max_table_width); ScreenContent { title: (title_text.to_string(), title), items, help: (help_text, help_line), status_message, max_width, new_token_line: Some((new_token_text, new_token_line)), } } fn apply_scroll_truncation( &self, mut content: ScreenContent, max_height: usize, ) -> ScreenContent { let total_token_items = content.items.len(); // Only token items, not including "create new token" // If all token items fit, no need to truncate if total_token_items <= max_height { return content; } let scroll_info = self.calculate_scroll_info(total_token_items, max_height); // Extract the visible range let mut visible_items: Vec<Vec<Text>> = content .items .into_iter() .skip(scroll_info.start_index) .take( scroll_info .end_index .saturating_sub(scroll_info.start_index), ) .collect(); // Add truncation indicators if scroll_info.truncated_top > 0 { self.add_truncation_indicator(&mut visible_items[0], scroll_info.truncated_top); } if scroll_info.truncated_bottom > 0 { let last_idx = visible_items.len().saturating_sub(1); self.add_truncation_indicator( &mut visible_items[last_idx], scroll_info.truncated_bottom, ); } content.items = visible_items; content } fn calculate_scroll_info(&self, total_token_items: usize, max_height: usize) -> ScrollInfo { // Only consider token items for scrolling (not the "create new token" line) // The "create new token" line is always visible and handled separately // Find the selected index within the token list only let selected_index = if let Some(idx) = self.selected_list_index { idx } else { // If "create new token" is selected or no selection, // we don't need to center anything in the token list 0 }; // Calculate how many items to show above and below the selected item let items_above = max_height / 2; let items_below = max_height.saturating_sub(items_above).saturating_sub(1); // -1 for the selected item itself // Calculate the start and end indices let start_index = if selected_index < items_above { 0 } else if selected_index + items_below >= total_token_items { total_token_items.saturating_sub(max_height) } else { selected_index.saturating_sub(items_above) }; let end_index = std::cmp::min(start_index + max_height, total_token_items); ScrollInfo { start_index, end_index, truncated_top: start_index, truncated_bottom: total_token_items.saturating_sub(end_index), } } fn add_truncation_indicator(&self, row: &mut Vec<Text>, count: usize) { let indicator = format!("+[{}]", count); // Replace the last cell (controls column) with the truncation indicator if let Some(last_cell) = row.last_mut() { *last_cell = Text::new(&indicator).color_range(1, ..); } } fn create_token_item( &self, token: &str, created_at: &str, is_read_only: bool, is_selected: bool, column_widths: &ColumnWidths, ) -> (String, Vec<Text>) { if is_selected { if let Some(new_name) = &self.renaming_token { self.create_renaming_item(new_name, created_at, is_read_only, column_widths) } else { self.create_selected_item(token, created_at, is_read_only, column_widths) } } else { self.create_regular_item(token, created_at, is_read_only, column_widths) } } fn create_renaming_item( &self, new_name: &str, created_at: &str, is_read_only: bool, column_widths: &ColumnWidths, ) -> (String, Vec<Text>) { let truncated_name = self.truncate_token_name(new_name, column_widths.token.saturating_sub(1)); // -1 for cursor let item_text = format!("{}_", truncated_name); let date_text = self.format_date(created_at, column_widths.date, true); let read_only_text = self.format_read_only(is_read_only, column_widths.read_only); let controls_text = " ".repeat(column_widths.controls); let token_end = truncated_name.chars().count(); let items = vec![ Text::new(&item_text) .color_range(0, ..token_end + 1) .selected(), Text::new(&date_text), Text::new(&read_only_text).color_all(1), Text::new(&controls_text), ]; ( format!( "{} {} {} {}", item_text, date_text, read_only_text, controls_text ), items, ) } fn create_selected_item( &self, token: &str, created_at: &str, is_read_only: bool, column_widths: &ColumnWidths, ) -> (String, Vec<Text>) { let mut item_text = self.truncate_token_name(token, column_widths.token); if item_text.is_empty() { // otherwise the table gets messed up item_text.push(' '); }; let date_text = self.format_date(created_at, column_widths.date, true); let read_only_text = self.format_read_only(is_read_only, column_widths.read_only); let controls_text = self.format_controls(column_widths.controls, true); // Determine highlight ranges for controls based on the actual content let (x_range, r_range) = if controls_text.contains("revoke") { // Full controls: "(<x> revoke, <r> rename)" (1..=3, 13..=15) } else { // Short controls: "(<x>, <r>)" (1..=3, 6..=8) }; let controls_colored = if controls_text.trim().is_empty() { Text::new(&controls_text).selected() } else { Text::new(&controls_text) .color_range(3, x_range) .color_range(3, r_range) .selected() }; let items = vec![ Text::new(&item_text).color_range(0, ..).selected(), Text::new(&date_text).selected(), Text::new(&read_only_text).color_all(1).selected(), controls_colored, ]; ( format!( "{} {} {} {}", item_text, date_text, read_only_text, controls_text ), items, ) } fn create_regular_item( &self, token: &str, created_at: &str, is_read_only: bool, column_widths: &ColumnWidths, ) -> (String, Vec<Text>) { let mut item_text = self.truncate_token_name(token, column_widths.token); if item_text.is_empty() { // otherwise the table gets messed up item_text.push(' '); }; let date_text = self.format_date(created_at, column_widths.date, true); let read_only_text = self.format_read_only(is_read_only, column_widths.read_only); let controls_text = " ".repeat(column_widths.controls); let items = vec![ Text::new(&item_text).color_range(0, ..), Text::new(&date_text), Text::new(&read_only_text).color_all(1), Text::new(&controls_text), ]; ( format!( "{} {} {} {}", item_text, date_text, read_only_text, controls_text ), items, ) } fn create_new_token_line(&self) -> (String, Text) { let full_create_text = "<n> - create new token, <o> - create read-only token".to_string(); let medium_create_text = "<n> - new token, <o> - read-only".to_string(); let short_create_text = "<n> - new, <o> - RO".to_string(); if let Some(name) = &self.entering_new_token_name { let max_width = self.cols.saturating_sub(1); // Leave room for cursor let truncated_name = if name.chars().count() > max_width { let chars: Vec<char> = name.chars().take(max_width).collect(); chars.into_iter().collect() } else { name.clone() }; let text = format!("{}_", truncated_name); (text.clone(), Text::new(&text).color_range(3, ..)) } else { // Check which text fits let (text_to_use, n_range, o_range) = if full_create_text.chars().count() <= self.cols { (&full_create_text, 0..=2, 24..=26) } else if medium_create_text.chars().count() <= self.cols { (&medium_create_text, 0..=2, 16..=19) } else { (&short_create_text, 0..=2, 11..=14) }; ( text_to_use.to_string(), Text::new(text_to_use) .color_range(3, n_range) .color_range(3, o_range), ) } } fn create_help_line(&self) -> (String, Text) { let (text, highlight_range) = if self.entering_new_token_name.is_some() { ( "Help: Enter optional name for new token, <Enter> to submit", 41..=47, ) } else if self.renaming_token.is_some() { ( "Help: Enter new name for this token, <Enter> to submit", 39..=45, ) } else { ( "Help: <Ctrl x> - revoke all tokens, <Esc> - go back", 6..=13, ) }; let mut help_line = Text::new(text).color_range(3, highlight_range); // Add second highlight for the back option if self.entering_new_token_name.is_none() && self.renaming_token.is_none() { help_line = help_line.color_range(3, 36..=40); } (text.to_string(), help_line) } fn create_status_message(&self) -> Option<(String, Text)> { if let Some(error) = &self.error { Some((error.clone(), Text::new(error).color_range(3, ..))) } else if let Some(info) = &self.info { Some((info.clone(), Text::new(info).color_range(1, ..))) } else { None } } fn calculate_layout(&self, content: &ScreenContent) -> Layout { // Calculate fixed UI elements that must always be present: // - 1 row for title // - 1 row for spacing after title (always preserved) // - token items (variable, potentially truncated) // - 1 row for "create new token" line // - 1 row for spacing before help (always preserved) // - 1 row for help text OR status message (mutually exclusive now) let fixed_ui_rows = 4; // title + spacing after title + spacing before help + help/status let create_new_token_rows = 1; let token_item_rows = content.items.len(); let total_content_rows = fixed_ui_rows + create_new_token_rows + token_item_rows; // Only add top/bottom padding if we have extra space let base_y = if total_content_rows < self.rows { // We have room for padding - center the content (self.rows.saturating_sub(total_content_rows)) / 2 } else { // No room for padding - start at the top 0 }; // Calculate positions relative to base_y let item_start_y = base_y + 2; // title + spacing after title let new_token_y = item_start_y + token_item_rows; let help_y = new_token_y + 1 + 1; // new token line + spacing before help Layout { base_x: (self.cols.saturating_sub(content.max_width) as f64 / 2.0).floor() as usize, base_y, title_x: self.cols.saturating_sub(content.title.0.len()) / 2, new_token_y, help_y, status_y: help_y, // Status message uses the same position as help } } fn print_items_to_screen(&self, content: ScreenContent, layout: Layout) { print_text_with_coordinates(content.title.1, layout.title_x, layout.base_y, None, None); let mut table = Table::new().add_row(vec![" ", " ", " ", " "]); for item in content.items.into_iter() { table = table.add_styled_row(item); } print_table_with_coordinates(table, layout.base_x, layout.base_y + 1, None, None); if let Some((_, new_token_text)) = content.new_token_line { print_text_with_coordinates( new_token_text, layout.base_x, layout.new_token_y, None, None, ); } if let Some((_, status_text)) = content.status_message { print_text_with_coordinates(status_text, layout.base_x, layout.status_y, None, None); } else { print_text_with_coordinates(content.help.1, layout.base_x, layout.help_y, None, None); } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/share/src/token_screen.rs
default-plugins/share/src/token_screen.rs
use zellij_tile::prelude::*; // Constants for text content const TOKEN_LABEL_LONG: &str = "New log-in token: "; const TOKEN_LABEL_SHORT: &str = "Token: "; const EXPLANATION_1_LONG: &str = "Use this token to log-in from the browser."; const EXPLANATION_1_SHORT: &str = "Use to log-in from the browser."; const EXPLANATION_2_LONG: &str = "Copy this token, because it will not be saved and can't be retrieved."; const EXPLANATION_2_SHORT: &str = "It will not be saved and can't be retrieved."; const EXPLANATION_3_LONG: &str = "If lost, it can always be revoked and a new one generated."; const EXPLANATION_3_SHORT: &str = "It can always be revoked and a regenerated."; const ESC_INSTRUCTION: &str = "<Esc> - go back"; // Screen layout constants const SCREEN_HEIGHT: usize = 7; const TOKEN_Y_OFFSET: usize = 0; const EXPLANATION_1_Y_OFFSET: usize = 2; const EXPLANATION_2_Y_OFFSET: usize = 4; const EXPLANATION_3_Y_OFFSET: usize = 5; const ESC_Y_OFFSET: usize = 7; const ERROR_Y_OFFSET: usize = 8; struct TextVariant { long: &'static str, short: &'static str, } impl TextVariant { fn select(&self, cols: usize) -> &'static str { if cols >= self.long.chars().count() { self.long } else { self.short } } } pub struct TokenScreen { token: String, web_server_error: Option<String>, rows: usize, cols: usize, } impl TokenScreen { pub fn new(token: String, web_server_error: Option<String>, rows: usize, cols: usize) -> Self { Self { token, web_server_error, rows, cols, } } pub fn render(&self) { let elements = self.prepare_screen_elements(); let width = self.calculate_max_width(&elements); let (base_x, base_y) = self.calculate_base_position(width); self.render_elements(&elements, base_x, base_y); self.render_error_if_present(base_x, base_y); } fn prepare_screen_elements(&self) -> ScreenElements { let token_variant = TextVariant { long: TOKEN_LABEL_LONG, short: TOKEN_LABEL_SHORT, }; let explanation_variants = [ TextVariant { long: EXPLANATION_1_LONG, short: EXPLANATION_1_SHORT, }, TextVariant { long: EXPLANATION_2_LONG, short: EXPLANATION_2_SHORT, }, TextVariant { long: EXPLANATION_3_LONG, short: EXPLANATION_3_SHORT, }, ]; let token_label = token_variant.select( self.cols .saturating_sub(self.token.chars().count().saturating_sub(1)), ); let token_text = format!("{}{}", token_label, self.token); let token_element = self.create_token_text_element(&token_text, token_label); let explanation_texts: Vec<&str> = explanation_variants .iter() .map(|variant| variant.select(self.cols)) .collect(); let explanation_elements: Vec<Text> = explanation_texts .iter() .enumerate() .map(|(i, &text)| { if i == 0 { Text::new(text).color_range(0, ..) } else { Text::new(text) } }) .collect(); let esc_element = Text::new(ESC_INSTRUCTION).color_range(3, ..=4); ScreenElements { token: token_element, token_text, explanation_texts, explanations: explanation_elements, esc: esc_element, } } fn create_token_text_element(&self, token_text: &str, token_label: &str) -> Text { Text::new(token_text).color_range(2, ..token_label.chars().count()) } fn calculate_max_width(&self, elements: &ScreenElements) -> usize { let token_width = elements.token_text.chars().count(); let explanation_widths = elements .explanation_texts .iter() .map(|text| text.chars().count()); let esc_width = ESC_INSTRUCTION.chars().count(); [token_width, esc_width] .into_iter() .chain(explanation_widths) .max() .unwrap_or(0) } fn calculate_base_position(&self, width: usize) -> (usize, usize) { let base_x = self.cols.saturating_sub(width) / 2; let base_y = self.rows.saturating_sub(SCREEN_HEIGHT) / 2; (base_x, base_y) } fn render_elements(&self, elements: &ScreenElements, base_x: usize, base_y: usize) { print_text_with_coordinates( elements.token.clone(), base_x, base_y + TOKEN_Y_OFFSET, None, None, ); let y_offsets = [ EXPLANATION_1_Y_OFFSET, EXPLANATION_2_Y_OFFSET, EXPLANATION_3_Y_OFFSET, ]; for (explanation, &y_offset) in elements.explanations.iter().zip(y_offsets.iter()) { print_text_with_coordinates(explanation.clone(), base_x, base_y + y_offset, None, None); } print_text_with_coordinates( elements.esc.clone(), base_x, base_y + ESC_Y_OFFSET, None, None, ); } fn render_error_if_present(&self, base_x: usize, base_y: usize) { if let Some(error) = &self.web_server_error { print_text_with_coordinates( Text::new(error).color_range(3, ..), base_x, base_y + ERROR_Y_OFFSET, None, None, ); } } } struct ScreenElements { token: Text, token_text: String, explanation_texts: Vec<&'static str>, explanations: Vec<Text>, esc: Text, }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/resurrectable_sessions.rs
default-plugins/session-manager/src/resurrectable_sessions.rs
use fuzzy_matcher::skim::SkimMatcherV2; use fuzzy_matcher::FuzzyMatcher; use humantime::format_duration; use std::time::Duration; use zellij_tile::shim::*; #[derive(Debug, Default)] pub struct ResurrectableSessions { pub all_resurrectable_sessions: Vec<(String, Duration)>, pub selected_index: Option<usize>, pub selected_search_index: Option<usize>, pub search_results: Vec<SearchResult>, pub is_searching: bool, pub search_term: String, pub delete_all_dead_sessions_warning: bool, } impl ResurrectableSessions { pub fn update(&mut self, mut list: Vec<(String, Duration)>) { list.sort_by(|a, b| a.1.cmp(&b.1)); self.all_resurrectable_sessions = list; if self.is_searching { self.update_search_term(); } } pub fn render(&self, rows: usize, columns: usize, x: usize, y: usize) { if self.delete_all_dead_sessions_warning { self.render_delete_all_sessions_warning(rows, columns, x, y); return; } let search_indication = Text::new(format!("Search: {}_", self.search_term)).color_range(2, ..7); let table_rows = rows.saturating_sub(5); // search row, toggle row and some padding let table_columns = columns; let table = if self.is_searching { self.render_search_results(table_rows, columns) } else { self.render_all_entries(table_rows, columns) }; print_text_with_coordinates(search_indication, x.saturating_sub(1), y + 2, None, None); print_table_with_coordinates(table, x, y + 3, Some(table_columns), Some(table_rows)); } fn render_search_results(&self, table_rows: usize, _table_columns: usize) -> Table { let mut table = Table::new().add_row(vec![" ", " ", " "]); // skip the title row let (first_row_index_to_render, last_row_index_to_render) = self.range_to_render( table_rows, self.search_results.len(), self.selected_search_index, ); for i in first_row_index_to_render..last_row_index_to_render { if let Some(search_result) = self.search_results.get(i) { let is_selected = Some(i) == self.selected_search_index; let mut table_cells = vec![ self.render_session_name( &search_result.session_name, Some(search_result.indices.clone()), ), self.render_ctime(&search_result.ctime), self.render_more_indication_or_enter_as_needed( i, first_row_index_to_render, last_row_index_to_render, self.search_results.len(), is_selected, ), ]; if is_selected { table_cells = table_cells.drain(..).map(|t| t.selected()).collect(); } table = table.add_styled_row(table_cells); } } table } fn render_all_entries(&self, table_rows: usize, _table_columns: usize) -> Table { let mut table = Table::new().add_row(vec![" ", " ", " "]); // skip the title row let (first_row_index_to_render, last_row_index_to_render) = self.range_to_render( table_rows, self.all_resurrectable_sessions.len(), self.selected_index, ); for i in first_row_index_to_render..last_row_index_to_render { if let Some(session) = self.all_resurrectable_sessions.get(i) { let is_selected = Some(i) == self.selected_index; let mut table_cells = vec![ self.render_session_name(&session.0, None), self.render_ctime(&session.1), self.render_more_indication_or_enter_as_needed( i, first_row_index_to_render, last_row_index_to_render, self.all_resurrectable_sessions.len(), is_selected, ), ]; if is_selected { table_cells = table_cells.drain(..).map(|t| t.selected()).collect(); } table = table.add_styled_row(table_cells); } } table } fn render_delete_all_sessions_warning(&self, rows: usize, columns: usize, x: usize, y: usize) { if rows == 0 || columns == 0 { return; } let session_count = self.all_resurrectable_sessions.len(); let session_count_len = session_count.to_string().chars().count(); let warning_description_text = format!("This will delete {} resurrectable sessions", session_count,); let confirmation_text = "Are you sure? (y/n)"; let warning_y_location = y + (rows / 2).saturating_sub(1); let confirmation_y_location = y + (rows / 2) + 1; let warning_x_location = x + columns.saturating_sub(warning_description_text.chars().count()) / 2; let confirmation_x_location = x + columns.saturating_sub(confirmation_text.chars().count()) / 2; print_text_with_coordinates( Text::new(warning_description_text).color_range(0, 17..18 + session_count_len), warning_x_location, warning_y_location, None, None, ); print_text_with_coordinates( Text::new(confirmation_text).color_indices(2, vec![15, 17]), confirmation_x_location, confirmation_y_location, None, None, ); } fn range_to_render( &self, table_rows: usize, results_len: usize, selected_index: Option<usize>, ) -> (usize, usize) { if table_rows <= results_len { let row_count_to_render = table_rows.saturating_sub(1); // 1 for the title let first_row_index_to_render = selected_index .unwrap_or(0) .saturating_sub(row_count_to_render / 2); let last_row_index_to_render = first_row_index_to_render + row_count_to_render; (first_row_index_to_render, last_row_index_to_render) } else { let first_row_index_to_render = 0; let last_row_index_to_render = results_len; (first_row_index_to_render, last_row_index_to_render) } } fn render_session_name(&self, session_name: &str, indices: Option<Vec<usize>>) -> Text { let text = Text::new(&session_name).color_range(0, ..); match indices { Some(indices) => text.color_indices(1, indices), None => text, } } fn render_ctime(&self, ctime: &Duration) -> Text { let duration = format_duration(ctime.clone()).to_string(); let duration_parts = duration.split_whitespace(); let mut formatted_duration = String::new(); for part in duration_parts { if !part.ends_with('s') { if !formatted_duration.is_empty() { formatted_duration.push(' '); } formatted_duration.push_str(part); } } if formatted_duration.is_empty() { formatted_duration.push_str("<1m"); } let duration_len = formatted_duration.chars().count(); Text::new(format!("Created {} ago", formatted_duration)).color_range(2, 8..9 + duration_len) } fn render_more_indication_or_enter_as_needed( &self, i: usize, first_row_index_to_render: usize, last_row_index_to_render: usize, results_len: usize, is_selected: bool, ) -> Text { if is_selected { Text::new(format!("<ENTER> - Resurrect Session")).color_range(3, 0..7) } else if i == first_row_index_to_render && i > 0 { Text::new(format!("+ {} more", first_row_index_to_render)).color_range(1, ..) } else if i == last_row_index_to_render.saturating_sub(1) && last_row_index_to_render < results_len { Text::new(format!( "+ {} more", results_len.saturating_sub(last_row_index_to_render) )) .color_range(1, ..) } else { Text::new(" ") } } pub fn move_selection_down(&mut self) { if self.is_searching { if let Some(selected_index) = self.selected_search_index.as_mut() { if *selected_index == self.search_results.len().saturating_sub(1) { *selected_index = 0; } else { *selected_index = *selected_index + 1; } } else { self.selected_search_index = Some(0); } } else { if let Some(selected_index) = self.selected_index.as_mut() { if *selected_index == self.all_resurrectable_sessions.len().saturating_sub(1) { *selected_index = 0; } else { *selected_index = *selected_index + 1; } } else { self.selected_index = Some(0); } } } pub fn move_selection_up(&mut self) { if self.is_searching { if let Some(selected_index) = self.selected_search_index.as_mut() { if *selected_index == 0 { *selected_index = self.search_results.len().saturating_sub(1); } else { *selected_index = selected_index.saturating_sub(1); } } else { self.selected_search_index = Some(self.search_results.len().saturating_sub(1)); } } else { if let Some(selected_index) = self.selected_index.as_mut() { if *selected_index == 0 { *selected_index = self.all_resurrectable_sessions.len().saturating_sub(1); } else { *selected_index = selected_index.saturating_sub(1); } } else { self.selected_index = Some(self.all_resurrectable_sessions.len().saturating_sub(1)); } } } pub fn get_selected_session_name(&self) -> Option<String> { if self.is_searching { self.selected_search_index .and_then(|i| self.search_results.get(i)) .map(|search_result| search_result.session_name.clone()) } else { self.selected_index .and_then(|i| self.all_resurrectable_sessions.get(i)) .map(|session_name_and_creation_time| session_name_and_creation_time.0.clone()) } } pub fn delete_selected_session(&mut self) { if self.is_searching { self.selected_search_index .and_then(|i| self.search_results.get(i)) .map(|search_result| delete_dead_session(&search_result.session_name)); } else { self.selected_index .and_then(|i| { if self.all_resurrectable_sessions.len() > i { // optimistic update if i == 0 { self.selected_index = None; } else if i == self.all_resurrectable_sessions.len().saturating_sub(1) { self.selected_index = Some(i.saturating_sub(1)); } Some(self.all_resurrectable_sessions.remove(i)) } else { None } }) .map(|session_name_and_creation_time| { delete_dead_session(&session_name_and_creation_time.0) }); } } fn delete_all_sessions(&mut self) { // optimistic update self.all_resurrectable_sessions = vec![]; self.delete_all_dead_sessions_warning = false; delete_all_dead_sessions(); } pub fn show_delete_all_sessions_warning(&mut self) { self.delete_all_dead_sessions_warning = true; } pub fn handle_character(&mut self, character: char) { if self.delete_all_dead_sessions_warning && character == 'y' { self.delete_all_sessions(); } else if self.delete_all_dead_sessions_warning && character == 'n' { self.delete_all_dead_sessions_warning = false; } else { self.search_term.push(character); self.update_search_term(); } } pub fn handle_backspace(&mut self) { self.search_term.pop(); self.update_search_term(); } pub fn has_session(&self, session_name: &str) -> bool { self.all_resurrectable_sessions .iter() .any(|s| s.0 == session_name) } fn update_search_term(&mut self) { let mut matches = vec![]; let matcher = SkimMatcherV2::default().use_cache(true); for (session_name, ctime) in &self.all_resurrectable_sessions { if let Some((score, indices)) = matcher.fuzzy_indices(&session_name, &self.search_term) { matches.push(SearchResult { session_name: session_name.to_owned(), ctime: ctime.clone(), score, indices, }); } } matches.sort_by(|a, b| b.score.cmp(&a.score)); self.search_results = matches; self.is_searching = !self.search_term.is_empty(); match self.selected_search_index { Some(search_index) => { if self.search_results.is_empty() { self.selected_search_index = None; } else if search_index >= self.search_results.len() { self.selected_search_index = Some(self.search_results.len().saturating_sub(1)); } }, None => { self.selected_search_index = Some(0); }, } } } #[derive(Debug)] pub struct SearchResult { score: i64, indices: Vec<usize>, session_name: String, ctime: Duration, }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/main.rs
default-plugins/session-manager/src/main.rs
mod new_session_info; mod resurrectable_sessions; mod session_list; mod ui; use std::collections::BTreeMap; use uuid::Uuid; use zellij_tile::prelude::*; use new_session_info::NewSessionInfo; use ui::{ components::{ render_controls_line, render_error, render_new_session_block, render_prompt, render_renaming_session_screen, render_screen_toggle, Colors, }, welcome_screen::{render_banner, render_welcome_boundaries}, SessionUiInfo, }; use resurrectable_sessions::ResurrectableSessions; use session_list::SessionList; #[derive(Clone, Debug, Copy)] enum ActiveScreen { NewSession, AttachToSession, ResurrectSession, } impl Default for ActiveScreen { fn default() -> Self { ActiveScreen::AttachToSession } } #[derive(Default)] struct State { session_name: Option<String>, sessions: SessionList, resurrectable_sessions: ResurrectableSessions, search_term: String, new_session_info: NewSessionInfo, renaming_session_name: Option<String>, error: Option<String>, active_screen: ActiveScreen, colors: Colors, is_welcome_screen: bool, show_kill_all_sessions_warning: bool, request_ids: Vec<String>, is_web_client: bool, } register_plugin!(State); impl ZellijPlugin for State { fn load(&mut self, configuration: BTreeMap<String, String>) { self.is_welcome_screen = configuration .get("welcome_screen") .map(|v| v == "true") .unwrap_or(false); if self.is_welcome_screen { self.active_screen = ActiveScreen::NewSession; } subscribe(&[ EventType::ModeUpdate, EventType::SessionUpdate, EventType::Key, EventType::RunCommandResult, ]); } fn pipe(&mut self, pipe_message: PipeMessage) -> bool { if pipe_message.name == "filepicker_result" { match (pipe_message.payload, pipe_message.args.get("request_id")) { (Some(payload), Some(request_id)) => { match self.request_ids.iter().position(|p| p == request_id) { Some(request_id_position) => { self.request_ids.remove(request_id_position); let new_session_folder = std::path::PathBuf::from(payload); self.new_session_info.new_session_folder = Some(new_session_folder); }, None => { eprintln!("request id not found"); }, } }, _ => {}, } true } else { false } } fn update(&mut self, event: Event) -> bool { let mut should_render = false; match event { Event::ModeUpdate(mode_info) => { self.colors = Colors::new(mode_info.style.colors); self.is_web_client = mode_info.is_web_client.unwrap_or(false); should_render = true; }, Event::Key(key) => { should_render = self.handle_key(key); }, Event::PermissionRequestResult(_result) => { should_render = true; }, Event::SessionUpdate(session_infos, resurrectable_session_list) => { for session_info in &session_infos { if session_info.is_current_session { self.new_session_info .update_layout_list(session_info.available_layouts.clone()); } } self.resurrectable_sessions .update(resurrectable_session_list); self.update_session_infos(session_infos); should_render = true; }, _ => (), }; should_render } fn render(&mut self, rows: usize, cols: usize) { let (x, y, width, height) = self.main_menu_size(rows, cols); let background = self.colors.palette.text_unselected.background; if self.is_welcome_screen { render_banner(x, 0, rows.saturating_sub(height), width); } render_screen_toggle( self.active_screen, x, y, width.saturating_sub(2), &background, ); match self.active_screen { ActiveScreen::NewSession => { render_new_session_block( &self.new_session_info, self.colors, height.saturating_sub(2), width, x, y + 2, ); }, ActiveScreen::AttachToSession => { if let Some(new_session_name) = self.renaming_session_name.as_ref() { render_renaming_session_screen(&new_session_name, height, width, x, y + 2); } else if self.show_kill_all_sessions_warning { self.render_kill_all_sessions_warning(height, width, x, y); } else { render_prompt(&self.search_term, self.colors, x, y + 2); let room_for_list = height.saturating_sub(6); // search line and controls; self.sessions.update_rows(room_for_list); let list = self.sessions .render(room_for_list, width.saturating_sub(7), self.colors); // 7 for various ui for (i, line) in list.iter().enumerate() { print!("\u{1b}[{};{}H{}", y + i + 5, x, line.render()); } } }, ActiveScreen::ResurrectSession => { self.resurrectable_sessions.render(height, width, x, y); }, } if let Some(error) = self.error.as_ref() { render_error(&error, height, width, x, y); } else { render_controls_line(self.active_screen, width, self.colors, x + 1, rows); } if self.is_welcome_screen { render_welcome_boundaries(rows, cols); // explicitly done in the end to override some // stuff, see comment in function } } } impl State { fn reset_selected_index(&mut self) { self.sessions.reset_selected_index(); } fn handle_key(&mut self, key: KeyWithModifier) -> bool { if self.error.is_some() { self.error = None; return true; } match self.active_screen { ActiveScreen::NewSession => self.handle_new_session_key(key), ActiveScreen::AttachToSession => self.handle_attach_to_session(key), ActiveScreen::ResurrectSession => self.handle_resurrect_session_key(key), } } fn handle_new_session_key(&mut self, key: KeyWithModifier) -> bool { let mut should_render = false; match key.bare_key { BareKey::Down if key.has_no_modifiers() => { self.new_session_info.handle_key(key); should_render = true; }, BareKey::Up if key.has_no_modifiers() => { self.new_session_info.handle_key(key); should_render = true; }, BareKey::Enter if key.has_no_modifiers() => { self.handle_selection(); should_render = true; }, BareKey::Char(character) if key.has_no_modifiers() => { if character == '\n' { self.handle_selection(); } else { self.new_session_info.handle_key(key); } should_render = true; }, BareKey::Backspace if key.has_no_modifiers() => { self.new_session_info.handle_key(key); should_render = true; }, BareKey::Char('w') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.active_screen = ActiveScreen::NewSession; should_render = true; }, BareKey::Tab if key.has_no_modifiers() => { self.toggle_active_screen(); should_render = true; }, BareKey::Char('f') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let request_id = Uuid::new_v4(); let mut config = BTreeMap::new(); let mut args = BTreeMap::new(); self.request_ids.push(request_id.to_string()); // we insert this into the config so that a new plugin will be opened (the plugin's // uniqueness is determined by its name/url as well as its config) config.insert("request_id".to_owned(), request_id.to_string()); // we also insert this into the args so that the plugin will have an easier access to // it args.insert("request_id".to_owned(), request_id.to_string()); pipe_message_to_plugin( MessageToPlugin::new("filepicker") .with_plugin_url("filepicker") .with_plugin_config(config) .new_plugin_instance_should_have_pane_title( "Select folder for the new session...", ) .new_plugin_instance_should_be_focused() .with_args(args), ); should_render = true; }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.new_session_info.new_session_folder = None; should_render = true; }, BareKey::Esc if key.has_no_modifiers() => { self.new_session_info.handle_key(key); should_render = true; }, _ => {}, } should_render } fn handle_attach_to_session(&mut self, key: KeyWithModifier) -> bool { let mut should_render = false; if self.show_kill_all_sessions_warning { match key.bare_key { BareKey::Char('y') if key.has_no_modifiers() => { let all_other_sessions = self.sessions.all_other_sessions(); kill_sessions(&all_other_sessions); self.reset_selected_index(); self.search_term.clear(); self.sessions .update_search_term(&self.search_term, &self.colors); self.show_kill_all_sessions_warning = false; should_render = true; }, BareKey::Char('n') | BareKey::Esc if key.has_no_modifiers() => { self.show_kill_all_sessions_warning = false; should_render = true; }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.show_kill_all_sessions_warning = false; should_render = true; }, _ => {}, } } else { match key.bare_key { BareKey::Right if key.has_no_modifiers() => { self.sessions.result_expand(); should_render = true; }, BareKey::Left if key.has_no_modifiers() => { self.sessions.result_shrink(); should_render = true; }, BareKey::Down if key.has_no_modifiers() => { self.sessions.move_selection_down(); should_render = true; }, BareKey::Up if key.has_no_modifiers() => { self.sessions.move_selection_up(); should_render = true; }, BareKey::Enter if key.has_no_modifiers() => { self.handle_selection(); should_render = true; }, BareKey::Char(character) if key.has_no_modifiers() => { if character == '\n' { self.handle_selection(); } else if let Some(new_session_name) = self.renaming_session_name.as_mut() { new_session_name.push(character); } else { self.search_term.push(character); self.sessions .update_search_term(&self.search_term, &self.colors); } should_render = true; }, BareKey::Backspace if key.has_no_modifiers() => { if let Some(new_session_name) = self.renaming_session_name.as_mut() { if new_session_name.is_empty() { self.renaming_session_name = None; } else { new_session_name.pop(); } } else { self.search_term.pop(); self.sessions .update_search_term(&self.search_term, &self.colors); } should_render = true; }, BareKey::Char('w') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.active_screen = ActiveScreen::NewSession; should_render = true; }, BareKey::Char('r') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.renaming_session_name = Some(String::new()); should_render = true; }, BareKey::Delete if key.has_no_modifiers() => { if let Some(selected_session_name) = self.sessions.get_selected_session_name() { kill_sessions(&[selected_session_name]); self.reset_selected_index(); self.search_term.clear(); self.sessions .update_search_term(&self.search_term, &self.colors); } else { self.show_error("Must select session before killing it."); } should_render = true; }, BareKey::Char('d') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let all_other_sessions = self.sessions.all_other_sessions(); if all_other_sessions.is_empty() { self.show_error("No other sessions to kill. Quit to kill the current one."); } else { self.show_kill_all_sessions_warning = true; } should_render = true; }, BareKey::Char('x') if key.has_modifiers(&[KeyModifier::Ctrl]) => { disconnect_other_clients() }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Ctrl]) => { if !self.search_term.is_empty() { self.search_term.clear(); self.sessions .update_search_term(&self.search_term, &self.colors); self.reset_selected_index(); } else if !self.is_welcome_screen { self.reset_selected_index(); hide_self(); } should_render = true; }, BareKey::Tab if key.has_no_modifiers() => { self.toggle_active_screen(); should_render = true; }, BareKey::Esc if key.has_no_modifiers() => { if self.renaming_session_name.is_some() { self.renaming_session_name = None; should_render = true; } else if !self.is_welcome_screen { hide_self(); } }, _ => {}, } } should_render } fn handle_resurrect_session_key(&mut self, key: KeyWithModifier) -> bool { let mut should_render = false; match key.bare_key { BareKey::Down if key.has_no_modifiers() => { self.resurrectable_sessions.move_selection_down(); should_render = true; }, BareKey::Up if key.has_no_modifiers() => { self.resurrectable_sessions.move_selection_up(); should_render = true; }, BareKey::Enter if key.has_no_modifiers() => { self.handle_selection(); should_render = true; }, BareKey::Char(character) if key.has_no_modifiers() => { if character == '\n' { self.handle_selection(); } else { self.resurrectable_sessions.handle_character(character); } should_render = true; }, BareKey::Backspace if key.has_no_modifiers() => { self.resurrectable_sessions.handle_backspace(); should_render = true; }, BareKey::Char('w') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.active_screen = ActiveScreen::NewSession; should_render = true; }, BareKey::Tab if key.has_no_modifiers() => { self.toggle_active_screen(); should_render = true; }, BareKey::Delete if key.has_no_modifiers() => { self.resurrectable_sessions.delete_selected_session(); should_render = true; }, BareKey::Char('d') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.resurrectable_sessions .show_delete_all_sessions_warning(); should_render = true; }, BareKey::Esc if key.has_no_modifiers() => { if !self.is_welcome_screen { hide_self(); } }, _ => {}, } should_render } fn handle_selection(&mut self) { match self.active_screen { ActiveScreen::NewSession => { if self.new_session_info.name().len() >= 108 { // this is due to socket path limitations // TODO: get this from Zellij (for reference: this is part of the interprocess // package, we should get if from there if possible because it's configurable // through the package) self.show_error("Session name must be shorter than 108 bytes"); return; } else if self.new_session_info.name().contains('/') { self.show_error("Session name cannot contain '/'"); return; } else if self .sessions .has_forbidden_session(self.new_session_info.name()) { self.show_error("This session exists and web clients cannot attach to it."); return; } self.new_session_info.handle_selection(&self.session_name); }, ActiveScreen::AttachToSession => { if let Some(renaming_session_name) = &self.renaming_session_name.take() { if renaming_session_name.is_empty() { self.show_error("New name must not be empty."); return; // so that we don't hide self } else if self.session_name.as_ref() == Some(renaming_session_name) { // noop - we're already called that! return; // so that we don't hide self } else if self.sessions.has_session(&renaming_session_name) { self.show_error("A session by this name already exists."); return; // so that we don't hide self } else if self .resurrectable_sessions .has_session(&renaming_session_name) { self.show_error("A resurrectable session by this name already exists."); return; // s that we don't hide self } else { if renaming_session_name.contains('/') { self.show_error("Session names cannot contain '/'"); return; } self.update_current_session_name_in_ui(&renaming_session_name); rename_session(&renaming_session_name); return; // s that we don't hide self } } if let Some(selected_session_name) = self.sessions.get_selected_session_name() { let selected_tab = self.sessions.get_selected_tab_position(); let selected_pane = self.sessions.get_selected_pane_id(); let is_current_session = self.sessions.selected_is_current_session(); if is_current_session { if let Some((pane_id, is_plugin)) = selected_pane { if is_plugin { focus_plugin_pane(pane_id, true, false); } else { focus_terminal_pane(pane_id, true, false); } } else if let Some(tab_position) = selected_tab { go_to_tab(tab_position as u32); } else { self.show_error("Already attached..."); } } else { switch_session_with_focus( &selected_session_name, selected_tab, selected_pane, ); } } self.reset_selected_index(); self.search_term.clear(); self.sessions .update_search_term(&self.search_term, &self.colors); if !self.is_welcome_screen { // we usually don't want to hide_self() if we're the welcome screen because // unless the user did something odd like opening an extra pane/tab in the // welcome screen, this will result in the current session closing, as this is // the last selectable pane... hide_self(); } }, ActiveScreen::ResurrectSession => { if let Some(session_name_to_resurrect) = self.resurrectable_sessions.get_selected_session_name() { switch_session(Some(&session_name_to_resurrect)); } }, } } fn toggle_active_screen(&mut self) { self.active_screen = match self.active_screen { ActiveScreen::NewSession => ActiveScreen::AttachToSession, ActiveScreen::AttachToSession => ActiveScreen::ResurrectSession, ActiveScreen::ResurrectSession => ActiveScreen::NewSession, }; } fn show_error(&mut self, error_text: &str) { self.error = Some(error_text.to_owned()); } fn update_current_session_name_in_ui(&mut self, new_name: &str) { if let Some(old_session_name) = self.session_name.as_ref() { self.sessions .update_session_name(&old_session_name, new_name); } self.session_name = Some(new_name.to_owned()); } fn update_session_infos(&mut self, session_infos: Vec<SessionInfo>) { let session_ui_infos: Vec<SessionUiInfo> = session_infos .iter() .filter_map(|s| { if self.is_web_client && !s.web_clients_allowed { None } else if self.is_welcome_screen && s.is_current_session { // do not display current session if we're the welcome screen // because: // 1. attaching to the welcome screen from the welcome screen is not a thing // 2. it can cause issues on the web (since we're disconnecting and // reconnecting to a session we just closed by disconnecting...) None } else { Some(SessionUiInfo::from_session_info(s)) } }) .collect(); let forbidden_sessions: Vec<SessionUiInfo> = session_infos .iter() .filter_map(|s| { if self.is_web_client && !s.web_clients_allowed { Some(SessionUiInfo::from_session_info(s)) } else { None } }) .collect(); let current_session_name = session_infos.iter().find_map(|s| { if s.is_current_session { Some(s.name.clone()) } else { None } }); if let Some(current_session_name) = current_session_name { self.session_name = Some(current_session_name); } self.sessions .set_sessions(session_ui_infos, forbidden_sessions); } fn main_menu_size(&self, rows: usize, cols: usize) -> (usize, usize, usize, usize) { // x, y, width, height let width = if self.is_welcome_screen { std::cmp::min(cols, 101) } else { cols }; let x = if self.is_welcome_screen { (cols.saturating_sub(width) as f64 / 2.0).floor() as usize + 2 } else { 0 }; let y = if self.is_welcome_screen { (rows.saturating_sub(15) as f64 / 2.0).floor() as usize } else { 0 }; let height = rows.saturating_sub(y); (x, y, width, height) } fn render_kill_all_sessions_warning(&self, rows: usize, columns: usize, x: usize, y: usize) { if rows == 0 || columns == 0 { return; } let session_count = self.sessions.all_other_sessions().len(); let session_count_len = session_count.to_string().chars().count(); let warning_description_text = format!("This will kill {} active sessions", session_count); let confirmation_text = "Are you sure? (y/n)"; let warning_y_location = y + (rows / 2).saturating_sub(1); let confirmation_y_location = y + (rows / 2) + 1; let warning_x_location = x + columns.saturating_sub(warning_description_text.chars().count()) / 2; let confirmation_x_location = x + columns.saturating_sub(confirmation_text.chars().count()) / 2; print_text_with_coordinates( Text::new(warning_description_text).color_range(0, 15..16 + session_count_len), warning_x_location, warning_y_location, None, None, ); print_text_with_coordinates( Text::new(confirmation_text).color_indices(2, vec![15, 17]), confirmation_x_location, confirmation_y_location, None, None, ); } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/new_session_info.rs
default-plugins/session-manager/src/new_session_info.rs
use fuzzy_matcher::skim::SkimMatcherV2; use fuzzy_matcher::FuzzyMatcher; use std::path::PathBuf; use zellij_tile::prelude::*; #[derive(Default)] pub struct NewSessionInfo { name: String, layout_list: LayoutList, entering_new_session_info: EnteringState, pub new_session_folder: Option<PathBuf>, } #[derive(Eq, PartialEq)] enum EnteringState { EnteringName, EnteringLayoutSearch, } impl Default for EnteringState { fn default() -> Self { EnteringState::EnteringName } } impl NewSessionInfo { pub fn name(&self) -> &str { &self.name } pub fn layout_search_term(&self) -> &str { &self.layout_list.layout_search_term } pub fn entering_new_session_name(&self) -> bool { self.entering_new_session_info == EnteringState::EnteringName } pub fn entering_layout_search_term(&self) -> bool { self.entering_new_session_info == EnteringState::EnteringLayoutSearch } pub fn add_char(&mut self, character: char) { match self.entering_new_session_info { EnteringState::EnteringName => { self.name.push(character); }, EnteringState::EnteringLayoutSearch => { self.layout_list.layout_search_term.push(character); self.update_layout_search_term(); }, } } pub fn handle_backspace(&mut self) { match self.entering_new_session_info { EnteringState::EnteringName => { self.name.pop(); }, EnteringState::EnteringLayoutSearch => { self.layout_list.layout_search_term.pop(); self.update_layout_search_term(); }, } } pub fn handle_break(&mut self) { match self.entering_new_session_info { EnteringState::EnteringName => { self.name.clear(); }, EnteringState::EnteringLayoutSearch => { self.layout_list.layout_search_term.clear(); self.entering_new_session_info = EnteringState::EnteringName; self.update_layout_search_term(); }, } } pub fn handle_key(&mut self, key: KeyWithModifier) { match key.bare_key { BareKey::Backspace if key.has_no_modifiers() => { self.handle_backspace(); }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.handle_break(); }, BareKey::Esc if key.has_no_modifiers() => { self.handle_break(); }, BareKey::Char(character) if key.has_no_modifiers() => { self.add_char(character); }, BareKey::Up if key.has_no_modifiers() => { self.move_selection_up(); }, BareKey::Down if key.has_no_modifiers() => { self.move_selection_down(); }, _ => {}, } } pub fn handle_selection(&mut self, current_session_name: &Option<String>) { match self.entering_new_session_info { EnteringState::EnteringLayoutSearch => { let new_session_layout: Option<LayoutInfo> = self.selected_layout_info(); let new_session_name = if self.name.is_empty() { None } else { Some(self.name.as_str()) }; if new_session_name != current_session_name.as_ref().map(|s| s.as_str()) { match new_session_layout { Some(new_session_layout) => { let cwd = self.new_session_folder.as_ref().map(|c| PathBuf::from(c)); switch_session_with_layout(new_session_name, new_session_layout, cwd) }, None => { switch_session(new_session_name); }, } } self.name.clear(); self.layout_list.clear_selection(); hide_self(); }, EnteringState::EnteringName => { self.entering_new_session_info = EnteringState::EnteringLayoutSearch; }, } } pub fn update_layout_list(&mut self, layout_info: Vec<LayoutInfo>) { self.layout_list.update_layout_list(layout_info); } pub fn layout_list(&self, max_rows: usize) -> Vec<(LayoutInfo, bool)> { // bool - is_selected let range_to_render = self.range_to_render( max_rows, self.layout_count(), Some(self.layout_list.selected_layout_index), ); self.layout_list .layout_list .iter() .enumerate() .map(|(i, l)| (l.clone(), i == self.layout_list.selected_layout_index)) .take(range_to_render.1) .skip(range_to_render.0) .collect() } pub fn layouts_to_render(&self, max_rows: usize) -> Vec<(LayoutInfo, Vec<usize>, bool)> { // (layout_info, // search_indices, // is_selected) if self.is_searching() { self.layout_search_results(max_rows) .into_iter() .map(|(layout_search_result, is_selected)| { ( layout_search_result.layout_info, layout_search_result.indices, is_selected, ) }) .collect() } else { self.layout_list(max_rows) .into_iter() .map(|(layout_info, is_selected)| (layout_info, vec![], is_selected)) .collect() } } pub fn layout_search_results(&self, max_rows: usize) -> Vec<(LayoutSearchResult, bool)> { // bool - is_selected let range_to_render = self.range_to_render( max_rows, self.layout_list.layout_search_results.len(), Some(self.layout_list.selected_layout_index), ); self.layout_list .layout_search_results .iter() .enumerate() .map(|(i, l)| (l.clone(), i == self.layout_list.selected_layout_index)) .take(range_to_render.1) .skip(range_to_render.0) .collect() } // TODO: merge with similar function in resurrectable_sessions fn range_to_render( &self, table_rows: usize, results_len: usize, selected_index: Option<usize>, ) -> (usize, usize) { if table_rows <= results_len { let row_count_to_render = table_rows.saturating_sub(1); // 1 for the title let first_row_index_to_render = selected_index .unwrap_or(0) .saturating_sub(row_count_to_render / 2); let last_row_index_to_render = first_row_index_to_render + row_count_to_render; (first_row_index_to_render, last_row_index_to_render) } else { let first_row_index_to_render = 0; let last_row_index_to_render = results_len; (first_row_index_to_render, last_row_index_to_render) } } pub fn is_searching(&self) -> bool { !self.layout_list.layout_search_term.is_empty() } pub fn layout_count(&self) -> usize { self.layout_list.layout_list.len() } pub fn selected_layout_info(&self) -> Option<LayoutInfo> { self.layout_list.selected_layout_info() } fn update_layout_search_term(&mut self) { if self.layout_list.layout_search_term.is_empty() { self.layout_list.clear_selection(); self.layout_list.layout_search_results = vec![]; } else { let mut matches = vec![]; let matcher = SkimMatcherV2::default().use_cache(true); for layout_info in &self.layout_list.layout_list { if let Some((score, indices)) = matcher.fuzzy_indices(&layout_info.name(), &self.layout_list.layout_search_term) { matches.push(LayoutSearchResult { layout_info: layout_info.clone(), score, indices, }); } } matches.sort_by(|a, b| b.score.cmp(&a.score)); self.layout_list.layout_search_results = matches; self.layout_list.clear_selection(); } } fn move_selection_up(&mut self) { self.layout_list.move_selection_up(); } fn move_selection_down(&mut self) { self.layout_list.move_selection_down(); } } #[derive(Default)] pub struct LayoutList { layout_list: Vec<LayoutInfo>, layout_search_results: Vec<LayoutSearchResult>, selected_layout_index: usize, layout_search_term: String, } impl LayoutList { pub fn update_layout_list(&mut self, layout_list: Vec<LayoutInfo>) { let old_layout_length = self.layout_list.len(); self.layout_list = layout_list; if old_layout_length != self.layout_list.len() { // honestly, this is just the UX choice that sucks the least... self.clear_selection(); } } pub fn selected_layout_info(&self) -> Option<LayoutInfo> { if !self.layout_search_term.is_empty() { self.layout_search_results .get(self.selected_layout_index) .map(|l| l.layout_info.clone()) } else { self.layout_list.get(self.selected_layout_index).cloned() } } pub fn clear_selection(&mut self) { self.selected_layout_index = 0; } fn max_index(&self) -> usize { if self.layout_search_term.is_empty() { self.layout_list.len().saturating_sub(1) } else { self.layout_search_results.len().saturating_sub(1) } } fn move_selection_up(&mut self) { let max_index = self.max_index(); if self.selected_layout_index > 0 { self.selected_layout_index -= 1; } else { self.selected_layout_index = max_index; } } fn move_selection_down(&mut self) { let max_index = self.max_index(); if self.selected_layout_index < max_index { self.selected_layout_index += 1; } else { self.selected_layout_index = 0; } } } #[derive(Clone)] pub struct LayoutSearchResult { pub layout_info: LayoutInfo, pub score: i64, pub indices: Vec<usize>, }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/session_list.rs
default-plugins/session-manager/src/session_list.rs
use fuzzy_matcher::skim::SkimMatcherV2; use fuzzy_matcher::FuzzyMatcher; use crate::ui::{ components::{Colors, LineToRender, ListItem}, SessionUiInfo, }; #[derive(Debug, Default)] pub struct SessionList { pub session_ui_infos: Vec<SessionUiInfo>, pub forbidden_sessions: Vec<SessionUiInfo>, pub selected_index: SelectedIndex, pub selected_search_index: Option<usize>, pub search_results: Vec<SearchResult>, pub is_searching: bool, } impl SessionList { pub fn set_sessions( &mut self, mut session_ui_infos: Vec<SessionUiInfo>, mut forbidden_sessions: Vec<SessionUiInfo>, ) { session_ui_infos.sort_unstable_by(|a, b| { if a.is_current_session { std::cmp::Ordering::Less } else if b.is_current_session { std::cmp::Ordering::Greater } else { a.name.cmp(&b.name) } }); forbidden_sessions.sort_unstable_by(|a, b| a.name.cmp(&b.name)); self.session_ui_infos = session_ui_infos; self.forbidden_sessions = forbidden_sessions; } pub fn update_search_term(&mut self, search_term: &str, colors: &Colors) { let mut flattened_assets = self.flatten_assets(colors); let mut matches = vec![]; let matcher = SkimMatcherV2::default().use_cache(true); for (list_item, session_name, tab_position, pane_id, is_current_session) in flattened_assets.drain(..) { if let Some((score, indices)) = matcher.fuzzy_indices(&list_item.name, &search_term) { matches.push(SearchResult::new( score, indices, list_item, session_name, tab_position, pane_id, is_current_session, )); } } matches.sort_by(|a, b| b.score.cmp(&a.score)); self.search_results = matches; self.is_searching = !search_term.is_empty(); self.selected_search_index = Some(0); } fn flatten_assets( &self, colors: &Colors, ) -> Vec<(ListItem, String, Option<usize>, Option<(u32, bool)>, bool)> { // list_item, session_name, tab_position, (pane_id, is_plugin), is_current_session let mut list_items = vec![]; for session in &self.session_ui_infos { let session_name = session.name.clone(); let is_current_session = session.is_current_session; list_items.push(( ListItem::from_session_info(session, *colors), session_name.clone(), None, None, is_current_session, )); for tab in &session.tabs { let tab_position = tab.position; list_items.push(( ListItem::from_tab_info(session, tab, *colors), session_name.clone(), Some(tab_position), None, is_current_session, )); for pane in &tab.panes { let pane_id = (pane.pane_id, pane.is_plugin); list_items.push(( ListItem::from_pane_info(session, tab, pane, *colors), session_name.clone(), Some(tab_position), Some(pane_id), is_current_session, )); } } } list_items } pub fn get_selected_session_name(&self) -> Option<String> { if self.is_searching { self.selected_search_index .and_then(|i| self.search_results.get(i)) .map(|s| s.session_name.clone()) } else { self.selected_index .0 .and_then(|i| self.session_ui_infos.get(i)) .map(|s_i| s_i.name.clone()) } } pub fn selected_is_current_session(&self) -> bool { if self.is_searching { self.selected_search_index .and_then(|i| self.search_results.get(i)) .map(|s| s.is_current_session) .unwrap_or(false) } else { self.selected_index .0 .and_then(|i| self.session_ui_infos.get(i)) .map(|s_i| s_i.is_current_session) .unwrap_or(false) } } pub fn get_selected_tab_position(&self) -> Option<usize> { if self.is_searching { self.selected_search_index .and_then(|i| self.search_results.get(i)) .and_then(|s| s.tab_position) } else { self.selected_index .0 .and_then(|i| self.session_ui_infos.get(i)) .and_then(|s_i| { self.selected_index .1 .and_then(|i| s_i.tabs.get(i)) .map(|t| t.position) }) } } pub fn get_selected_pane_id(&self) -> Option<(u32, bool)> { // (pane_id, is_plugin) if self.is_searching { self.selected_search_index .and_then(|i| self.search_results.get(i)) .and_then(|s| s.pane_id) } else { self.selected_index .0 .and_then(|i| self.session_ui_infos.get(i)) .and_then(|s_i| { self.selected_index .1 .and_then(|i| s_i.tabs.get(i)) .and_then(|t| { self.selected_index .2 .and_then(|i| t.panes.get(i)) .map(|p| (p.pane_id, p.is_plugin)) }) }) } } pub fn move_selection_down(&mut self) { if self.is_searching { match self.selected_search_index.as_mut() { Some(search_index) => { *search_index = search_index.saturating_add(1); }, None => { if !self.search_results.is_empty() { self.selected_search_index = Some(0); } }, } } else { match self.selected_index { SelectedIndex(None, None, None) => { if !self.session_ui_infos.is_empty() { self.selected_index.0 = Some(0); } }, SelectedIndex(Some(selected_session), None, None) => { if self.session_ui_infos.len() > selected_session + 1 { self.selected_index.0 = Some(selected_session + 1); } else { self.selected_index.0 = None; self.selected_index.1 = None; self.selected_index.2 = None; } }, SelectedIndex(Some(selected_session), Some(selected_tab), None) => { if self .get_session(selected_session) .map(|s| s.tabs.len() > selected_tab + 1) .unwrap_or(false) { self.selected_index.1 = Some(selected_tab + 1); } else { self.selected_index.1 = Some(0); } }, SelectedIndex(Some(selected_session), Some(selected_tab), Some(selected_pane)) => { if self .get_session(selected_session) .and_then(|s| s.tabs.get(selected_tab)) .map(|t| t.panes.len() > selected_pane + 1) .unwrap_or(false) { self.selected_index.2 = Some(selected_pane + 1); } else { self.selected_index.2 = Some(0); } }, _ => {}, } } } pub fn move_selection_up(&mut self) { if self.is_searching { match self.selected_search_index.as_mut() { Some(search_index) => { *search_index = search_index.saturating_sub(1); }, None => { if !self.search_results.is_empty() { self.selected_search_index = Some(0); } }, } } else { match self.selected_index { SelectedIndex(None, None, None) => { if !self.session_ui_infos.is_empty() { self.selected_index.0 = Some(self.session_ui_infos.len().saturating_sub(1)) } }, SelectedIndex(Some(selected_session), None, None) => { if selected_session > 0 { self.selected_index.0 = Some(selected_session - 1); } else { self.selected_index.0 = None; } }, SelectedIndex(Some(selected_session), Some(selected_tab), None) => { if selected_tab > 0 { self.selected_index.1 = Some(selected_tab - 1); } else { let tab_count = self .get_session(selected_session) .map(|s| s.tabs.len()) .unwrap_or(0); self.selected_index.1 = Some(tab_count.saturating_sub(1)) } }, SelectedIndex(Some(selected_session), Some(selected_tab), Some(selected_pane)) => { if selected_pane > 0 { self.selected_index.2 = Some(selected_pane - 1); } else { let pane_count = self .get_session(selected_session) .and_then(|s| s.tabs.get(selected_tab)) .map(|t| t.panes.len()) .unwrap_or(0); self.selected_index.2 = Some(pane_count.saturating_sub(1)) } }, _ => {}, } } } fn get_session(&self, index: usize) -> Option<&SessionUiInfo> { self.session_ui_infos.get(index) } pub fn result_expand(&mut self) { // we can't move this to SelectedIndex because the borrow checker is mean match self.selected_index { SelectedIndex(Some(selected_session), None, None) => { let selected_session_has_tabs = self .get_session(selected_session) .map(|s| !s.tabs.is_empty()) .unwrap_or(false); if selected_session_has_tabs { self.selected_index.1 = Some(0); } }, SelectedIndex(Some(selected_session), Some(selected_tab), None) => { let selected_tab_has_panes = self .get_session(selected_session) .and_then(|s| s.tabs.get(selected_tab)) .map(|t| !t.panes.is_empty()) .unwrap_or(false); if selected_tab_has_panes { self.selected_index.2 = Some(0); } }, _ => {}, } } pub fn result_shrink(&mut self) { self.selected_index.result_shrink(); } pub fn update_rows(&mut self, rows: usize) { if let Some(search_result_rows_until_selected) = self.selected_search_index.map(|i| { self.search_results .iter() .enumerate() .take(i + 1) .fold(0, |acc, s| acc + s.1.lines_to_render()) }) { if search_result_rows_until_selected > rows || self.selected_search_index >= Some(self.search_results.len()) { self.selected_search_index = None; } } } pub fn reset_selected_index(&mut self) { self.selected_index.reset(); } pub fn has_session(&self, session_name: &str) -> bool { self.session_ui_infos.iter().any(|s| s.name == session_name) } pub fn has_forbidden_session(&self, session_name: &str) -> bool { self.forbidden_sessions .iter() .any(|s| s.name == session_name) } pub fn update_session_name(&mut self, old_name: &str, new_name: &str) { self.session_ui_infos .iter_mut() .find(|s| s.name == old_name) .map(|s| s.name = new_name.to_owned()); } pub fn all_other_sessions(&self) -> Vec<String> { self.session_ui_infos .iter() .filter_map(|s| { if !s.is_current_session { Some(s.name.clone()) } else { None } }) .collect() } } #[derive(Debug, Clone, Default)] pub struct SelectedIndex(pub Option<usize>, pub Option<usize>, pub Option<usize>); impl SelectedIndex { pub fn tabs_are_visible(&self) -> bool { self.1.is_some() } pub fn panes_are_visible(&self) -> bool { self.2.is_some() } pub fn selected_tab_index(&self) -> Option<usize> { self.1 } pub fn session_index_is_selected(&self, index: usize) -> bool { self.0 == Some(index) } pub fn result_shrink(&mut self) { match self { SelectedIndex(Some(_selected_session), None, None) => self.0 = None, SelectedIndex(Some(_selected_session), Some(_selected_tab), None) => self.1 = None, SelectedIndex(Some(_selected_session), Some(_selected_tab), Some(_selected_pane)) => { self.2 = None }, _ => {}, } } pub fn reset(&mut self) { self.0 = None; self.1 = None; self.2 = None; } } #[derive(Debug)] pub struct SearchResult { score: i64, indices: Vec<usize>, list_item: ListItem, session_name: String, tab_position: Option<usize>, pane_id: Option<(u32, bool)>, is_current_session: bool, } impl SearchResult { pub fn new( score: i64, indices: Vec<usize>, list_item: ListItem, session_name: String, tab_position: Option<usize>, pane_id: Option<(u32, bool)>, is_current_session: bool, ) -> Self { SearchResult { score, indices, list_item, session_name, tab_position, pane_id, is_current_session, } } pub fn lines_to_render(&self) -> usize { self.list_item.line_count() } pub fn render(&self, max_width: usize) -> Vec<LineToRender> { self.list_item.render(Some(self.indices.clone()), max_width) } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/ui/welcome_screen.rs
default-plugins/session-manager/src/ui/welcome_screen.rs
static BANNER: &str = " ██╗ ██╗██╗ ███████╗██████╗ ██████╗ ███╗ ███╗ ███████╗███████╗██╗ ██╗ ██╗ ██╗██╗ ██║ ██║██║ ██╔════╝██╔══██╗██╔═══██╗████╗ ████║ ╚══███╔╝██╔════╝██║ ██║ ██║ ██║██║ ███████║██║ █████╗ ██████╔╝██║ ██║██╔████╔██║ ███╔╝ █████╗ ██║ ██║ ██║ ██║██║ ██╔══██║██║ ██╔══╝ ██╔══██╗██║ ██║██║╚██╔╝██║ ███╔╝ ██╔══╝ ██║ ██║ ██║██ ██║╚═╝ ██║ ██║██║ ██║ ██║ ██║╚██████╔╝██║ ╚═╝ ██║ ███████╗███████╗███████╗███████╗██║╚█████╔╝██╗ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚══════╝╚═╝ ╚════╝ ╚═╝ "; static SMALL_BANNER: &str = " ██╗ ██╗██╗ ██╗ ██║ ██║██║ ██║ ███████║██║ ██║ ██╔══██║██║ ╚═╝ ██║ ██║██║ ██╗ ╚═╝ ╚═╝╚═╝ ╚═╝ "; static MEDIUM_BANNER: &str = " ██╗ ██╗██╗ ████████╗██╗ ██╗███████╗██████╗ ███████╗ ██╗ ██║ ██║██║ ╚══██╔══╝██║ ██║██╔════╝██╔══██╗██╔════╝ ██║ ███████║██║ ██║ ███████║█████╗ ██████╔╝█████╗ ██║ ██╔══██║██║ ██║ ██╔══██║██╔══╝ ██╔══██╗██╔══╝ ╚═╝ ██║ ██║██║ ██║ ██║ ██║███████╗██║ ██║███████╗ ██╗ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ "; pub fn render_banner(x: usize, y: usize, rows: usize, cols: usize) { if rows >= 8 { if cols > 100 { println!("\u{1b}[{}H", y + rows.saturating_sub(8) / 2); for line in BANNER.lines() { println!("\u{1b}[{}C{}", x.saturating_sub(1), line); } } else if cols > 63 { println!("\u{1b}[{}H", y + rows.saturating_sub(8) / 2); let x = (cols.saturating_sub(63) as f64 / 2.0) as usize; for line in MEDIUM_BANNER.lines() { println!("\u{1b}[{}C{}", x, line); } } else { println!("\u{1b}[{}H", y + rows.saturating_sub(8) / 2); let x = (cols.saturating_sub(18) as f64 / 2.0) as usize; for line in SMALL_BANNER.lines() { println!("\u{1b}[{}C{}", x, line); } } } else if rows > 2 { println!( "\u{1b}[{};{}H\u{1b}[1mHi from Zellij!", (y + rows / 2) + 1, (x + cols.saturating_sub(15) / 2).saturating_sub(1) ); } } pub fn render_welcome_boundaries(rows: usize, cols: usize) { let width_of_main_menu = std::cmp::min(cols, 101); let has_room_for_logos = cols.saturating_sub(width_of_main_menu) > 100; let left_boundary_x = (cols.saturating_sub(width_of_main_menu) as f64 / 2.0).floor() as usize; let right_boundary_x = left_boundary_x + width_of_main_menu; let y_starting_point = rows.saturating_sub(15) / 2; let middle_row = (y_starting_point + rows.saturating_sub(y_starting_point) / 2).saturating_sub(1); for i in y_starting_point..rows { if i == middle_row { if has_room_for_logos { print!("\u{1b}[{};{}H┤", i + 1, left_boundary_x + 1); print!( "\u{1b}[m\u{1b}[{};{}H├\u{1b}[K", i + 1, right_boundary_x + 1 ); print!("\u{1b}[{};{}H", i + 1, left_boundary_x.saturating_sub(9)); for _ in 0..10 { print!("─"); } print!("\u{1b}[{};{}H", i + 1, right_boundary_x + 2); for _ in 0..10 { print!("─"); } } else { print!("\u{1b}[{};{}H│", i + 1, left_boundary_x + 1); print!( "\u{1b}[m\u{1b}[{};{}H│\u{1b}[K", i + 1, right_boundary_x + 1 ); } } else { if i == y_starting_point { print!("\u{1b}[{};{}H┌", i + 1, left_boundary_x + 1); print!( "\u{1b}[m\u{1b}[{};{}H┐\u{1b}[K", i + 1, right_boundary_x + 1 ); } else if i == rows.saturating_sub(1) { print!("\u{1b}[{};{}H└", i + 1, left_boundary_x + 1); print!( "\u{1b}[m\u{1b}[{};{}H┘\u{1b}[K", i + 1, right_boundary_x + 1 ); } else { print!("\u{1b}[{};{}H│", i + 1, left_boundary_x + 1); print!( "\u{1b}[m\u{1b}[{};{}H│\u{1b}[K", i + 1, right_boundary_x + 1 ); // this includes some // ANSI magic to delete // everything after this // boundary in order to // fix some rendering // bugs in the legacy // components of this // plugin } } } if rows.saturating_sub(y_starting_point) > 25 && has_room_for_logos { for (i, line) in LOGO.lines().enumerate() { print!( "\u{1b}[{};{}H{}", middle_row.saturating_sub(12) + i, 0, line ); } for (i, line) in LOGO.lines().enumerate() { print!( "\u{1b}[{};{}H{}", middle_row.saturating_sub(12) + i, cols.saturating_sub(47), line ); } } } static LOGO: &str = r#"    _y$ y@g_  ya@@@@L4@@@@gy_  u@@@@@@F "@@@@@@@@y_  _a@@, @@@P~` __ ~T@@@@@@@@g  _yg@@@@@$ "~ _yg@@@@gy `~PR@F~_yggy_  y$@@@@@@PF _y$@@@@@@@@@@gy_ 4@@@@@@@y_  g@@@@@F~ _yg@@@@@@@@@@@@@@@@@@g_ ~F@@@@@@  $@@@F yg@@@@@@@@@@@@@@@@@@@@@@@@gy 9@@F"  $@@@$ 4@@@@@@~@@@@@@@@@@@@@@@@@@@@@ "_yg$  $@@@$ 4@@@@@ ~@@@@@@@@@@@@@@@@@@@ g@@@@  $@@@$ 4@@@@@@y ~@@@@@@@@@@@@@@@@@ $@@@F  $@@@$ 4@@@@@@@@y ~@@@@@@@@@@@@@@@ `~_y_  $@@@$ 4@@@@@@@P` _g@@@@@@@@@@@@@@@ y@@@@  $@@@$ 4@@@@@P` _y@@@@@@@@@@@@@@@@@ 4@@@@  $@@@$ 4@@@@$_ y@@@@@ $@@@@ 4@@@@  $@@@$ 4@@@@@@g@@@@@@@@@@@@@@@@@@@@@ ~@@@  $@@P 7R@@@@@@@@@@@@@@@@@@@@@@@@P~ _@g_7@  ~~_yg@gy_ ~5@@@@@@@@@@@@@@@@@@F~ _yg@@@@y  R@@@@@@@ ~~@@@@@@@@@@@P~` ya@@@@@@@@F  ~5@@@@ 4@gy `~4@@@@F~ y@@@@@@@P~`  `~P 4@@@@gy_ `` _yr a@@@@@F~  5@@@@@@@gg@@~_g@@@~`  ~~@@@@@@@^y@F~  `~4@F ~   "#;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/ui/mod.rs
default-plugins/session-manager/src/ui/mod.rs
pub mod components; pub mod welcome_screen; use zellij_tile::prelude::*; use crate::session_list::{SelectedIndex, SessionList}; use components::{ build_pane_ui_line, build_session_ui_line, build_tab_ui_line, minimize_lines, Colors, LineToRender, }; macro_rules! render_assets { ($assets:expr, $line_count_to_remove:expr, $selected_index:expr, $to_render_until_selected: expr, $to_render_after_selected:expr, $has_deeper_selected_assets:expr, $max_cols:expr, $colors:expr) => {{ let (start_index, anchor_asset_index, end_index, line_count_to_remove) = minimize_lines($assets.len(), $line_count_to_remove, $selected_index); let mut truncated_result_count_above = start_index; let mut truncated_result_count_below = $assets.len().saturating_sub(end_index); let mut current_index = 1; if let Some(assets_to_render_before_selected) = $assets.get(start_index..anchor_asset_index) { for asset in assets_to_render_before_selected { let mut asset: LineToRender = asset.as_line_to_render(current_index, $max_cols, $colors); asset.add_truncated_results(truncated_result_count_above); truncated_result_count_above = 0; current_index += 1; $to_render_until_selected.push(asset); } } if let Some(selected_asset) = $assets.get(anchor_asset_index) { if $selected_index.is_some() && !$has_deeper_selected_assets { let mut selected_asset: LineToRender = selected_asset.as_line_to_render(current_index, $max_cols, $colors); selected_asset.make_selected(true); selected_asset.add_truncated_results(truncated_result_count_above); if anchor_asset_index + 1 >= end_index { // no more results below, let's add the more indication if we need to selected_asset.add_truncated_results(truncated_result_count_below); } current_index += 1; $to_render_until_selected.push(selected_asset); } else { $to_render_until_selected.push(selected_asset.as_line_to_render( current_index, $max_cols, $colors, )); current_index += 1; } } if let Some(assets_to_render_after_selected) = $assets.get(anchor_asset_index + 1..end_index) { for asset in assets_to_render_after_selected.iter().rev() { let mut asset: LineToRender = asset.as_line_to_render(current_index, $max_cols, $colors); asset.add_truncated_results(truncated_result_count_below); truncated_result_count_below = 0; current_index += 1; $to_render_after_selected.insert(0, asset.into()); } } line_count_to_remove }}; } impl SessionList { pub fn render(&self, max_rows: usize, max_cols: usize, colors: Colors) -> Vec<LineToRender> { if self.is_searching { self.render_search_results(max_rows, max_cols) } else { self.render_list(max_rows, max_cols, colors) } } fn render_search_results(&self, max_rows: usize, max_cols: usize) -> Vec<LineToRender> { let mut lines_to_render = vec![]; for (i, result) in self.search_results.iter().enumerate() { if lines_to_render.len() + result.lines_to_render() <= max_rows { let mut result_lines = result.render(max_cols); if Some(i) == self.selected_search_index { let mut render_arrows = true; for line_to_render in result_lines.iter_mut() { line_to_render.make_selected_as_search(render_arrows); render_arrows = false; // only render arrows on the first search result } } lines_to_render.append(&mut result_lines); } else { break; } } lines_to_render } fn render_list(&self, max_rows: usize, max_cols: usize, colors: Colors) -> Vec<LineToRender> { let mut lines_to_render_until_selected = vec![]; let mut lines_to_render_after_selected = vec![]; let total_lines_to_render = self.total_lines_to_render(); let line_count_to_remove = total_lines_to_render.saturating_sub(max_rows); let line_count_to_remove = self.render_sessions( &mut lines_to_render_until_selected, &mut lines_to_render_after_selected, line_count_to_remove, max_cols, colors, ); let line_count_to_remove = self.render_tabs( &mut lines_to_render_until_selected, &mut lines_to_render_after_selected, line_count_to_remove, max_cols, colors, ); self.render_panes( &mut lines_to_render_until_selected, &mut lines_to_render_after_selected, line_count_to_remove, max_cols, colors, ); let mut lines_to_render = lines_to_render_until_selected; lines_to_render.append(&mut lines_to_render_after_selected); lines_to_render } fn render_sessions( &self, to_render_until_selected: &mut Vec<LineToRender>, to_render_after_selected: &mut Vec<LineToRender>, line_count_to_remove: usize, max_cols: usize, colors: Colors, ) -> usize { render_assets!( self.session_ui_infos, line_count_to_remove, self.selected_index.0, to_render_until_selected, to_render_after_selected, self.selected_index.1.is_some(), max_cols, colors ) } fn render_tabs( &self, to_render_until_selected: &mut Vec<LineToRender>, to_render_after_selected: &mut Vec<LineToRender>, line_count_to_remove: usize, max_cols: usize, colors: Colors, ) -> usize { if self.selected_index.1.is_none() { return line_count_to_remove; } if let Some(tabs_in_session) = self .selected_index .0 .and_then(|i| self.session_ui_infos.get(i)) .map(|s| &s.tabs) { render_assets!( tabs_in_session, line_count_to_remove, self.selected_index.1, to_render_until_selected, to_render_after_selected, self.selected_index.2.is_some(), max_cols, colors ) } else { line_count_to_remove } } fn render_panes( &self, to_render_until_selected: &mut Vec<LineToRender>, to_render_after_selected: &mut Vec<LineToRender>, line_count_to_remove: usize, max_cols: usize, colors: Colors, ) -> usize { if self.selected_index.2.is_none() { return line_count_to_remove; } if let Some(panes_in_session) = self .selected_index .0 .and_then(|i| self.session_ui_infos.get(i)) .map(|s| &s.tabs) .and_then(|tabs| { self.selected_index .1 .and_then(|i| tabs.get(i)) .map(|t| &t.panes) }) { render_assets!( panes_in_session, line_count_to_remove, self.selected_index.2, to_render_until_selected, to_render_after_selected, false, max_cols, colors ) } else { line_count_to_remove } } fn total_lines_to_render(&self) -> usize { self.session_ui_infos .iter() .enumerate() .fold(0, |acc, (index, s)| { if self.selected_index.session_index_is_selected(index) { acc + s.line_count(&self.selected_index) } else { acc + 1 } }) } } #[derive(Debug, Clone)] pub struct SessionUiInfo { pub name: String, pub tabs: Vec<TabUiInfo>, pub connected_users: usize, pub is_current_session: bool, } impl SessionUiInfo { pub fn from_session_info(session_info: &SessionInfo) -> Self { SessionUiInfo { name: session_info.name.clone(), tabs: session_info .tabs .iter() .map(|t| TabUiInfo::new(t, &session_info.panes)) .collect(), connected_users: session_info.connected_clients, is_current_session: session_info.is_current_session, } } pub fn line_count(&self, selected_index: &SelectedIndex) -> usize { let mut line_count = 1; // self if selected_index.tabs_are_visible() { match selected_index .selected_tab_index() .and_then(|i| self.tabs.get(i)) .map(|t| t.line_count(&selected_index)) { Some(line_count_of_selected_tab) => { // we add the line count in the selected tab minus 1 because we will account // for the selected tab line itself in self.tabs.len() below line_count += line_count_of_selected_tab.saturating_sub(1); line_count += self.tabs.len(); }, None => { line_count += self.tabs.len(); }, } } line_count } fn as_line_to_render( &self, _session_index: u8, mut max_cols: usize, colors: Colors, ) -> LineToRender { let mut line_to_render = LineToRender::new(colors); let ui_spans = build_session_ui_line(&self, colors); for span in ui_spans { span.render(None, &mut line_to_render, &mut max_cols); } line_to_render } } #[derive(Debug, Clone)] pub struct TabUiInfo { pub name: String, pub panes: Vec<PaneUiInfo>, pub position: usize, } impl TabUiInfo { pub fn new(tab_info: &TabInfo, pane_manifest: &PaneManifest) -> Self { let panes = pane_manifest .panes .get(&tab_info.position) .map(|p| { p.iter() .filter_map(|pane_info| { if pane_info.is_selectable { Some(PaneUiInfo { name: pane_info.title.clone(), exit_code: pane_info.exit_status.clone(), pane_id: pane_info.id, is_plugin: pane_info.is_plugin, }) } else { None } }) .collect() }) .unwrap_or_default(); TabUiInfo { name: tab_info.name.clone(), panes, position: tab_info.position, } } pub fn line_count(&self, selected_index: &SelectedIndex) -> usize { let mut line_count = 1; // self if selected_index.panes_are_visible() { line_count += self.panes.len() } line_count } fn as_line_to_render( &self, _session_index: u8, mut max_cols: usize, colors: Colors, ) -> LineToRender { let mut line_to_render = LineToRender::new(colors); let ui_spans = build_tab_ui_line(&self, colors); for span in ui_spans { span.render(None, &mut line_to_render, &mut max_cols); } line_to_render } } #[derive(Debug, Clone)] pub struct PaneUiInfo { pub name: String, pub exit_code: Option<i32>, pub pane_id: u32, pub is_plugin: bool, } impl PaneUiInfo { fn as_line_to_render( &self, _session_index: u8, mut max_cols: usize, colors: Colors, ) -> LineToRender { let mut line_to_render = LineToRender::new(colors); let ui_spans = build_pane_ui_line(&self, colors); for span in ui_spans { span.render(None, &mut line_to_render, &mut max_cols); } line_to_render } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/session-manager/src/ui/components.rs
default-plugins/session-manager/src/ui/components.rs
use std::path::PathBuf; use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthStr; use zellij_tile::prelude::*; use crate::ui::{PaneUiInfo, SessionUiInfo, TabUiInfo}; use crate::{ActiveScreen, NewSessionInfo}; #[derive(Debug)] pub struct ListItem { pub name: String, pub session_name: Option<Vec<UiSpan>>, pub tab_name: Option<Vec<UiSpan>>, pub pane_name: Option<Vec<UiSpan>>, colors: Colors, } impl ListItem { pub fn from_session_info(session_ui_info: &SessionUiInfo, colors: Colors) -> Self { let session_ui_line = build_session_ui_line(session_ui_info, colors); ListItem { name: session_ui_info.name.clone(), session_name: Some(session_ui_line), tab_name: None, pane_name: None, colors, } } pub fn from_tab_info( session_ui_info: &SessionUiInfo, tab_ui_info: &TabUiInfo, colors: Colors, ) -> Self { let session_ui_line = build_session_ui_line(session_ui_info, colors); let tab_ui_line = build_tab_ui_line(tab_ui_info, colors); ListItem { name: tab_ui_info.name.clone(), session_name: Some(session_ui_line), tab_name: Some(tab_ui_line), pane_name: None, colors, } } pub fn from_pane_info( session_ui_info: &SessionUiInfo, tab_ui_info: &TabUiInfo, pane_ui_info: &PaneUiInfo, colors: Colors, ) -> Self { let session_ui_line = build_session_ui_line(session_ui_info, colors); let tab_ui_line = build_tab_ui_line(tab_ui_info, colors); let pane_ui_line = build_pane_ui_line(pane_ui_info, colors); ListItem { name: pane_ui_info.name.clone(), session_name: Some(session_ui_line), tab_name: Some(tab_ui_line), pane_name: Some(pane_ui_line), colors, } } pub fn line_count(&self) -> usize { let mut line_count = 0; if self.session_name.is_some() { line_count += 1 }; if self.tab_name.is_some() { line_count += 1 }; if self.pane_name.is_some() { line_count += 1 }; line_count } pub fn render(&self, indices: Option<Vec<usize>>, max_cols: usize) -> Vec<LineToRender> { let mut lines_to_render = vec![]; if let Some(session_name) = &self.session_name { let indices = if self.tab_name.is_none() && self.pane_name.is_none() { indices.clone() } else { None }; let mut line_to_render = LineToRender::new(self.colors); let mut remaining_cols = max_cols; for span in session_name { span.render( indices.clone().map(|i| { ( SpanStyle::ForegroundBold( self.colors.palette.text_unselected.emphasis_3, ), i, ) }), &mut line_to_render, &mut remaining_cols, ); } lines_to_render.push(line_to_render); } if let Some(tab_name) = &self.tab_name { let indices = if self.pane_name.is_none() { indices.clone() } else { None }; let mut line_to_render = LineToRender::new(self.colors); let mut remaining_cols = max_cols; for span in tab_name { span.render( indices.clone().map(|i| { ( SpanStyle::ForegroundBold( self.colors.palette.text_unselected.emphasis_3, ), i, ) }), &mut line_to_render, &mut remaining_cols, ); } lines_to_render.push(line_to_render); } if let Some(pane_name) = &self.pane_name { let mut line_to_render = LineToRender::new(self.colors); let mut remaining_cols = max_cols; for span in pane_name { span.render( indices.clone().map(|i| { ( SpanStyle::ForegroundBold( self.colors.palette.text_unselected.emphasis_3, ), i, ) }), &mut line_to_render, &mut remaining_cols, ); } lines_to_render.push(line_to_render); } lines_to_render } } #[derive(Debug)] pub enum UiSpan { UiSpanTelescope(UiSpanTelescope), TruncatableUiSpan(TruncatableUiSpan), } impl UiSpan { pub fn render( &self, indices: Option<(SpanStyle, Vec<usize>)>, line_to_render: &mut LineToRender, remaining_cols: &mut usize, ) { match self { UiSpan::UiSpanTelescope(ui_span_telescope) => { ui_span_telescope.render(line_to_render, remaining_cols) }, UiSpan::TruncatableUiSpan(truncatable_ui_span) => { truncatable_ui_span.render(indices, line_to_render, remaining_cols) }, } } } #[allow(dead_code)] // in the future this will be moved to be its own component #[derive(Debug)] pub enum SpanStyle { None, Bold, Foreground(PaletteColor), ForegroundBold(PaletteColor), } impl SpanStyle { pub fn style_string(&self, to_style: &str) -> String { match self { SpanStyle::None => to_style.to_owned(), SpanStyle::Bold => format!("\u{1b}[1m{}\u{1b}[22m", to_style), SpanStyle::Foreground(color) => match color { PaletteColor::EightBit(byte) => { format!("\u{1b}[38;5;{byte}m{}\u{1b}[39m", to_style) }, PaletteColor::Rgb((r, g, b)) => { format!("\u{1b}[38;2;{};{};{}m{}\u{1b}[39m", r, g, b, to_style) }, }, SpanStyle::ForegroundBold(color) => match color { PaletteColor::EightBit(byte) => { format!("\u{1b}[38;5;{byte};1m{}\u{1b}[39;22m", to_style) }, PaletteColor::Rgb((r, g, b)) => { format!("\u{1b}[38;2;{};{};{};1m{}\u{1b}[39;22m", r, g, b, to_style) }, }, } } } impl Default for SpanStyle { fn default() -> Self { SpanStyle::None } } #[derive(Debug, Default)] pub struct TruncatableUiSpan { text: String, style: SpanStyle, } impl TruncatableUiSpan { pub fn new(text: String, style: SpanStyle) -> Self { TruncatableUiSpan { text, style } } pub fn render( &self, indices: Option<(SpanStyle, Vec<usize>)>, line_to_render: &mut LineToRender, remaining_cols: &mut usize, ) { let mut rendered = String::new(); let truncated = if *remaining_cols >= self.text.width() { self.text.clone() } else { let mut truncated = String::new(); for character in self.text.chars() { if truncated.width() + character.width().unwrap_or(0) <= *remaining_cols { truncated.push(character); } else { break; } } truncated }; match indices { Some((index_style, indices)) => { for (i, character) in truncated.chars().enumerate() { // TODO: optimize this by splitting the string up by its indices and only pushing those // chu8nks if indices.contains(&i) { rendered.push_str(&index_style.style_string(&character.to_string())); } else { rendered.push_str(&self.style.style_string(&character.to_string())); } } }, None => { rendered.push_str(&self.style.style_string(&truncated)); }, } *remaining_cols = remaining_cols.saturating_sub(truncated.width()); line_to_render.append(&rendered); } } #[derive(Debug, Default)] pub struct UiSpanTelescope(Vec<StringAndLength>); impl UiSpanTelescope { pub fn new(string_and_lengths: Vec<StringAndLength>) -> Self { UiSpanTelescope(string_and_lengths) } pub fn render(&self, line_to_render: &mut LineToRender, remaining_cols: &mut usize) { for string_and_length in &self.0 { if string_and_length.length < *remaining_cols { line_to_render.append(&string_and_length.string); *remaining_cols -= string_and_length.length; break; } } } } #[derive(Debug, Default, Clone)] pub struct StringAndLength { pub string: String, pub length: usize, } impl StringAndLength { pub fn new(string: String, length: usize) -> Self { StringAndLength { string, length } } } #[derive(Debug, Clone)] pub struct LineToRender { line: String, is_selected: bool, truncated_result_count: usize, colors: Colors, } impl LineToRender { pub fn new(colors: Colors) -> Self { LineToRender { line: String::default(), is_selected: false, truncated_result_count: 0, colors, } } pub fn append(&mut self, to_append: &str) { self.line.push_str(to_append) } pub fn make_selected_as_search(&mut self, add_arrows: bool) { self.is_selected = true; let arrows = if add_arrows { self.colors.shortcuts(" <↓↑> ") } else { " ".to_owned() }; match self.colors.palette.list_selected.background { PaletteColor::EightBit(byte) => { self.line = format!( "\u{1b}[48;5;{byte}m\u{1b}[K\u{1b}[48;5;{byte}m{arrows}{}", self.line ); }, PaletteColor::Rgb((r, g, b)) => { self.line = format!( "\u{1b}[48;2;{};{};{}m\u{1b}[K\u{1b}[48;2;{};{};{}m{arrows}{}", r, g, b, r, g, b, self.line ); }, } } pub fn make_selected(&mut self, add_arrows: bool) { self.is_selected = true; let arrows = if add_arrows { self.colors.shortcuts("<←↓↑→>") } else { " ".to_owned() }; match self.colors.palette.list_selected.background { PaletteColor::EightBit(byte) => { self.line = format!( "\u{1b}[48;5;{byte}m\u{1b}[K\u{1b}[48;5;{byte}m{arrows}{}", self.line ); }, PaletteColor::Rgb((r, g, b)) => { self.line = format!( "\u{1b}[48;2;{};{};{}m\u{1b}[K\u{1b}[48;2;{};{};{}m{arrows}{}", r, g, b, r, g, b, self.line ); }, } } pub fn render(&self) -> String { let mut line = self.line.clone(); let more = if self.truncated_result_count > 0 { self.colors .exit_code_error(&format!(" [+{}]", self.truncated_result_count)) } else { String::new() }; line.push_str(&more); if self.is_selected { self.line.clone() } else { format!("\u{1b}[49m {}", line) } } pub fn add_truncated_results(&mut self, result_count: usize) { self.truncated_result_count += result_count; } } pub fn build_session_ui_line(session_ui_info: &SessionUiInfo, colors: Colors) -> Vec<UiSpan> { let mut ui_spans = vec![]; let tab_count_text = session_ui_info.tabs.len(); let total_pane_count_text = session_ui_info .tabs .iter() .fold(0, |acc, tab| acc + tab.panes.len()); let tab_count = format!("{}", tab_count_text); let tab_count_styled = colors.tab_count(&tab_count); let total_pane_count = format!("{}", total_pane_count_text); let total_pane_count_styled = colors.pane_count(&total_pane_count); let session_name = &session_ui_info.name; let connected_users = format!("{}", session_ui_info.connected_users); let connected_users_styled = colors.connected_users(&connected_users); let session_bullet_span = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![StringAndLength::new( format!(" > "), 3, )])); let session_name_span = UiSpan::TruncatableUiSpan(TruncatableUiSpan::new( session_name.clone(), SpanStyle::ForegroundBold(colors.palette.text_unselected.emphasis_0), )); let tab_and_pane_count = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![ StringAndLength::new( format!(" ({tab_count_styled} tabs, {total_pane_count_styled} panes)"), 2 + tab_count.width() + 7 + total_pane_count.width() + 7, ), StringAndLength::new( format!(" ({tab_count_styled}, {total_pane_count_styled})"), 2 + tab_count.width() + 2 + total_pane_count.width() + 3, ), ])); let connected_users_count = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![ StringAndLength::new( format!(" [{connected_users_styled} connected users]"), 2 + connected_users.width() + 17, ), StringAndLength::new( format!(" [{connected_users_styled}]"), 2 + connected_users.width() + 1, ), ])); ui_spans.push(session_bullet_span); ui_spans.push(session_name_span); ui_spans.push(tab_and_pane_count); ui_spans.push(connected_users_count); if session_ui_info.is_current_session { let current_session_indication = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![ StringAndLength::new( colors.current_session_marker(&format!(" <CURRENT SESSION>")), 18, ), StringAndLength::new(colors.current_session_marker(&format!(" <CURRENT>")), 10), StringAndLength::new(colors.current_session_marker(&format!(" <C>")), 4), ])); ui_spans.push(current_session_indication); } ui_spans } pub fn build_tab_ui_line(tab_ui_info: &TabUiInfo, colors: Colors) -> Vec<UiSpan> { let mut ui_spans = vec![]; let tab_name = &tab_ui_info.name; let pane_count_text = tab_ui_info.panes.len(); let pane_count = format!("{}", pane_count_text); let pane_count_styled = colors.pane_count(&pane_count); let tab_bullet_span = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![StringAndLength::new( format!(" - "), 4, )])); let tab_name_span = UiSpan::TruncatableUiSpan(TruncatableUiSpan::new( tab_name.clone(), SpanStyle::ForegroundBold(colors.palette.text_unselected.emphasis_1), )); let connected_users_count_span = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![ StringAndLength::new( format!(" ({pane_count_styled} panes)"), 2 + pane_count.width() + 7, ), StringAndLength::new( format!(" ({pane_count_styled})"), 2 + pane_count.width() + 1, ), ])); ui_spans.push(tab_bullet_span); ui_spans.push(tab_name_span); ui_spans.push(connected_users_count_span); ui_spans } pub fn build_pane_ui_line(pane_ui_info: &PaneUiInfo, colors: Colors) -> Vec<UiSpan> { let mut ui_spans = vec![]; let pane_name = pane_ui_info.name.clone(); let exit_code = pane_ui_info.exit_code.map(|exit_code_number| { let exit_code = format!("{}", exit_code_number); let exit_code = if exit_code_number == 0 { colors.session_and_folder_entry(&exit_code) } else { colors.exit_code_error(&exit_code) }; exit_code }); let pane_bullet_span = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![StringAndLength::new( format!(" > "), 6, )])); ui_spans.push(pane_bullet_span); let pane_name_span = UiSpan::TruncatableUiSpan(TruncatableUiSpan::new(pane_name, SpanStyle::Bold)); ui_spans.push(pane_name_span); if let Some(exit_code) = exit_code { let pane_name_span = UiSpan::UiSpanTelescope(UiSpanTelescope::new(vec![ StringAndLength::new( format!(" (EXIT CODE: {exit_code})"), 13 + exit_code.width() + 1, ), StringAndLength::new(format!(" ({exit_code})"), 2 + exit_code.width() + 1), ])); ui_spans.push(pane_name_span); } ui_spans } pub fn minimize_lines( total_count: usize, line_count_to_remove: usize, selected_index: Option<usize>, ) -> (usize, usize, usize, usize) { // returns: (start_index, anchor_index, end_index, lines_left_to_remove) let (count_to_render, line_count_to_remove) = if line_count_to_remove > total_count { (1, line_count_to_remove.saturating_sub(total_count) + 1) } else { (total_count.saturating_sub(line_count_to_remove), 0) }; let anchor_index = selected_index.unwrap_or(0); // 5 let mut start_index = anchor_index.saturating_sub(count_to_render / 2); let mut end_index = start_index + count_to_render; if end_index > total_count { start_index = start_index.saturating_sub(end_index - total_count); end_index = total_count; } (start_index, anchor_index, end_index, line_count_to_remove) } pub fn render_prompt(search_term: &str, colors: Colors, x: usize, y: usize) { let prompt = colors.session_and_folder_entry(&format!("Search:")); let search_term = colors.bold(&format!("{}_", search_term)); println!( "\u{1b}[{};{}H\u{1b}[0m{} {}\n", y + 1, x, prompt, search_term ); } pub fn render_screen_toggle( active_screen: ActiveScreen, x: usize, y: usize, max_cols: usize, background: &PaletteColor, ) { let key_indication_text = "<TAB>"; let (new_session_text, running_sessions_text, exited_sessions_text) = if max_cols > 66 { ("New Session", "Attach to Session", "Resurrect Session") } else { ("New", "Attach", "Resurrect") }; let key_indication_len = key_indication_text.chars().count() + 1; let first_ribbon_length = new_session_text.chars().count() + 4; let second_ribbon_length = running_sessions_text.chars().count() + 4; let key_indication_x = x; let first_ribbon_x = key_indication_x + key_indication_len; let second_ribbon_x = first_ribbon_x + first_ribbon_length; let third_ribbon_x = second_ribbon_x + second_ribbon_length; let mut new_session_text = Text::new(new_session_text); let mut running_sessions_text = Text::new(running_sessions_text); let mut exited_sessions_text = Text::new(exited_sessions_text); match active_screen { ActiveScreen::NewSession => { new_session_text = new_session_text.selected(); }, ActiveScreen::AttachToSession => { running_sessions_text = running_sessions_text.selected(); }, ActiveScreen::ResurrectSession => { exited_sessions_text = exited_sessions_text.selected(); }, } let bg_color = match background { PaletteColor::Rgb((r, g, b)) => format!("\u{1b}[48;2;{};{};{}m\u{1b}[0K", r, g, b), PaletteColor::EightBit(color) => format!("\u{1b}[48;5;{}m\u{1b}[0K", color), }; print_text_with_coordinates( Text::new(key_indication_text).color_range(3, ..).opaque(), key_indication_x, y, None, None, ); println!("\u{1b}[{};{}H{}", y + 1, first_ribbon_x, bg_color); print_ribbon_with_coordinates(new_session_text, first_ribbon_x, y, None, None); print_ribbon_with_coordinates(running_sessions_text, second_ribbon_x, y, None, None); print_ribbon_with_coordinates(exited_sessions_text, third_ribbon_x, y, None, None); } fn render_new_session_folder_prompt( new_session_info: &NewSessionInfo, colors: Colors, x: usize, y: usize, max_cols: usize, ) { match new_session_info.new_session_folder.as_ref() { Some(new_session_folder) => { let folder_prompt = "New session folder:"; let short_folder_prompt = "Folder:"; let new_session_path = new_session_folder.clone(); let new_session_folder = new_session_folder.display().to_string(); let change_folder_shortcut_text = "<Ctrl f>"; let change_folder_shortcut = colors.shortcuts(&change_folder_shortcut_text); let to_change = "to change"; let reset_folder_shortcut_text = "<Ctrl c>"; let reset_folder_shortcut = colors.shortcuts(reset_folder_shortcut_text); let to_reset = "to reset"; if max_cols >= folder_prompt.width() + new_session_folder.width() + change_folder_shortcut_text.width() + to_change.width() + reset_folder_shortcut_text.width() + to_reset.width() + 8 { print!( "\u{1b}[m{}{} {} ({} {}, {} {})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(folder_prompt), colors.session_and_folder_entry(&new_session_folder), change_folder_shortcut, to_change, reset_folder_shortcut, to_reset, ); } else if max_cols >= short_folder_prompt.width() + new_session_folder.width() + change_folder_shortcut_text.width() + to_change.width() + reset_folder_shortcut_text.width() + to_reset.width() + 8 { print!( "\u{1b}[m{}{} {} ({} {}, {} {})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(short_folder_prompt), colors.session_and_folder_entry(&new_session_folder), change_folder_shortcut, to_change, reset_folder_shortcut, to_reset, ); } else if max_cols >= short_folder_prompt.width() + new_session_folder.width() + change_folder_shortcut_text.width() + reset_folder_shortcut_text.width() + 5 { print!( "\u{1b}[m{}{} {} ({}/{})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(short_folder_prompt), colors.session_and_folder_entry(&new_session_folder), change_folder_shortcut, reset_folder_shortcut, ); } else { let total_len = short_folder_prompt.width() + change_folder_shortcut_text.width() + reset_folder_shortcut_text.width() + 5; let max_path_len = max_cols.saturating_sub(total_len); let truncated_path = truncate_path( new_session_path, new_session_folder.width().saturating_sub(max_path_len), ); print!( "\u{1b}[m{}{} {} ({}/{})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(short_folder_prompt), colors.session_and_folder_entry(&truncated_path), change_folder_shortcut, reset_folder_shortcut, ); } }, None => { let folder_prompt = "New session folder:"; let short_folder_prompt = "Folder:"; let change_folder_shortcut_text = "<Ctrl f>"; let change_folder_shortcut = colors.shortcuts(change_folder_shortcut_text); let to_set = "to set"; if max_cols >= folder_prompt.width() + change_folder_shortcut_text.width() + to_set.width() + 4 { print!( "\u{1b}[m{}{} ({} {})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(folder_prompt), change_folder_shortcut, to_set, ); } else if max_cols >= short_folder_prompt.width() + change_folder_shortcut_text.width() + to_set.width() + 4 { print!( "\u{1b}[m{}{} ({} {})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(short_folder_prompt), change_folder_shortcut, to_set, ); } else { print!( "\u{1b}[m{}{} {}", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(short_folder_prompt), change_folder_shortcut, ); } }, } } pub fn render_new_session_block( new_session_info: &NewSessionInfo, colors: Colors, max_rows_of_new_session_block: usize, max_cols_of_new_session_block: usize, x: usize, y: usize, ) { let enter = colors.shortcuts("<ENTER>"); if new_session_info.entering_new_session_name() { let prompt = "New session name:"; let long_instruction = "when done, blank for random"; let new_session_name = new_session_info.name(); if max_cols_of_new_session_block > prompt.width() + long_instruction.width() + new_session_name.width() + 15 { println!( "\u{1b}[m{}{} {}_ ({} {})", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(prompt), colors.session_and_folder_entry(&new_session_name), enter, long_instruction, ); } else { let space_for_new_session_name = max_cols_of_new_session_block.saturating_sub(prompt.width() + 18); let new_session_name = if new_session_name.width() > space_for_new_session_name { let mut truncated = String::new(); for character in new_session_name.chars().rev() { if truncated.width() + character.width().unwrap_or(0) < space_for_new_session_name { truncated.push(character); } else { break; } } format!("...{}", truncated.chars().rev().collect::<String>()) } else { new_session_name.to_owned() }; println!( "\u{1b}[m{}{} {}_ {}", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(prompt), colors.session_and_folder_entry(&new_session_name), enter, ); } } else if new_session_info.entering_layout_search_term() { let new_session_name = if new_session_info.name().is_empty() { "<RANDOM>" } else { new_session_info.name() }; let prompt = "New session name:"; let long_instruction = "to correct"; let esc = colors.shortcuts("<ESC>"); if max_cols_of_new_session_block > prompt.width() + long_instruction.width() + new_session_name.width() + 15 { println!( "\u{1b}[m{}{}: {} ({} to correct)", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt(prompt), colors.session_and_folder_entry(new_session_name), esc, ); } else { println!( "\u{1b}[m{}{}: {} {}", format!("\u{1b}[{};{}H", y + 1, x + 1), colors.session_name_prompt("New session name"), colors.session_and_folder_entry(new_session_name), esc, ); } render_layout_selection_list( new_session_info, max_rows_of_new_session_block.saturating_sub(8), max_cols_of_new_session_block, x, y + 1, ); } render_new_session_folder_prompt( new_session_info, colors, x, (y + max_rows_of_new_session_block).saturating_sub(3), max_cols_of_new_session_block, ); } pub fn render_layout_selection_list( new_session_info: &NewSessionInfo, max_rows_of_new_session_block: usize, max_cols_of_new_session_block: usize, x: usize, y: usize, ) { let layout_search_term = new_session_info.layout_search_term(); let search_term_len = layout_search_term.width(); let layout_indication_line = if max_cols_of_new_session_block > 73 + search_term_len { Text::new(format!( "New session layout: {}_ (Search and select from list, <ENTER> when done)", layout_search_term )) .color_range(2, ..20 + search_term_len) .color_range(3, 20..20 + search_term_len) .color_range(3, 52 + search_term_len..59 + search_term_len) } else { Text::new(format!( "New session layout: {}_ <ENTER>", layout_search_term )) .color_range(2, ..20 + search_term_len) .color_range(3, 20..20 + search_term_len) .color_range(3, 22 + search_term_len..) }; print_text_with_coordinates(layout_indication_line, x, y + 1, None, None); println!(); let mut table = Table::new(); for (i, (layout_info, indices, is_selected)) in new_session_info .layouts_to_render(max_rows_of_new_session_block) .into_iter() .enumerate() { let layout_name = layout_info.name(); let layout_name_len = layout_name.width(); let is_builtin = layout_info.is_builtin(); if i > max_rows_of_new_session_block.saturating_sub(1) { break; } else { let mut layout_cell = if is_builtin { Text::new(format!("{} (built-in)", layout_name)) .color_range(1, 0..layout_name_len) .color_range(0, layout_name_len + 1..) .color_indices(3, indices) } else { Text::new(format!("{}", layout_name)) .color_range(1, ..) .color_indices(3, indices) }; if is_selected { layout_cell = layout_cell.selected(); } let arrow_cell = if is_selected { Text::new(format!("<↓↑>")).selected().color_range(3, ..) } else { Text::new(format!(" ")).color_range(3, ..) }; table = table.add_styled_row(vec![arrow_cell, layout_cell]); } } let table_y = y + 3; print_table_with_coordinates(table, x, table_y, None, None); } pub fn render_error(error_text: &str, rows: usize, columns: usize, x: usize, y: usize) { print_text_with_coordinates( Text::new(format!("Error: {}", error_text)).color_range(3, ..), x, y + rows, Some(columns), None, ); } pub fn render_renaming_session_screen( new_session_name: &str, rows: usize, columns: usize, x: usize, y: usize, ) { if rows == 0 || columns == 0 { return; } let text = Text::new(format!( "New name for current session: {}_ (<ENTER> when done)", new_session_name ))
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/tab-bar/src/main.rs
default-plugins/tab-bar/src/main.rs
mod line; mod tab; use std::cmp::{max, min}; use std::collections::BTreeMap; use std::convert::TryInto; use tab::get_tab_to_focus; use zellij_tile::prelude::*; use crate::line::tab_line; use crate::tab::tab_style; #[derive(Debug, Default)] pub struct LinePart { part: String, len: usize, tab_index: Option<usize>, } impl LinePart { pub fn append(&mut self, to_append: &LinePart) { self.part.push_str(&to_append.part); self.len += to_append.len; } } #[derive(Default, Debug)] struct State { tabs: Vec<TabInfo>, active_tab_idx: usize, mode_info: ModeInfo, tab_line: Vec<LinePart>, hide_swap_layout_indication: bool, } static ARROW_SEPARATOR: &str = ""; register_plugin!(State); impl ZellijPlugin for State { fn load(&mut self, configuration: BTreeMap<String, String>) { self.hide_swap_layout_indication = configuration .get("hide_swap_layout_indication") .map(|s| s == "true") .unwrap_or(false); set_selectable(false); subscribe(&[ EventType::TabUpdate, EventType::ModeUpdate, EventType::Mouse, ]); } fn update(&mut self, event: Event) -> bool { let mut should_render = false; match event { Event::ModeUpdate(mode_info) => { if self.mode_info != mode_info { should_render = true; } self.mode_info = mode_info; }, Event::TabUpdate(tabs) => { if let Some(active_tab_index) = tabs.iter().position(|t| t.active) { // tabs are indexed starting from 1 so we need to add 1 let active_tab_idx = active_tab_index + 1; if self.active_tab_idx != active_tab_idx || self.tabs != tabs { should_render = true; } self.active_tab_idx = active_tab_idx; self.tabs = tabs; } else { eprintln!("Could not find active tab."); } }, Event::Mouse(me) => match me { Mouse::LeftClick(_, col) => { let tab_to_focus = get_tab_to_focus(&self.tab_line, self.active_tab_idx, col); if let Some(idx) = tab_to_focus { switch_tab_to(idx.try_into().unwrap()); } }, Mouse::ScrollUp(_) => { switch_tab_to(min(self.active_tab_idx + 1, self.tabs.len()) as u32); }, Mouse::ScrollDown(_) => { switch_tab_to(max(self.active_tab_idx.saturating_sub(1), 1) as u32); }, _ => {}, }, _ => { eprintln!("Got unrecognized event: {:?}", event); }, } if self.tabs.is_empty() { // no need to render if we have no tabs, this can sometimes happen on startup before we // get the tab update and then we definitely don't want to render should_render = false; } should_render } fn render(&mut self, _rows: usize, cols: usize) { if self.tabs.is_empty() { return; } let mut all_tabs: Vec<LinePart> = vec![]; let mut active_tab_index = 0; let mut is_alternate_tab = false; for t in &mut self.tabs { let mut tabname = t.name.clone(); if t.active && self.mode_info.mode == InputMode::RenameTab { if tabname.is_empty() { tabname = String::from("Enter name..."); } active_tab_index = t.position; } else if t.active { active_tab_index = t.position; } let tab = tab_style( tabname, t, is_alternate_tab, self.mode_info.style.colors, self.mode_info.capabilities, ); is_alternate_tab = !is_alternate_tab; all_tabs.push(tab); } let background = self.mode_info.style.colors.text_unselected.background; self.tab_line = tab_line( self.mode_info.session_name.as_deref(), all_tabs, active_tab_index, cols.saturating_sub(1), self.mode_info.style.colors, self.mode_info.capabilities, self.mode_info.style.hide_session_name, self.tabs.iter().find(|t| t.active), &self.mode_info, self.hide_swap_layout_indication, &background, ); let output = self .tab_line .iter() .fold(String::new(), |output, part| output + &part.part); match background { PaletteColor::Rgb((r, g, b)) => { print!("{}\u{1b}[48;2;{};{};{}m\u{1b}[0K", output, r, g, b); }, PaletteColor::EightBit(color) => { print!("{}\u{1b}[48;5;{}m\u{1b}[0K", output, color); }, } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/tab-bar/src/line.rs
default-plugins/tab-bar/src/line.rs
use ansi_term::ANSIStrings; use unicode_width::UnicodeWidthStr; use crate::{LinePart, ARROW_SEPARATOR}; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; use zellij_tile_utils::style; fn get_current_title_len(current_title: &[LinePart]) -> usize { current_title.iter().map(|p| p.len).sum() } // move elements from before_active and after_active into tabs_to_render while they fit in cols // adds collapsed_tabs to the left and right if there's left over tabs that don't fit fn populate_tabs_in_tab_line( tabs_before_active: &mut Vec<LinePart>, tabs_after_active: &mut Vec<LinePart>, tabs_to_render: &mut Vec<LinePart>, cols: usize, palette: Styling, capabilities: PluginCapabilities, ) { let mut middle_size = get_current_title_len(tabs_to_render); let mut total_left = 0; let mut total_right = 0; loop { let left_count = tabs_before_active.len(); let right_count = tabs_after_active.len(); // left_more_tab_index is first tab to the left of the leftmost visible tab let left_more_tab_index = left_count.saturating_sub(1); let collapsed_left = left_more_message( left_count, palette, tab_separator(capabilities), left_more_tab_index, ); // right_more_tab_index is the first tab to the right of the rightmost visible tab let right_more_tab_index = left_count + tabs_to_render.len(); let collapsed_right = right_more_message( right_count, palette, tab_separator(capabilities), right_more_tab_index, ); let total_size = collapsed_left.len + middle_size + collapsed_right.len; if total_size > cols { // break and dont add collapsed tabs to tabs_to_render, they will not fit break; } let left = if let Some(tab) = tabs_before_active.last() { tab.len } else { usize::MAX }; let right = if let Some(tab) = tabs_after_active.first() { tab.len } else { usize::MAX }; // total size is shortened if the next tab to be added is the last one, as that will remove the collapsed tab let size_by_adding_left = left.saturating_add(total_size) .saturating_sub(if left_count == 1 { collapsed_left.len } else { 0 }); let size_by_adding_right = right .saturating_add(total_size) .saturating_sub(if right_count == 1 { collapsed_right.len } else { 0 }); let left_fits = size_by_adding_left <= cols; let right_fits = size_by_adding_right <= cols; // active tab is kept in the middle by adding to the side that // has less width, or if the tab on the other side doesn't fit if (total_left <= total_right || !right_fits) && left_fits { // add left tab let tab = tabs_before_active.pop().unwrap(); middle_size += tab.len; total_left += tab.len; tabs_to_render.insert(0, tab); } else if right_fits { // add right tab let tab = tabs_after_active.remove(0); middle_size += tab.len; total_right += tab.len; tabs_to_render.push(tab); } else { // there's either no space to add more tabs or no more tabs to add, so we're done tabs_to_render.insert(0, collapsed_left); tabs_to_render.push(collapsed_right); break; } } } fn left_more_message( tab_count_to_the_left: usize, palette: Styling, separator: &str, tab_index: usize, ) -> LinePart { if tab_count_to_the_left == 0 { return LinePart::default(); } let more_text = if tab_count_to_the_left < 10000 { format!(" ← +{} ", tab_count_to_the_left) } else { " ← +many ".to_string() }; // 238 // chars length plus separator length on both sides let more_text_len = more_text.width() + 2 * separator.width(); let (text_color, sep_color) = ( palette.ribbon_unselected.base, palette.text_unselected.background, ); let left_separator = style!(sep_color, palette.ribbon_unselected.background).paint(separator); let more_styled_text = style!(text_color, palette.ribbon_unselected.background) .bold() .paint(more_text); let right_separator = style!(palette.ribbon_unselected.background, sep_color).paint(separator); let more_styled_text = ANSIStrings(&[left_separator, more_styled_text, right_separator]).to_string(); LinePart { part: more_styled_text, len: more_text_len, tab_index: Some(tab_index), } } fn right_more_message( tab_count_to_the_right: usize, palette: Styling, separator: &str, tab_index: usize, ) -> LinePart { if tab_count_to_the_right == 0 { return LinePart::default(); }; let more_text = if tab_count_to_the_right < 10000 { format!(" +{} → ", tab_count_to_the_right) } else { " +many → ".to_string() }; // chars length plus separator length on both sides let more_text_len = more_text.width() + 2 * separator.width(); let (text_color, sep_color) = ( palette.ribbon_unselected.base, palette.text_unselected.background, ); let left_separator = style!(sep_color, palette.ribbon_unselected.background).paint(separator); let more_styled_text = style!(text_color, palette.ribbon_unselected.background) .bold() .paint(more_text); let right_separator = style!(palette.ribbon_unselected.background, sep_color).paint(separator); let more_styled_text = ANSIStrings(&[left_separator, more_styled_text, right_separator]).to_string(); LinePart { part: more_styled_text, len: more_text_len, tab_index: Some(tab_index), } } fn tab_line_prefix(session_name: Option<&str>, palette: Styling, cols: usize) -> Vec<LinePart> { let prefix_text = " Zellij ".to_string(); let running_text_len = prefix_text.chars().count(); let text_color = palette.text_unselected.base; let bg_color = palette.text_unselected.background; let prefix_styled_text = style!(text_color, bg_color).bold().paint(prefix_text); let mut parts = vec![LinePart { part: prefix_styled_text.to_string(), len: running_text_len, tab_index: None, }]; if let Some(name) = session_name { let name_part = format!("({}) ", name); let name_part_len = name_part.width(); let text_color = palette.text_unselected.base; let name_part_styled_text = style!(text_color, bg_color).bold().paint(name_part); if cols.saturating_sub(running_text_len) >= name_part_len { parts.push(LinePart { part: name_part_styled_text.to_string(), len: name_part_len, tab_index: None, }) } } parts } pub fn tab_separator(capabilities: PluginCapabilities) -> &'static str { if !capabilities.arrow_fonts { ARROW_SEPARATOR } else { "" } } pub fn tab_line( session_name: Option<&str>, mut all_tabs: Vec<LinePart>, active_tab_index: usize, cols: usize, palette: Styling, capabilities: PluginCapabilities, hide_session_name: bool, tab_info: Option<&TabInfo>, mode_info: &ModeInfo, hide_swap_layout_indicator: bool, background: &PaletteColor, ) -> Vec<LinePart> { let mut tabs_after_active = all_tabs.split_off(active_tab_index); let mut tabs_before_active = all_tabs; let active_tab = if !tabs_after_active.is_empty() { tabs_after_active.remove(0) } else { tabs_before_active.pop().unwrap() }; let mut prefix = match hide_session_name { true => tab_line_prefix(None, palette, cols), false => tab_line_prefix(session_name, palette, cols), }; let mut swap_layout_indicator = if hide_swap_layout_indicator { None } else { tab_info.and_then(|tab_info| { swap_layout_status( &tab_info.active_swap_layout_name, tab_info.is_swap_layout_dirty, mode_info, !capabilities.arrow_fonts, ) }) }; let non_tab_len = get_current_title_len(&prefix) + swap_layout_indicator.as_ref().map(|s| s.len).unwrap_or(0); let mut tabs_to_render = vec![active_tab]; populate_tabs_in_tab_line( &mut tabs_before_active, &mut tabs_after_active, &mut tabs_to_render, cols.saturating_sub(non_tab_len), palette, capabilities, ); prefix.append(&mut tabs_to_render); prefix.append(&mut vec![LinePart { part: match background { PaletteColor::Rgb((r, g, b)) => format!("\u{1b}[48;2;{};{};{}m\u{1b}[0K", r, g, b), PaletteColor::EightBit(color) => format!("\u{1b}[48;5;{}m\u{1b}[0K", color), }, len: 0, tab_index: None, }]); if let Some(mut swap_layout_indicator) = swap_layout_indicator.take() { let remaining_space = cols .saturating_sub(prefix.iter().fold(0, |len, part| len + part.len)) .saturating_sub(swap_layout_indicator.len); let mut padding = String::new(); let mut padding_len = 0; for _ in 0..remaining_space { padding.push_str( &style!( palette.text_unselected.background, palette.text_unselected.background ) .paint(" ") .to_string(), ); padding_len += 1; } swap_layout_indicator.part = format!("{}{}", padding, swap_layout_indicator.part); swap_layout_indicator.len += padding_len; prefix.push(swap_layout_indicator); } prefix } fn swap_layout_status( swap_layout_name: &Option<String>, is_swap_layout_dirty: bool, mode_info: &ModeInfo, supports_arrow_fonts: bool, ) -> Option<LinePart> { match swap_layout_name { Some(swap_layout_name) => { let mode_keybinds = mode_info.get_mode_keybinds(); let prev_next_keys = action_key_group( &mode_keybinds, &[&[Action::PreviousSwapLayout], &[Action::NextSwapLayout]], ); let mut text = style_key_with_modifier(&prev_next_keys, Some(0)); text.append(&ribbon_as_line_part( &swap_layout_name.to_uppercase(), !is_swap_layout_dirty, supports_arrow_fonts, )); Some(text) }, None => None, } } pub fn ribbon_as_line_part(text: &str, is_selected: bool, supports_arrow_fonts: bool) -> LinePart { let ribbon_text = if is_selected { Text::new(text).selected() } else { Text::new(text) }; let part = serialize_ribbon(&ribbon_text); let mut len = text.width() + 2; if supports_arrow_fonts { len += 2; }; LinePart { part, len, tab_index: None, } } pub fn style_key_with_modifier(keyvec: &[KeyWithModifier], color_index: Option<usize>) -> LinePart { if keyvec.is_empty() { return LinePart::default(); } let common_modifiers = get_common_modifiers(keyvec.iter().collect()); let no_common_modifier = common_modifiers.is_empty(); let modifier_str = common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-"); // Prints the keys let key = keyvec .iter() .map(|key| { if no_common_modifier || keyvec.len() == 1 { format!("{}", key) } else { format!("{}", key.strip_common_modifiers(&common_modifiers)) } }) .collect::<Vec<String>>(); // Special handling of some pre-defined keygroups let key_string = key.join(""); let key_separator = match &key_string[..] { "HJKL" => "", "hjkl" => "", "←↓↑→" => "", "←→" => "", "↓↑" => "", "[]" => "", _ => "|", }; if no_common_modifier || key.len() == 1 { let key_string_text = format!(" {} ", key.join(key_separator)); let text = if let Some(color_index) = color_index { Text::new(&key_string_text) .color_range(color_index, ..) .opaque() } else { Text::new(&key_string_text).opaque() }; LinePart { part: serialize_text(&text), len: key_string_text.width(), ..Default::default() } } else { let key_string_without_modifier = format!("{}", key.join(key_separator)); let key_string_text = format!(" {} <{}> ", modifier_str, key_string_without_modifier); let text = if let Some(color_index) = color_index { Text::new(&key_string_text) .color_range(color_index, ..modifier_str.width() + 1) .color_range( color_index, modifier_str.width() + 3 ..modifier_str.width() + 3 + key_string_without_modifier.width(), ) .opaque() } else { Text::new(&key_string_text).opaque() }; LinePart { part: serialize_text(&text), len: key_string_text.width(), ..Default::default() } } } pub fn get_common_modifiers(mut keyvec: Vec<&KeyWithModifier>) -> Vec<KeyModifier> { if keyvec.is_empty() { return vec![]; } let mut common_modifiers = keyvec.pop().unwrap().key_modifiers.clone(); for key in keyvec { common_modifiers = common_modifiers .intersection(&key.key_modifiers) .cloned() .collect(); } common_modifiers.into_iter().collect() } pub fn action_key_group( keymap: &[(KeyWithModifier, Vec<Action>)], actions: &[&[Action]], ) -> Vec<KeyWithModifier> { let mut ret = vec![]; for action in actions { ret.extend(action_key(keymap, action)); } ret } pub fn action_key( keymap: &[(KeyWithModifier, Vec<Action>)], action: &[Action], ) -> Vec<KeyWithModifier> { keymap .iter() .filter_map(|(key, acvec)| { let matching = acvec .iter() .zip(action) .filter(|(a, b)| a.shallow_eq(b)) .count(); if matching == acvec.len() && matching == action.len() { Some(key.clone()) } else { None } }) .collect::<Vec<KeyWithModifier>>() }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/tab-bar/src/tab.rs
default-plugins/tab-bar/src/tab.rs
use crate::{line::tab_separator, LinePart}; use ansi_term::{ANSIString, ANSIStrings}; use unicode_width::UnicodeWidthStr; use zellij_tile::prelude::*; use zellij_tile_utils::style; fn cursors<'a>( focused_clients: &'a [ClientId], multiplayer_colors: MultiplayerColors, ) -> (Vec<ANSIString<'a>>, usize) { // cursor section, text length let mut len = 0; let mut cursors = vec![]; for client_id in focused_clients.iter() { if let Some(color) = client_id_to_colors(*client_id, multiplayer_colors) { cursors.push(style!(color.1, color.0).paint(" ")); len += 1; } } (cursors, len) } pub fn render_tab( text: String, tab: &TabInfo, is_alternate_tab: bool, palette: Styling, separator: &str, ) -> LinePart { let focused_clients = tab.other_focused_clients.as_slice(); let separator_width = separator.width(); let alternate_tab_color = if is_alternate_tab { palette.ribbon_unselected.emphasis_1 } else { palette.ribbon_unselected.background }; let background_color = if tab.active { palette.ribbon_selected.background } else if is_alternate_tab { alternate_tab_color } else { palette.ribbon_unselected.background }; let foreground_color = if tab.active { palette.ribbon_selected.base } else { palette.ribbon_unselected.base }; let separator_fill_color = palette.text_unselected.background; let left_separator = style!(separator_fill_color, background_color).paint(separator); let mut tab_text_len = text.width() + (separator_width * 2) + 2; // +2 for padding let tab_styled_text = style!(foreground_color, background_color) .bold() .paint(format!(" {} ", text)); let right_separator = style!(background_color, separator_fill_color).paint(separator); let tab_styled_text = if !focused_clients.is_empty() { let (cursor_section, extra_length) = cursors(focused_clients, palette.multiplayer_user_colors); tab_text_len += extra_length + 2; // 2 for cursor_beginning and cursor_end let mut s = String::new(); let cursor_beginning = style!(foreground_color, background_color) .bold() .paint("[") .to_string(); let cursor_section = ANSIStrings(&cursor_section).to_string(); let cursor_end = style!(foreground_color, background_color) .bold() .paint("]") .to_string(); s.push_str(&left_separator.to_string()); s.push_str(&tab_styled_text.to_string()); s.push_str(&cursor_beginning); s.push_str(&cursor_section); s.push_str(&cursor_end); s.push_str(&right_separator.to_string()); s } else { ANSIStrings(&[left_separator, tab_styled_text, right_separator]).to_string() }; LinePart { part: tab_styled_text, len: tab_text_len, tab_index: Some(tab.position), } } pub fn tab_style( mut tabname: String, tab: &TabInfo, mut is_alternate_tab: bool, palette: Styling, capabilities: PluginCapabilities, ) -> LinePart { let separator = tab_separator(capabilities); if tab.is_fullscreen_active { tabname.push_str(" (FULLSCREEN)"); } else if tab.is_sync_panes_active { tabname.push_str(" (SYNC)"); } // we only color alternate tabs differently if we can't use the arrow fonts to separate them if !capabilities.arrow_fonts { is_alternate_tab = false; } render_tab(tabname, tab, is_alternate_tab, palette, separator) } pub(crate) fn get_tab_to_focus( tab_line: &[LinePart], active_tab_idx: usize, mouse_click_col: usize, ) -> Option<usize> { let clicked_line_part = get_clicked_line_part(tab_line, mouse_click_col)?; let clicked_tab_idx = clicked_line_part.tab_index?; // tabs are indexed starting from 1 so we need to add 1 let clicked_tab_idx = clicked_tab_idx + 1; if clicked_tab_idx != active_tab_idx { return Some(clicked_tab_idx); } None } pub(crate) fn get_clicked_line_part( tab_line: &[LinePart], mouse_click_col: usize, ) -> Option<&LinePart> { let mut len = 0; for tab_line_part in tab_line { if mouse_click_col >= len && mouse_click_col < len + tab_line_part.len { return Some(tab_line_part); } len += tab_line_part.len; } None }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/one_line_ui.rs
default-plugins/status-bar/src/one_line_ui.rs
use ansi_term::{ANSIString, ANSIStrings}; use ansi_term::{ Color::{Fixed, RGB}, Style, }; use std::collections::HashMap; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; use zellij_tile_utils::palette_match; use crate::first_line::{to_char, KeyAction, KeyMode, KeyShortcut}; use crate::second_line::{system_clipboard_error, text_copied_hint}; use crate::{action_key, action_key_group, color_elements, MORE_MSG, TO_NORMAL}; use crate::{ColoredElements, LinePart}; use unicode_width::UnicodeWidthStr; pub fn one_line_ui( help: &ModeInfo, tab_info: Option<&TabInfo>, mut max_len: usize, separator: &str, base_mode_is_locked: bool, text_copied_to_clipboard_destination: Option<CopyDestination>, clipboard_failure: bool, ) -> LinePart { if let Some(text_copied_to_clipboard_destination) = text_copied_to_clipboard_destination { return text_copied_hint(text_copied_to_clipboard_destination); } if clipboard_failure { return system_clipboard_error(&help.style.colors); } let mut line_part_to_render = LinePart::default(); let mut append = |line_part: &LinePart, max_len: &mut usize| { line_part_to_render.append(line_part); *max_len = max_len.saturating_sub(line_part.len); }; render_mode_key_indicators(help, max_len, separator, base_mode_is_locked) .map(|mode_key_indicators| append(&mode_key_indicators, &mut max_len)) .and_then(|_| match help.mode { InputMode::Normal | InputMode::Locked => render_secondary_info(help, tab_info, max_len) .map(|secondary_info| append(&secondary_info, &mut max_len)), _ => add_keygroup_separator(help, max_len) .map(|key_group_separator| append(&key_group_separator, &mut max_len)) .and_then(|_| keybinds(help, max_len)) .map(|keybinds| append(&keybinds, &mut max_len)), }); line_part_to_render } fn to_base_mode(base_mode: InputMode) -> Action { Action::SwitchToMode { input_mode: base_mode, } } fn base_mode_locked_mode_indicators(help: &ModeInfo) -> HashMap<InputMode, Vec<KeyShortcut>> { let locked_binds = &help.get_keybinds_for_mode(InputMode::Locked); let normal_binds = &help.get_keybinds_for_mode(InputMode::Normal); let pane_binds = &help.get_keybinds_for_mode(InputMode::Pane); let tab_binds = &help.get_keybinds_for_mode(InputMode::Tab); let resize_binds = &help.get_keybinds_for_mode(InputMode::Resize); let move_binds = &help.get_keybinds_for_mode(InputMode::Move); let scroll_binds = &help.get_keybinds_for_mode(InputMode::Scroll); let session_binds = &help.get_keybinds_for_mode(InputMode::Session); HashMap::from([ ( InputMode::Locked, vec![KeyShortcut::new( KeyMode::Unselected, KeyAction::Unlock, to_char(action_key( locked_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Normal, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Pane, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Pane, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Tab, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Tab, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Resize, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Resize, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Move, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Move, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Search, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Scroll, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Session, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Session, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Quit, to_char(action_key(normal_binds, &[Action::Quit])), ), ], ), ( InputMode::Pane, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( pane_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::Selected, KeyAction::Pane, to_char(action_key( pane_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), ), ], ), ( InputMode::Tab, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( tab_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::Selected, KeyAction::Tab, to_char(action_key( tab_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), ), ], ), ( InputMode::Resize, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( resize_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::Selected, KeyAction::Resize, to_char(action_key( resize_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), ), ], ), ( InputMode::Move, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( move_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::Selected, KeyAction::Move, to_char(action_key( move_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), ), ], ), ( InputMode::Scroll, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( scroll_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::Selected, KeyAction::Search, to_char(action_key( scroll_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), ), ], ), ( InputMode::Session, vec![ KeyShortcut::new( KeyMode::Selected, KeyAction::Unlock, to_char(action_key( session_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::Selected, KeyAction::Session, to_char(action_key( session_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), ), ], ), ]) } fn base_mode_normal_mode_indicators(help: &ModeInfo) -> HashMap<InputMode, Vec<KeyShortcut>> { let locked_binds = &help.get_keybinds_for_mode(InputMode::Locked); let normal_binds = &help.get_keybinds_for_mode(InputMode::Normal); let pane_binds = &help.get_keybinds_for_mode(InputMode::Pane); let tab_binds = &help.get_keybinds_for_mode(InputMode::Tab); let resize_binds = &help.get_keybinds_for_mode(InputMode::Resize); let move_binds = &help.get_keybinds_for_mode(InputMode::Move); let scroll_binds = &help.get_keybinds_for_mode(InputMode::Scroll); let session_binds = &help.get_keybinds_for_mode(InputMode::Session); HashMap::from([ ( InputMode::Locked, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Lock, to_char(action_key( locked_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Normal, vec![ KeyShortcut::new( KeyMode::Unselected, KeyAction::Lock, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Pane, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Pane, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Tab, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Tab, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Resize, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Resize, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Move, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Move, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Search, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Scroll, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Session, to_char(action_key( normal_binds, &[Action::SwitchToMode { input_mode: InputMode::Session, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Quit, to_char(action_key(normal_binds, &[Action::Quit])), ), ], ), ( InputMode::Pane, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Pane, to_char(action_key( pane_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Tab, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Tab, to_char(action_key( tab_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Resize, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Resize, to_char(action_key( resize_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Move, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Move, to_char(action_key( move_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Scroll, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Search, to_char(action_key( scroll_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ( InputMode::Session, vec![KeyShortcut::new( KeyMode::Selected, KeyAction::Session, to_char(action_key( session_binds, &[Action::SwitchToMode { input_mode: InputMode::Normal, }], )), )], ), ]) } fn render_mode_key_indicators( help: &ModeInfo, max_len: usize, separator: &str, base_mode_is_locked: bool, ) -> Option<LinePart> { let mut line_part_to_render = LinePart::default(); let supports_arrow_fonts = !help.capabilities.arrow_fonts; let colored_elements = color_elements(help.style.colors, !supports_arrow_fonts); let default_keys = if base_mode_is_locked { base_mode_locked_mode_indicators(help) } else { base_mode_normal_mode_indicators(help) }; match common_modifiers_in_all_modes(&default_keys) { Some(modifiers) => { if let Some(default_keys) = default_keys.get(&help.mode) { let keys_without_common_modifiers: Vec<KeyShortcut> = default_keys .iter() .map(|key_shortcut| { let key = key_shortcut .get_key() .map(|k| k.strip_common_modifiers(&modifiers)); let mode = key_shortcut.get_mode(); let action = key_shortcut.get_action(); KeyShortcut::new(mode, action, key) }) .collect(); render_common_modifiers( &colored_elements, help, &modifiers, &mut line_part_to_render, separator, ); let full_shortcut_list = full_inline_keys_modes_shortcut_list(&keys_without_common_modifiers, help); if line_part_to_render.len + full_shortcut_list.len <= max_len { line_part_to_render.append(&full_shortcut_list); } else { let shortened_shortcut_list = shortened_inline_keys_modes_shortcut_list( &keys_without_common_modifiers, help, ); if line_part_to_render.len + shortened_shortcut_list.len <= max_len { line_part_to_render.append(&shortened_shortcut_list); } } } }, None => { if let Some(default_keys) = default_keys.get(&help.mode) { let full_shortcut_list = full_modes_shortcut_list(&default_keys, help); if line_part_to_render.len + full_shortcut_list.len <= max_len { line_part_to_render.append(&full_shortcut_list); } else { let shortened_shortcut_list = shortened_modes_shortcut_list(&default_keys, help); if line_part_to_render.len + shortened_shortcut_list.len <= max_len { line_part_to_render.append(&shortened_shortcut_list); } } } }, } if line_part_to_render.len <= max_len { Some(line_part_to_render) } else { None } } fn full_inline_keys_modes_shortcut_list( keys_without_common_modifiers: &Vec<KeyShortcut>, help: &ModeInfo, ) -> LinePart { let mut full_shortcut_list = LinePart::default(); for key in keys_without_common_modifiers { let is_selected = key.is_selected(); let shortcut = add_shortcut_with_inline_key( help, &key.full_text(), key.key .as_ref() .map(|k| vec![k.clone()]) .unwrap_or_else(|| vec![]), is_selected, ); full_shortcut_list.append(&shortcut); } full_shortcut_list } fn shortened_inline_keys_modes_shortcut_list( keys_without_common_modifiers: &Vec<KeyShortcut>, help: &ModeInfo, ) -> LinePart { let mut shortened_shortcut_list = LinePart::default(); for key in keys_without_common_modifiers { let is_selected = key.is_selected(); let shortcut = add_shortcut_with_key_only( help, key.key .as_ref() .map(|k| vec![k.clone()]) .unwrap_or_else(|| vec![]), is_selected, ); shortened_shortcut_list.append(&shortcut); } shortened_shortcut_list } fn full_modes_shortcut_list(default_keys: &Vec<KeyShortcut>, help: &ModeInfo) -> LinePart { let mut full_shortcut_list = LinePart::default(); for key in default_keys { let is_selected = key.is_selected(); full_shortcut_list.append(&add_shortcut( help, &key.full_text(), &key.key .as_ref() .map(|k| vec![k.clone()]) .unwrap_or_else(|| vec![]), is_selected, Some(3), )); } full_shortcut_list } fn shortened_modes_shortcut_list(default_keys: &Vec<KeyShortcut>, help: &ModeInfo) -> LinePart { let mut shortened_shortcut_list = LinePart::default(); for key in default_keys { let is_selected = key.is_selected(); shortened_shortcut_list.append(&add_shortcut( help, &key.short_text(), &key.key .as_ref() .map(|k| vec![k.clone()]) .unwrap_or_else(|| vec![]), is_selected, Some(3), )); } shortened_shortcut_list } fn common_modifiers_in_all_modes( key_shortcuts: &HashMap<InputMode, Vec<KeyShortcut>>, ) -> Option<Vec<KeyModifier>> { let Some(mut common_modifiers) = key_shortcuts.iter().next().and_then(|k| { k.1.iter() .next() .and_then(|k| k.get_key().map(|k| k.key_modifiers.clone())) }) else { return None; }; for (_mode, key_shortcuts) in key_shortcuts { if key_shortcuts.is_empty() { return None; } let Some(mut common_modifiers_for_mode) = key_shortcuts .iter() .next() .unwrap() .get_key() .map(|k| k.key_modifiers.clone()) else { return None; }; for key in key_shortcuts { let Some(key) = key.get_key() else { return None; }; common_modifiers_for_mode = common_modifiers_for_mode .intersection(&key.key_modifiers) .cloned() .collect(); } common_modifiers = common_modifiers .intersection(&common_modifiers_for_mode) .cloned() .collect(); } if common_modifiers.is_empty() { return None; } Some(common_modifiers.into_iter().collect()) } fn render_common_modifiers( palette: &ColoredElements, mode_info: &ModeInfo, common_modifiers: &Vec<KeyModifier>, line_part_to_render: &mut LinePart, separator: &str, ) { let prefix_text = if mode_info.capabilities.arrow_fonts { // Add extra space in simplified ui format!( " {} + ", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") ) } else { format!( " {} +", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") ) }; let suffix_separator = palette.superkey_suffix_separator.paint(separator); line_part_to_render.part = format!( "{}{}{}", line_part_to_render.part, serialize_text(&Text::new(&prefix_text).opaque()), suffix_separator ); line_part_to_render.len += prefix_text.chars().count() + separator.chars().count(); } fn render_secondary_info( help: &ModeInfo, tab_info: Option<&TabInfo>, max_len: usize, ) -> Option<LinePart> { let mut secondary_info = LinePart::default(); let supports_arrow_fonts = !help.capabilities.arrow_fonts; let colored_elements = color_elements(help.style.colors, !supports_arrow_fonts); let secondary_keybinds = secondary_keybinds(&help, tab_info, max_len); secondary_info.append(&secondary_keybinds); let remaining_space = max_len.saturating_sub(secondary_info.len).saturating_sub(1); // 1 for the end padding of the line let mut padding = String::new(); let mut padding_len = 0; for _ in 0..remaining_space { padding.push_str(&ANSIStrings(&[colored_elements.superkey_prefix.paint(" ")]).to_string()); padding_len += 1; } secondary_info.part = format!("{}{}", padding, secondary_info.part); secondary_info.len += padding_len; if secondary_info.len <= max_len { Some(secondary_info) } else { None } } fn should_show_focus_and_resize_shortcuts(tab_info: Option<&TabInfo>) -> bool { let Some(tab_info) = tab_info else { return false; }; let are_floating_panes_visible = tab_info.are_floating_panes_visible; if are_floating_panes_visible { tab_info.selectable_floating_panes_count > 1 } else { tab_info.selectable_tiled_panes_count > 1 } } fn secondary_keybinds(help: &ModeInfo, tab_info: Option<&TabInfo>, max_len: usize) -> LinePart { let mut secondary_info = LinePart::default(); let binds = &help.get_mode_keybinds(); let should_show_focus_and_resize_shortcuts = should_show_focus_and_resize_shortcuts(tab_info); // New Pane let new_pane_action_key = action_key( binds, &[Action::NewPane { direction: None, pane_name: None, start_suppressed: false, }], ); let mut new_pane_key_to_display = new_pane_action_key .iter() .find(|k| k.is_key_with_alt_modifier(BareKey::Char('n'))) .or_else(|| new_pane_action_key.iter().next()); let new_pane_key_to_display = if let Some(new_pane_key_to_display) = new_pane_key_to_display.take() { vec![new_pane_key_to_display.clone()] } else { vec![] }; // Resize let resize_increase_action_key = action_key( binds, &[Action::Resize { resize: Resize::Increase, direction: None, }], ); let resize_increase_key = resize_increase_action_key .iter() .find(|k| k.bare_key == BareKey::Char('+')) .or_else(|| resize_increase_action_key.iter().next()); let resize_decrease_action_key = action_key( binds, &[Action::Resize { resize: Resize::Decrease, direction: None, }], ); let resize_decrease_key = resize_decrease_action_key .iter() .find(|k| k.bare_key == BareKey::Char('-')) .or_else(|| resize_increase_action_key.iter().next()); let mut resize_shortcuts = vec![]; if let Some(resize_increase_key) = resize_increase_key { resize_shortcuts.push(resize_increase_key.clone()); } if let Some(resize_decrease_key) = resize_decrease_key { resize_shortcuts.push(resize_decrease_key.clone()); } // Move focus let mut move_focus_shortcuts: Vec<KeyWithModifier> = vec![]; // Left let move_focus_left_action_key = action_key( binds, &[Action::MoveFocusOrTab { direction: Direction::Left, }], ); let move_focus_left_key = move_focus_left_action_key .iter() .find(|k| k.bare_key == BareKey::Left) .or_else(|| move_focus_left_action_key.iter().next()); if let Some(move_focus_left_key) = move_focus_left_key { move_focus_shortcuts.push(move_focus_left_key.clone()); } // Down let move_focus_left_action_key = action_key( binds, &[Action::MoveFocus { direction: Direction::Down, }], ); let move_focus_left_key = move_focus_left_action_key .iter() .find(|k| k.bare_key == BareKey::Down) .or_else(|| move_focus_left_action_key.iter().next()); if let Some(move_focus_left_key) = move_focus_left_key { move_focus_shortcuts.push(move_focus_left_key.clone()); } // Up let move_focus_left_action_key = action_key( binds, &[Action::MoveFocus { direction: Direction::Up, }], ); let move_focus_left_key = move_focus_left_action_key .iter() .find(|k| k.bare_key == BareKey::Up) .or_else(|| move_focus_left_action_key.iter().next()); if let Some(move_focus_left_key) = move_focus_left_key { move_focus_shortcuts.push(move_focus_left_key.clone()); } // Right let move_focus_left_action_key = action_key( binds, &[Action::MoveFocusOrTab { direction: Direction::Right, }], ); let move_focus_left_key = move_focus_left_action_key .iter() .find(|k| k.bare_key == BareKey::Right) .or_else(|| move_focus_left_action_key.iter().next()); if let Some(move_focus_left_key) = move_focus_left_key { move_focus_shortcuts.push(move_focus_left_key.clone()); } let toggle_floating_action_key = action_key(binds, &[Action::ToggleFloatingPanes]); let mut toggle_floating_action_key = toggle_floating_action_key .iter() .find(|k| k.is_key_with_alt_modifier(BareKey::Char('f'))) .or_else(|| toggle_floating_action_key.iter().next()); let toggle_floating_key_to_display = if let Some(toggle_floating_key_to_display) = toggle_floating_action_key.take() { vec![toggle_floating_key_to_display.clone()] } else { vec![] }; let are_floating_panes_visible = tab_info .map(|t| t.are_floating_panes_visible) .unwrap_or(false); let common_modifiers = get_common_modifiers( [ new_pane_key_to_display.clone(), move_focus_shortcuts.clone(), resize_shortcuts.clone(), toggle_floating_key_to_display.clone(), ] .iter() .flatten() .collect(), ); let no_common_modifier = common_modifiers.is_empty(); if no_common_modifier { secondary_info.append(&add_shortcut( help, "New Pane", &new_pane_key_to_display, false, Some(0), )); if should_show_focus_and_resize_shortcuts { secondary_info.append(&add_shortcut( help, "Change Focus", &move_focus_shortcuts, false, Some(0), )); secondary_info.append(&add_shortcut( help, "Resize", &resize_shortcuts, false, Some(0), )); } secondary_info.append(&add_shortcut( help, "Floating", &toggle_floating_key_to_display, are_floating_panes_visible, Some(0), )); } else { let modifier_str = text_as_line_part_with_emphasis( format!( "{} + ", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") ), 0, ); secondary_info.append(&modifier_str); let new_pane_key_to_display: Vec<KeyWithModifier> = new_pane_key_to_display .iter()
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/second_line.rs
default-plugins/status-bar/src/second_line.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; use zellij_tile_utils::palette_match; use crate::{ action_key, action_key_group, style_key_with_modifier, tip::{data::TIPS, TipFn}, LinePart, MORE_MSG, TO_NORMAL, }; fn full_length_shortcut( is_first_shortcut: bool, key: Vec<KeyWithModifier>, action: &str, palette: Styling, ) -> LinePart { if key.is_empty() { return LinePart::default(); } let text_color = palette_match!(palette.text_unselected.base); let separator = if is_first_shortcut { " " } else { " / " }; let mut bits: Vec<ANSIString> = vec![Style::new().fg(text_color).paint(separator)]; bits.extend(style_key_with_modifier(&key, &palette, None)); bits.push( Style::new() .fg(text_color) .bold() .paint(format!(" {}", action)), ); let part = ANSIStrings(&bits); LinePart { part: part.to_string(), len: unstyled_len(&part), } } fn locked_interface_indication(palette: Styling) -> LinePart { let locked_text = " -- INTERFACE LOCKED -- "; let locked_text_len = locked_text.chars().count(); let text_color = palette_match!(palette.text_unselected.base); let locked_styled_text = Style::new().fg(text_color).bold().paint(locked_text); LinePart { part: locked_styled_text.to_string(), len: locked_text_len, } } fn add_shortcut( help: &ModeInfo, linepart: &LinePart, text: &str, keys: Vec<KeyWithModifier>, ) -> LinePart { let shortcut = if linepart.len == 0 { full_length_shortcut(true, keys, text, help.style.colors) } else { full_length_shortcut(false, keys, text, help.style.colors) }; let mut new_linepart = LinePart::default(); new_linepart.len += linepart.len + shortcut.len; new_linepart.part = format!("{}{}", linepart.part, shortcut); new_linepart } fn full_shortcut_list_nonstandard_mode(help: &ModeInfo) -> LinePart { let mut line_part = LinePart::default(); let keys_and_hints = get_keys_and_hints(help); for (long, _short, keys) in keys_and_hints.into_iter() { line_part = add_shortcut(help, &line_part, &long, keys.to_vec()); } line_part } /// Collect all relevant keybindings and hints to display. /// /// Creates a vector with tuples containing the following entries: /// /// - A String to display for this keybinding when there are no size restrictions, /// - A shortened String (where sensible) to display if the whole second line becomes too long, /// - A `Vec<Key>` of the keys that map to this keyhint /// /// This vector is created by iterating over the keybindings for the current [`InputMode`] and /// storing all Keybindings that match pre-defined patterns of `Action`s. For example, the /// `InputMode::Pane` input mode determines which keys to display for the "Move focus" hint by /// searching the keybindings for anything that matches the `Action::MoveFocus(_)` action. Since by /// default multiple keybindings map to some action patterns (e.g. `Action::MoveFocus(_)` is bound /// to "hjkl", the arrow keys and "Alt + <hjkl>"), we deduplicate the vector of all keybindings /// before processing it. /// /// Therefore we sort it by the [`Key`]s of the current keymap and deduplicate the resulting sorted /// vector by the `Vec<Action>` action vectors bound to the keys. As such, when multiple keys map /// to the same sequence of actions, the keys that appear first in the [`Key`] structure will be /// displayed. // Please don't let rustfmt play with the formatting. It will stretch out the function to about // three times the length and all the keybinding vectors we generate become virtually unreadable // for humans. #[rustfmt::skip] fn get_keys_and_hints(mi: &ModeInfo) -> Vec<(String, String, Vec<KeyWithModifier>)> { use Action as A; use InputMode as IM; use Direction as Dir; use actions::SearchDirection as SDir; use actions::SearchOption as SOpt; let mut old_keymap = mi.get_mode_keybinds(); let s = |string: &str| string.to_string(); // Find a keybinding to get back to "Normal" input mode. In this case we prefer '\n' over other // choices. Do it here before we dedupe the keymap below! let to_normal_keys = action_key(&old_keymap, &[TO_NORMAL]); let to_normal_key = if to_normal_keys.contains(&KeyWithModifier::new(BareKey::Enter)) { vec![KeyWithModifier::new(BareKey::Enter)] } else { // Yield `vec![key]` if `to_normal_keys` has at least one key, or an empty vec otherwise. to_normal_keys.into_iter().take(1).collect() }; // Sort and deduplicate the keybindings first. We sort after the `Key`s, and deduplicate by // their `Action` vectors. An unstable sort is fine here because if the user maps anything to // the same key again, anything will happen... old_keymap.sort_unstable_by(|(keya, _), (keyb, _)| keya.partial_cmp(keyb).unwrap()); let mut known_actions: Vec<Vec<Action>> = vec![]; let mut km = vec![]; for (key, acvec) in old_keymap { if known_actions.contains(&acvec) { // This action is known already continue; } else { known_actions.push(acvec.to_vec()); km.push((key, acvec)); } } if mi.mode == IM::Pane { vec![ (s("New"), s("New"), action_key(&km, &[A::NewPane{direction: None, pane_name: None, start_suppressed: false}, TO_NORMAL])), (s("Change Focus"), s("Move"), action_key_group(&km, &[&[A::MoveFocus{direction: Dir::Left}], &[A::MoveFocus{direction: Dir::Down}], &[A::MoveFocus{direction: Dir::Up}], &[A::MoveFocus{direction: Dir::Right}]])), (s("Close"), s("Close"), action_key(&km, &[A::CloseFocus, TO_NORMAL])), (s("Rename"), s("Rename"), action_key(&km, &[A::SwitchToMode{input_mode: IM::RenamePane}, A::PaneNameInput{input: vec![0]}])), (s("Toggle Fullscreen"), s("Fullscreen"), action_key(&km, &[A::ToggleFocusFullscreen, TO_NORMAL])), (s("Toggle Floating"), s("Floating"), action_key(&km, &[A::ToggleFloatingPanes, TO_NORMAL])), (s("Toggle Embed"), s("Embed"), action_key(&km, &[A::TogglePaneEmbedOrFloating, TO_NORMAL])), (s("Select pane"), s("Select"), to_normal_key), ]} else if mi.mode == IM::Tab { // With the default bindings, "Move focus" for tabs is tricky: It binds all the arrow keys // to moving tabs focus (left/up go left, right/down go right). Since we sort the keys // above and then dedpulicate based on the actions, we will end up with LeftArrow for // "left" and DownArrow for "right". What we really expect is to see LeftArrow and // RightArrow. // FIXME: So for lack of a better idea we just check this case manually here. let old_keymap = mi.get_mode_keybinds(); let focus_keys_full: Vec<KeyWithModifier> = action_key_group(&old_keymap, &[&[A::GoToPreviousTab], &[A::GoToNextTab]]); let focus_keys = if focus_keys_full.contains(&KeyWithModifier::new(BareKey::Left)) && focus_keys_full.contains(&KeyWithModifier::new(BareKey::Right)) { vec![KeyWithModifier::new(BareKey::Left), KeyWithModifier::new(BareKey::Right)] } else { action_key_group(&km, &[&[A::GoToPreviousTab], &[A::GoToNextTab]]) }; vec![ (s("New"), s("New"), action_key(&km, &[A::NewTab{ tiled_layout: None, floating_layouts: vec![], swap_tiled_layouts: None, swap_floating_layouts: None, tab_name: None, should_change_focus_to_new_tab: true, cwd: None, initial_panes: None, first_pane_unblock_condition: None, }, TO_NORMAL])), (s("Change focus"), s("Move"), focus_keys), (s("Close"), s("Close"), action_key(&km, &[A::CloseTab, TO_NORMAL])), (s("Rename"), s("Rename"), action_key(&km, &[A::SwitchToMode{input_mode: IM::RenameTab}, A::TabNameInput{input: vec![0]}])), (s("Sync"), s("Sync"), action_key(&km, &[A::ToggleActiveSyncTab, TO_NORMAL])), (s("Break pane to new tab"), s("Break out"), action_key(&km, &[A::BreakPane, TO_NORMAL])), (s("Break pane left/right"), s("Break"), action_key_group(&km, &[ &[Action::BreakPaneLeft, TO_NORMAL], &[Action::BreakPaneRight, TO_NORMAL], ])), (s("Toggle"), s("Toggle"), action_key(&km, &[A::ToggleTab])), (s("Select pane"), s("Select"), to_normal_key), ]} else if mi.mode == IM::Resize { vec![ (s("Increase/Decrease size"), s("Increase/Decrease"), action_key_group(&km, &[ &[A::Resize{resize: Resize::Increase, direction: None}], &[A::Resize{resize: Resize::Decrease, direction: None}] ])), (s("Increase to"), s("Increase"), action_key_group(&km, &[ &[A::Resize{resize: Resize::Increase, direction: Some(Dir::Left)}], &[A::Resize{resize: Resize::Increase, direction: Some(Dir::Down)}], &[A::Resize{resize: Resize::Increase, direction: Some(Dir::Up)}], &[A::Resize{resize: Resize::Increase, direction: Some(Dir::Right)}] ])), (s("Decrease from"), s("Decrease"), action_key_group(&km, &[ &[A::Resize{resize: Resize::Decrease, direction: Some(Dir::Left)}], &[A::Resize{resize: Resize::Decrease, direction: Some(Dir::Down)}], &[A::Resize{resize: Resize::Decrease, direction: Some(Dir::Up)}], &[A::Resize{resize: Resize::Decrease, direction: Some(Dir::Right)}] ])), (s("Select pane"), s("Select"), to_normal_key), ]} else if mi.mode == IM::Move { vec![ (s("Switch Location"), s("Move"), action_key_group(&km, &[ &[Action::MovePane{direction: Some(Dir::Left)}], &[Action::MovePane{direction: Some(Dir::Down)}], &[Action::MovePane{direction: Some(Dir::Up)}], &[Action::MovePane{direction: Some(Dir::Right)}]])), ]} else if mi.mode == IM::Scroll { vec![ (s("Enter search term"), s("Search"), action_key(&km, &[A::SwitchToMode{input_mode: IM::EnterSearch}, A::SearchInput{input: vec![0]}])), (s("Scroll"), s("Scroll"), action_key_group(&km, &[&[Action::ScrollDown], &[Action::ScrollUp]])), (s("Scroll page"), s("Scroll"), action_key_group(&km, &[&[Action::PageScrollDown], &[Action::PageScrollUp]])), (s("Scroll half page"), s("Scroll"), action_key_group(&km, &[&[Action::HalfPageScrollDown], &[Action::HalfPageScrollUp]])), (s("Edit scrollback in default editor"), s("Edit"), action_key(&km, &[Action::EditScrollback, TO_NORMAL])), (s("Select pane"), s("Select"), to_normal_key), ]} else if mi.mode == IM::EnterSearch { vec![ (s("When done"), s("Done"), action_key(&km, &[A::SwitchToMode{input_mode: IM::Search}])), (s("Cancel"), s("Cancel"), action_key(&km, &[A::SearchInput{input: vec![27]}, A::SwitchToMode{input_mode: IM::Scroll}])), ]} else if mi.mode == IM::Search { vec![ (s("Enter Search term"), s("Search"), action_key(&km, &[A::SwitchToMode{input_mode: IM::EnterSearch}, A::SearchInput{input: vec![0]}])), (s("Scroll"), s("Scroll"), action_key_group(&km, &[&[Action::ScrollDown], &[Action::ScrollUp]])), (s("Scroll page"), s("Scroll"), action_key_group(&km, &[&[Action::PageScrollDown], &[Action::PageScrollUp]])), (s("Scroll half page"), s("Scroll"), action_key_group(&km, &[&[Action::HalfPageScrollDown], &[Action::HalfPageScrollUp]])), (s("Search down"), s("Down"), action_key(&km, &[A::Search{direction: SDir::Down}])), (s("Search up"), s("Up"), action_key(&km, &[A::Search{direction: SDir::Up}])), (s("Case sensitive"), s("Case"), action_key(&km, &[A::SearchToggleOption{option: SOpt::CaseSensitivity}])), (s("Wrap"), s("Wrap"), action_key(&km, &[A::SearchToggleOption{option: SOpt::Wrap}])), (s("Whole words"), s("Whole"), action_key(&km, &[A::SearchToggleOption{option: SOpt::WholeWord}])), ]} else if mi.mode == IM::Session { vec![ (s("Detach"), s("Detach"), action_key(&km, &[Action::Detach])), (s("Session Manager"), s("Manager"), action_key(&km, &[A::LaunchOrFocusPlugin{plugin: Default::default(), should_float: true, move_to_focused_tab: true, should_open_in_place: false, skip_cache: false}, TO_NORMAL])), // not entirely accurate (s("Select pane"), s("Select"), to_normal_key), ]} else if mi.mode == IM::Tmux { vec![ (s("Move focus"), s("Move"), action_key_group(&km, &[ &[A::MoveFocus{direction: Dir::Left}], &[A::MoveFocus{direction: Dir::Down}], &[A::MoveFocus{direction: Dir::Up}], &[A::MoveFocus{direction: Dir::Right}]])), (s("Split down"), s("Down"), action_key(&km, &[A::NewPane{direction: Some(Dir::Down), pane_name: None, start_suppressed: false}, TO_NORMAL])), (s("Split right"), s("Right"), action_key(&km, &[A::NewPane{direction: Some(Dir::Right), pane_name: None, start_suppressed: false}, TO_NORMAL])), (s("Fullscreen"), s("Fullscreen"), action_key(&km, &[A::ToggleFocusFullscreen, TO_NORMAL])), (s("New tab"), s("New"), action_key(&km, &[A::NewTab{ tiled_layout: None, floating_layouts: vec![], swap_tiled_layouts: None, swap_floating_layouts: None, tab_name: None, should_change_focus_to_new_tab: true, cwd: None, initial_panes: None, first_pane_unblock_condition: None, }, TO_NORMAL])), (s("Rename tab"), s("Rename"), action_key(&km, &[A::SwitchToMode{input_mode: IM::RenameTab}, A::TabNameInput{input: vec![0]}])), (s("Previous Tab"), s("Previous"), action_key(&km, &[A::GoToPreviousTab, TO_NORMAL])), (s("Next Tab"), s("Next"), action_key(&km, &[A::GoToNextTab, TO_NORMAL])), (s("Select pane"), s("Select"), to_normal_key), ]} else if matches!(mi.mode, IM::RenamePane | IM::RenameTab) { vec![ (s("When done"), s("Done"), to_normal_key), (s("Select pane"), s("Select"), action_key_group(&km, &[ &[A::MoveFocus{direction: Dir::Left}], &[A::MoveFocus{direction: Dir::Down}], &[A::MoveFocus{direction: Dir::Up}], &[A::MoveFocus{direction: Dir::Right}]])), ]} else { vec![] } } fn full_shortcut_list(help: &ModeInfo, tip: TipFn) -> LinePart { match help.mode { InputMode::Normal => tip(help), InputMode::Locked => locked_interface_indication(help.style.colors), _ => full_shortcut_list_nonstandard_mode(help), } } fn shortened_shortcut_list_nonstandard_mode(help: &ModeInfo) -> LinePart { let mut line_part = LinePart::default(); let keys_and_hints = get_keys_and_hints(help); for (_, short, keys) in keys_and_hints.into_iter() { line_part = add_shortcut(help, &line_part, &short, keys.to_vec()); } line_part } fn shortened_shortcut_list(help: &ModeInfo, tip: TipFn) -> LinePart { match help.mode { InputMode::Normal => tip(help), InputMode::Locked => locked_interface_indication(help.style.colors), _ => shortened_shortcut_list_nonstandard_mode(help), } } fn best_effort_shortcut_list_nonstandard_mode(help: &ModeInfo, max_len: usize) -> LinePart { let mut line_part = LinePart::default(); let keys_and_hints = get_keys_and_hints(help); for (_, short, keys) in keys_and_hints.into_iter() { let new_line_part = add_shortcut(help, &line_part, &short, keys.to_vec()); if new_line_part.len + MORE_MSG.chars().count() > max_len { line_part.part = format!("{}{}", line_part.part, MORE_MSG); line_part.len += MORE_MSG.chars().count(); break; } line_part = new_line_part; } line_part } fn best_effort_shortcut_list(help: &ModeInfo, tip: TipFn, max_len: usize) -> LinePart { match help.mode { InputMode::Normal => { let line_part = tip(help); if line_part.len <= max_len { line_part } else { LinePart::default() } }, InputMode::Locked => { let line_part = locked_interface_indication(help.style.colors); if line_part.len <= max_len { line_part } else { LinePart::default() } }, _ => best_effort_shortcut_list_nonstandard_mode(help, max_len), } } pub fn keybinds(help: &ModeInfo, tip_name: &str, max_width: usize) -> LinePart { // It is assumed that there is at least one TIP data in the TIPS HasMap. let tip_body = TIPS .get(tip_name) .unwrap_or_else(|| TIPS.get("quicknav").unwrap()); let full_shortcut_list = full_shortcut_list(help, tip_body.full); if full_shortcut_list.len <= max_width { return full_shortcut_list; } let shortened_shortcut_list = shortened_shortcut_list(help, tip_body.medium); if shortened_shortcut_list.len <= max_width { return shortened_shortcut_list; } best_effort_shortcut_list(help, tip_body.short, max_width) } pub fn text_copied_hint(copy_destination: CopyDestination) -> LinePart { let hint = match copy_destination { CopyDestination::Command => "Text piped to external command", #[cfg(not(target_os = "macos"))] CopyDestination::Primary => "Text copied to system primary selection", #[cfg(target_os = "macos")] // primary selection does not exist on macos CopyDestination::Primary => "Text copied to system clipboard", CopyDestination::System => "Text copied to system clipboard", }; LinePart { part: serialize_text(&Text::new(&hint).color_range(2, ..).opaque()), len: hint.len(), } } pub fn system_clipboard_error(palette: &Styling) -> LinePart { let hint = " Error using the system clipboard."; let red_color = palette_match!(palette.text_unselected.emphasis_3); LinePart { part: Style::new().fg(red_color).bold().paint(hint).to_string(), len: hint.len(), } } pub fn fullscreen_panes_to_hide(palette: &Styling, panes_to_hide: usize) -> LinePart { let text_color = palette_match!(palette.text_unselected.base); let green_color = palette_match!(palette.text_unselected.emphasis_2); let orange_color = palette_match!(palette.text_unselected.emphasis_0); let shortcut_left_separator = Style::new().fg(text_color).bold().paint(" ("); let shortcut_right_separator = Style::new().fg(text_color).bold().paint("): "); let fullscreen = "FULLSCREEN"; let puls = "+ "; let panes = panes_to_hide.to_string(); let hide = " hidden panes"; let len = fullscreen.chars().count() + puls.chars().count() + panes.chars().count() + hide.chars().count() + 5; // 3 for ():'s around shortcut, 2 for the space LinePart { part: format!( "{}{}{}{}{}{}", shortcut_left_separator, Style::new().fg(orange_color).bold().paint(fullscreen), shortcut_right_separator, Style::new().fg(text_color).bold().paint(puls), Style::new().fg(green_color).bold().paint(panes), Style::new().fg(text_color).bold().paint(hide) ), len, } } pub fn floating_panes_are_visible(mode_info: &ModeInfo) -> LinePart { let palette = mode_info.style.colors; let km = &mode_info.get_mode_keybinds(); let white_color = palette_match!(palette.text_unselected.base); let green_color = palette_match!(palette.text_unselected.emphasis_2); let orange_color = palette_match!(palette.text_unselected.emphasis_0); let shortcut_left_separator = Style::new().fg(white_color).bold().paint(" ("); let shortcut_right_separator = Style::new().fg(white_color).bold().paint("): "); let floating_panes = "FLOATING PANES VISIBLE"; let press = "Press "; let pane_mode = format!( "{}", action_key( km, &[Action::SwitchToMode { input_mode: InputMode::Pane }] ) .first() .unwrap_or(&KeyWithModifier::new(BareKey::Char('?'))) ); let plus = ", "; let p_left_separator = "<"; let p = format!( "{}", action_key( &mode_info.get_keybinds_for_mode(InputMode::Pane), &[Action::ToggleFloatingPanes, TO_NORMAL] ) .first() .unwrap_or(&KeyWithModifier::new(BareKey::Char('?'))) ); let p_right_separator = "> "; let to_hide = "to hide."; let len = floating_panes.chars().count() + press.chars().count() + pane_mode.chars().count() + plus.chars().count() + p_left_separator.chars().count() + p.chars().count() + p_right_separator.chars().count() + to_hide.chars().count() + 5; // 3 for ():'s around floating_panes, 2 for the space LinePart { part: format!( "{}{}{}{}{}{}{}{}{}{}", shortcut_left_separator, Style::new().fg(orange_color).bold().paint(floating_panes), shortcut_right_separator, Style::new().fg(white_color).bold().paint(press), Style::new().fg(green_color).bold().paint(pane_mode), Style::new().fg(white_color).bold().paint(plus), Style::new().fg(white_color).bold().paint(p_left_separator), Style::new().fg(green_color).bold().paint(p), Style::new().fg(white_color).bold().paint(p_right_separator), Style::new().fg(white_color).bold().paint(to_hide), ), len, } } pub fn locked_fullscreen_panes_to_hide(palette: &Styling, panes_to_hide: usize) -> LinePart { let text_color = palette_match!(palette.text_unselected.base); let green_color = palette_match!(palette.text_unselected.emphasis_2); let orange_color = palette_match!(palette.text_unselected.emphasis_0); let locked_text = " -- INTERFACE LOCKED -- "; let shortcut_left_separator = Style::new().fg(text_color).bold().paint(" ("); let shortcut_right_separator = Style::new().fg(text_color).bold().paint("): "); let fullscreen = "FULLSCREEN"; let puls = "+ "; let panes = panes_to_hide.to_string(); let hide = " hidden panes"; let len = locked_text.chars().count() + fullscreen.chars().count() + puls.chars().count() + panes.chars().count() + hide.chars().count() + 5; // 3 for ():'s around shortcut, 2 for the space LinePart { part: format!( "{}{}{}{}{}{}{}", Style::new().fg(text_color).bold().paint(locked_text), shortcut_left_separator, Style::new().fg(orange_color).bold().paint(fullscreen), shortcut_right_separator, Style::new().fg(text_color).bold().paint(puls), Style::new().fg(green_color).bold().paint(panes), Style::new().fg(text_color).bold().paint(hide) ), len, } } pub fn locked_floating_panes_are_visible(palette: &Styling) -> LinePart { let white_color = palette_match!(palette.text_unselected.base); let orange_color = palette_match!(palette.text_unselected.emphasis_0); let shortcut_left_separator = Style::new().fg(white_color).bold().paint(" ("); let shortcut_right_separator = Style::new().fg(white_color).bold().paint(")"); let locked_text = " -- INTERFACE LOCKED -- "; let floating_panes = "FLOATING PANES VISIBLE"; let len = locked_text.chars().count() + floating_panes.chars().count(); LinePart { part: format!( "{}{}{}{}", Style::new().fg(white_color).bold().paint(locked_text), shortcut_left_separator, Style::new().fg(orange_color).bold().paint(floating_panes), shortcut_right_separator, ), len, } } #[cfg(test)] /// Unit tests. /// /// Note that we cheat a little here, because the number of things one may want to test is endless, /// and creating a Mockup of [`ModeInfo`] by hand for all these testcases is nothing less than /// torture. Hence, we test the most atomic unit thoroughly ([`full_length_shortcut`] and then test /// the public API ([`keybinds`]) to ensure correct operation. mod tests { use super::*; // Strip style information from `LinePart` and return a raw String instead fn unstyle(line_part: LinePart) -> String { let string = line_part.to_string(); let re = regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap(); let string = re.replace_all(&string, "".to_string()); string.to_string() } #[test] fn full_length_shortcut_with_key() { let keyvec = vec![KeyWithModifier::new(BareKey::Char('a'))]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / <a> Foobar"); } #[test] fn full_length_shortcut_with_key_first_element() { let keyvec = vec![KeyWithModifier::new(BareKey::Char('a'))]; let palette = Styling::default(); let ret = full_length_shortcut(true, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " <a> Foobar"); } #[test] // When there is no binding, we print no shortcut either fn full_length_shortcut_without_key() { let keyvec = vec![]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, ""); } #[test] fn full_length_shortcut_with_key_unprintable_1() { let keyvec = vec![KeyWithModifier::new(BareKey::Enter)]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / <ENTER> Foobar"); } #[test] fn full_length_shortcut_with_key_unprintable_2() { let keyvec = vec![KeyWithModifier::new(BareKey::Backspace)]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / <BACKSPACE> Foobar"); } #[test] fn full_length_shortcut_with_ctrl_key() { let keyvec = vec![KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier()]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / Ctrl + <a> Foobar"); } #[test] fn full_length_shortcut_with_alt_key() { let keyvec = vec![KeyWithModifier::new(BareKey::Char('a')).with_alt_modifier()]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / Alt + <a> Foobar"); } #[test] fn full_length_shortcut_with_homogenous_key_group() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')), KeyWithModifier::new(BareKey::Char('b')), KeyWithModifier::new(BareKey::Char('c')), ]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / <a|b|c> Foobar"); } #[test] fn full_length_shortcut_with_heterogenous_key_group() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')), KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Enter), ]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / <a|Ctrl b|ENTER> Foobar"); } #[test] fn full_length_shortcut_with_key_group_shared_ctrl_modifier() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('c')).with_ctrl_modifier(), ]; let palette = Styling::default(); let ret = full_length_shortcut(false, keyvec, "Foobar", palette); let ret = unstyle(ret); assert_eq!(ret, " / Ctrl + <a|b|c> Foobar"); } //pub fn keybinds(help: &ModeInfo, tip_name: &str, max_width: usize) -> LinePart { #[test] // Note how it leaves out elements that don't exist! fn keybinds_wide() { let mode_info = ModeInfo { mode: InputMode::Pane, keybinds: vec![( InputMode::Pane, vec![ ( KeyWithModifier::new(BareKey::Left), vec![Action::MoveFocus { direction: Direction::Left, }], ), ( KeyWithModifier::new(BareKey::Down), vec![Action::MoveFocus { direction: Direction::Down, }], ), ( KeyWithModifier::new(BareKey::Up), vec![Action::MoveFocus { direction: Direction::Up, }], ), ( KeyWithModifier::new(BareKey::Right), vec![Action::MoveFocus { direction: Direction::Right, }], ), ( KeyWithModifier::new(BareKey::Char('n')), vec![ Action::NewPane { direction: None, pane_name: None, start_suppressed: false, }, TO_NORMAL, ], ), ( KeyWithModifier::new(BareKey::Char('x')), vec![Action::CloseFocus, TO_NORMAL], ), ( KeyWithModifier::new(BareKey::Char('f')), vec![Action::ToggleFocusFullscreen, TO_NORMAL], ), ], )], ..ModeInfo::default() }; let ret = keybinds(&mode_info, "quicknav", 500); let ret = unstyle(ret); assert_eq!( ret, " <n> New / <←↓↑→> Change Focus / <x> Close / <f> Toggle Fullscreen", ); } #[test] // Note how "Move focus" becomes "Move" fn keybinds_tight_width() { let mode_info = ModeInfo { mode: InputMode::Pane, keybinds: vec![( InputMode::Pane, vec![ ( KeyWithModifier::new(BareKey::Left), vec![Action::MoveFocus { direction: Direction::Left, }], ), ( KeyWithModifier::new(BareKey::Down), vec![Action::MoveFocus { direction: Direction::Down, }], ), ( KeyWithModifier::new(BareKey::Up), vec![Action::MoveFocus { direction: Direction::Up, }], ), ( KeyWithModifier::new(BareKey::Right), vec![Action::MoveFocus { direction: Direction::Right, }], ), ( KeyWithModifier::new(BareKey::Char('n')), vec![
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/main.rs
default-plugins/status-bar/src/main.rs
mod first_line; mod one_line_ui; mod second_line; mod tip; use ansi_term::{ ANSIString, Colour::{Fixed, RGB}, Style, }; use std::collections::BTreeMap; use std::fmt::{Display, Error, Formatter}; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; use zellij_tile_utils::{palette_match, style}; use first_line::first_line; use one_line_ui::one_line_ui; use second_line::{ floating_panes_are_visible, fullscreen_panes_to_hide, keybinds, locked_floating_panes_are_visible, locked_fullscreen_panes_to_hide, system_clipboard_error, text_copied_hint, }; use tip::utils::get_cached_tip_name; // for more of these, copy paste from: https://en.wikipedia.org/wiki/Box-drawing_character static ARROW_SEPARATOR: &str = ""; static MORE_MSG: &str = " ... "; /// Shorthand for `Action::SwitchToMode{input_mode: InputMode::Normal}`. const TO_NORMAL: Action = Action::SwitchToMode { input_mode: InputMode::Normal, }; #[derive(Default)] struct State { tabs: Vec<TabInfo>, tip_name: String, mode_info: ModeInfo, text_copy_destination: Option<CopyDestination>, display_system_clipboard_failure: bool, classic_ui: bool, base_mode_is_locked: bool, } register_plugin!(State); #[derive(Default)] pub struct LinePart { part: String, len: usize, } impl LinePart { pub fn append(&mut self, to_append: &LinePart) { self.part.push_str(&to_append.part); self.len += to_append.len; } } impl Display for LinePart { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "{}", self.part) } } #[derive(Clone, Copy)] pub struct ColoredElements { pub selected: SegmentStyle, pub unselected: SegmentStyle, pub unselected_alternate: SegmentStyle, pub disabled: SegmentStyle, // superkey pub superkey_prefix: Style, pub superkey_suffix_separator: Style, } #[derive(Clone, Copy)] pub struct SegmentStyle { pub prefix_separator: Style, pub char_left_separator: Style, pub char_shortcut: Style, pub char_right_separator: Style, pub styled_text: Style, pub suffix_separator: Style, } // I really hate this, but I can't come up with a good solution for this, // we need different colors from palette for the default theme // plus here we can add new sources in the future, like Theme // that can be defined in the config perhaps fn color_elements(palette: Styling, different_color_alternates: bool) -> ColoredElements { let background = palette.text_unselected.background; let foreground = palette.text_unselected.base; let alternate_background_color = if different_color_alternates { palette.ribbon_unselected.base } else { palette.ribbon_unselected.background }; ColoredElements { selected: SegmentStyle { prefix_separator: style!(background, palette.ribbon_selected.background), char_left_separator: style!( palette.ribbon_selected.base, palette.ribbon_selected.background ) .bold(), char_shortcut: style!( palette.ribbon_selected.emphasis_0, palette.ribbon_selected.background ) .bold(), char_right_separator: style!( palette.ribbon_selected.base, palette.ribbon_selected.background ) .bold(), styled_text: style!( palette.ribbon_selected.base, palette.ribbon_selected.background ) .bold(), suffix_separator: style!(palette.ribbon_selected.background, background).bold(), }, unselected: SegmentStyle { prefix_separator: style!(background, palette.ribbon_unselected.background), char_left_separator: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .bold(), char_shortcut: style!( palette.ribbon_unselected.emphasis_0, palette.ribbon_unselected.background ) .bold(), char_right_separator: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .bold(), styled_text: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .bold(), suffix_separator: style!(palette.ribbon_unselected.background, background).bold(), }, unselected_alternate: SegmentStyle { prefix_separator: style!(background, alternate_background_color), char_left_separator: style!(background, alternate_background_color).bold(), char_shortcut: style!( palette.ribbon_unselected.emphasis_0, alternate_background_color ) .bold(), char_right_separator: style!(background, alternate_background_color).bold(), styled_text: style!(palette.ribbon_unselected.base, alternate_background_color).bold(), suffix_separator: style!(alternate_background_color, background).bold(), }, disabled: SegmentStyle { prefix_separator: style!(background, palette.ribbon_unselected.background), char_left_separator: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .dimmed() .italic(), char_shortcut: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .dimmed() .italic(), char_right_separator: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .dimmed() .italic(), styled_text: style!( palette.ribbon_unselected.base, palette.ribbon_unselected.background ) .dimmed() .italic(), suffix_separator: style!(palette.ribbon_unselected.background, background), }, superkey_prefix: style!(foreground, background).bold(), superkey_suffix_separator: style!(background, background), } } impl ZellijPlugin for State { fn load(&mut self, configuration: BTreeMap<String, String>) { // TODO: Should be able to choose whether to use the cache through config. self.tip_name = get_cached_tip_name(); self.classic_ui = configuration .get("classic") .map(|c| c == "true") .unwrap_or(false); set_selectable(false); subscribe(&[ EventType::ModeUpdate, EventType::TabUpdate, EventType::PaneUpdate, EventType::CopyToClipboard, EventType::InputReceived, EventType::SystemClipboardFailure, ]); } fn update(&mut self, event: Event) -> bool { let mut should_render = false; match event { Event::ModeUpdate(mode_info) => { if self.mode_info != mode_info { should_render = true; } self.mode_info = mode_info; self.base_mode_is_locked = self.mode_info.base_mode == Some(InputMode::Locked); }, Event::TabUpdate(tabs) => { if self.tabs != tabs { should_render = true; } self.tabs = tabs; }, Event::CopyToClipboard(copy_destination) => { match self.text_copy_destination { Some(text_copy_destination) => { if text_copy_destination != copy_destination { should_render = true; } }, None => { should_render = true; }, } self.text_copy_destination = Some(copy_destination); }, Event::SystemClipboardFailure => { should_render = true; self.display_system_clipboard_failure = true; }, Event::InputReceived => { if self.text_copy_destination.is_some() || self.display_system_clipboard_failure == true { should_render = true; } self.text_copy_destination = None; self.display_system_clipboard_failure = false; }, _ => {}, }; should_render } fn render(&mut self, rows: usize, cols: usize) { let supports_arrow_fonts = !self.mode_info.capabilities.arrow_fonts; let separator = if supports_arrow_fonts { ARROW_SEPARATOR } else { "" }; let background = self.mode_info.style.colors.text_unselected.background; if rows == 1 && !self.classic_ui { let fill_bg = match background { PaletteColor::Rgb((r, g, b)) => format!("\u{1b}[48;2;{};{};{}m\u{1b}[0K", r, g, b), PaletteColor::EightBit(color) => format!("\u{1b}[48;5;{}m\u{1b}[0K", color), }; let active_tab = self.tabs.iter().find(|t| t.active); print!( "{}{}", one_line_ui( &self.mode_info, active_tab, cols, separator, self.base_mode_is_locked, self.text_copy_destination, self.display_system_clipboard_failure, ), fill_bg, ); return; } //TODO: Switch to UI components here let active_tab = self.tabs.iter().find(|t| t.active); let first_line = first_line(&self.mode_info, active_tab, cols, separator); let second_line = self.second_line(cols); // [48;5;238m is white background, [0K is so that it fills the rest of the line // [m is background reset, [0K is so that it clears the rest of the line match background { PaletteColor::Rgb((r, g, b)) => { if rows > 1 { println!("{}\u{1b}[48;2;{};{};{}m\u{1b}[0K", first_line, r, g, b); } else { if self.mode_info.mode == InputMode::Normal { print!("{}\u{1b}[48;2;{};{};{}m\u{1b}[0K", first_line, r, g, b); } else { print!("\u{1b}[m{}\u{1b}[0K", second_line); } } }, PaletteColor::EightBit(color) => { if rows > 1 { println!("{}\u{1b}[48;5;{}m\u{1b}[0K", first_line, color); } else { if self.mode_info.mode == InputMode::Normal { print!("{}\u{1b}[48;5;{}m\u{1b}[0K", first_line, color); } else { print!("\u{1b}[m{}\u{1b}[0K", second_line); } } }, } if rows > 1 { print!("\u{1b}[m{}\u{1b}[0K", second_line); } } } impl State { fn second_line(&self, cols: usize) -> LinePart { let active_tab = self.tabs.iter().find(|t| t.active); if let Some(copy_destination) = self.text_copy_destination { text_copied_hint(copy_destination) } else if self.display_system_clipboard_failure { system_clipboard_error(&self.mode_info.style.colors) } else if let Some(active_tab) = active_tab { if active_tab.is_fullscreen_active { match self.mode_info.mode { InputMode::Normal => fullscreen_panes_to_hide( &self.mode_info.style.colors, active_tab.panes_to_hide, ), InputMode::Locked => locked_fullscreen_panes_to_hide( &self.mode_info.style.colors, active_tab.panes_to_hide, ), _ => keybinds(&self.mode_info, &self.tip_name, cols), } } else if active_tab.are_floating_panes_visible { match self.mode_info.mode { InputMode::Normal => floating_panes_are_visible(&self.mode_info), InputMode::Locked => { locked_floating_panes_are_visible(&self.mode_info.style.colors) }, _ => keybinds(&self.mode_info, &self.tip_name, cols), } } else { keybinds(&self.mode_info, &self.tip_name, cols) } } else { LinePart::default() } } } pub fn get_common_modifiers(mut keyvec: Vec<&KeyWithModifier>) -> Vec<KeyModifier> { if keyvec.is_empty() { return vec![]; } let mut common_modifiers = keyvec.pop().unwrap().key_modifiers.clone(); for key in keyvec { common_modifiers = common_modifiers .intersection(&key.key_modifiers) .cloned() .collect(); } common_modifiers.into_iter().collect() } /// Get key from action pattern(s). /// /// This function takes as arguments a `keymap` that is a `Vec<(Key, Vec<Action>)>` and contains /// all keybindings for the current mode and one or more `p` patterns which match a sequence of /// actions to search for. If within the keymap a sequence of actions matching `p` is found, all /// keys that trigger the action pattern are returned as vector of `Vec<Key>`. pub fn action_key( keymap: &[(KeyWithModifier, Vec<Action>)], action: &[Action], ) -> Vec<KeyWithModifier> { keymap .iter() .filter_map(|(key, acvec)| { let matching = acvec .iter() .zip(action) .filter(|(a, b)| a.shallow_eq(b)) .count(); if matching == acvec.len() && matching == action.len() { Some(key.clone()) } else { None } }) .collect::<Vec<KeyWithModifier>>() } /// Get multiple keys for multiple actions. /// /// An extension of [`action_key`] that iterates over all action tuples and collects the results. pub fn action_key_group( keymap: &[(KeyWithModifier, Vec<Action>)], actions: &[&[Action]], ) -> Vec<KeyWithModifier> { let mut ret = vec![]; for action in actions { ret.extend(action_key(keymap, action)); } ret } /// Style a vector of [`Key`]s with the given [`Palette`]. /// /// Creates a line segment of style `<KEYS>`, with correct theming applied: The brackets have the /// regular text color, the enclosed keys are painted green and bold. If the keys share a common /// modifier (See [`get_common_modifier`]), it is printed in front of the keys, painted green and /// bold, separated with a `+`: `MOD + <KEYS>`. /// /// If multiple [`Key`]s are given, the individual keys are separated with a `|` char. This does /// not apply to the following groups of keys which are treated specially and don't have a /// separator between them: /// /// - "hjkl" /// - "HJKL" /// - "←↓↑→" /// - "←→" /// - "↓↑" /// /// The returned Vector of [`ANSIString`] is suitable for transformation into an [`ANSIStrings`] /// type. pub fn style_key_with_modifier( keyvec: &[KeyWithModifier], palette: &Styling, background: Option<PaletteColor>, ) -> Vec<ANSIString<'static>> { if keyvec.is_empty() { return vec![]; } let text_color = palette_match!(palette.text_unselected.base); let green_color = palette_match!(palette.text_unselected.emphasis_2); let orange_color = palette_match!(palette.text_unselected.emphasis_0); let mut ret = vec![]; let common_modifiers = get_common_modifiers(keyvec.iter().collect()); let no_common_modifier = common_modifiers.is_empty(); let modifier_str = common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-"); let painted_modifier = if modifier_str.is_empty() { Style::new().paint("") } else { if let Some(background) = background { let background = palette_match!(background); Style::new() .fg(orange_color) .on(background) .bold() .paint(modifier_str) } else { Style::new().fg(orange_color).bold().paint(modifier_str) } }; ret.push(painted_modifier); // Prints key group start let group_start_str = if no_common_modifier { "<" } else { " + <" }; if let Some(background) = background { let background = palette_match!(background); ret.push( Style::new() .fg(text_color) .on(background) .paint(group_start_str), ); } else { ret.push(Style::new().fg(text_color).paint(group_start_str)); } // Prints the keys let key = keyvec .iter() .map(|key| { if no_common_modifier { format!("{}", key) } else { let key_modifier_for_key = key .key_modifiers .iter() .filter(|m| !common_modifiers.contains(m)) .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" "); if key_modifier_for_key.is_empty() { format!("{}", key.bare_key) } else { format!("{} {}", key_modifier_for_key, key.bare_key) } } }) .collect::<Vec<String>>(); // Special handling of some pre-defined keygroups let key_string = key.join(""); let key_separator = match &key_string[..] { "HJKL" => "", "hjkl" => "", "←↓↑→" => "", "←→" => "", "↓↑" => "", "[]" => "", _ => "|", }; for (idx, key) in key.iter().enumerate() { if idx > 0 && !key_separator.is_empty() { if let Some(background) = background { let background = palette_match!(background); ret.push( Style::new() .fg(text_color) .on(background) .paint(key_separator), ); } else { ret.push(Style::new().fg(text_color).paint(key_separator)); } } if let Some(background) = background { let background = palette_match!(background); ret.push( Style::new() .fg(green_color) .on(background) .bold() .paint(key.clone()), ); } else { ret.push(Style::new().fg(green_color).bold().paint(key.clone())); } } let group_end_str = ">"; if let Some(background) = background { let background = palette_match!(background); ret.push( Style::new() .fg(text_color) .on(background) .paint(group_end_str), ); } else { ret.push(Style::new().fg(text_color).paint(group_end_str)); } ret } #[cfg(test)] pub mod tests { use super::*; use ansi_term::unstyle; use ansi_term::ANSIStrings; fn big_keymap() -> Vec<(KeyWithModifier, Vec<Action>)> { vec![ (KeyWithModifier::new(BareKey::Char('a')), vec![Action::Quit]), ( KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier(), vec![Action::ScrollUp], ), ( KeyWithModifier::new(BareKey::Char('d')).with_ctrl_modifier(), vec![Action::ScrollDown], ), ( KeyWithModifier::new(BareKey::Char('c')).with_alt_modifier(), vec![ Action::ScrollDown, Action::SwitchToMode { input_mode: InputMode::Normal, }, ], ), ( KeyWithModifier::new(BareKey::Char('1')), vec![ TO_NORMAL, Action::SwitchToMode { input_mode: InputMode::Locked, }, ], ), ] } #[test] fn common_modifier_with_ctrl_keys() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('c')).with_ctrl_modifier(), ]; let ret = get_common_modifiers(keyvec.iter().collect()); assert_eq!(ret, vec![KeyModifier::Ctrl]); } #[test] fn common_modifier_with_alt_keys_chars() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('1')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('t')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('z')).with_alt_modifier(), ]; let ret = get_common_modifiers(keyvec.iter().collect()); assert_eq!(ret, vec![KeyModifier::Alt]); } #[test] fn common_modifier_with_mixed_alt_ctrl_keys() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('1')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('t')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('z')).with_alt_modifier(), ]; let ret = get_common_modifiers(keyvec.iter().collect()); assert_eq!(ret, vec![]); // no common modifiers } #[test] fn common_modifier_with_any_keys() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('1')), KeyWithModifier::new(BareKey::Char('t')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('z')).with_alt_modifier(), ]; let ret = get_common_modifiers(keyvec.iter().collect()); assert_eq!(ret, vec![]); // no common modifiers } #[test] fn action_key_simple_pattern_match_exact() { let keymap = &[(KeyWithModifier::new(BareKey::Char('f')), vec![Action::Quit])]; let ret = action_key(keymap, &[Action::Quit]); assert_eq!(ret, vec![KeyWithModifier::new(BareKey::Char('f'))]); } #[test] fn action_key_simple_pattern_match_pattern_too_long() { let keymap = &[(KeyWithModifier::new(BareKey::Char('f')), vec![Action::Quit])]; let ret = action_key(keymap, &[Action::Quit, Action::ScrollUp]); assert_eq!(ret, Vec::new()); } #[test] fn action_key_simple_pattern_match_pattern_empty() { let keymap = &[(KeyWithModifier::new(BareKey::Char('f')), vec![Action::Quit])]; let ret = action_key(keymap, &[]); assert_eq!(ret, Vec::new()); } #[test] fn action_key_long_pattern_match_exact() { let keymap = big_keymap(); let ret = action_key(&keymap, &[Action::ScrollDown, TO_NORMAL]); assert_eq!( ret, vec![KeyWithModifier::new(BareKey::Char('c')).with_alt_modifier()] ); } #[test] fn action_key_long_pattern_match_too_short() { let keymap = big_keymap(); let ret = action_key(&keymap, &[TO_NORMAL]); assert_eq!(ret, Vec::new()); } #[test] fn action_key_group_single_pattern() { let keymap = big_keymap(); let ret = action_key_group(&keymap, &[&[Action::Quit]]); assert_eq!(ret, vec![KeyWithModifier::new(BareKey::Char('a'))]); } #[test] fn action_key_group_two_patterns() { let keymap = big_keymap(); let ret = action_key_group(&keymap, &[&[Action::ScrollDown], &[Action::ScrollUp]]); // Mind the order! assert_eq!( ret, vec![ KeyWithModifier::new(BareKey::Char('d')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier() ] ); } #[test] fn style_key_with_modifier_only_chars() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')), KeyWithModifier::new(BareKey::Char('b')), KeyWithModifier::new(BareKey::Char('c')), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "<a|b|c>".to_string()) } #[test] fn style_key_with_modifier_special_group_hjkl() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('h')), KeyWithModifier::new(BareKey::Char('j')), KeyWithModifier::new(BareKey::Char('k')), KeyWithModifier::new(BareKey::Char('l')), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "<hjkl>".to_string()) } #[test] fn style_key_with_modifier_special_group_all_arrows() { let keyvec = vec![ KeyWithModifier::new(BareKey::Left), KeyWithModifier::new(BareKey::Down), KeyWithModifier::new(BareKey::Up), KeyWithModifier::new(BareKey::Right), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "<←↓↑→>".to_string()) } #[test] fn style_key_with_modifier_special_group_left_right_arrows() { let keyvec = vec![ KeyWithModifier::new(BareKey::Left), KeyWithModifier::new(BareKey::Right), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "<←→>".to_string()) } #[test] fn style_key_with_modifier_special_group_down_up_arrows() { let keyvec = vec![ KeyWithModifier::new(BareKey::Down), KeyWithModifier::new(BareKey::Up), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "<↓↑>".to_string()) } #[test] fn style_key_with_modifier_common_ctrl_modifier_chars() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('c')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('d')).with_ctrl_modifier(), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "Ctrl + <a|b|c|d>".to_string()) } #[test] fn style_key_with_modifier_common_alt_modifier_chars() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('b')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('c')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('d')).with_alt_modifier(), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "Alt + <a|b|c|d>".to_string()) } #[test] fn style_key_with_modifier_common_alt_modifier_with_special_group_all_arrows() { let keyvec = vec![ KeyWithModifier::new(BareKey::Left).with_alt_modifier(), KeyWithModifier::new(BareKey::Down).with_alt_modifier(), KeyWithModifier::new(BareKey::Up).with_alt_modifier(), KeyWithModifier::new(BareKey::Right).with_alt_modifier(), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "Alt + <←↓↑→>".to_string()) } #[test] fn style_key_with_modifier_ctrl_alt_char_mixed() { let keyvec = vec![ KeyWithModifier::new(BareKey::Char('a')).with_alt_modifier(), KeyWithModifier::new(BareKey::Char('b')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char('c')), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "<Alt a|Ctrl b|c>".to_string()) } #[test] fn style_key_with_modifier_unprintables() { let keyvec = vec![ KeyWithModifier::new(BareKey::Backspace), KeyWithModifier::new(BareKey::Enter), KeyWithModifier::new(BareKey::Char(' ')), KeyWithModifier::new(BareKey::Tab), KeyWithModifier::new(BareKey::PageDown), KeyWithModifier::new(BareKey::Delete), KeyWithModifier::new(BareKey::Home), KeyWithModifier::new(BareKey::End), KeyWithModifier::new(BareKey::Insert), KeyWithModifier::new(BareKey::Tab), KeyWithModifier::new(BareKey::Esc), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!( ret, "<BACKSPACE|ENTER|SPACE|TAB|PgDn|DEL|HOME|END|INS|TAB|ESC>".to_string() ) } #[test] fn style_key_with_modifier_unprintables_with_common_ctrl_modifier() { let keyvec = vec![ KeyWithModifier::new(BareKey::Enter).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Char(' ')).with_ctrl_modifier(), KeyWithModifier::new(BareKey::Tab).with_ctrl_modifier(), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "Ctrl + <ENTER|SPACE|TAB>".to_string()) } #[test] fn style_key_with_modifier_unprintables_with_common_alt_modifier() { let keyvec = vec![ KeyWithModifier::new(BareKey::Enter).with_alt_modifier(), KeyWithModifier::new(BareKey::Char(' ')).with_alt_modifier(), KeyWithModifier::new(BareKey::Tab).with_alt_modifier(), ]; let palette = Styling::default(); let ret = style_key_with_modifier(&keyvec, &palette, None); let ret = unstyle(&ANSIStrings(&ret)); assert_eq!(ret, "Alt + <ENTER|SPACE|TAB>".to_string()) } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/first_line.rs
default-plugins/status-bar/src/first_line.rs
use ansi_term::{unstyled_len, ANSIStrings}; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; use crate::color_elements; use crate::{ action_key, action_key_group, get_common_modifiers, style_key_with_modifier, TO_NORMAL, }; use crate::{ColoredElements, LinePart}; #[derive(Debug)] pub struct KeyShortcut { pub mode: KeyMode, pub action: KeyAction, pub key: Option<KeyWithModifier>, } #[derive(Debug, Copy, Clone, PartialEq)] pub enum KeyAction { Unlock, Lock, Pane, Tab, Resize, Search, Quit, Session, Move, Tmux, } #[derive(Debug, Copy, Clone)] pub enum KeyMode { Unselected, UnselectedAlternate, Selected, Disabled, } impl KeyShortcut { pub fn new(mode: KeyMode, action: KeyAction, key: Option<KeyWithModifier>) -> Self { KeyShortcut { mode, action, key } } pub fn full_text(&self) -> String { match self.action { KeyAction::Lock => String::from("LOCK"), KeyAction::Unlock => String::from("UNLOCK"), KeyAction::Pane => String::from("PANE"), KeyAction::Tab => String::from("TAB"), KeyAction::Resize => String::from("RESIZE"), KeyAction::Search => String::from("SEARCH"), KeyAction::Quit => String::from("QUIT"), KeyAction::Session => String::from("SESSION"), KeyAction::Move => String::from("MOVE"), KeyAction::Tmux => String::from("TMUX"), } } pub fn with_shortened_modifiers(&self, common_modifiers: &Vec<KeyModifier>) -> String { let key = match &self.key { Some(k) => k.strip_common_modifiers(common_modifiers), None => return String::from("?"), }; let shortened_modifiers = key .key_modifiers .iter() .map(|m| match m { KeyModifier::Ctrl => "^C", KeyModifier::Alt => "^A", KeyModifier::Super => "^Su", KeyModifier::Shift => "^Sh", }) .collect::<Vec<_>>() .join("-"); if shortened_modifiers.is_empty() { format!("{}", key) } else { format!("{} {}", shortened_modifiers, key.bare_key) } } pub fn letter_shortcut(&self, common_modifiers: &Vec<KeyModifier>) -> String { let key = match &self.key { Some(k) => k.strip_common_modifiers(common_modifiers), None => return String::from("?"), }; format!("{}", key) } pub fn get_key(&self) -> Option<KeyWithModifier> { self.key.clone() } pub fn get_mode(&self) -> KeyMode { self.mode } pub fn get_action(&self) -> KeyAction { self.action } pub fn is_selected(&self) -> bool { match self.mode { KeyMode::Selected => true, _ => false, } } pub fn short_text(&self) -> String { match self.action { KeyAction::Lock => String::from("Lo"), KeyAction::Unlock => String::from("Un"), KeyAction::Pane => String::from("Pa"), KeyAction::Tab => String::from("Ta"), KeyAction::Resize => String::from("Re"), KeyAction::Search => String::from("Se"), KeyAction::Quit => String::from("Qu"), KeyAction::Session => String::from("Se"), KeyAction::Move => String::from("Mo"), KeyAction::Tmux => String::from("Tm"), } } } /// Generate long mode shortcut tile. /// /// A long mode shortcut tile consists of a leading and trailing `separator`, a keybinding enclosed /// in `<>` brackets and the name of the mode displayed in capitalized letters next to it. For /// example, the default long mode shortcut tile for "Locked" mode is: ` <g> LOCK `. /// /// # Arguments /// /// - `key`: A [`KeyShortcut`] that defines how the tile is displayed (active/disabled/...), what /// action it belongs to (roughly equivalent to [`InputMode`]s) and the keybinding to trigger /// this action. /// - `palette`: A structure holding styling information. /// - `separator`: The separator printed before and after the mode shortcut tile. The default is an /// arrow head-like separator. /// - `shared_super`: If set to true, all mode shortcut keybindings share a common modifier (see /// [`get_common_modifier`]) and the modifier belonging to the keybinding is **not** printed in /// the shortcut tile. /// - `first_tile`: If set to true, the leading separator for this tile will be ommited so no gap /// appears on the screen. fn long_mode_shortcut( key: &KeyShortcut, palette: ColoredElements, separator: &str, common_modifiers: &Vec<KeyModifier>, first_tile: bool, ) -> LinePart { let key_hint = key.full_text(); let has_common_modifiers = !common_modifiers.is_empty(); let key_binding = match (&key.mode, &key.key) { (KeyMode::Disabled, None) => "".to_string(), (_, None) => return LinePart::default(), (_, Some(_)) => key.letter_shortcut(common_modifiers), }; let colors = match key.mode { KeyMode::Unselected => palette.unselected, KeyMode::UnselectedAlternate => palette.unselected_alternate, KeyMode::Selected => palette.selected, KeyMode::Disabled => palette.disabled, }; let start_separator = if !has_common_modifiers && first_tile { "" } else { separator }; let prefix_separator = colors.prefix_separator.paint(start_separator); let char_left_separator = colors.char_left_separator.paint(" <".to_string()); let char_shortcut = colors.char_shortcut.paint(key_binding.to_string()); let char_right_separator = colors.char_right_separator.paint("> ".to_string()); let styled_text = colors.styled_text.paint(format!("{} ", key_hint)); let suffix_separator = colors.suffix_separator.paint(separator); LinePart { part: ANSIStrings(&[ prefix_separator, char_left_separator, char_shortcut, char_right_separator, styled_text, suffix_separator, ]) .to_string(), len: start_separator.chars().count() // Separator + 2 // " <" + key_binding.chars().count() // Key binding + 2 // "> " + key_hint.chars().count() // Key hint (mode) + 1 // " " + separator.chars().count(), // Separator } } fn shortened_modifier_shortcut( key: &KeyShortcut, palette: ColoredElements, separator: &str, common_modifiers: &Vec<KeyModifier>, first_tile: bool, ) -> LinePart { let key_hint = key.full_text(); let has_common_modifiers = !common_modifiers.is_empty(); let key_binding = match (&key.mode, &key.key) { (KeyMode::Disabled, None) => "".to_string(), (_, None) => return LinePart::default(), (_, Some(_)) => key.with_shortened_modifiers(common_modifiers), }; let colors = match key.mode { KeyMode::Unselected => palette.unselected, KeyMode::UnselectedAlternate => palette.unselected_alternate, KeyMode::Selected => palette.selected, KeyMode::Disabled => palette.disabled, }; let start_separator = if !has_common_modifiers && first_tile { "" } else { separator }; let prefix_separator = colors.prefix_separator.paint(start_separator); let char_left_separator = colors.char_left_separator.paint(" <".to_string()); let char_shortcut = colors.char_shortcut.paint(key_binding.to_string()); let char_right_separator = colors.char_right_separator.paint("> ".to_string()); let styled_text = colors.styled_text.paint(format!("{} ", key_hint)); let suffix_separator = colors.suffix_separator.paint(separator); LinePart { part: ANSIStrings(&[ prefix_separator, char_left_separator, char_shortcut, char_right_separator, styled_text, suffix_separator, ]) .to_string(), len: start_separator.chars().count() // Separator + 2 // " <" + key_binding.chars().count() // Key binding + 2 // "> " + key_hint.chars().count() // Key hint (mode) + 1 // " " + separator.chars().count(), // Separator } } /// Generate short mode shortcut tile. /// /// A short mode shortcut tile consists of a leading and trailing `separator` and a keybinding. For /// example, the default short mode shortcut tile for "Locked" mode is: ` g `. /// /// # Arguments /// /// - `key`: A [`KeyShortcut`] that defines how the tile is displayed (active/disabled/...), what /// action it belongs to (roughly equivalent to [`InputMode`]s) and the keybinding to trigger /// this action. /// - `palette`: A structure holding styling information. /// - `separator`: The separator printed before and after the mode shortcut tile. The default is an /// arrow head-like separator. /// - `shared_super`: If set to true, all mode shortcut keybindings share a common modifier (see /// [`get_common_modifier`]) and the modifier belonging to the keybinding is **not** printed in /// the shortcut tile. /// - `first_tile`: If set to true, the leading separator for this tile will be ommited so no gap /// appears on the screen. fn short_mode_shortcut( key: &KeyShortcut, palette: ColoredElements, separator: &str, common_modifiers: &Vec<KeyModifier>, first_tile: bool, ) -> LinePart { let has_common_modifiers = !common_modifiers.is_empty(); let key_binding = match (&key.mode, &key.key) { (KeyMode::Disabled, None) => "".to_string(), (_, None) => return LinePart::default(), (_, Some(_)) => key.letter_shortcut(common_modifiers), }; let colors = match key.mode { KeyMode::Unselected => palette.unselected, KeyMode::UnselectedAlternate => palette.unselected_alternate, KeyMode::Selected => palette.selected, KeyMode::Disabled => palette.disabled, }; let start_separator = if !has_common_modifiers && first_tile { "" } else { separator }; let prefix_separator = colors.prefix_separator.paint(start_separator); let char_shortcut = colors.char_shortcut.paint(format!(" {} ", key_binding)); let suffix_separator = colors.suffix_separator.paint(separator); LinePart { part: ANSIStrings(&[prefix_separator, char_shortcut, suffix_separator]).to_string(), len: separator.chars().count() // Separator + 1 // " " + key_binding.chars().count() // Key binding + 1 // " " + separator.chars().count(), // Separator } } fn key_indicators( max_len: usize, keys: &[KeyShortcut], palette: ColoredElements, separator: &str, mode_info: &ModeInfo, ) -> LinePart { // Print full-width hints let (shared_modifiers, mut line_part) = superkey(palette, separator, mode_info); for key in keys { let line_empty = line_part.len == 0; let key = long_mode_shortcut(key, palette, separator, &shared_modifiers, line_empty); line_part.part = format!("{}{}", line_part.part, key.part); line_part.len += key.len; } if line_part.len < max_len { return line_part; } // Full-width doesn't fit, try shortened modifiers (eg. "^C" instead of "Ctrl") line_part = superkey(palette, separator, mode_info).1; for key in keys { let line_empty = line_part.len == 0; let key = shortened_modifier_shortcut(key, palette, separator, &shared_modifiers, line_empty); line_part.part = format!("{}{}", line_part.part, key.part); line_part.len += key.len; } if line_part.len < max_len { return line_part; } // Full-width doesn't fit, try shortened hints (just keybindings, no meanings/actions) line_part = superkey(palette, separator, mode_info).1; for key in keys { let line_empty = line_part.len == 0; let key = short_mode_shortcut(key, palette, separator, &shared_modifiers, line_empty); line_part.part = format!("{}{}", line_part.part, key.part); line_part.len += key.len; } if line_part.len < max_len { return line_part; } // Shortened doesn't fit, print nothing line_part = LinePart::default(); line_part } fn swap_layout_keycode(mode_info: &ModeInfo) -> LinePart { let mode_keybinds = mode_info.get_mode_keybinds(); let prev_next_keys = action_key_group( &mode_keybinds, &[&[Action::PreviousSwapLayout], &[Action::NextSwapLayout]], ); let prev_next_keys_indicator = style_key_with_modifier( &prev_next_keys, &mode_info.style.colors, Some(mode_info.style.colors.text_unselected.background), ); let keycode = ANSIStrings(&prev_next_keys_indicator); let len = unstyled_len(&keycode); let part = keycode.to_string(); LinePart { part, len } } fn swap_layout_status( max_len: usize, swap_layout_name: &Option<String>, is_swap_layout_damaged: bool, mode_info: &ModeInfo, colored_elements: ColoredElements, separator: &str, ) -> Option<LinePart> { match swap_layout_name { Some(swap_layout_name) => { let mut swap_layout_name = format!(" {} ", swap_layout_name); swap_layout_name.make_ascii_uppercase(); let keycode = swap_layout_keycode(mode_info); let swap_layout_name_len = swap_layout_name.len() + 3; // 2 for the arrow separators, one for the screen end buffer // macro_rules! style_swap_layout_indicator { ($style_name:ident) => {{ ( colored_elements .$style_name .prefix_separator .paint(separator), colored_elements .$style_name .styled_text .paint(&swap_layout_name), colored_elements .$style_name .suffix_separator .paint(separator), ) }}; } let (prefix_separator, swap_layout_name, suffix_separator) = if mode_info.mode == InputMode::Locked { style_swap_layout_indicator!(disabled) } else if is_swap_layout_damaged { style_swap_layout_indicator!(unselected) } else { style_swap_layout_indicator!(selected) }; let swap_layout_indicator = format!( "{}{}{}", prefix_separator, swap_layout_name, suffix_separator ); let (part, full_len) = if mode_info.mode == InputMode::Locked { ( format!("{}", swap_layout_indicator), swap_layout_name_len, // 1 is the space between ) } else { ( format!( "{}{}{}{}", keycode, colored_elements.superkey_prefix.paint(" "), swap_layout_indicator, colored_elements.superkey_prefix.paint(" ") ), keycode.len + swap_layout_name_len + 1, // 1 is the space between ) }; let short_len = swap_layout_name_len + 1; // 1 is the space between if full_len <= max_len { Some(LinePart { part, len: full_len, }) } else if short_len <= max_len && mode_info.mode != InputMode::Locked { Some(LinePart { part: swap_layout_indicator, len: short_len, }) } else { None } }, None => None, } } /// Get the keybindings for switching `InputMode`s and `Quit` visible in status bar. /// /// Return a Vector of `Key`s where each `Key` is a shortcut to switch to some `InputMode` or Quit /// zellij. Given the vast amount of things a user can configure in their zellij config, this /// function has some limitations to keep in mind: /// /// - The vector is not deduplicated: If switching to a certain `InputMode` is bound to multiple /// `Key`s, all of these bindings will be part of the returned vector. There is also no /// guaranteed sort order. Which key ends up in the status bar in such a situation isn't defined. /// - The vector will **not** contain the ' ', '\n' and 'Esc' keys: These are the default bindings /// to get back to normal mode from any input mode, but they aren't of interest when searching /// for the super key. If for any input mode the user has bound only these keys to switching back /// to `InputMode::Normal`, a '?' will be displayed as keybinding instead. pub fn mode_switch_keys(mode_info: &ModeInfo) -> Vec<KeyWithModifier> { mode_info .get_mode_keybinds() .iter() .filter_map(|(key, vac)| match vac.first() { // No actions defined, ignore None => None, Some(vac) => { // We ignore certain "default" keybindings that switch back to normal InputMode. // These include: ' ', '\n', 'Esc' if matches!( key, KeyWithModifier { bare_key: BareKey::Char(' '), .. } | KeyWithModifier { bare_key: BareKey::Enter, .. } | KeyWithModifier { bare_key: BareKey::Esc, .. } ) { return None; } if let actions::Action::SwitchToMode { input_mode: mode } = vac { return match mode { // Store the keys that switch to displayed modes InputMode::Normal | InputMode::Locked | InputMode::Pane | InputMode::Tab | InputMode::Resize | InputMode::Move | InputMode::Scroll | InputMode::Session => Some(key.clone()), _ => None, }; } if let actions::Action::Quit = vac { return Some(key.clone()); } // Not a `SwitchToMode` or `Quit` action, ignore None }, }) .collect() } pub fn superkey( palette: ColoredElements, separator: &str, mode_info: &ModeInfo, ) -> (Vec<KeyModifier>, LinePart) { // Find a common modifier if any let common_modifiers = get_common_modifiers(mode_switch_keys(mode_info).iter().collect()); if common_modifiers.is_empty() { return (common_modifiers, LinePart::default()); } let prefix_text = if mode_info.capabilities.arrow_fonts { // Add extra space in simplified ui format!( " {} + ", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") ) } else { format!( " {} +", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") ) }; let prefix = palette.superkey_prefix.paint(&prefix_text); let suffix_separator = palette.superkey_suffix_separator.paint(separator); ( common_modifiers, LinePart { part: ANSIStrings(&[prefix, suffix_separator]).to_string(), len: prefix_text.chars().count() + separator.chars().count(), }, ) } pub fn to_char(kv: Vec<KeyWithModifier>) -> Option<KeyWithModifier> { let key = kv .iter() .filter(|key| { // These are general "keybindings" to get back to normal, they aren't interesting here. !matches!( key, KeyWithModifier { bare_key: BareKey::Enter, .. } | KeyWithModifier { bare_key: BareKey::Char(' '), .. } | KeyWithModifier { bare_key: BareKey::Esc, .. } ) }) .collect::<Vec<&KeyWithModifier>>() .into_iter() .next(); // Maybe the user bound one of the ignored keys? if key.is_none() { return kv.first().cloned(); } key.cloned() } /// Get the [`KeyShortcut`] for a specific [`InputMode`]. /// /// Iterates over the contents of `shortcuts` to find the [`KeyShortcut`] with the [`KeyAction`] /// matching the [`InputMode`]. Returns a mutable reference to the entry in `shortcuts` if a match /// is found or `None` otherwise. /// /// In case multiple entries in `shortcuts` match `mode` (which shouldn't happen), the first match /// is returned. fn get_key_shortcut_for_mode<'a>( shortcuts: &'a mut [KeyShortcut], mode: &InputMode, ) -> Option<&'a mut KeyShortcut> { let key_action = match mode { InputMode::Normal | InputMode::Prompt | InputMode::Tmux => return None, InputMode::Locked => KeyAction::Lock, InputMode::Pane | InputMode::RenamePane => KeyAction::Pane, InputMode::Tab | InputMode::RenameTab => KeyAction::Tab, InputMode::Resize => KeyAction::Resize, InputMode::Move => KeyAction::Move, InputMode::Scroll | InputMode::Search | InputMode::EnterSearch => KeyAction::Search, InputMode::Session => KeyAction::Session, }; for shortcut in shortcuts.iter_mut() { if shortcut.action == key_action { return Some(shortcut); } } None } pub fn first_line( help: &ModeInfo, tab_info: Option<&TabInfo>, max_len: usize, separator: &str, ) -> LinePart { let supports_arrow_fonts = !help.capabilities.arrow_fonts; let colored_elements = color_elements(help.style.colors, !supports_arrow_fonts); let binds = &help.get_mode_keybinds(); // Unselect all by default let mut default_keys = vec![ KeyShortcut::new( KeyMode::Unselected, KeyAction::Lock, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Locked, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Pane, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Pane, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Tab, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Tab, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Resize, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Resize, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Move, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Move, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Search, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Scroll, }], )), ), KeyShortcut::new( KeyMode::Unselected, KeyAction::Session, to_char(action_key( binds, &[Action::SwitchToMode { input_mode: InputMode::Session, }], )), ), KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Quit, to_char(action_key(binds, &[Action::Quit])), ), ]; if let Some(key_shortcut) = get_key_shortcut_for_mode(&mut default_keys, &help.mode) { key_shortcut.mode = KeyMode::Selected; key_shortcut.key = to_char(action_key(binds, &[TO_NORMAL])); } // In locked mode we must disable all other mode keybindings if help.mode == InputMode::Locked { for key in default_keys.iter_mut().skip(1) { key.mode = KeyMode::Disabled; } } if help.mode == InputMode::Tmux { // Tmux tile is hidden by default default_keys.push(KeyShortcut::new( KeyMode::Selected, KeyAction::Tmux, to_char(action_key(binds, &[TO_NORMAL])), )); } let mut key_indicators = key_indicators(max_len, &default_keys, colored_elements, separator, help); if key_indicators.len < max_len { if let Some(tab_info) = tab_info { let mut remaining_space = max_len - key_indicators.len; if let Some(swap_layout_status) = swap_layout_status( remaining_space, &tab_info.active_swap_layout_name, tab_info.is_swap_layout_dirty, help, colored_elements, separator, ) { remaining_space -= swap_layout_status.len; for _ in 0..remaining_space { key_indicators.part.push_str( &ANSIStrings(&[colored_elements.superkey_prefix.paint(" ")]).to_string(), ); key_indicators.len += 1; } key_indicators.append(&swap_layout_status); } } } key_indicators } #[cfg(test)] /// Unit tests. /// /// Note that we cheat a little here, because the number of things one may want to test is endless, /// and creating a Mockup of [`ModeInfo`] by hand for all these testcases is nothing less than /// torture. Hence, we test the most atomic units thoroughly ([`long_mode_shortcut`] and /// [`short_mode_shortcut`]) and then test the public API ([`first_line`]) to ensure correct /// operation. mod tests { use super::*; fn colored_elements() -> ColoredElements { let palette = Styling::default(); color_elements(palette, false) } // Strip style information from `LinePart` and return a raw String instead fn unstyle(line_part: LinePart) -> String { let string = line_part.to_string(); let re = regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap(); let string = re.replace_all(&string, "".to_string()); string.to_string() } #[test] fn long_mode_shortcut_selected_with_binding() { let key = KeyShortcut::new( KeyMode::Selected, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0'))), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "+ <0> SESSION +".to_string()); } #[test] // Displayed like selected(alternate), but different styling fn long_mode_shortcut_unselected_with_binding() { let key = KeyShortcut::new( KeyMode::Unselected, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0'))), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "+ <0> SESSION +".to_string()); } #[test] // Treat exactly like "unselected" variant fn long_mode_shortcut_unselected_alternate_with_binding() { let key = KeyShortcut::new( KeyMode::UnselectedAlternate, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0'))), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "+ <0> SESSION +".to_string()); } #[test] // KeyShortcuts without binding are only displayed when "disabled" (for locked mode indications) fn long_mode_shortcut_selected_without_binding() { let key = KeyShortcut::new(KeyMode::Selected, KeyAction::Session, None); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "".to_string()); } #[test] // First tile doesn't print a starting separator fn long_mode_shortcut_selected_with_binding_first_tile() { let key = KeyShortcut::new( KeyMode::Selected, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0'))), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], true); let ret = unstyle(ret); assert_eq!(ret, " <0> SESSION +".to_string()); } #[test] // Modifier is the superkey, mustn't appear in angled brackets fn long_mode_shortcut_selected_with_ctrl_binding_shared_superkey() { let key = KeyShortcut::new( KeyMode::Selected, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0')).with_ctrl_modifier()), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![KeyModifier::Ctrl], false); let ret = unstyle(ret); assert_eq!(ret, "+ <0> SESSION +".to_string()); } #[test] // Modifier must be in the angled brackets fn long_mode_shortcut_selected_with_ctrl_binding_no_shared_superkey() { let key = KeyShortcut::new( KeyMode::Selected, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0')).with_ctrl_modifier()), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "+ <Ctrl 0> SESSION +".to_string()); } #[test] // Must be displayed as usual, but it is styled to be greyed out which we don't test here fn long_mode_shortcut_disabled_with_binding() { let key = KeyShortcut::new( KeyMode::Disabled, KeyAction::Session, Some(KeyWithModifier::new(BareKey::Char('0'))), ); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "+ <0> SESSION +".to_string()); } #[test] // Must be displayed but without keybinding fn long_mode_shortcut_disabled_without_binding() { let key = KeyShortcut::new(KeyMode::Disabled, KeyAction::Session, None); let color = colored_elements(); let ret = long_mode_shortcut(&key, color, "+", &vec![], false); let ret = unstyle(ret); assert_eq!(ret, "+ <> SESSION +".to_string()); } #[test] // Test all at once // Note that when "shared_super" is true, the tile **cannot** be the first on the line, so we // ignore **first** here. fn long_mode_shortcut_selected_with_ctrl_binding_and_shared_super_and_first_tile() { let key = KeyShortcut::new( KeyMode::Selected, KeyAction::Session,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/consts.rs
default-plugins/status-bar/src/tip/consts.rs
pub const DEFAULT_CACHE_FILE_PATH: &str = "/tmp/status-bar-tips.cache"; pub const MAX_CACHE_HITS: usize = 20; // this should be 10, but right now there's a bug where the plugin load function is called twice, and sot he cache is hit twice
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/utils.rs
default-plugins/status-bar/src/tip/utils.rs
use std::path::PathBuf; use rand::prelude::{IteratorRandom, SliceRandom}; use zellij_tile::prelude::get_zellij_version; use super::cache::LocalCache; use super::consts::{DEFAULT_CACHE_FILE_PATH, MAX_CACHE_HITS}; use super::data::TIPS; macro_rules! get_name_and_caching { ($cache:expr) => {{ let name = get_random_tip_name(); $cache.caching(name.clone()).unwrap(); return name; }}; ($cache:expr, $from:expr) => {{ let name = $from.choose(&mut rand::thread_rng()).unwrap().to_string(); $cache.caching(name.clone()).unwrap(); return name; }}; } macro_rules! populate_cache { ($cache:expr) => {{ for tip_name in TIPS.keys() { $cache.caching(tip_name.clone()).unwrap(); } }}; } pub fn get_random_tip_name() -> String { TIPS.keys() .choose(&mut rand::thread_rng()) .unwrap() .to_string() } pub fn get_cached_tip_name() -> String { let mut local_cache = match LocalCache::new(PathBuf::from(DEFAULT_CACHE_FILE_PATH)) { // TODO: it might be a good to leave an log with warn later, if possible. Err(_) => return String::from("quicknav"), Ok(cache) => cache, }; let zellij_version = get_zellij_version(); if zellij_version.ne(local_cache.get_version()) { local_cache.set_version(zellij_version); local_cache.clear().unwrap(); } if local_cache.is_empty() { populate_cache!(local_cache); } let quicknav_show_count = local_cache.get_cached_data().get("quicknav").unwrap_or(&0); if quicknav_show_count <= &MAX_CACHE_HITS { let _ = local_cache.caching("quicknav"); return String::from("quicknav"); } let usable_tips = local_cache .get_cached_data() .iter() .map(|(k, _)| k.to_string()) .collect::<Vec<String>>(); if usable_tips.is_empty() { let cached_set = local_cache.get_cached_data_set(); let diff = TIPS .keys() .cloned() .filter(|k| !cached_set.contains(&k.to_string())) .collect::<Vec<&str>>(); if !diff.is_empty() { get_name_and_caching!(local_cache, diff); } else { local_cache.clear().unwrap(); get_name_and_caching!(local_cache); } } else { get_name_and_caching!(local_cache, usable_tips); } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/mod.rs
default-plugins/status-bar/src/tip/mod.rs
pub mod cache; pub mod consts; pub mod data; pub mod utils; use crate::LinePart; use zellij_tile::prelude::*; pub type TipFn = fn(&ModeInfo) -> LinePart; pub struct TipBody { pub short: TipFn, pub medium: TipFn, pub full: TipFn, }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/cache.rs
default-plugins/status-bar/src/tip/cache.rs
use std::collections::{HashMap, HashSet}; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::path::PathBuf; use serde::{Deserialize, Serialize}; use thiserror::Error; use zellij_tile::prelude::get_zellij_version; #[derive(Debug, Serialize, Deserialize)] pub struct Metadata { zellij_version: String, cached_data: HashMap<String, usize>, } #[derive(Debug)] pub struct LocalCache { path: PathBuf, metadata: Metadata, } pub type LocalCacheResult = Result<LocalCache, LocalCacheError>; #[derive(Error, Debug)] pub enum LocalCacheError { // Io error #[error("IoError: {0}")] Io(#[from] io::Error), // Io error with path context #[error("IoError: {0}, File: {1}")] IoPath(io::Error, PathBuf), // Deserialization error #[error("Deserialization error: {0}")] Serde(#[from] serde_json::Error), } impl LocalCache { fn from_json(json_cache: &str) -> Result<Metadata, LocalCacheError> { match serde_json::from_str::<Metadata>(json_cache) { Ok(metadata) => Ok(metadata), Err(err) => { if json_cache.is_empty() { return Ok(Metadata { zellij_version: get_zellij_version(), cached_data: HashMap::new(), }); } Err(LocalCacheError::Serde(err)) }, } } pub fn new(path: PathBuf) -> LocalCacheResult { match OpenOptions::new() .read(true) .create(true) .open(path.as_path()) { Ok(mut file) => { let mut json_cache = String::new(); file.read_to_string(&mut json_cache) .map_err(LocalCacheError::Io)?; let metadata = LocalCache::from_json(&json_cache)?; Ok(LocalCache { path, metadata }) }, Err(e) => Err(LocalCacheError::IoPath(e, path)), } } pub fn flush(&mut self) -> Result<(), LocalCacheError> { match serde_json::to_string(&self.metadata) { Ok(json_cache) => { let mut file = File::create(self.path.as_path()) .map_err(|e| LocalCacheError::IoPath(e, self.path.clone()))?; file.write_all(json_cache.as_bytes()) .map_err(LocalCacheError::Io)?; Ok(()) }, Err(e) => Err(LocalCacheError::Serde(e)), } } pub fn clear(&mut self) -> Result<(), LocalCacheError> { self.metadata.cached_data.clear(); self.flush() } pub fn get_version(&self) -> &String { &self.metadata.zellij_version } pub fn set_version<S: Into<String>>(&mut self, version: S) { self.metadata.zellij_version = version.into(); } pub fn is_empty(&self) -> bool { self.metadata.cached_data.is_empty() } pub fn get_cached_data(&self) -> &HashMap<String, usize> { &self.metadata.cached_data } pub fn get_cached_data_set(&self) -> HashSet<String> { self.get_cached_data().keys().cloned().collect() } pub fn caching<S: Into<String>>(&mut self, key: S) -> Result<(), LocalCacheError> { let key = key.into(); if let Some(item) = self.metadata.cached_data.get_mut(&key) { *item += 1; } else { self.metadata.cached_data.insert(key, 1); } self.flush() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/use_mouse.rs
default-plugins/status-bar/src/tip/data/use_mouse.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use crate::LinePart; use zellij_tile::prelude::*; use zellij_tile_utils::palette_match; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn use_mouse_full(help: &ModeInfo) -> LinePart { // Tip: Use the mouse to switch pane focus, scroll through the pane // scrollbuffer, switch or scroll through tabs let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); strings!(&[ Style::new().paint(" Tip: "), Style::new().fg(green_color).bold().paint("Use the mouse"), Style::new().paint(" to switch pane focus, scroll through the pane scrollbuffer, switch or scroll through the tabs."), ]) } pub fn use_mouse_medium(help: &ModeInfo) -> LinePart { // Tip: Use the mouse to switch panes/tabs or scroll through the pane // scrollbuffer let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); strings!(&[ Style::new().paint(" Tip: "), Style::new().fg(green_color).bold().paint("Use the mouse"), Style::new().paint(" to switch pane/tabs or scroll through the pane scrollbuffer."), ]) } pub fn use_mouse_short(help: &ModeInfo) -> LinePart { // Tip: Use the mouse to switch panes/tabs or scroll let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); strings!(&[ Style::new().fg(green_color).bold().paint(" Use the mouse"), Style::new().paint(" to switch pane/tabs or scroll."), ]) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/move_focus_hjkl_tab_switch.rs
default-plugins/status-bar/src/tip/data/move_focus_hjkl_tab_switch.rs
use ansi_term::{unstyled_len, ANSIString, ANSIStrings, Style}; use crate::{action_key_group, style_key_with_modifier, LinePart}; use zellij_tile::prelude::{actions::Action, *}; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn move_focus_hjkl_tab_switch_full(help: &ModeInfo) -> LinePart { // Tip: When changing focus with Alt + <←↓↑→> moving off screen left/right focuses the next tab. let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("When changing focus with "), ]; bits.extend(add_keybinds(help)); bits.push(Style::new().paint(" moving off screen left/right focuses the next tab.")); strings!(&bits) } pub fn move_focus_hjkl_tab_switch_medium(help: &ModeInfo) -> LinePart { // Tip: Changing focus with Alt + <←↓↑→> off screen focuses the next tab. let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Changing focus with "), ]; bits.extend(add_keybinds(help)); bits.push(Style::new().paint(" off screen focuses the next tab.")); strings!(&bits) } pub fn move_focus_hjkl_tab_switch_short(help: &ModeInfo) -> LinePart { // Alt + <←↓↑→> off screen edge focuses next tab. let mut bits = add_keybinds(help); bits.push(Style::new().paint(" off screen edge focuses next tab.")); strings!(&bits) } fn add_keybinds<'a>(help: &'a ModeInfo) -> Vec<ANSIString<'a>> { let pane_keymap = help.get_keybinds_for_mode(InputMode::Pane); let move_focus_keys = action_key_group( &pane_keymap, &[ &[Action::MoveFocusOrTab { direction: Direction::Left, }], &[Action::MoveFocusOrTab { direction: Direction::Right, }], ], ); // Let's see if we have some pretty groups in common here let mut arrows = vec![]; let mut letters = vec![]; for key in move_focus_keys.into_iter() { let key_str = key.to_string(); if key_str.contains('←') || key_str.contains('↓') || key_str.contains('↑') || key_str.contains('→') { arrows.push(key); } else { letters.push(key); } } let arrows = style_key_with_modifier(&arrows, &help.style.colors, None); let letters = style_key_with_modifier(&letters, &help.style.colors, None); if arrows.is_empty() && letters.is_empty() { vec![Style::new().bold().paint("UNBOUND")] } else if arrows.is_empty() || letters.is_empty() { arrows.into_iter().chain(letters.into_iter()).collect() } else { arrows .into_iter() .chain(vec![Style::new().paint(" or ")].into_iter()) .chain(letters.into_iter()) .collect() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/move_tabs.rs
default-plugins/status-bar/src/tip/data/move_tabs.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use zellij_tile::prelude::*; use zellij_tile_utils::palette_match; use crate::LinePart; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn move_tabs_full(help: &ModeInfo) -> LinePart { // Tip: Wrong order of tabs? You can move them to left and right with: // Alt + i (left) and Alt + o (right) let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); let bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Wrong order of tabs? You can move them to left and right with: "), Style::new().fg(green_color).bold().paint("Alt + i"), Style::new().paint(" (left) and "), Style::new().fg(green_color).bold().paint("Alt + o"), Style::new().paint(" (right)"), ]; strings!(&bits) } pub fn move_tabs_medium(help: &ModeInfo) -> LinePart { // Tip: You can move tabs to left and right with: // Alt + i (left) and Alt + o (right) let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); let bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("You can move tabs to left and right with: "), Style::new().fg(green_color).bold().paint("Alt + i"), Style::new().paint(" (left) and "), Style::new().fg(green_color).bold().paint("Alt + o"), Style::new().paint(" (right)"), ]; strings!(&bits) } pub fn move_tabs_short(help: &ModeInfo) -> LinePart { // Move tabs with: Alt + i (left) and Alt + o (right) let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); let bits = vec![ Style::new().paint(" Move tabs with: "), Style::new().fg(green_color).bold().paint("Alt + i"), Style::new().paint(" (left) and "), Style::new().fg(green_color).bold().paint("Alt + o"), Style::new().paint(" (right)"), ]; strings!(&bits) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/compact_layout.rs
default-plugins/status-bar/src/tip/data/compact_layout.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use crate::LinePart; use crate::{action_key, style_key_with_modifier}; use zellij_tile::prelude::{actions::Action, *}; use zellij_tile_utils::palette_match; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn compact_layout_full(help: &ModeInfo) -> LinePart { // Tip: UI taking up too much space? Start Zellij with // zellij -l compact or remove pane frames with Ctrl + <p> + <z> let green_color = palette_match!(help.style.colors.text_unselected.emphasis_0); let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("UI taking up too much space? Start Zellij with "), Style::new() .fg(green_color) .bold() .paint("zellij -l compact"), Style::new().paint(" or remove pane frames with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn compact_layout_medium(help: &ModeInfo) -> LinePart { // Tip: To save screen space, start Zellij with // zellij -l compact or remove pane frames with Ctrl + <p> + <z> let green_color = palette_match!(help.style.colors.text_unselected.emphasis_0); let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("To save screen space, start Zellij with "), Style::new() .fg(green_color) .bold() .paint("zellij -l compact"), Style::new().paint(" or remove frames with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn compact_layout_short(help: &ModeInfo) -> LinePart { // Save screen space, start Zellij with // zellij -l compact or remove pane frames with Ctrl + <p> + <z> let green_color = palette_match!(help.style.colors.text_unselected.emphasis_0); let mut bits = vec![ Style::new().paint(" Save screen space, start with: "), Style::new() .fg(green_color) .bold() .paint("zellij -l compact"), Style::new().paint(" or remove frames with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } fn add_keybinds<'a>(help: &'a ModeInfo) -> Vec<ANSIString<'a>> { let to_pane = action_key( &help.get_mode_keybinds(), &[Action::SwitchToMode { input_mode: InputMode::Pane, }], ); let pane_frames = action_key( &help.get_keybinds_for_mode(InputMode::Pane), &[ Action::TogglePaneFrames, Action::SwitchToMode { input_mode: InputMode::Normal, }, ], ); if pane_frames.is_empty() { return vec![Style::new().bold().paint("UNBOUND")]; } let mut bits = vec![]; bits.extend(style_key_with_modifier(&to_pane, &help.style.colors, None)); bits.push(Style::new().paint(", ")); bits.extend(style_key_with_modifier( &pane_frames, &help.style.colors, None, )); bits }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/sync_tab.rs
default-plugins/status-bar/src/tip/data/sync_tab.rs
use ansi_term::{unstyled_len, ANSIString, ANSIStrings, Style}; use crate::{action_key, style_key_with_modifier, LinePart}; use zellij_tile::prelude::{actions::Action, *}; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn sync_tab_full(help: &ModeInfo) -> LinePart { // Tip: Sync a tab and write keyboard input to all panes with Ctrl + <t> + <s> let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Sync a tab and write keyboard input to all its panes with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn sync_tab_medium(help: &ModeInfo) -> LinePart { // Tip: Sync input to panes in a tab with Ctrl + <t> + <s> let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Sync input to panes in a tab with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn sync_tab_short(help: &ModeInfo) -> LinePart { // Sync input in a tab with Ctrl + <t> + <s> let mut bits = vec![Style::new().paint(" Sync input in a tab with ")]; bits.extend(add_keybinds(help)); strings!(&bits) } fn add_keybinds<'a>(help: &'a ModeInfo) -> Vec<ANSIString<'a>> { let to_tab = action_key( &help.get_mode_keybinds(), &[Action::SwitchToMode { input_mode: InputMode::Tab, }], ); let sync_tabs = action_key( &help.get_keybinds_for_mode(InputMode::Tab), &[ Action::ToggleActiveSyncTab, Action::SwitchToMode { input_mode: InputMode::Normal, }, ], ); if sync_tabs.is_empty() { return vec![Style::new().bold().paint("UNBOUND")]; } let mut bits = vec![]; bits.extend(style_key_with_modifier(&to_tab, &help.style.colors, None)); bits.push(Style::new().paint(", ")); bits.extend(style_key_with_modifier( &sync_tabs, &help.style.colors, None, )); bits }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/mod.rs
default-plugins/status-bar/src/tip/data/mod.rs
use std::collections::HashMap; use lazy_static::lazy_static; use crate::tip::TipBody; mod compact_layout; mod edit_scrollbuffer; mod floating_panes_mouse; mod move_focus_hjkl_tab_switch; mod move_tabs; mod quicknav; mod send_mouse_click_to_terminal; mod sync_tab; mod use_mouse; mod zellij_setup_check; lazy_static! { pub static ref TIPS: HashMap<&'static str, TipBody> = HashMap::from([ ( "quicknav", TipBody { short: quicknav::quicknav_short, medium: quicknav::quicknav_medium, full: quicknav::quicknav_full, } ), ( "floating_panes_mouse", TipBody { short: floating_panes_mouse::floating_panes_mouse_short, medium: floating_panes_mouse::floating_panes_mouse_medium, full: floating_panes_mouse::floating_panes_mouse_full, } ), ( "send_mouse_clicks_to_terminal", TipBody { short: send_mouse_click_to_terminal::mouse_click_to_terminal_short, medium: send_mouse_click_to_terminal::mouse_click_to_terminal_medium, full: send_mouse_click_to_terminal::mouse_click_to_terminal_full, } ), ( "move_focus_hjkl_tab_switch", TipBody { short: move_focus_hjkl_tab_switch::move_focus_hjkl_tab_switch_short, medium: move_focus_hjkl_tab_switch::move_focus_hjkl_tab_switch_medium, full: move_focus_hjkl_tab_switch::move_focus_hjkl_tab_switch_full, } ), ( "zellij_setup_check", TipBody { short: zellij_setup_check::zellij_setup_check_short, medium: zellij_setup_check::zellij_setup_check_medium, full: zellij_setup_check::zellij_setup_check_full, } ), ( "use_mouse", TipBody { short: use_mouse::use_mouse_short, medium: use_mouse::use_mouse_medium, full: use_mouse::use_mouse_full, } ), ( "sync_tab", TipBody { short: sync_tab::sync_tab_short, medium: sync_tab::sync_tab_medium, full: sync_tab::sync_tab_full, } ), ( "edit_scrollbuffer", TipBody { short: edit_scrollbuffer::edit_scrollbuffer_short, medium: edit_scrollbuffer::edit_scrollbuffer_medium, full: edit_scrollbuffer::edit_scrollbuffer_full, } ), ( "compact_layout", TipBody { short: compact_layout::compact_layout_short, medium: compact_layout::compact_layout_medium, full: compact_layout::compact_layout_full, } ), ( "move_tabs", TipBody { short: move_tabs::move_tabs_short, medium: move_tabs::move_tabs_medium, full: move_tabs::move_tabs_full, } ) ]); }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/quicknav.rs
default-plugins/status-bar/src/tip/data/quicknav.rs
use ansi_term::{unstyled_len, ANSIString, ANSIStrings, Style}; use crate::{action_key, action_key_group, style_key_with_modifier, LinePart}; use zellij_tile::prelude::{actions::Action, *}; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn quicknav_full(help: &ModeInfo) -> LinePart { let groups = add_keybinds(help); let mut bits = vec![Style::new().paint(" Tip: ")]; bits.extend(groups.new_pane); bits.push(Style::new().paint(" => open new pane. ")); bits.extend(groups.move_focus); bits.push(Style::new().paint(" => navigate between panes. ")); bits.extend(groups.resize); bits.push(Style::new().paint(" => increase/decrease pane size.")); strings!(&bits) } pub fn quicknav_medium(help: &ModeInfo) -> LinePart { let groups = add_keybinds(help); let mut bits = vec![Style::new().paint(" Tip: ")]; bits.extend(groups.new_pane); bits.push(Style::new().paint(" => new pane. ")); bits.extend(groups.move_focus); bits.push(Style::new().paint(" => navigate. ")); bits.extend(groups.resize); bits.push(Style::new().paint(" => resize pane.")); strings!(&bits) } pub fn quicknav_short(help: &ModeInfo) -> LinePart { let groups = add_keybinds(help); let mut bits = vec![Style::new().paint(" QuickNav: ")]; bits.extend(groups.new_pane); bits.push(Style::new().paint(" / ")); bits.extend(groups.move_focus); bits.push(Style::new().paint(" / ")); bits.extend(groups.resize); strings!(&bits) } struct Keygroups<'a> { new_pane: Vec<ANSIString<'a>>, move_focus: Vec<ANSIString<'a>>, resize: Vec<ANSIString<'a>>, } fn add_keybinds<'a>(help: &'a ModeInfo) -> Keygroups<'a> { let normal_keymap = help.get_mode_keybinds(); let new_pane_keys = action_key( &normal_keymap, &[Action::NewPane { direction: None, pane_name: None, start_suppressed: false, }], ); let new_pane = if new_pane_keys.is_empty() { vec![Style::new().bold().paint("UNBOUND")] } else { style_key_with_modifier(&new_pane_keys, &help.style.colors, None) }; let mut resize_keys = action_key_group( &normal_keymap, &[ &[Action::Resize { resize: Resize::Increase, direction: None, }], &[Action::Resize { resize: Resize::Decrease, direction: None, }], ], ); if resize_keys.contains(&KeyWithModifier::new(BareKey::Char('=')).with_alt_modifier()) && resize_keys.contains(&KeyWithModifier::new(BareKey::Char('+')).with_alt_modifier()) { resize_keys.retain(|k| k != &KeyWithModifier::new(BareKey::Char('=')).with_alt_modifier()) } let resize = if resize_keys.is_empty() { vec![Style::new().bold().paint("UNBOUND")] } else { style_key_with_modifier(&resize_keys, &help.style.colors, None) }; let move_focus_keys = action_key_group( &normal_keymap, &[ &[Action::MoveFocus { direction: Direction::Left, }], &[Action::MoveFocusOrTab { direction: Direction::Left, }], &[Action::MoveFocus { direction: Direction::Down, }], &[Action::MoveFocus { direction: Direction::Up, }], &[Action::MoveFocus { direction: Direction::Right, }], &[Action::MoveFocusOrTab { direction: Direction::Right, }], ], ); // Let's see if we have some pretty groups in common here let mut arrows = vec![]; let mut letters = vec![]; for key in move_focus_keys.into_iter() { let key_str = key.to_string(); if key_str.contains('←') || key_str.contains('↓') || key_str.contains('↑') || key_str.contains('→') { arrows.push(key); } else { letters.push(key); } } let arrows = style_key_with_modifier(&arrows, &help.style.colors, None); let letters = style_key_with_modifier(&letters, &help.style.colors, None); let move_focus = if arrows.is_empty() && letters.is_empty() { vec![Style::new().bold().paint("UNBOUND")] } else if arrows.is_empty() || letters.is_empty() { arrows.into_iter().chain(letters.into_iter()).collect() } else { arrows .into_iter() .chain(vec![Style::new().paint(" or ")].into_iter()) .chain(letters.into_iter()) .collect() }; Keygroups { new_pane, move_focus, resize, } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/send_mouse_click_to_terminal.rs
default-plugins/status-bar/src/tip/data/send_mouse_click_to_terminal.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use crate::LinePart; use zellij_tile::prelude::*; use zellij_tile_utils::palette_match; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn mouse_click_to_terminal_full(help: &ModeInfo) -> LinePart { // Tip: SHIFT + <mouse-click> bypasses Zellij and sends the mouse click directly to the terminal let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); let orange_color = palette_match!(help.style.colors.text_unselected.emphasis_0); strings!(&[ Style::new().paint(" Tip: "), Style::new().fg(orange_color).bold().paint("Shift"), Style::new().paint(" + <"), Style::new().fg(green_color).bold().paint("mouse-click"), Style::new().paint("> bypasses Zellij and sends the mouse click directly to the terminal."), ]) } pub fn mouse_click_to_terminal_medium(help: &ModeInfo) -> LinePart { // Tip: SHIFT + <mouse-click> sends the click directly to the terminal let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); let orange_color = palette_match!(help.style.colors.text_unselected.emphasis_0); strings!(&[ Style::new().paint(" Tip: "), Style::new().fg(orange_color).bold().paint("Shift"), Style::new().paint(" + <"), Style::new().fg(green_color).bold().paint("mouse-click"), Style::new().paint("> sends the click directly to the terminal."), ]) } pub fn mouse_click_to_terminal_short(help: &ModeInfo) -> LinePart { // Tip: SHIFT + <mouse-click> => sends click to terminal. let green_color = palette_match!(help.style.colors.text_unselected.emphasis_2); let orange_color = palette_match!(help.style.colors.text_unselected.emphasis_0); strings!(&[ Style::new().paint(" Tip: "), Style::new().fg(orange_color).bold().paint("Shift"), Style::new().paint(" + <"), Style::new().fg(green_color).bold().paint("mouse-click"), Style::new().paint("> => sends click to terminal."), ]) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/zellij_setup_check.rs
default-plugins/status-bar/src/tip/data/zellij_setup_check.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use crate::LinePart; use zellij_tile::prelude::*; use zellij_tile_utils::palette_match; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn zellij_setup_check_full(help: &ModeInfo) -> LinePart { // Tip: Having issues with Zellij? Try running "zellij setup --check" let orange_color = palette_match!(help.style.colors.text_unselected.emphasis_0); strings!(&[ Style::new().paint(" Tip: "), Style::new().paint("Having issues with Zellij? Try running "), Style::new() .fg(orange_color) .bold() .paint("zellij setup --check"), ]) } pub fn zellij_setup_check_medium(help: &ModeInfo) -> LinePart { // Tip: Run "zellij setup --check" to find issues let orange_color = palette_match!(help.style.colors.text_unselected.emphasis_0); strings!(&[ Style::new().paint(" Tip: "), Style::new().paint("Run "), Style::new() .fg(orange_color) .bold() .paint("zellij setup --check"), Style::new().paint(" to find issues"), ]) } pub fn zellij_setup_check_short(help: &ModeInfo) -> LinePart { // Run "zellij setup --check" to find issues let orange_color = palette_match!(help.style.colors.text_unselected.emphasis_0); strings!(&[ Style::new().paint(" Run "), Style::new() .fg(orange_color) .bold() .paint("zellij setup --check"), Style::new().paint(" to find issues"), ]) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/edit_scrollbuffer.rs
default-plugins/status-bar/src/tip/data/edit_scrollbuffer.rs
use ansi_term::{ unstyled_len, ANSIString, ANSIStrings, Color::{Fixed, RGB}, Style, }; use crate::{action_key, style_key_with_modifier, LinePart}; use zellij_tile::prelude::{actions::Action, *}; use zellij_tile_utils::palette_match; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn edit_scrollbuffer_full(help: &ModeInfo) -> LinePart { // Tip: Search through the scrollbuffer using your default $EDITOR with // Ctrl + <s> + <e> let green_color = palette_match!(help.style.colors.text_unselected.emphasis_0); let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Search through the scrollbuffer using your default "), Style::new().fg(green_color).bold().paint("$EDITOR"), Style::new().paint(" with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn edit_scrollbuffer_medium(help: &ModeInfo) -> LinePart { // Tip: Search the scrollbuffer using your $EDITOR with // Ctrl + <s> + <e> let green_color = palette_match!(help.style.colors.text_unselected.emphasis_0); let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Search the scrollbuffer using your "), Style::new().fg(green_color).bold().paint("$EDITOR"), Style::new().paint(" with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn edit_scrollbuffer_short(help: &ModeInfo) -> LinePart { // Search using $EDITOR with // Ctrl + <s> + <e> let green_color = palette_match!(help.style.colors.text_unselected.emphasis_0); let mut bits = vec![ Style::new().paint(" Search using "), Style::new().fg(green_color).bold().paint("$EDITOR"), Style::new().paint(" with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } fn add_keybinds<'a>(help: &'a ModeInfo) -> Vec<ANSIString<'a>> { let to_pane = action_key( &help.get_mode_keybinds(), &[Action::SwitchToMode { input_mode: InputMode::Scroll, }], ); let edit_buffer = action_key( &help.get_keybinds_for_mode(InputMode::Scroll), &[ Action::EditScrollback, Action::SwitchToMode { input_mode: InputMode::Normal, }, ], ); if edit_buffer.is_empty() { return vec![Style::new().bold().paint("UNBOUND")]; } let mut bits = vec![]; bits.extend(style_key_with_modifier(&to_pane, &help.style.colors, None)); bits.push(Style::new().paint(", ")); bits.extend(style_key_with_modifier( &edit_buffer, &help.style.colors, None, )); bits }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/status-bar/src/tip/data/floating_panes_mouse.rs
default-plugins/status-bar/src/tip/data/floating_panes_mouse.rs
use ansi_term::{unstyled_len, ANSIString, ANSIStrings, Style}; use crate::{action_key, style_key_with_modifier, LinePart}; use zellij_tile::prelude::{actions::Action, *}; macro_rules! strings { ($ANSIStrings:expr) => {{ let strings: &[ANSIString] = $ANSIStrings; let ansi_strings = ANSIStrings(strings); LinePart { part: format!("{}", ansi_strings), len: unstyled_len(&ansi_strings), } }}; } pub fn floating_panes_mouse_full(help: &ModeInfo) -> LinePart { // Tip: Toggle floating panes with Ctrl + <p> + <w> and move them with keyboard or mouse let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Toggle floating panes with "), ]; bits.extend(add_keybinds(help)); bits.push(Style::new().paint(" and move them with keyboard or mouse")); strings!(&bits) } pub fn floating_panes_mouse_medium(help: &ModeInfo) -> LinePart { // Tip: Toggle floating panes with Ctrl + <p> + <w> let mut bits = vec![ Style::new().paint(" Tip: "), Style::new().paint("Toggle floating panes with "), ]; bits.extend(add_keybinds(help)); strings!(&bits) } pub fn floating_panes_mouse_short(help: &ModeInfo) -> LinePart { // Ctrl + <p> + <w> => floating panes let mut bits = add_keybinds(help); bits.push(Style::new().paint(" => floating panes")); strings!(&bits) } fn add_keybinds<'a>(help: &'a ModeInfo) -> Vec<ANSIString<'a>> { let to_pane = action_key( &help.get_mode_keybinds(), &[Action::SwitchToMode { input_mode: InputMode::Pane, }], ); let floating_toggle = action_key( &help.get_keybinds_for_mode(InputMode::Pane), &[ Action::ToggleFloatingPanes, Action::SwitchToMode { input_mode: InputMode::Normal, }, ], ); if floating_toggle.is_empty() { return vec![Style::new().bold().paint("UNBOUND")]; } let mut bits = vec![]; bits.extend(style_key_with_modifier(&to_pane, &help.style.colors, None)); bits.push(Style::new().paint(", ")); bits.extend(style_key_with_modifier( &floating_toggle, &help.style.colors, None, )); bits }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/about/src/tips.rs
default-plugins/about/src/tips.rs
use zellij_tile::prelude::*; use std::cell::RefCell; use std::rc::Rc; use crate::active_component::{ActiveComponent, ClickAction}; use crate::pages::{BulletinList, ComponentLine, Page, TextOrCustomRender}; pub const MAX_TIP_INDEX: usize = 11; impl Page { pub fn new_tip_screen( link_executable: Rc<RefCell<String>>, base_mode: Rc<RefCell<InputMode>>, tip_index: usize, ) -> Self { if tip_index == 0 { Page::tip_1(link_executable) } else if tip_index == 1 { Page::tip_2(link_executable, base_mode) } else if tip_index == 2 { Page::tip_3(link_executable) } else if tip_index == 3 { Page::tip_4(link_executable, base_mode) } else if tip_index == 4 { Page::tip_5(link_executable) } else if tip_index == 5 { Page::tip_6(link_executable, base_mode) } else if tip_index == 6 { Page::tip_7(link_executable) } else if tip_index == 7 { Page::tip_8(link_executable) } else if tip_index == 8 { Page::tip_9(link_executable) } else if tip_index == 9 { Page::tip_10(link_executable, base_mode) } else if tip_index == 10 { Page::tip_11(link_executable) } else if tip_index == 11 { Page::tip_12(link_executable, base_mode) } else { Page::tip_1(link_executable) } } pub fn tip_1(link_executable: Rc<RefCell<String>>) -> Self { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #1").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Check out the Zellij screencasts/tutorials to learn how to better take advantage") )) ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("of all the Zellij features. Learn about basic usage, layouts, sessions and more!") )) ]) ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("Follow this link: ").color_range(2, ..))), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://zellij.dev/screencasts"))) .with_hover(TextOrCustomRender::CustomRender( Box::new(screencasts_link_selected()), Box::new(screencasts_link_selected_len()), )) .with_left_click_action(ClickAction::new_open_link( format!("https://zellij.dev/screencasts"), link_executable.clone(), )), ])]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_2(link_executable: Rc<RefCell<String>>, base_mode: Rc<RefCell<InputMode>>) -> Self { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #2").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("You can open the terminal contents in your $EDITOR, allowing you to search") .color_range(2, 43..=49) )) ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("through them, copy to your clipboard or even save them for later.") )) ]) ]) .with_paragraph(vec![ComponentLine::new(vec![ match *base_mode.borrow() { InputMode::Locked => { ActiveComponent::new(TextOrCustomRender::Text( Text::new("While focused on a terminal pane: Ctrl g + s + e") .color_range(0, 34..=39) .color_indices(0, vec![43, 47]) )) }, _ => { ActiveComponent::new(TextOrCustomRender::Text( Text::new("While focused on a terminal pane: Ctrl s + e") .color_range(0, 34..=39) .color_indices(0, vec![43]) )) } } ])]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_3(link_executable: Rc<RefCell<String>>) -> Self { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #3").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("Want to make your floating pane bigger?"), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new( "You can switch to the ENLARGED layout with Alt ] while focused on it.", ) .color_range(2, 22..=29) .color_range(0, 43..=47), ))]), ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } fn tip_4(link_executable: Rc<RefCell<String>>, base_mode: Rc<RefCell<InputMode>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij tip #4").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("It's possible to \"pin\" a floating pane so that it will always"), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("be visible even if floating panes are hidden."), ))]), ]) .with_bulletin_list( BulletinList::new( Text::new(format!("Floating panes can be \"pinned\": ")).color_range(2, ..), ) .with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new(format!("With a mouse click on their top right corner")) .color_range(3, 7..=17), )), ActiveComponent::new(TextOrCustomRender::Text(match *base_mode.borrow() { InputMode::Locked => Text::new(format!("With Ctrl g + p + i")) .color_range(3, 5..=10) .color_range(3, 14..15) .color_range(3, 18..19), _ => Text::new("With Ctrl p + i") .color_range(3, 5..=10) .color_range(3, 14..15), })), ]), ) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("A great use case for these is to tail log files or to show"), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new(format!( "real-time compiler output while working in other panes." )), ))]), ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_5(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #5").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("Panes can be resized into stacks to be managed easier."))), ]), ]) .with_bulletin_list(BulletinList::new(Text::new("To try it out:").color_range(2, ..)) .with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Hide this pane with Alt f (you can bring it back with Alt f again)") .color_range(3, 20..=24) .color_range(3, 54..=58) )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Open 4-5 panes with Alt n") .color_range(3, 20..=24) )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Press Alt + until you reach full screen") .color_range(3, 6..=10) )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Press Alt - until you are back at the original state") .color_range(3, 6..=10) )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("You can always snap back to the built-in swap layouts with Alt <[]>") .color_range(3, 59..=61) .color_range(3, 64..=65) )), ]) ) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("To disable this behavior, add stacked_resize false to the Zellij Configuration") .color_range(3, 30..=49) )), ]) ]) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("For more details, see: ") .color_range(2, ..) )), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://zellij.dev/tutorials/stacked-resize"))) .with_hover(TextOrCustomRender::CustomRender(Box::new(stacked_resize_screencast_link_selected), Box::new(stacked_resize_screencast_link_selected_len))) .with_left_click_action(ClickAction::new_open_link("https://zellij.dev/tutorials/stacked-resize".to_owned(), link_executable.clone())) ]) ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_6(link_executable: Rc<RefCell<String>>, base_mode: Rc<RefCell<InputMode>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #6").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("Are the Zellij keybindings colliding with other applications for you?"))) ]), ]) .with_bulletin_list(BulletinList::new(Text::new("Check out the non-colliding keybindings preset:")) .with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text( match *base_mode.borrow() { InputMode::Locked => { Text::new("Open the Zellij configuration with Ctrl g + o + c") .color_range(3, 35..=40) .color_indices(3, vec![44, 48]) }, _ => { Text::new("Open the Zellij configuration with Ctrl o + c") .color_range(3, 35..=40) .color_indices(3, vec![44]) } } )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Press TAB to go to Change Mode Behavior") .color_range(3, 6..=9) )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Select non-colliding temporarily with ENTER or permanently with Ctrl a") .color_range(3, 38..=42) .color_range(3, 64..=69) )), ]) ) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("For more details, see: ") .color_range(2, ..) )), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://zellij.dev/tutorials/colliding-keybindings"))) .with_hover(TextOrCustomRender::CustomRender(Box::new(colliding_keybindings_link_selected), Box::new(colliding_keybindings_link_selected_len))) .with_left_click_action(ClickAction::new_open_link("https://zellij.dev/tutorials/colliding-keybindings".to_owned(), link_executable.clone())) ]) ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_7(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #7").color_range(0, ..)) .with_paragraph(vec![ComponentLine::new(vec![ActiveComponent::new( TextOrCustomRender::Text(Text::new( "Want to customize the appearance and colors of Zellij?", )), )])]) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Check out the built-in themes: ").color_range(2, ..), )), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "https://zellij.dev/documentation/theme-list", ))) .with_hover(TextOrCustomRender::CustomRender( Box::new(theme_list_selected), Box::new(theme_list_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://zellij.dev/documentation/theme-list".to_owned(), link_executable.clone(), )), ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Or create your own theme: ").color_range(2, ..), )), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "https://zellij.dev/documentation/themes", ))) .with_hover(TextOrCustomRender::CustomRender( Box::new(theme_link_selected), Box::new(theme_link_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://zellij.dev/documentation/themes".to_owned(), link_executable.clone(), )), ]), ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_8(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #8").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("If you change the pane focus with Alt + <←↓↑→> or Alt + <hjkl> beyond the") .color_range(0, 34..=36) .color_range(2, 40..=45) .color_range(0, 50..=52) .color_range(2, 56..=61) )) ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("right or left side of the screen, the next or previous tab will be focused."))) ]), ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_9(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #9").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("For plugins, integrations and tutorials created by the community, check out the") )) ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Awesome-zellij repository: ") .color_range(2, ..=39) )), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://github.com/zellij-org/awesome-zellij"))) .with_hover(TextOrCustomRender::CustomRender( Box::new(awesome_zellij_link_text_selected), Box::new(awesome_zellij_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/zellij-org/awesome-zellij".to_owned(), link_executable.clone(), )), ]), ]) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("For community and support:") .color_range(2, ..) )) ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("Discord: "))), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://discord.com/invite/CrUAFH3"))) .with_hover(TextOrCustomRender::CustomRender( Box::new(discord_link_text_selected), Box::new(discord_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://discord.com/invite/CrUAFH3".to_owned(), link_executable.clone(), )), ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("Matrix: "))), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://matrix.to/#/#zellij_general:matrix.org"))) .with_hover(TextOrCustomRender::CustomRender( Box::new(matrix_link_text_selected), Box::new(matrix_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://matrix.to/#/#zellij_general:matrix.org".to_owned(), link_executable.clone(), )), ]) ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_10(link_executable: Rc<RefCell<String>>, base_mode: Rc<RefCell<InputMode>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #10").color_range(0, ..)) .with_bulletin_list( BulletinList::new( Text::new("The Zellij session-manager can:").color_range(2, 11..=25), ) .with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new( "Create new sessions", ))), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "Switch between existing sessions", ))), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "Resurrect exited sessions", ))), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "Change the session name", ))), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "Disconnect other users from the current session", ))), ]), ) .with_paragraph(vec![ComponentLine::new(vec![ActiveComponent::new( TextOrCustomRender::Text(match *base_mode.borrow() { InputMode::Locked => Text::new("Check it out with with: Ctrl g + o + w") .color_range(3, 24..=29) .color_indices(3, vec![33, 37]), _ => Text::new("Check it out with with: Ctrl o + w") .color_range(3, 24..=29) .color_indices(3, vec![33]), }), )])]) .with_paragraph(vec![ComponentLine::new(vec![ActiveComponent::new( TextOrCustomRender::Text( Text::new("You can also use it as a welcome screen with: zellij -l welcome") .color_range(0, 46..=62), ), )])]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, _menu_item_is_selected| { tips_help_text(hovering_over_link) })) } pub fn tip_11(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .main_screen() .with_title(Text::new("Zellij Tip #11").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("You can change the arrangement of panes on screen with Alt + []") .color_range(0, 55..=57) .color_range(2, 61..=62) )), ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("This works with tiled or floating panes, depending which is visible.") )) ]) ]) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Resizing or splitting a pane breaks out of this arrangement. It is then possible") )), ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("to snap back by pressing Alt + [] once more. This status can be seen") .color_range(0, 25..=27) .color_range(2, 31..=32) )), ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("on the top right corner of the screen.") )), ]), ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(),
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/about/src/active_component.rs
default-plugins/about/src/active_component.rs
use std::cell::RefCell; use std::rc::Rc; use zellij_tile::prelude::*; use crate::pages::{Page, TextOrCustomRender}; #[derive(Debug)] pub struct ActiveComponent { text_no_hover: TextOrCustomRender, text_hover: Option<TextOrCustomRender>, left_click_action: Option<ClickAction>, last_rendered_coordinates: Option<ComponentCoordinates>, pub is_active: bool, } impl ActiveComponent { pub fn new(text_no_hover: TextOrCustomRender) -> Self { ActiveComponent { text_no_hover, text_hover: None, left_click_action: None, is_active: false, last_rendered_coordinates: None, } } pub fn with_hover(mut self, text_hover: TextOrCustomRender) -> Self { self.text_hover = Some(text_hover); self } pub fn with_left_click_action(mut self, left_click_action: ClickAction) -> Self { self.left_click_action = Some(left_click_action); self } pub fn render(&mut self, x: usize, y: usize, rows: usize, columns: usize) -> usize { let mut component_width = 0; match self.text_hover.as_mut() { Some(text) if self.is_active => { let text_len = text.render(x, y, rows, columns); component_width += text_len; }, _ => { let text_len = self.text_no_hover.render(x, y, rows, columns); component_width += text_len; }, } self.last_rendered_coordinates = Some(ComponentCoordinates::new(x, y, 1, columns)); component_width } pub fn left_click_action(&mut self) -> Option<Page> { match self.left_click_action.take() { Some(ClickAction::ChangePage(go_to_page)) => Some(go_to_page()), Some(ClickAction::OpenLink(link, executable)) => { self.left_click_action = Some(ClickAction::OpenLink(link.clone(), executable.clone())); run_command(&[&executable.borrow(), &link], Default::default()); None }, None => None, } } pub fn handle_left_click_at_position(&mut self, x: usize, y: usize) -> Option<Page> { let Some(last_rendered_coordinates) = &self.last_rendered_coordinates else { return None; }; if last_rendered_coordinates.contains(x, y) { self.left_click_action() } else { None } } pub fn handle_hover_at_position(&mut self, x: usize, y: usize) -> bool { let Some(last_rendered_coordinates) = &self.last_rendered_coordinates else { return false; }; if last_rendered_coordinates.contains(x, y) && self.text_hover.is_some() { self.is_active = true; true } else { false } } pub fn handle_selection(&mut self) -> Option<Page> { if self.is_active { self.left_click_action() } else { None } } pub fn column_count(&self) -> usize { match self.text_hover.as_ref() { Some(text) if self.is_active => text.len(), _ => self.text_no_hover.len(), } } pub fn clear_hover(&mut self) { self.is_active = false; } } #[derive(Debug)] struct ComponentCoordinates { x: usize, y: usize, rows: usize, columns: usize, } impl ComponentCoordinates { pub fn contains(&self, x: usize, y: usize) -> bool { x >= self.x && x < self.x + self.columns && y >= self.y && y < self.y + self.rows } } impl ComponentCoordinates { pub fn new(x: usize, y: usize, rows: usize, columns: usize) -> Self { ComponentCoordinates { x, y, rows, columns, } } } pub enum ClickAction { ChangePage(Box<dyn FnOnce() -> Page>), OpenLink(String, Rc<RefCell<String>>), // (destination, executable) } impl std::fmt::Debug for ClickAction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ClickAction::ChangePage(_) => write!(f, "ChangePage"), ClickAction::OpenLink(destination, executable) => { write!(f, "OpenLink: {}, {:?}", destination, executable) }, } } } impl ClickAction { pub fn new_change_page<F>(go_to_page: F) -> Self where F: FnOnce() -> Page + 'static, { ClickAction::ChangePage(Box::new(go_to_page)) } pub fn new_open_link(destination: String, executable: Rc<RefCell<String>>) -> Self { ClickAction::OpenLink(destination, executable) } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/about/src/pages.rs
default-plugins/about/src/pages.rs
use zellij_tile::prelude::*; use std::cell::RefCell; use std::rc::Rc; use crate::active_component::{ActiveComponent, ClickAction}; #[derive(Debug)] pub struct Page { title: Option<Text>, components_to_render: Vec<RenderedComponent>, has_hover: bool, hovering_over_link: bool, menu_item_is_selected: bool, pub is_main_screen: bool, } impl Page { pub fn new_main_screen( link_executable: Rc<RefCell<String>>, zellij_version: String, _base_mode: Rc<RefCell<InputMode>>, is_release_notes: bool, ) -> Self { Page::new() .main_screen() .with_title(main_screen_title(zellij_version.clone(), is_release_notes)) .with_bulletin_list(BulletinList::new(whats_new_title()).with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text(main_menu_item( "Web Client", ))) .with_hover(TextOrCustomRender::Text( main_menu_item("Web Client").selected(), )) .with_left_click_action(ClickAction::new_change_page({ let link_executable = link_executable.clone(); move || Page::new_web_client(link_executable.clone()) })), ActiveComponent::new(TextOrCustomRender::Text(main_menu_item( "Multiple Pane Select", ))) .with_hover(TextOrCustomRender::Text( main_menu_item("Multiple Pane Select").selected(), )) .with_left_click_action(ClickAction::new_change_page(move || { Page::new_multiple_select() })), ActiveComponent::new(TextOrCustomRender::Text(main_menu_item( "Key Tooltips for the compact-bar", ))) .with_hover(TextOrCustomRender::Text( main_menu_item("Key Tooltips for the compact-bar").selected(), )) .with_left_click_action(ClickAction::new_change_page({ let link_executable = link_executable.clone(); move || Page::new_key_tooltips_for_compact_bar(link_executable.clone()) })), ActiveComponent::new(TextOrCustomRender::Text(main_menu_item( "Stack Keybinding", ))) .with_hover(TextOrCustomRender::Text( main_menu_item("Stack Keybinding").selected(), )) .with_left_click_action(ClickAction::new_change_page(move || { Page::new_stack_keybinding() })), ActiveComponent::new(TextOrCustomRender::Text(main_menu_item( "Performance Improvements", ))) .with_hover(TextOrCustomRender::Text( main_menu_item("Performance Improvements").selected(), )) .with_left_click_action(ClickAction::new_change_page({ move || Page::new_performance_improvements() })), ])) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(Text::new("Full Changelog: "))), ActiveComponent::new(TextOrCustomRender::Text(changelog_link_unselected( zellij_version.clone(), ))) .with_hover(TextOrCustomRender::CustomRender( Box::new(changelog_link_selected(zellij_version.clone())), Box::new(changelog_link_selected_len(zellij_version.clone())), )) .with_left_click_action(ClickAction::new_open_link( format!( "https://github.com/zellij-org/zellij/releases/tag/v{}", zellij_version.clone() ), link_executable.clone(), )), ])]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text(support_the_developer_text())), ActiveComponent::new(TextOrCustomRender::Text(sponsors_link_text_unselected())) .with_hover(TextOrCustomRender::CustomRender( Box::new(sponsors_link_text_selected), Box::new(sponsors_link_text_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://github.com/sponsors/imsnif".to_owned(), link_executable.clone(), )), ])]) .with_help(if is_release_notes { Box::new(|hovering_over_link, menu_item_is_selected| { release_notes_main_help(hovering_over_link, menu_item_is_selected) }) } else { Box::new(|hovering_over_link, menu_item_is_selected| { main_screen_help_text(hovering_over_link, menu_item_is_selected) }) }) } pub fn new_web_client(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .with_title(Text::new("Web Client").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ // ActiveComponent::new(TextOrCustomRender::Text(Text::new("This version includes a new resizing algorithm that helps better manage panes"))), ActiveComponent::new(TextOrCustomRender::Text(Text::new("This version includes a web client, allowing you to share sessions in the browser."))), ]), ]) .with_bulletin_list(BulletinList::new(Text::new("The web client:").color_range(2, ..)) .with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("Allows you to bookmark sessions") .color_substring(3, "bookmark sessions") )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Includes built-in authentication") )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Can be used as a daily-driver, making your terminal emulator optional") )), ActiveComponent::new(TextOrCustomRender::Text( Text::new("Is completely opt-in") )), ]) ) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("For more details, see: ") .color_range(2, ..) )), ActiveComponent::new(TextOrCustomRender::Text(Text::new("https://zellij.dev/tutorials/web-client"))) .with_hover(TextOrCustomRender::CustomRender(Box::new(web_client_screencast_link_selected), Box::new(web_client_screencast_link_selected_len))) .with_left_click_action(ClickAction::new_open_link("https://zellij.dev/tutorials/web-client".to_owned(), link_executable.clone())) ]) ]) .with_help(Box::new(|hovering_over_link, menu_item_is_selected| esc_go_back_plus_link_hover(hovering_over_link, menu_item_is_selected))) } fn new_multiple_select() -> Page { Page::new() .with_title(Text::new("Multiple Pane Select").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("This version adds the ability to perform bulk operations on panes"), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("eg. close, make floating, break to a new tab, etc."), ))]), ]) .with_bulletin_list( BulletinList::new( Text::new(format!("To select multiple panes: ")).color_range(2, ..), ) .with_items(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new(format!("Alt <left-click> them")) .color_substring(3, "Alt <left-click>"), )), ActiveComponent::new(TextOrCustomRender::Text( Text::new(format!("Toggle with Alt p")).color_substring(3, "Alt p"), )), ]), ) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("To disable this behavior (and the associated hover effects)"), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new(format!("add advanced_mouse_actions false to the config.")) .color_substring(3, "advanced_mouse_actions false"), ))]), ]) .with_help(Box::new(|_hovering_over_link, _menu_item_is_selected| { esc_to_go_back_help() })) } fn new_key_tooltips_for_compact_bar(link_executable: Rc<RefCell<String>>) -> Page { Page::new() .with_title(Text::new("Key Tooltips for the compact-bar").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new( "Starting this version, it's possible to add toggle-able key tooltips", ) .color_range(3, 37..=58), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("when using the compact-bar.").color_substring(3, "compact-bar"), ))]), ]) .with_paragraph(vec![ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("For more information: ").color_range(2, ..), )), ActiveComponent::new(TextOrCustomRender::Text(Text::new( "https://zellij.dev/documentation/faq.html", ))) .with_hover(TextOrCustomRender::CustomRender( Box::new(compact_bar_link_selected), Box::new(compact_bar_link_selected_len), )) .with_left_click_action(ClickAction::new_open_link( "https://zellij.dev/documentation/faq.html".to_owned(), link_executable.clone(), )), ])]) .with_help(Box::new(|hovering_over_link, menu_item_is_selected| { esc_go_back_plus_link_hover(hovering_over_link, menu_item_is_selected) })) } fn new_stack_keybinding() -> Page { Page::new() .with_title(Text::new("New Stack Keybinding").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("It's now possible to open a stacked pane directly on top of the current pane").color_substring(2, "stacked pane"), ))]), ]) .with_paragraph(vec![ ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("By default: Ctrl p + s").color_substring(3, "Ctrl p").color_substring(3, " s"), )), ]), ComponentLine::new(vec![ ActiveComponent::new(TextOrCustomRender::Text( Text::new("In unlock first: Ctrl g + p + s").color_substring(3, "Ctrl g").color_substring(3, " p").color_substring(3, " s"), )), ]), ]) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("To add to an existing config, see the release notes.") ))]), ]) .with_help(Box::new(|_hovering_over_link, _menu_item_is_selected| { esc_to_go_back_help() })) } fn new_performance_improvements() -> Page { Page::new() .with_title(Text::new("Performance Improvements").color_range(0, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("This version adds a debounced asynchronous render mechanism"), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("making rendering much smoother across the whole application."), ))]), ]) .with_help(Box::new(|_hovering_over_link, _menu_item_is_selected| { esc_to_go_back_help() })) } } impl Page { pub fn new() -> Self { Page { title: None, components_to_render: vec![], has_hover: false, hovering_over_link: false, menu_item_is_selected: false, is_main_screen: false, } } pub fn main_screen(mut self) -> Self { self.is_main_screen = true; self } pub fn with_title(mut self, title: Text) -> Self { self.title = Some(title); self } pub fn with_bulletin_list(mut self, bulletin_list: BulletinList) -> Self { self.components_to_render .push(RenderedComponent::BulletinList(bulletin_list)); self } pub fn with_paragraph(mut self, paragraph: Vec<ComponentLine>) -> Self { self.components_to_render .push(RenderedComponent::Paragraph(paragraph)); self } pub fn with_help(mut self, help_text_fn: Box<dyn Fn(bool, bool) -> Text>) -> Self { self.components_to_render .push(RenderedComponent::HelpText(help_text_fn)); self } pub fn handle_key(&mut self, key: KeyWithModifier) -> bool { let mut should_render = false; if key.bare_key == BareKey::Down && key.has_no_modifiers() { self.move_selection_down(); should_render = true; } else if key.bare_key == BareKey::Up && key.has_no_modifiers() { self.move_selection_up(); should_render = true; } should_render } pub fn handle_mouse_left_click(&mut self, x: usize, y: usize) -> Option<Page> { for rendered_component in &mut self.components_to_render { match rendered_component { RenderedComponent::BulletinList(bulletin_list) => { let page_to_render = bulletin_list.handle_left_click_at_position(x, y); if page_to_render.is_some() { return page_to_render; } }, RenderedComponent::Paragraph(paragraph) => { for component_line in paragraph { let page_to_render = component_line.handle_left_click_at_position(x, y); if page_to_render.is_some() { return page_to_render; } } }, _ => {}, } } None } pub fn handle_selection(&mut self) -> Option<Page> { for rendered_component in &mut self.components_to_render { match rendered_component { RenderedComponent::BulletinList(bulletin_list) => { let page_to_render = bulletin_list.handle_selection(); if page_to_render.is_some() { return page_to_render; } }, _ => {}, } } None } pub fn handle_mouse_hover(&mut self, x: usize, y: usize) -> bool { let hover_cleared = self.clear_hover(); // TODO: do the right thing if the same component was hovered from // previous motion for rendered_component in &mut self.components_to_render { match rendered_component { RenderedComponent::BulletinList(bulletin_list) => { let should_render = bulletin_list.handle_hover_at_position(x, y); if should_render { self.has_hover = true; self.menu_item_is_selected = true; return should_render; } }, RenderedComponent::Paragraph(paragraph) => { for component_line in paragraph { let should_render = component_line.handle_hover_at_position(x, y); if should_render { self.has_hover = true; self.hovering_over_link = true; return should_render; } } }, _ => {}, } } hover_cleared } fn move_selection_up(&mut self) { match self.position_of_active_bulletin() { Some(position_of_active_bulletin) if position_of_active_bulletin > 0 => { self.clear_active_bulletins(); self.set_active_bulletin(position_of_active_bulletin.saturating_sub(1)); }, Some(0) => { self.clear_active_bulletins(); }, _ => { self.clear_active_bulletins(); self.set_last_active_bulletin(); }, } } fn move_selection_down(&mut self) { match self.position_of_active_bulletin() { Some(position_of_active_bulletin) => { self.clear_active_bulletins(); self.set_active_bulletin(position_of_active_bulletin + 1); }, None => { self.set_active_bulletin(0); }, } } fn position_of_active_bulletin(&self) -> Option<usize> { self.components_to_render.iter().find_map(|c| match c { RenderedComponent::BulletinList(bulletin_list) => { bulletin_list.active_component_position() }, _ => None, }) } fn clear_active_bulletins(&mut self) { self.components_to_render.iter_mut().for_each(|c| { match c { RenderedComponent::BulletinList(bulletin_list) => { Some(bulletin_list.clear_active_bulletins()) }, _ => None, }; }); } fn set_active_bulletin(&mut self, active_bulletin_position: usize) { self.components_to_render.iter_mut().for_each(|c| { match c { RenderedComponent::BulletinList(bulletin_list) => { bulletin_list.set_active_bulletin(active_bulletin_position) }, _ => {}, }; }); } fn set_last_active_bulletin(&mut self) { self.components_to_render.iter_mut().for_each(|c| { match c { RenderedComponent::BulletinList(bulletin_list) => { bulletin_list.set_last_active_bulletin() }, _ => {}, }; }); } fn clear_hover(&mut self) -> bool { let had_hover = self.has_hover; self.menu_item_is_selected = false; self.hovering_over_link = false; for rendered_component in &mut self.components_to_render { match rendered_component { RenderedComponent::BulletinList(bulletin_list) => { bulletin_list.clear_hover(); }, RenderedComponent::Paragraph(paragraph) => { for active_component in paragraph { active_component.clear_hover(); } }, _ => {}, } } self.has_hover = false; had_hover } pub fn ui_column_count(&mut self) -> usize { let mut column_count = 0; for rendered_component in &self.components_to_render { match rendered_component { RenderedComponent::BulletinList(bulletin_list) => { column_count = std::cmp::max(column_count, bulletin_list.column_count()); }, RenderedComponent::Paragraph(paragraph) => { for active_component in paragraph { column_count = std::cmp::max(column_count, active_component.column_count()); } }, RenderedComponent::HelpText(_text) => {}, // we ignore help text in column // calculation because it's always left // justified } } column_count } pub fn ui_row_count(&mut self) -> usize { let mut row_count = 0; if self.title.is_some() { row_count += 1; } for rendered_component in &self.components_to_render { match rendered_component { RenderedComponent::BulletinList(bulletin_list) => { row_count += bulletin_list.len(); }, RenderedComponent::Paragraph(paragraph) => { row_count += paragraph.len(); }, RenderedComponent::HelpText(_text) => {}, // we ignore help text as it is outside // the UI container } } row_count += self.components_to_render.len(); row_count } pub fn render(&mut self, rows: usize, columns: usize, error: &Option<String>) { let base_x = columns.saturating_sub(self.ui_column_count()) / 2; let base_y = rows.saturating_sub(self.ui_row_count()) / 2; let mut current_y = base_y; if let Some(title) = &self.title { print_text_with_coordinates( title.clone(), base_x, current_y, Some(columns), Some(rows), ); current_y += 2; } for rendered_component in &mut self.components_to_render { let is_help = match rendered_component { RenderedComponent::HelpText(_) => true, _ => false, }; if is_help { if let Some(error) = error { render_error(error, rows); continue; } } let y = if is_help { rows } else { current_y }; let columns = if is_help { columns } else { columns.saturating_sub(base_x * 2) }; let rendered_rows = rendered_component.render( base_x, y, rows, columns, self.hovering_over_link, self.menu_item_is_selected, ); current_y += rendered_rows + 1; // 1 for the line space between components } } } fn render_error(error: &str, y: usize) { print_text_with_coordinates( Text::new(format!("ERROR: {}", error)).color_range(3, ..), 0, y, None, None, ); } fn changelog_link_unselected(version: String) -> Text { let full_changelog_text = format!( "https://github.com/zellij-org/zellij/releases/tag/v{}", version ); Text::new(full_changelog_text) } fn changelog_link_selected(version: String) -> Box<dyn Fn(usize, usize) -> usize> { Box::new(move |x, y| { print!( "\u{1b}[{};{}H\u{1b}[m\u{1b}[1;4mhttps://github.com/zellij-org/zellij/releases/tag/v{}", y + 1, x + 1, version ); 51 + version.chars().count() }) } fn changelog_link_selected_len(version: String) -> Box<dyn Fn() -> usize> { Box::new(move || 51 + version.chars().count()) } fn sponsors_link_text_unselected() -> Text { Text::new("https://github.com/sponsors/imsnif") } fn sponsors_link_text_selected(x: usize, y: usize) -> usize { print!( "\u{1b}[{};{}H\u{1b}[m\u{1b}[1;4mhttps://github.com/sponsors/imsnif", y + 1, x + 1 ); 34 } fn sponsors_link_text_selected_len() -> usize { 34 } fn web_client_screencast_link_selected(x: usize, y: usize) -> usize { print!( "\u{1b}[{};{}H\u{1b}[m\u{1b}[1;4mhttps://zellij.dev/tutorials/web-client", y + 1, x + 1 ); 39 } fn web_client_screencast_link_selected_len() -> usize { 39 } fn compact_bar_link_selected(x: usize, y: usize) -> usize { print!( "\u{1b}[{};{}H\u{1b}[m\u{1b}[1;4mhttps://zellij.dev/documentation/faq.html", y + 1, x + 1 ); 41 } fn compact_bar_link_selected_len() -> usize { 41 } // Text components fn whats_new_title() -> Text { Text::new("What's new?") } fn main_screen_title(version: String, is_release_notes: bool) -> Text { if is_release_notes { let title_text = format!("Hi there, welcome to Zellij {}!", &version); Text::new(title_text).color_range(2, 21..=27 + version.chars().count()) } else { let title_text = format!("Zellij {}", &version); Text::new(title_text).color_range(2, ..) } } fn main_screen_help_text(hovering_over_link: bool, menu_item_is_selected: bool) -> Text { if hovering_over_link { let help_text = format!("Help: Click or Shift-Click to open in browser"); Text::new(help_text) .color_range(3, 6..=10) .color_range(3, 15..=25) } else if menu_item_is_selected { let help_text = format!("Help: <↓↑> - Navigate, <ENTER> - Learn More, <ESC> - Dismiss"); Text::new(help_text) .color_range(1, 6..=9) .color_range(1, 23..=29) .color_range(1, 45..=49) } else { let help_text = format!("Help: <↓↑> - Navigate, <ESC> - Dismiss, <?> - Usage Tips"); Text::new(help_text) .color_range(1, 6..=9) .color_range(1, 23..=27) .color_range(1, 40..=42) } } fn release_notes_main_help(hovering_over_link: bool, menu_item_is_selected: bool) -> Text { if hovering_over_link { let help_text = format!("Help: Click or Shift-Click to open in browser"); Text::new(help_text) .color_range(3, 6..=10) .color_range(3, 15..=25) } else if menu_item_is_selected { let help_text = format!("Help: <↓↑> - Navigate, <ENTER> - Learn More, <ESC> - Dismiss"); Text::new(help_text) .color_range(1, 6..=9) .color_range(1, 23..=29) .color_range(1, 45..=49) } else { let help_text = format!("Help: <↓↑> - Navigate, <ESC> - Dismiss"); Text::new(help_text) .color_range(1, 6..=9) .color_range(1, 23..=27) } } fn esc_go_back_plus_link_hover(hovering_over_link: bool, _menu_item_is_selected: bool) -> Text { if hovering_over_link { let help_text = format!("Help: Click or Shift-Click to open in browser"); Text::new(help_text) .color_range(3, 6..=10) .color_range(3, 15..=25) } else { let help_text = format!("Help: <ESC> - Go back"); Text::new(help_text).color_range(1, 6..=10) } } fn esc_to_go_back_help() -> Text { let help_text = format!("Help: <ESC> - Go back"); Text::new(help_text).color_range(1, 6..=10) } fn main_menu_item(item_name: &str) -> Text { Text::new(item_name).color_range(0, ..) } fn support_the_developer_text() -> Text { let support_text = format!("Please support the Zellij developer <3: "); Text::new(support_text).color_range(3, ..) } pub enum TextOrCustomRender { Text(Text), CustomRender( Box<dyn Fn(usize, usize) -> usize>, // (rows, columns) -> text_len (render function) Box<dyn Fn() -> usize>, // length of rendered component ), } impl TextOrCustomRender { pub fn len(&self) -> usize { match self { TextOrCustomRender::Text(text) => text.len(), TextOrCustomRender::CustomRender(_render_fn, len_fn) => len_fn(), } } pub fn render(&mut self, x: usize, y: usize, rows: usize, columns: usize) -> usize { match self { TextOrCustomRender::Text(text) => { print_text_with_coordinates(text.clone(), x, y, Some(columns), Some(rows)); text.len() }, TextOrCustomRender::CustomRender(render_fn, _len_fn) => render_fn(x, y), } } } impl std::fmt::Debug for TextOrCustomRender { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TextOrCustomRender::Text(text) => write!(f, "Text {{ {:?} }}", text), TextOrCustomRender::CustomRender(..) => write!(f, "CustomRender"), } } } enum RenderedComponent { HelpText(Box<dyn Fn(bool, bool) -> Text>), BulletinList(BulletinList), Paragraph(Vec<ComponentLine>), } impl std::fmt::Debug for RenderedComponent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { RenderedComponent::HelpText(_) => write!(f, "HelpText"), RenderedComponent::BulletinList(bulletinlist) => write!(f, "{:?}", bulletinlist), RenderedComponent::Paragraph(component_list) => write!(f, "{:?}", component_list), } } } impl RenderedComponent { pub fn render( &mut self, x: usize, y: usize, rows: usize, columns: usize, hovering_over_link: bool, menu_item_is_selected: bool, ) -> usize { let mut rendered_rows = 0; match self { RenderedComponent::HelpText(text) => { rendered_rows += 1; print_text_with_coordinates( text(hovering_over_link, menu_item_is_selected), 0, y, Some(columns), Some(rows), ); }, RenderedComponent::BulletinList(bulletin_list) => { rendered_rows += bulletin_list.len(); bulletin_list.render(x, y, rows, columns); }, RenderedComponent::Paragraph(paragraph) => { let mut paragraph_rendered_rows = 0; for component_line in paragraph { component_line.render( x, y + paragraph_rendered_rows, rows.saturating_sub(paragraph_rendered_rows), columns, ); rendered_rows += 1; paragraph_rendered_rows += 1; } }, } rendered_rows } } #[derive(Debug)] pub struct BulletinList { title: Text, items: Vec<ActiveComponent>, } impl BulletinList { pub fn new(title: Text) -> Self { BulletinList { title, items: vec![], } } pub fn with_items(mut self, items: Vec<ActiveComponent>) -> Self { self.items = items; self } pub fn len(&self) -> usize { self.items.len() + 1 // 1 for the title } pub fn column_count(&self) -> usize { let mut column_count = 0; for item in &self.items { column_count = std::cmp::max(column_count, item.column_count()); } column_count }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/about/src/main.rs
default-plugins/about/src/main.rs
mod active_component; mod pages; mod tips; use zellij_tile::prelude::*; use pages::Page; use rand::prelude::*; use rand::rng; use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use tips::MAX_TIP_INDEX; use crate::active_component::ActiveComponent; use crate::pages::{ComponentLine, TextOrCustomRender}; const UI_ROWS: usize = 20; const UI_COLUMNS: usize = 90; #[derive(Debug)] struct App { active_page: Page, link_executable: Rc<RefCell<String>>, zellij_version: Rc<RefCell<String>>, base_mode: Rc<RefCell<InputMode>>, tab_rows: usize, tab_columns: usize, own_plugin_id: Option<u32>, is_release_notes: bool, is_startup_tip: bool, tip_index: usize, waiting_for_config_to_be_written: bool, error: Option<String>, } impl Default for App { fn default() -> Self { let link_executable = Rc::new(RefCell::new("".to_owned())); let zellij_version = Rc::new(RefCell::new("".to_owned())); let base_mode = Rc::new(RefCell::new(Default::default())); App { active_page: Page::new_main_screen( link_executable.clone(), "".to_owned(), base_mode.clone(), false, ), link_executable, zellij_version, base_mode, tab_rows: 0, tab_columns: 0, own_plugin_id: None, is_release_notes: false, is_startup_tip: false, tip_index: 0, waiting_for_config_to_be_written: false, error: None, } } } register_plugin!(App); impl ZellijPlugin for App { fn load(&mut self, configuration: BTreeMap<String, String>) { self.is_release_notes = configuration .get("is_release_notes") .map(|v| v == "true") .unwrap_or(false); self.is_startup_tip = configuration .get("is_startup_tip") .map(|v| v == "true") .unwrap_or(false); subscribe(&[ EventType::Key, EventType::Mouse, EventType::ModeUpdate, EventType::RunCommandResult, EventType::TabUpdate, EventType::FailedToWriteConfigToDisk, EventType::ConfigWasWrittenToDisk, ]); let own_plugin_id = get_plugin_ids().plugin_id; self.own_plugin_id = Some(own_plugin_id); *self.zellij_version.borrow_mut() = get_zellij_version(); self.change_own_title(); self.query_link_executable(); self.active_page = if self.is_startup_tip { let mut rng = rng(); self.tip_index = rng.random_range(0..=MAX_TIP_INDEX); Page::new_tip_screen( self.link_executable.clone(), self.base_mode.clone(), self.tip_index, ) } else { Page::new_main_screen( self.link_executable.clone(), self.zellij_version.borrow().clone(), self.base_mode.clone(), self.is_release_notes, ) }; } fn update(&mut self, event: Event) -> bool { let mut should_render = false; match event { Event::FailedToWriteConfigToDisk(file_path) => { if self.waiting_for_config_to_be_written { let error = match file_path { Some(file_path) => { format!("Failed to write config to disk at: {}", file_path) }, None => format!("Failed to write config to disk."), }; eprintln!("{}", error); self.error = Some(error); should_render = true; } }, Event::ConfigWasWrittenToDisk => { if self.waiting_for_config_to_be_written { close_self(); } }, Event::TabUpdate(tab_info) => { self.center_own_pane(tab_info); }, Event::Mouse(mouse_event) => { should_render = self.handle_mouse_event(mouse_event); }, Event::ModeUpdate(mode_info) => { if let Some(base_mode) = mode_info.base_mode { should_render = self.update_base_mode(base_mode); } }, Event::RunCommandResult(exit_code, _stdout, _stderr, context) => { let is_xdg_open = context.get("xdg_open_cli").is_some(); let is_open = context.get("open_cli").is_some(); if is_xdg_open { if exit_code == Some(0) { self.update_link_executable("xdg-open".to_owned()); } } else if is_open { if exit_code == Some(0) { self.update_link_executable("open".to_owned()); } } }, Event::Key(key) => { if let Some(_error) = self.error.take() { // dismiss error on any key should_render = true; } else { should_render = self.handle_key(key); } }, _ => {}, } should_render } fn render(&mut self, rows: usize, cols: usize) { if let Some(error) = &self.error { self.render_error(rows, cols, error.to_owned()) } else { self.active_page.render(rows, cols, &self.error); } } } impl App { pub fn change_own_title(&mut self) { if let Some(own_plugin_id) = self.own_plugin_id { if self.is_release_notes { rename_plugin_pane( own_plugin_id, format!("Release Notes {}", self.zellij_version.borrow()), ); } else { rename_plugin_pane(own_plugin_id, "About Zellij"); } } } pub fn query_link_executable(&self) { let mut xdg_open_context = BTreeMap::new(); xdg_open_context.insert("xdg_open_cli".to_owned(), String::new()); run_command(&["xdg-open", "--help"], xdg_open_context); let mut open_context = BTreeMap::new(); open_context.insert("open_cli".to_owned(), String::new()); run_command(&["open", "--help"], open_context); } pub fn update_link_executable(&mut self, new_link_executable: String) { *self.link_executable.borrow_mut() = new_link_executable; } pub fn update_base_mode(&mut self, new_base_mode: InputMode) -> bool { let mut should_render = false; if *self.base_mode.borrow() != new_base_mode { should_render = true; } *self.base_mode.borrow_mut() = new_base_mode; should_render } pub fn handle_mouse_event(&mut self, mouse_event: Mouse) -> bool { let mut should_render = false; match mouse_event { Mouse::LeftClick(line, column) => { if let Some(new_page) = self .active_page .handle_mouse_left_click(column, line as usize) { self.active_page = new_page; should_render = true; } }, Mouse::Hover(line, column) => { should_render = self.active_page.handle_mouse_hover(column, line as usize); }, _ => {}, } should_render } pub fn handle_key(&mut self, key: KeyWithModifier) -> bool { let mut should_render = false; if key.bare_key == BareKey::Up && key.has_no_modifiers() && self.is_startup_tip { self.previous_tip(); should_render = true; } else if key.bare_key == BareKey::Down && key.has_no_modifiers() && self.is_startup_tip { self.next_tip(); should_render = true; } else if key.bare_key == BareKey::Enter && key.has_no_modifiers() { if let Some(new_page) = self.active_page.handle_selection() { self.active_page = new_page; should_render = true; } } else if key.bare_key == BareKey::Char('c') && key.has_modifiers(&[KeyModifier::Ctrl]) && self.is_startup_tip { self.waiting_for_config_to_be_written = true; let save_configuration = true; reconfigure("show_startup_tips false".to_owned(), save_configuration); } else if key.bare_key == BareKey::Esc && key.has_no_modifiers() { if self.active_page.is_main_screen { close_self(); } else { self.active_page = Page::new_main_screen( self.link_executable.clone(), self.zellij_version.borrow().clone(), self.base_mode.clone(), self.is_release_notes, ); should_render = true; } } else if key.bare_key == BareKey::Char('?') && !self.is_release_notes && !self.is_startup_tip { self.is_startup_tip = true; self.active_page = Page::new_tip_screen( self.link_executable.clone(), self.base_mode.clone(), self.tip_index, ); should_render = true; } else { should_render = self.active_page.handle_key(key); } should_render } fn render_error(&self, rows: usize, cols: usize, error: String) { let mut error_page = Page::new() .main_screen() .with_title(Text::new(format!("{}", error)).color_range(3, ..)) .with_paragraph(vec![ ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("Unable to permanently dismiss tips."), ))]), ComponentLine::new(vec![ActiveComponent::new(TextOrCustomRender::Text( Text::new("You can do so manually by adding the following to your config:"), ))]), ]) .with_paragraph(vec![ComponentLine::new(vec![ActiveComponent::new( TextOrCustomRender::Text(Text::new("show_startup_tips false").color_range(0, ..)), )])]) .with_help(Box::new(|_hovering_over_link, _menu_item_is_selected| { Text::new("<ESC> - dismiss").color_range(1, ..=4) })); error_page.render(rows, cols, &None) } fn center_own_pane(&mut self, tab_info: Vec<TabInfo>) { // we only take the size of the first tab because at the time of writing this is // identical to all tabs, but this might not always be the case... if let Some(first_tab) = tab_info.get(0) { let prev_tab_columns = self.tab_columns; let prev_tab_rows = self.tab_rows; self.tab_columns = first_tab.display_area_columns; self.tab_rows = first_tab.display_area_rows; if self.tab_columns != prev_tab_columns || self.tab_rows != prev_tab_rows { let desired_x_coords = self.tab_columns.saturating_sub(UI_COLUMNS) / 2; let desired_y_coords = self.tab_rows.saturating_sub(UI_ROWS) / 2; change_floating_panes_coordinates(vec![( PaneId::Plugin(self.own_plugin_id.unwrap()), FloatingPaneCoordinates::new( Some(desired_x_coords.to_string()), Some(desired_y_coords.to_string()), Some(UI_COLUMNS.to_string()), Some(UI_ROWS.to_string()), None, ) .unwrap(), )]); } } } fn previous_tip(&mut self) { if self.tip_index == 0 { self.tip_index = MAX_TIP_INDEX; } else { self.tip_index = self.tip_index.saturating_sub(1); } self.active_page = Page::new_tip_screen( self.link_executable.clone(), self.base_mode.clone(), self.tip_index, ); } fn next_tip(&mut self) { if self.tip_index == MAX_TIP_INDEX { self.tip_index = 0; } else { self.tip_index += 1; } self.active_page = Page::new_tip_screen( self.link_executable.clone(), self.base_mode.clone(), self.tip_index, ); } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/configuration/src/rebind_leaders_screen.rs
default-plugins/configuration/src/rebind_leaders_screen.rs
use std::collections::BTreeSet; use zellij_tile::prelude::*; use crate::ui_components::{back_to_presets, info_line}; use crate::{POSSIBLE_MODIFIERS, WIDTH_BREAKPOINTS}; #[derive(Debug)] pub struct RebindLeadersScreen { selected_primary_key_index: usize, selected_secondary_key_index: usize, main_leader_selected: bool, rebinding_main_leader: bool, browsing_primary_modifier: bool, browsing_secondary_modifier: bool, main_leader: Option<KeyWithModifier>, primary_modifier: BTreeSet<KeyModifier>, secondary_modifier: BTreeSet<KeyModifier>, latest_mode_info: Option<ModeInfo>, notification: Option<String>, is_rebinding_for_presets: bool, ui_is_dirty: bool, } impl Default for RebindLeadersScreen { fn default() -> Self { let mut primary_modifier = BTreeSet::new(); primary_modifier.insert(KeyModifier::Ctrl); let mut secondary_modifier = BTreeSet::new(); secondary_modifier.insert(KeyModifier::Alt); RebindLeadersScreen { selected_primary_key_index: 0, selected_secondary_key_index: 0, main_leader_selected: false, rebinding_main_leader: false, browsing_primary_modifier: false, browsing_secondary_modifier: false, main_leader: None, primary_modifier, secondary_modifier, latest_mode_info: None, notification: None, is_rebinding_for_presets: false, ui_is_dirty: false, } } } impl RebindLeadersScreen { // temporarily commented out for the time being because the extra leaders screen was deemed a bit // confusing, see commend in <l> key // pub fn with_rebinding_for_presets(mut self) -> Self { // self.is_rebinding_for_presets = true; // self // } pub fn with_mode_info(mut self, latest_mode_info: Option<ModeInfo>) -> Self { self.latest_mode_info = latest_mode_info; self.hard_reset_ui_state(); self } pub fn update_mode_info(&mut self, mode_info: ModeInfo) { self.latest_mode_info = Some(mode_info); if !self.ui_is_dirty { self.set_main_leader_from_keybindings(); self.set_primary_and_secondary_modifiers_from_keybindings(); } } pub fn primary_and_secondary_modifiers( &self, ) -> (BTreeSet<KeyModifier>, BTreeSet<KeyModifier>) { ( self.primary_modifier.clone(), self.secondary_modifier.clone(), ) } fn set_main_leader_from_keybindings(&mut self) { self.main_leader = self.latest_mode_info.as_ref().and_then(|mode_info| { mode_info .keybinds .iter() .find_map(|m| { if m.0 == InputMode::Locked { Some(m.1.clone()) } else { None } }) .and_then(|k| { k.into_iter().find_map(|(k, a)| { if a == &[actions::Action::SwitchToMode { input_mode: InputMode::Normal, }] { Some(k) } else { None } }) }) }); } fn set_primary_and_secondary_modifiers_from_keybindings(&mut self) { let mut primary_modifier = self.latest_mode_info.as_ref().and_then(|mode_info| { mode_info .keybinds .iter() .find_map(|m| { if m.0 == InputMode::Locked { Some(m.1.clone()) } else { None } }) .and_then(|k| { k.into_iter().find_map(|(k, a)| { if a == &[actions::Action::SwitchToMode { input_mode: InputMode::Normal, }] { Some(k.key_modifiers.clone()) } else { None } }) }) }); let mut secondary_modifier = self.latest_mode_info.as_ref().and_then(|mode_info| { let base_mode = mode_info.base_mode.unwrap_or(InputMode::Normal); mode_info .keybinds .iter() .find_map(|m| { if m.0 == base_mode { Some(m.1.clone()) } else { None } }) .and_then(|k| { k.into_iter().find_map(|(k, a)| { if a == &[actions::Action::NewPane { direction: None, pane_name: None, start_suppressed: false, }] { Some(k.key_modifiers.clone()) } else { None } }) }) }); if let Some(primary_modifier) = primary_modifier.take() { self.primary_modifier = primary_modifier; } if let Some(secondary_modifier) = secondary_modifier.take() { self.secondary_modifier = secondary_modifier; } } pub fn set_unlock_toggle_selected(&mut self) { self.main_leader_selected = true; self.selected_primary_key_index = 0; self.selected_secondary_key_index = 0; self.rebinding_main_leader = false; self.browsing_primary_modifier = false; self.browsing_secondary_modifier = false; } pub fn set_primary_modifier_selected(&mut self) { self.browsing_primary_modifier = true; self.main_leader_selected = false; self.selected_primary_key_index = 0; self.selected_secondary_key_index = 0; self.rebinding_main_leader = false; self.browsing_secondary_modifier = false; } pub fn set_secondary_modifier_selected(&mut self) { self.browsing_secondary_modifier = true; self.browsing_primary_modifier = false; self.main_leader_selected = false; self.selected_primary_key_index = 0; self.selected_secondary_key_index = 0; self.rebinding_main_leader = false; } pub fn set_rebinding_unlock_toggle(&mut self) { self.rebinding_main_leader = true; self.browsing_secondary_modifier = false; self.browsing_primary_modifier = false; self.main_leader_selected = false; self.selected_primary_key_index = 0; self.selected_secondary_key_index = 0; } pub fn move_secondary_index_down(&mut self) { if self.selected_secondary_key_index < POSSIBLE_MODIFIERS.len().saturating_sub(1) { self.selected_secondary_key_index += 1; } else { self.set_unlock_toggle_selected(); } } pub fn move_secondary_index_up(&mut self) { if self.selected_secondary_key_index > 0 { self.selected_secondary_key_index -= 1; } else { self.set_unlock_toggle_selected(); } } pub fn move_selection_for_default_preset(&mut self, key: &KeyWithModifier) { if self.browsing_primary_modifier { if key.bare_key == BareKey::Left && key.has_no_modifiers() { self.browsing_primary_modifier = false; self.browsing_secondary_modifier = true; self.selected_secondary_key_index = self.selected_primary_key_index; } else if key.bare_key == BareKey::Right && key.has_no_modifiers() { self.browsing_primary_modifier = false; self.browsing_secondary_modifier = true; self.selected_secondary_key_index = self.selected_primary_key_index; } else if key.bare_key == BareKey::Down && key.has_no_modifiers() { if self.selected_primary_key_index < POSSIBLE_MODIFIERS.len().saturating_sub(1) { self.selected_primary_key_index += 1; } } else if key.bare_key == BareKey::Up && key.has_no_modifiers() { if self.selected_primary_key_index > 0 { self.selected_primary_key_index -= 1; } } } else if self.browsing_secondary_modifier { if key.bare_key == BareKey::Left && key.has_no_modifiers() { self.browsing_secondary_modifier = false; self.browsing_primary_modifier = true; self.selected_primary_key_index = self.selected_secondary_key_index; } else if key.bare_key == BareKey::Right && key.has_no_modifiers() { self.browsing_secondary_modifier = false; self.browsing_primary_modifier = true; self.selected_primary_key_index = self.selected_secondary_key_index; } else if key.bare_key == BareKey::Down && key.has_no_modifiers() { if self.selected_secondary_key_index < POSSIBLE_MODIFIERS.len().saturating_sub(1) { self.selected_secondary_key_index += 1; } } else if key.bare_key == BareKey::Up && key.has_no_modifiers() { if self.selected_secondary_key_index > 0 { self.selected_secondary_key_index -= 1; } } } else { self.set_primary_modifier_selected(); } } pub fn move_selection_for_unlock_first(&mut self, key: &KeyWithModifier) { if self.browsing_secondary_modifier { if (key.bare_key == BareKey::Left || key.bare_key == BareKey::Right) && key.has_no_modifiers() { self.set_unlock_toggle_selected(); } else if key.bare_key == BareKey::Down && key.has_no_modifiers() { self.move_secondary_index_down(); } else if key.bare_key == BareKey::Up && key.has_no_modifiers() { self.move_secondary_index_up(); } } else if self.main_leader_selected { if (key.bare_key == BareKey::Down || key.bare_key == BareKey::Up || key.bare_key == BareKey::Right || key.bare_key == BareKey::Left) && key.has_no_modifiers() { self.set_secondary_modifier_selected(); } } else { self.set_unlock_toggle_selected(); } } pub fn render( &mut self, rows: usize, cols: usize, ui_size: usize, notification: &Option<String>, ) { if self.is_rebinding_for_presets { back_to_presets(); } let notification = notification.clone().or_else(|| self.notification.clone()); if self.currently_in_unlock_first() { self.render_unlock_first(rows, cols); } else { self.render_default_preset(rows, cols); } let warning_text = self.warning_text(cols); info_line(rows, cols, ui_size, &notification, &warning_text, None); } fn render_unlock_first(&mut self, rows: usize, cols: usize) { self.render_screen_title_unlock_first(rows, cols); self.render_unlock_toggle(rows, cols); self.render_secondary_modifier_selector(rows, cols); self.render_help_text(rows, cols); } fn render_default_preset(&mut self, rows: usize, cols: usize) { self.render_screen_title_default_preset(rows, cols); self.render_primary_modifier_selector(rows, cols); self.render_secondary_modifier_selector(rows, cols); self.render_help_text(rows, cols); } fn render_primary_modifier_selector(&self, rows: usize, cols: usize) { let screen_width = if cols >= WIDTH_BREAKPOINTS.0 { WIDTH_BREAKPOINTS.0 } else { WIDTH_BREAKPOINTS.1 }; let base_x = cols.saturating_sub(screen_width) / 2; let base_y = rows.saturating_sub(10) / 2; let primary_modifier_key_text = self.primary_modifier_text(); let (primary_modifier_text, primary_modifier_start_position) = if cols >= WIDTH_BREAKPOINTS.0 { (format!("Primary: {}", primary_modifier_key_text), 9) } else { (format!("{}", primary_modifier_key_text), 0) }; let primary_modifier_menu_width = primary_modifier_text.chars().count(); print_text_with_coordinates( Text::new(primary_modifier_text).color_range(3, primary_modifier_start_position..), base_x, base_y + 5, None, None, ); print_nested_list_with_coordinates( POSSIBLE_MODIFIERS .iter() .enumerate() .map(|(i, m)| { let item = if self.primary_modifier.contains(m) { NestedListItem::new(m.to_string()).color_range(3, ..) } else { NestedListItem::new(m.to_string()) }; if self.browsing_primary_modifier && self.selected_primary_key_index == i { item.selected() } else { item } }) .collect(), base_x, base_y + 6, Some(primary_modifier_menu_width), None, ); } pub fn render_screen_title_unlock_first(&self, rows: usize, cols: usize) { let screen_width = if cols >= WIDTH_BREAKPOINTS.0 { WIDTH_BREAKPOINTS.0 } else { WIDTH_BREAKPOINTS.1 }; let leader_keys_text = if cols >= WIDTH_BREAKPOINTS.0 { "Rebind leader keys (Non-Colliding preset)" } else if cols >= WIDTH_BREAKPOINTS.1 { "Rebind leader keys (Non-Colliding)" } else { "Rebind leader keys" }; let base_x = cols.saturating_sub(screen_width) / 2; let base_y = rows.saturating_sub(10) / 2; let explanation_text_1 = if cols >= WIDTH_BREAKPOINTS.0 { "Unlock toggle - used to expose the other modes (eg. PANE, TAB)" } else if cols >= WIDTH_BREAKPOINTS.1 { "Unlock toggle - expose other modes" } else { "" }; let explanation_text_2 = if cols >= WIDTH_BREAKPOINTS.0 { "Secondary modifier - prefixes common actions (eg. New Pane)" } else if cols >= WIDTH_BREAKPOINTS.1 { "Secondary modifier - common actions" } else { "" }; print_text_with_coordinates( Text::new(leader_keys_text).color_range(2, ..), base_x, base_y, None, None, ); print_text_with_coordinates( Text::new(explanation_text_1).color_range(1, ..=12), base_x, base_y + 2, None, None, ); print_text_with_coordinates( Text::new(explanation_text_2).color_range(1, ..=17), base_x, base_y + 3, None, None, ); } fn render_screen_title_default_preset(&self, rows: usize, cols: usize) { let screen_width = if cols >= WIDTH_BREAKPOINTS.0 { WIDTH_BREAKPOINTS.0 } else { WIDTH_BREAKPOINTS.1 }; let leader_keys_text = if cols >= WIDTH_BREAKPOINTS.0 { "Rebind leader keys (Default preset)" } else { "Rebind leader keys" }; let base_x = cols.saturating_sub(screen_width) / 2; let base_y = rows.saturating_sub(10) / 2; let explanation_text_1 = if cols >= WIDTH_BREAKPOINTS.0 { "Primary - the modifier used to switch modes (eg. PANE, TAB)" } else if cols >= WIDTH_BREAKPOINTS.1 { "Primary - used to switch modes" } else { "" }; let explanation_text_2 = if cols >= WIDTH_BREAKPOINTS.0 { "Secondary - the modifier used for common actions (eg. New Pane)" } else if cols >= WIDTH_BREAKPOINTS.1 { "Secondary - common actions" } else { "" }; print_text_with_coordinates( Text::new(leader_keys_text).color_range(2, ..), base_x, base_y, None, None, ); print_text_with_coordinates( Text::new(explanation_text_1).color_range(1, ..=6), base_x, base_y + 2, None, None, ); print_text_with_coordinates( Text::new(explanation_text_2).color_range(1, ..=8), base_x, base_y + 3, None, None, ); } fn render_unlock_toggle(&self, rows: usize, cols: usize) { let screen_width = if cols >= WIDTH_BREAKPOINTS.0 { WIDTH_BREAKPOINTS.0 } else { WIDTH_BREAKPOINTS.1 }; let base_x = cols.saturating_sub(screen_width) / 2; let base_y = rows.saturating_sub(10) / 2; if let Some(main_leader_key_text) = self.main_leader_text() { let main_leader_key_text = if self.rebinding_main_leader { "...".to_owned() } else { main_leader_key_text }; let (primary_modifier_text, primary_modifier_start_position) = if cols >= WIDTH_BREAKPOINTS.0 { (format!("Unlock Toggle: {}", main_leader_key_text), 15) } else { (format!("{}", main_leader_key_text), 0) }; let mut primary_modifier = Text::new(primary_modifier_text).color_range(3, primary_modifier_start_position..); if self.main_leader_selected { primary_modifier = primary_modifier.selected(); } print_text_with_coordinates(primary_modifier, base_x, base_y + 5, None, None); if self.rebinding_main_leader { let first_bulletin = "[Enter new key] eg."; let second_bulletin = "\"Ctrl g\", \"Alt g\","; let third_bulletin = "\"Alt ESC\", \"Ctrl SPACE\""; print_nested_list_with_coordinates( vec![ NestedListItem::new(first_bulletin).color_range(3, ..=14), NestedListItem::new(second_bulletin), NestedListItem::new(third_bulletin), ], base_x, base_y + 6, None, None, ); } } } fn main_leader_text(&self) -> Option<String> { self.main_leader.as_ref().map(|m| format!("{}", m)) } fn render_secondary_modifier_selector(&mut self, rows: usize, cols: usize) { let screen_width = if cols >= WIDTH_BREAKPOINTS.0 { WIDTH_BREAKPOINTS.0 } else { WIDTH_BREAKPOINTS.1 }; let base_x = cols.saturating_sub(screen_width) / 2; let base_y = rows.saturating_sub(10) / 2; let secondary_modifier_key_text = self.secondary_modifier_text(); let (secondary_modifier_text, secondary_modifier_start_position) = if cols >= WIDTH_BREAKPOINTS.0 { if self.currently_in_unlock_first() { ( format!("Secondary Modifier: {}", secondary_modifier_key_text), 20, ) } else { (format!("Secondary: {}", secondary_modifier_key_text), 11) } } else { (format!("{}", secondary_modifier_key_text), 0) }; let secondary_modifier_menu_x_coords = base_x + (screen_width / 2); let secondary_modifier_menu_width = secondary_modifier_text.chars().count(); print_text_with_coordinates( Text::new(secondary_modifier_text).color_range(0, secondary_modifier_start_position..), secondary_modifier_menu_x_coords, base_y + 5, None, None, ); print_nested_list_with_coordinates( POSSIBLE_MODIFIERS .iter() .enumerate() .map(|(i, m)| { let item = if self.secondary_modifier.contains(m) { NestedListItem::new(m.to_string()).color_range(0, ..) } else { NestedListItem::new(m.to_string()) }; if self.browsing_secondary_modifier && self.selected_secondary_key_index == i { item.selected() } else { item } }) .collect(), secondary_modifier_menu_x_coords, base_y + 6, Some(secondary_modifier_menu_width), None, ); } fn primary_modifier_text(&self) -> String { if self.primary_modifier.is_empty() { "<UNBOUND>".to_owned() } else { self.primary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") } } fn secondary_modifier_text(&self) -> String { if self.secondary_modifier.is_empty() { "<UNBOUND>".to_owned() } else { self.secondary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") } } fn render_help_text(&self, rows: usize, cols: usize) { if self.is_rebinding_for_presets { return self.render_help_text_for_presets_rebinding(rows, cols); } let help_text_long = "Help: <←↓↑→> - navigate, <SPACE> - select, <ENTER> - apply, <Ctrl a> - save, <Ctrl c> - reset, <ESC> - close"; let help_text_medium = "Help: <←↓↑→/SPACE> - navigate/select, <ENTER/Ctrl a> - apply/save, <Ctrl c> - reset, <ESC> - close"; let help_text_short = "Help: <←↓↑→>/<SPACE>/<ENTER> select/<Ctrl a> save/<Ctrl c> reset/<ESC>"; let help_text_minimum = "<←↓↑→>/<SPACE>/<ENTER>/<Ctrl a>/<Ctrl c>/<ESC>"; if cols >= help_text_long.chars().count() { print_text_with_coordinates( Text::new(help_text_long) .color_range(2, 6..=12) .color_range(2, 25..=31) .color_range(2, 43..=49) .color_range(2, 60..=67) .color_range(2, 77..=84) .color_range(2, 95..=99), 0, rows, None, None, ); } else if cols >= help_text_medium.chars().count() { print_text_with_coordinates( Text::new(help_text_medium) .color_range(2, 6..=17) .color_range(2, 38..=51) .color_range(2, 67..=75) .color_range(2, 85..=89), 0, rows, None, None, ); } else if cols >= help_text_short.chars().count() { print_text_with_coordinates( Text::new(help_text_short) .color_range(2, 6..=11) .color_range(2, 13..=19) .color_range(2, 21..=27) .color_range(2, 36..=43) .color_range(2, 50..=57) .color_range(2, 65..=69), 0, rows, None, None, ); } else { print_text_with_coordinates( Text::new(help_text_minimum) .color_range(2, ..=5) .color_range(2, 7..=13) .color_range(2, 15..=21) .color_range(2, 23..=30) .color_range(2, 32..=39) .color_range(2, 41..=45), 0, rows, None, None, ); } } fn render_help_text_for_presets_rebinding(&self, rows: usize, cols: usize) { let help_text_long = "Help: <←↓↑→> - navigate, <SPACE> - select, <ENTER> - apply to presets in previous screen"; let help_text_medium = "Help: <←↓↑→> - navigate, <SPACE> - select, <ENTER> - apply"; let help_text_short = "<←↓↑→/SPACE> - navigate/select, <ENTER> - apply"; let help_text_minimum = "<←↓↑→>/<SPACE>/<ENTER>"; if cols >= help_text_long.chars().count() { print_text_with_coordinates( Text::new(help_text_long) .color_range(2, 6..=12) .color_range(2, 25..=31) .color_range(2, 43..=49), 0, rows, None, None, ); } else if cols >= help_text_medium.chars().count() { print_text_with_coordinates( Text::new(help_text_medium) .color_range(2, 6..=12) .color_range(2, 25..=31) .color_range(2, 43..=49), 0, rows, None, None, ); } else if cols >= help_text_short.chars().count() { print_text_with_coordinates( Text::new(help_text_short) .color_range(2, 1..=4) .color_range(2, 6..=10) .color_range(2, 32..=38), 0, rows, None, None, ); } else { print_text_with_coordinates( Text::new(help_text_minimum) .color_range(2, ..=5) .color_range(2, 7..=13) .color_range(2, 15..=21), 0, rows, None, None, ); } } pub fn handle_key(&mut self, key: KeyWithModifier) -> bool { if let Some(notification) = self.notification.take() { drop(notification); true } else if self.currently_in_unlock_first() { self.handle_unlock_first_key(key) } else { self.handle_default_preset_key(key) } } pub fn drain_notification(&mut self) -> Option<String> { self.notification.take() } pub fn set_notification(&mut self, notification: Option<String>) { self.notification = notification; } fn currently_in_unlock_first(&self) -> bool { if self.is_rebinding_for_presets { false } else { self.latest_mode_info .as_ref() .map(|m| m.base_mode == Some(InputMode::Locked)) .unwrap_or(false) } } fn handle_default_preset_key(&mut self, key: KeyWithModifier) -> bool { let should_render = true; if key.bare_key == BareKey::Char('a') && key.has_modifiers(&[KeyModifier::Ctrl]) && !self.is_rebinding_for_presets { let write_to_disk = true; self.rebind_keys(write_to_disk); self.hard_reset_ui_state(); } else if key.bare_key == BareKey::Enter && key.has_no_modifiers() { let write_to_disk = false; self.rebind_keys(write_to_disk); self.hard_reset_ui_state(); } else if key.is_key_with_ctrl_modifier(BareKey::Char('c')) { self.hard_reset_ui_state(); } else if key.bare_key == BareKey::Esc && key.has_no_modifiers() { close_self(); } else if key.bare_key == BareKey::Char(' ') && key.has_no_modifiers() { if self.browsing_primary_modifier { let selected_primary_key_index = self.selected_primary_key_index; self.toggle_primary_modifier(selected_primary_key_index); } else if self.browsing_secondary_modifier { let selected_secondary_key_index = self.selected_secondary_key_index; self.toggle_secondary_modifier(selected_secondary_key_index); } } else if (key.bare_key == BareKey::Left || key.bare_key == BareKey::Right || key.bare_key == BareKey::Up || key.bare_key == BareKey::Down) && key.has_no_modifiers() { self.move_selection_for_default_preset(&key); } else if self.rebinding_main_leader { self.soft_reset_ui_state(); self.main_leader = Some(key.clone()); self.ui_is_dirty = true; } should_render } fn toggle_secondary_modifier(&mut self, secondary_modifier_index: usize) { if let Some(selected_modifier) = POSSIBLE_MODIFIERS.get(secondary_modifier_index) { if self.secondary_modifier.contains(selected_modifier) { self.secondary_modifier.remove(selected_modifier); } else { self.secondary_modifier.insert(*selected_modifier); } self.ui_is_dirty = true; } } fn toggle_primary_modifier(&mut self, primary_modifier_index: usize) { if let Some(selected_modifier) = POSSIBLE_MODIFIERS.get(primary_modifier_index) { if self.primary_modifier.contains(selected_modifier) { self.primary_modifier.remove(selected_modifier); } else { self.primary_modifier.insert(*selected_modifier); } self.ui_is_dirty = true; } } fn rebind_keys(&mut self, write_to_disk: bool) { let mut keys_to_unbind = vec![]; let mut keys_to_bind = vec![]; if self.currently_in_unlock_first() { if let Some(unlock_key) = &self.main_leader { self.bind_unlock_key(&mut keys_to_unbind, &mut keys_to_bind, unlock_key); } self.bind_all_secondary_actions(&mut keys_to_unbind, &mut keys_to_bind); } else { self.bind_all_secondary_actions(&mut keys_to_unbind, &mut keys_to_bind); self.bind_all_primary_actions(&mut keys_to_unbind, &mut keys_to_bind); } if write_to_disk { self.notification = Some("Configuration applied and saved to disk.".to_owned()); } else { self.notification = Some("Configuration applied to current session.".to_owned()); } rebind_keys(keys_to_unbind, keys_to_bind, write_to_disk); } fn bind_all_primary_actions( &self, keys_to_unbind: &mut Vec<(InputMode, KeyWithModifier)>, keys_to_bind: &mut Vec<(InputMode, KeyWithModifier, Vec<actions::Action>)>, ) { self.bind_primary_switch_to_mode_action( keys_to_unbind, keys_to_bind, InputMode::Locked, KeyWithModifier::new_with_modifiers(BareKey::Char('g'), self.primary_modifier.clone()), ); self.bind_primary_switch_to_mode_action( keys_to_unbind, keys_to_bind, InputMode::Pane, KeyWithModifier::new_with_modifiers(BareKey::Char('p'), self.primary_modifier.clone()), ); self.bind_primary_switch_to_mode_action( keys_to_unbind, keys_to_bind, InputMode::Tab, KeyWithModifier::new_with_modifiers(BareKey::Char('t'), self.primary_modifier.clone()), ); self.bind_primary_switch_to_mode_action( keys_to_unbind, keys_to_bind, InputMode::Resize, KeyWithModifier::new_with_modifiers(BareKey::Char('n'), self.primary_modifier.clone()), ); self.bind_primary_switch_to_mode_action( keys_to_unbind, keys_to_bind, InputMode::Move, KeyWithModifier::new_with_modifiers(BareKey::Char('h'), self.primary_modifier.clone()), ); self.bind_primary_switch_to_mode_action( keys_to_unbind,
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/configuration/src/presets.rs
default-plugins/configuration/src/presets.rs
pub fn unlock_first_keybinds(primary_modifier: String, secondary_modifier: String) -> String { format!( r#" default_mode "locked" keybinds clear-defaults=true {{ normal {{ }} locked {{ bind "{primary_modifier} g" {{ SwitchToMode "Normal"; }} }} resize {{ bind "r" {{ SwitchToMode "Normal"; }} bind "h" "Left" {{ Resize "Increase Left"; }} bind "j" "Down" {{ Resize "Increase Down"; }} bind "k" "Up" {{ Resize "Increase Up"; }} bind "l" "Right" {{ Resize "Increase Right"; }} bind "H" {{ Resize "Decrease Left"; }} bind "J" {{ Resize "Decrease Down"; }} bind "K" {{ Resize "Decrease Up"; }} bind "L" {{ Resize "Decrease Right"; }} bind "=" "+" {{ Resize "Increase"; }} bind "-" {{ Resize "Decrease"; }} }} pane {{ bind "p" {{ SwitchToMode "Normal"; }} bind "h" "Left" {{ MoveFocus "Left"; }} bind "l" "Right" {{ MoveFocus "Right"; }} bind "j" "Down" {{ MoveFocus "Down"; }} bind "k" "Up" {{ MoveFocus "Up"; }} bind "Tab" {{ SwitchFocus; }} bind "n" {{ NewPane; SwitchToMode "Locked"; }} bind "d" {{ NewPane "Down"; SwitchToMode "Locked"; }} bind "r" {{ NewPane "Right"; SwitchToMode "Locked"; }} bind "s" {{ NewPane "stacked"; SwitchToMode "Locked"; }} bind "x" {{ CloseFocus; SwitchToMode "Locked"; }} bind "f" {{ ToggleFocusFullscreen; SwitchToMode "Locked"; }} bind "z" {{ TogglePaneFrames; SwitchToMode "Locked"; }} bind "w" {{ ToggleFloatingPanes; SwitchToMode "Locked"; }} bind "e" {{ TogglePaneEmbedOrFloating; SwitchToMode "Locked"; }} bind "c" {{ SwitchToMode "RenamePane"; PaneNameInput 0;}} bind "i" {{ TogglePanePinned; SwitchToMode "Locked"; }} }} move {{ bind "m" {{ SwitchToMode "Normal"; }} bind "n" "Tab" {{ MovePane; }} bind "p" {{ MovePaneBackwards; }} bind "h" "Left" {{ MovePane "Left"; }} bind "j" "Down" {{ MovePane "Down"; }} bind "k" "Up" {{ MovePane "Up"; }} bind "l" "Right" {{ MovePane "Right"; }} }} tab {{ bind "t" {{ SwitchToMode "Normal"; }} bind "r" {{ SwitchToMode "RenameTab"; TabNameInput 0; }} bind "h" "Left" "Up" "k" {{ GoToPreviousTab; }} bind "l" "Right" "Down" "j" {{ GoToNextTab; }} bind "n" {{ NewTab; SwitchToMode "Locked"; }} bind "x" {{ CloseTab; SwitchToMode "Locked"; }} bind "s" {{ ToggleActiveSyncTab; SwitchToMode "Locked"; }} bind "b" {{ BreakPane; SwitchToMode "Locked"; }} bind "]" {{ BreakPaneRight; SwitchToMode "Locked"; }} bind "[" {{ BreakPaneLeft; SwitchToMode "Locked"; }} bind "1" {{ GoToTab 1; SwitchToMode "Locked"; }} bind "2" {{ GoToTab 2; SwitchToMode "Locked"; }} bind "3" {{ GoToTab 3; SwitchToMode "Locked"; }} bind "4" {{ GoToTab 4; SwitchToMode "Locked"; }} bind "5" {{ GoToTab 5; SwitchToMode "Locked"; }} bind "6" {{ GoToTab 6; SwitchToMode "Locked"; }} bind "7" {{ GoToTab 7; SwitchToMode "Locked"; }} bind "8" {{ GoToTab 8; SwitchToMode "Locked"; }} bind "9" {{ GoToTab 9; SwitchToMode "Locked"; }} bind "Tab" {{ ToggleTab; }} }} scroll {{ bind "s" {{ SwitchToMode "Normal"; }} bind "e" {{ EditScrollback; SwitchToMode "Locked"; }} bind "f" {{ SwitchToMode "EnterSearch"; SearchInput 0; }} bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Locked"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "Ctrl f" "PageDown" "Right" "l" {{ PageScrollDown; }} bind "Ctrl b" "PageUp" "Left" "h" {{ PageScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} bind "Alt left" {{ MoveFocusOrTab "left"; SwitchToMode "locked"; }} bind "Alt down" {{ MoveFocus "down"; SwitchToMode "locked"; }} bind "Alt up" {{ MoveFocus "up"; SwitchToMode "locked"; }} bind "Alt right" {{ MoveFocusOrTab "right"; SwitchToMode "locked"; }} bind "Alt h" {{ MoveFocusOrTab "left"; SwitchToMode "locked"; }} bind "Alt j" {{ MoveFocus "down"; SwitchToMode "locked"; }} bind "Alt k" {{ MoveFocus "up"; SwitchToMode "locked"; }} bind "Alt l" {{ MoveFocusOrTab "right"; SwitchToMode "locked"; }} }} search {{ bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Locked"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "Ctrl f" "PageDown" "Right" "l" {{ PageScrollDown; }} bind "Ctrl b" "PageUp" "Left" "h" {{ PageScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} bind "n" {{ Search "down"; }} bind "p" {{ Search "up"; }} bind "c" {{ SearchToggleOption "CaseSensitivity"; }} bind "w" {{ SearchToggleOption "Wrap"; }} bind "o" {{ SearchToggleOption "WholeWord"; }} }} entersearch {{ bind "Ctrl c" "Esc" {{ SwitchToMode "Scroll"; }} bind "Enter" {{ SwitchToMode "Search"; }} }} renametab {{ bind "Ctrl c" "Enter" {{ SwitchToMode "Locked"; }} bind "Esc" {{ UndoRenameTab; SwitchToMode "Tab"; }} }} renamepane {{ bind "Ctrl c" "Enter" {{ SwitchToMode "Locked"; }} bind "Esc" {{ UndoRenamePane; SwitchToMode "Pane"; }} }} session {{ bind "o" {{ SwitchToMode "Normal"; }} bind "d" {{ Detach; }} bind "w" {{ LaunchOrFocusPlugin "session-manager" {{ floating true move_to_focused_tab true }}; SwitchToMode "Locked" }} bind "c" {{ LaunchOrFocusPlugin "configuration" {{ floating true move_to_focused_tab true }}; SwitchToMode "Locked" }} bind "p" {{ LaunchOrFocusPlugin "plugin-manager" {{ floating true move_to_focused_tab true }}; SwitchToMode "Locked" }} bind "a" {{ LaunchOrFocusPlugin "zellij:about" {{ floating true move_to_focused_tab true }}; SwitchToMode "Locked" }} bind "s" {{ LaunchOrFocusPlugin "zellij:share" {{ floating true move_to_focused_tab true }}; SwitchToMode "Locked" }} bind "q" {{ LaunchPlugin "zellij:sequence" {{ floating true }}; SwitchToMode "Locked" }} }} shared_except "locked" "renametab" "renamepane" {{ bind "{primary_modifier} g" {{ SwitchToMode "Locked"; }} bind "{primary_modifier} q" {{ Quit; }} }} shared_except "renamepane" "renametab" "entersearch" "locked" {{ bind "esc" {{ SwitchToMode "locked"; }} }} shared_among "normal" "locked" {{ bind "{secondary_modifier} n" {{ NewPane; }} bind "{secondary_modifier} f" {{ ToggleFloatingPanes; }} bind "{secondary_modifier} i" {{ MoveTab "Left"; }} bind "{secondary_modifier} o" {{ MoveTab "Right"; }} bind "{secondary_modifier} h" "{secondary_modifier} Left" {{ MoveFocusOrTab "Left"; }} bind "{secondary_modifier} l" "{secondary_modifier} Right" {{ MoveFocusOrTab "Right"; }} bind "{secondary_modifier} j" "{secondary_modifier} Down" {{ MoveFocus "Down"; }} bind "{secondary_modifier} k" "{secondary_modifier} Up" {{ MoveFocus "Up"; }} bind "{secondary_modifier} =" "{secondary_modifier} +" {{ Resize "Increase"; }} bind "{secondary_modifier} -" {{ Resize "Decrease"; }} bind "{secondary_modifier} [" {{ PreviousSwapLayout; }} bind "{secondary_modifier} ]" {{ NextSwapLayout; }} bind "{secondary_modifier} p" {{ TogglePaneInGroup; }} bind "{secondary_modifier} Shift p" {{ ToggleGroupMarking; }} }} shared_except "locked" "renametab" "renamepane" {{ bind "Enter" {{ SwitchToMode "Locked"; }} }} shared_except "pane" "locked" "renametab" "renamepane" "entersearch" {{ bind "p" {{ SwitchToMode "Pane"; }} }} shared_except "resize" "locked" "renametab" "renamepane" "entersearch" {{ bind "r" {{ SwitchToMode "Resize"; }} }} shared_except "scroll" "locked" "renametab" "renamepane" "entersearch" {{ bind "s" {{ SwitchToMode "Scroll"; }} }} shared_except "session" "locked" "renametab" "renamepane" "entersearch" {{ bind "o" {{ SwitchToMode "Session"; }} }} shared_except "tab" "locked" "renametab" "renamepane" "entersearch" {{ bind "t" {{ SwitchToMode "Tab"; }} }} shared_except "move" "locked" "renametab" "renamepane" "entersearch" {{ bind "m" {{ SwitchToMode "Move"; }} }} }}"# ) } pub fn default_keybinds(primary_modifier: String, secondary_modifier: String) -> String { if primary_modifier.is_empty() && secondary_modifier.is_empty() { return default_keybinds_no_modifiers(); } else if primary_modifier == secondary_modifier { return non_colliding_default_keybinds(primary_modifier, secondary_modifier); } else if primary_modifier.is_empty() { return default_keybinds_no_primary_modifier(secondary_modifier); } else if secondary_modifier.is_empty() { return default_keybinds_no_secondary_modifier(primary_modifier); } format!( r#" default_mode "normal" keybinds clear-defaults=true {{ normal {{}} locked {{ bind "{primary_modifier} g" {{ SwitchToMode "Normal"; }} }} resize {{ bind "{primary_modifier} n" {{ SwitchToMode "Normal"; }} bind "h" "Left" {{ Resize "Increase Left"; }} bind "j" "Down" {{ Resize "Increase Down"; }} bind "k" "Up" {{ Resize "Increase Up"; }} bind "l" "Right" {{ Resize "Increase Right"; }} bind "H" {{ Resize "Decrease Left"; }} bind "J" {{ Resize "Decrease Down"; }} bind "K" {{ Resize "Decrease Up"; }} bind "L" {{ Resize "Decrease Right"; }} bind "=" "+" {{ Resize "Increase"; }} bind "-" {{ Resize "Decrease"; }} }} pane {{ bind "{primary_modifier} p" {{ SwitchToMode "Normal"; }} bind "h" "Left" {{ MoveFocus "Left"; }} bind "l" "Right" {{ MoveFocus "Right"; }} bind "j" "Down" {{ MoveFocus "Down"; }} bind "k" "Up" {{ MoveFocus "Up"; }} bind "p" {{ SwitchFocus; }} bind "n" {{ NewPane; SwitchToMode "Normal"; }} bind "d" {{ NewPane "Down"; SwitchToMode "Normal"; }} bind "r" {{ NewPane "Right"; SwitchToMode "Normal"; }} bind "s" {{ NewPane "stacked"; SwitchToMode "Normal"; }} bind "x" {{ CloseFocus; SwitchToMode "Normal"; }} bind "f" {{ ToggleFocusFullscreen; SwitchToMode "Normal"; }} bind "z" {{ TogglePaneFrames; SwitchToMode "Normal"; }} bind "w" {{ ToggleFloatingPanes; SwitchToMode "Normal"; }} bind "e" {{ TogglePaneEmbedOrFloating; SwitchToMode "Normal"; }} bind "c" {{ SwitchToMode "RenamePane"; PaneNameInput 0;}} bind "i" {{ TogglePanePinned; SwitchToMode "Normal"; }} }} move {{ bind "{primary_modifier} h" {{ SwitchToMode "Normal"; }} bind "n" "Tab" {{ MovePane; }} bind "p" {{ MovePaneBackwards; }} bind "h" "Left" {{ MovePane "Left"; }} bind "j" "Down" {{ MovePane "Down"; }} bind "k" "Up" {{ MovePane "Up"; }} bind "l" "Right" {{ MovePane "Right"; }} }} tab {{ bind "{primary_modifier} t" {{ SwitchToMode "Normal"; }} bind "r" {{ SwitchToMode "RenameTab"; TabNameInput 0; }} bind "h" "Left" "Up" "k" {{ GoToPreviousTab; }} bind "l" "Right" "Down" "j" {{ GoToNextTab; }} bind "n" {{ NewTab; SwitchToMode "Normal"; }} bind "x" {{ CloseTab; SwitchToMode "Normal"; }} bind "s" {{ ToggleActiveSyncTab; SwitchToMode "Normal"; }} bind "b" {{ BreakPane; SwitchToMode "Normal"; }} bind "]" {{ BreakPaneRight; SwitchToMode "Normal"; }} bind "[" {{ BreakPaneLeft; SwitchToMode "Normal"; }} bind "1" {{ GoToTab 1; SwitchToMode "Normal"; }} bind "2" {{ GoToTab 2; SwitchToMode "Normal"; }} bind "3" {{ GoToTab 3; SwitchToMode "Normal"; }} bind "4" {{ GoToTab 4; SwitchToMode "Normal"; }} bind "5" {{ GoToTab 5; SwitchToMode "Normal"; }} bind "6" {{ GoToTab 6; SwitchToMode "Normal"; }} bind "7" {{ GoToTab 7; SwitchToMode "Normal"; }} bind "8" {{ GoToTab 8; SwitchToMode "Normal"; }} bind "9" {{ GoToTab 9; SwitchToMode "Normal"; }} bind "Tab" {{ ToggleTab; }} }} scroll {{ bind "{primary_modifier} s" {{ SwitchToMode "Normal"; }} bind "e" {{ EditScrollback; SwitchToMode "Normal"; }} bind "s" {{ SwitchToMode "EnterSearch"; SearchInput 0; }} bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Normal"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "Ctrl f" "PageDown" "Right" "l" {{ PageScrollDown; }} bind "Ctrl b" "PageUp" "Left" "h" {{ PageScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} bind "{secondary_modifier} left" {{ MoveFocusOrTab "left"; SwitchToMode "normal"; }} bind "{secondary_modifier} down" {{ MoveFocus "down"; SwitchToMode "normal"; }} bind "{secondary_modifier} up" {{ MoveFocus "up"; SwitchToMode "normal"; }} bind "{secondary_modifier} right" {{ MoveFocusOrTab "right"; SwitchToMode "normal"; }} bind "{secondary_modifier} h" {{ MoveFocusOrTab "left"; SwitchToMode "normal"; }} bind "{secondary_modifier} j" {{ MoveFocus "down"; SwitchToMode "normal"; }} bind "{secondary_modifier} k" {{ MoveFocus "up"; SwitchToMode "normal"; }} bind "{secondary_modifier} l" {{ MoveFocusOrTab "right"; SwitchToMode "normal"; }} }} search {{ bind "{primary_modifier} s" {{ SwitchToMode "Normal"; }} bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Normal"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "Ctrl f" "PageDown" "Right" "l" {{ PageScrollDown; }} bind "Ctrl b" "PageUp" "Left" "h" {{ PageScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} bind "n" {{ Search "down"; }} bind "p" {{ Search "up"; }} bind "c" {{ SearchToggleOption "CaseSensitivity"; }} bind "w" {{ SearchToggleOption "Wrap"; }} bind "o" {{ SearchToggleOption "WholeWord"; }} }} entersearch {{ bind "Ctrl c" "Esc" {{ SwitchToMode "Scroll"; }} bind "Enter" {{ SwitchToMode "Search"; }} }} renametab {{ bind "Ctrl c" {{ SwitchToMode "Normal"; }} bind "Esc" {{ UndoRenameTab; SwitchToMode "Tab"; }} }} renamepane {{ bind "Ctrl c" {{ SwitchToMode "Normal"; }} bind "Esc" {{ UndoRenamePane; SwitchToMode "Pane"; }} }} session {{ bind "{primary_modifier} o" {{ SwitchToMode "Normal"; }} bind "{primary_modifier} s" {{ SwitchToMode "Scroll"; }} bind "d" {{ Detach; }} bind "w" {{ LaunchOrFocusPlugin "session-manager" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "c" {{ LaunchOrFocusPlugin "configuration" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "p" {{ LaunchOrFocusPlugin "plugin-manager" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "a" {{ LaunchOrFocusPlugin "zellij:about" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "s" {{ LaunchOrFocusPlugin "zellij:share" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "q" {{ LaunchPlugin "zellij:sequence" {{ floating true }}; SwitchToMode "Normal" }} }} tmux {{ bind "[" {{ SwitchToMode "Scroll"; }} bind "{primary_modifier} b" {{ Write 2; SwitchToMode "Normal"; }} bind "\"" {{ NewPane "Down"; SwitchToMode "Normal"; }} bind "%" {{ NewPane "Right"; SwitchToMode "Normal"; }} bind "z" {{ ToggleFocusFullscreen; SwitchToMode "Normal"; }} bind "c" {{ NewTab; SwitchToMode "Normal"; }} bind "," {{ SwitchToMode "RenameTab"; }} bind "p" {{ GoToPreviousTab; SwitchToMode "Normal"; }} bind "n" {{ GoToNextTab; SwitchToMode "Normal"; }} bind "Left" {{ MoveFocus "Left"; SwitchToMode "Normal"; }} bind "Right" {{ MoveFocus "Right"; SwitchToMode "Normal"; }} bind "Down" {{ MoveFocus "Down"; SwitchToMode "Normal"; }} bind "Up" {{ MoveFocus "Up"; SwitchToMode "Normal"; }} bind "h" {{ MoveFocus "Left"; SwitchToMode "Normal"; }} bind "l" {{ MoveFocus "Right"; SwitchToMode "Normal"; }} bind "j" {{ MoveFocus "Down"; SwitchToMode "Normal"; }} bind "k" {{ MoveFocus "Up"; SwitchToMode "Normal"; }} bind "o" {{ FocusNextPane; }} bind "d" {{ Detach; }} bind "Space" {{ NextSwapLayout; }} bind "x" {{ CloseFocus; SwitchToMode "Normal"; }} }} shared_except "locked" {{ bind "{primary_modifier} g" {{ SwitchToMode "Locked"; }} bind "{primary_modifier} q" {{ Quit; }} bind "{secondary_modifier} f" {{ ToggleFloatingPanes; }} bind "{secondary_modifier} n" {{ NewPane; }} bind "{secondary_modifier} i" {{ MoveTab "Left"; }} bind "{secondary_modifier} o" {{ MoveTab "Right"; }} bind "{secondary_modifier} h" "{secondary_modifier} Left" {{ MoveFocusOrTab "Left"; }} bind "{secondary_modifier} l" "{secondary_modifier} Right" {{ MoveFocusOrTab "Right"; }} bind "{secondary_modifier} j" "{secondary_modifier} Down" {{ MoveFocus "Down"; }} bind "{secondary_modifier} k" "{secondary_modifier} Up" {{ MoveFocus "Up"; }} bind "{secondary_modifier} =" "{secondary_modifier} +" {{ Resize "Increase"; }} bind "{secondary_modifier} -" {{ Resize "Decrease"; }} bind "{secondary_modifier} [" {{ PreviousSwapLayout; }} bind "{secondary_modifier} ]" {{ NextSwapLayout; }} bind "{secondary_modifier} p" {{ TogglePaneInGroup; }} bind "{secondary_modifier} Shift p" {{ ToggleGroupMarking; }} }} shared_except "normal" "locked" {{ bind "Enter" "Esc" {{ SwitchToMode "Normal"; }} }} shared_except "pane" "locked" {{ bind "{primary_modifier} p" {{ SwitchToMode "Pane"; }} }} shared_except "resize" "locked" {{ bind "{primary_modifier} n" {{ SwitchToMode "Resize"; }} }} shared_except "scroll" "locked" {{ bind "{primary_modifier} s" {{ SwitchToMode "Scroll"; }} }} shared_except "session" "locked" {{ bind "{primary_modifier} o" {{ SwitchToMode "Session"; }} }} shared_except "tab" "locked" {{ bind "{primary_modifier} t" {{ SwitchToMode "Tab"; }} }} shared_except "move" "locked" {{ bind "{primary_modifier} h" {{ SwitchToMode "Move"; }} }} shared_except "tmux" "locked" {{ bind "{primary_modifier} b" {{ SwitchToMode "Tmux"; }} }} }} "# ) } pub fn default_keybinds_no_primary_modifier(secondary_modifier: String) -> String { format!( r#" default_mode "normal" keybinds clear-defaults=true {{ normal {{}} locked {{}} resize {{ bind "h" "Left" {{ Resize "Increase Left"; }} bind "j" "Down" {{ Resize "Increase Down"; }} bind "k" "Up" {{ Resize "Increase Up"; }} bind "l" "Right" {{ Resize "Increase Right"; }} bind "H" {{ Resize "Decrease Left"; }} bind "J" {{ Resize "Decrease Down"; }} bind "K" {{ Resize "Decrease Up"; }} bind "L" {{ Resize "Decrease Right"; }} bind "=" "+" {{ Resize "Increase"; }} bind "-" {{ Resize "Decrease"; }} }} pane {{ bind "h" "Left" {{ MoveFocus "Left"; }} bind "l" "Right" {{ MoveFocus "Right"; }} bind "j" "Down" {{ MoveFocus "Down"; }} bind "k" "Up" {{ MoveFocus "Up"; }} bind "p" {{ SwitchFocus; }} bind "n" {{ NewPane; SwitchToMode "Normal"; }} bind "d" {{ NewPane "Down"; SwitchToMode "Normal"; }} bind "r" {{ NewPane "Right"; SwitchToMode "Normal"; }} bind "s" {{ NewPane "stacked"; SwitchToMode "Normal"; }} bind "x" {{ CloseFocus; SwitchToMode "Normal"; }} bind "f" {{ ToggleFocusFullscreen; SwitchToMode "Normal"; }} bind "z" {{ TogglePaneFrames; SwitchToMode "Normal"; }} bind "w" {{ ToggleFloatingPanes; SwitchToMode "Normal"; }} bind "e" {{ TogglePaneEmbedOrFloating; SwitchToMode "Normal"; }} bind "c" {{ SwitchToMode "RenamePane"; PaneNameInput 0;}} bind "i" {{ TogglePanePinned; SwitchToMode "Normal"; }} }} move {{ bind "n" "Tab" {{ MovePane; }} bind "p" {{ MovePaneBackwards; }} bind "h" "Left" {{ MovePane "Left"; }} bind "j" "Down" {{ MovePane "Down"; }} bind "k" "Up" {{ MovePane "Up"; }} bind "l" "Right" {{ MovePane "Right"; }} }} tab {{ bind "r" {{ SwitchToMode "RenameTab"; TabNameInput 0; }} bind "h" "Left" "Up" "k" {{ GoToPreviousTab; }} bind "l" "Right" "Down" "j" {{ GoToNextTab; }} bind "n" {{ NewTab; SwitchToMode "Normal"; }} bind "x" {{ CloseTab; SwitchToMode "Normal"; }} bind "s" {{ ToggleActiveSyncTab; SwitchToMode "Normal"; }} bind "b" {{ BreakPane; SwitchToMode "Normal"; }} bind "]" {{ BreakPaneRight; SwitchToMode "Normal"; }} bind "[" {{ BreakPaneLeft; SwitchToMode "Normal"; }} bind "1" {{ GoToTab 1; SwitchToMode "Normal"; }} bind "2" {{ GoToTab 2; SwitchToMode "Normal"; }} bind "3" {{ GoToTab 3; SwitchToMode "Normal"; }} bind "4" {{ GoToTab 4; SwitchToMode "Normal"; }} bind "5" {{ GoToTab 5; SwitchToMode "Normal"; }} bind "6" {{ GoToTab 6; SwitchToMode "Normal"; }} bind "7" {{ GoToTab 7; SwitchToMode "Normal"; }} bind "8" {{ GoToTab 8; SwitchToMode "Normal"; }} bind "9" {{ GoToTab 9; SwitchToMode "Normal"; }} bind "Tab" {{ ToggleTab; }} }} scroll {{ bind "e" {{ EditScrollback; SwitchToMode "Normal"; }} bind "s" {{ SwitchToMode "EnterSearch"; SearchInput 0; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} bind "{secondary_modifier} left" {{ MoveFocusOrTab "left"; SwitchToMode "normal"; }} bind "{secondary_modifier} down" {{ MoveFocus "down"; SwitchToMode "normal"; }} bind "{secondary_modifier} up" {{ MoveFocus "up"; SwitchToMode "normal"; }} bind "{secondary_modifier} right" {{ MoveFocusOrTab "right"; SwitchToMode "normal"; }} bind "{secondary_modifier} h" {{ MoveFocusOrTab "left"; SwitchToMode "normal"; }} bind "{secondary_modifier} j" {{ MoveFocus "down"; SwitchToMode "normal"; }} bind "{secondary_modifier} k" {{ MoveFocus "up"; SwitchToMode "normal"; }} bind "{secondary_modifier} l" {{ MoveFocusOrTab "right"; SwitchToMode "normal"; }} }} search {{ bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Normal"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "Ctrl f" "PageDown" "Right" "l" {{ PageScrollDown; }} bind "Ctrl b" "PageUp" "Left" "h" {{ PageScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} bind "n" {{ Search "down"; }} bind "p" {{ Search "up"; }} bind "c" {{ SearchToggleOption "CaseSensitivity"; }} bind "w" {{ SearchToggleOption "Wrap"; }} bind "o" {{ SearchToggleOption "WholeWord"; }} }} entersearch {{ bind "Ctrl c" "Esc" {{ SwitchToMode "Scroll"; }} bind "Enter" {{ SwitchToMode "Search"; }} }} renametab {{ bind "Ctrl c" {{ SwitchToMode "Normal"; }} bind "Esc" {{ UndoRenameTab; SwitchToMode "Tab"; }} }} renamepane {{ bind "Ctrl c" {{ SwitchToMode "Normal"; }} bind "Esc" {{ UndoRenamePane; SwitchToMode "Pane"; }} }} session {{ bind "d" {{ Detach; }} bind "w" {{ LaunchOrFocusPlugin "session-manager" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "c" {{ LaunchOrFocusPlugin "configuration" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "p" {{ LaunchOrFocusPlugin "plugin-manager" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "a" {{ LaunchOrFocusPlugin "zellij:about" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "s" {{ LaunchOrFocusPlugin "zellij:share" {{ floating true move_to_focused_tab true }}; SwitchToMode "Normal" }} bind "q" {{ LaunchPlugin "zellij:sequence" {{ floating true }}; SwitchToMode "Normal" }} }} tmux {{ bind "[" {{ SwitchToMode "Scroll"; }} bind "\"" {{ NewPane "Down"; SwitchToMode "Normal"; }} bind "%" {{ NewPane "Right"; SwitchToMode "Normal"; }} bind "z" {{ ToggleFocusFullscreen; SwitchToMode "Normal"; }} bind "c" {{ NewTab; SwitchToMode "Normal"; }} bind "," {{ SwitchToMode "RenameTab"; }} bind "p" {{ GoToPreviousTab; SwitchToMode "Normal"; }} bind "n" {{ GoToNextTab; SwitchToMode "Normal"; }} bind "Left" {{ MoveFocus "Left"; SwitchToMode "Normal"; }} bind "Right" {{ MoveFocus "Right"; SwitchToMode "Normal"; }} bind "Down" {{ MoveFocus "Down"; SwitchToMode "Normal"; }} bind "Up" {{ MoveFocus "Up"; SwitchToMode "Normal"; }} bind "h" {{ MoveFocus "Left"; SwitchToMode "Normal"; }} bind "l" {{ MoveFocus "Right"; SwitchToMode "Normal"; }} bind "j" {{ MoveFocus "Down"; SwitchToMode "Normal"; }} bind "k" {{ MoveFocus "Up"; SwitchToMode "Normal"; }} bind "o" {{ FocusNextPane; }} bind "d" {{ Detach; }} bind "Space" {{ NextSwapLayout; }} bind "x" {{ CloseFocus; SwitchToMode "Normal"; }} }} shared_except "locked" {{ bind "{secondary_modifier} n" {{ NewPane; }} bind "{secondary_modifier} f" {{ ToggleFloatingPanes; }} bind "{secondary_modifier} i" {{ MoveTab "Left"; }} bind "{secondary_modifier} o" {{ MoveTab "Right"; }} bind "{secondary_modifier} h" "{secondary_modifier} Left" {{ MoveFocusOrTab "Left"; }} bind "{secondary_modifier} l" "{secondary_modifier} Right" {{ MoveFocusOrTab "Right"; }} bind "{secondary_modifier} j" "{secondary_modifier} Down" {{ MoveFocus "Down"; }} bind "{secondary_modifier} k" "{secondary_modifier} Up" {{ MoveFocus "Up"; }} bind "{secondary_modifier} =" "{secondary_modifier} +" {{ Resize "Increase"; }} bind "{secondary_modifier} -" {{ Resize "Decrease"; }} bind "{secondary_modifier} [" {{ PreviousSwapLayout; }} bind "{secondary_modifier} ]" {{ NextSwapLayout; }} bind "{secondary_modifier} p" {{ TogglePaneInGroup; }} bind "{secondary_modifier} Shift p" {{ ToggleGroupMarking; }} }} shared_except "normal" "locked" {{ bind "Enter" "Esc" {{ SwitchToMode "Normal"; }} }} }} "# ) } pub fn default_keybinds_no_secondary_modifier(primary_modifier: String) -> String { format!( r#" default_mode "normal" keybinds clear-defaults=true {{ normal {{}} locked {{ bind "{primary_modifier} g" {{ SwitchToMode "Normal"; }} }} resize {{ bind "{primary_modifier} n" {{ SwitchToMode "Normal"; }} bind "h" "Left" {{ Resize "Increase Left"; }} bind "j" "Down" {{ Resize "Increase Down"; }} bind "k" "Up" {{ Resize "Increase Up"; }} bind "l" "Right" {{ Resize "Increase Right"; }} bind "H" {{ Resize "Decrease Left"; }} bind "J" {{ Resize "Decrease Down"; }} bind "K" {{ Resize "Decrease Up"; }} bind "L" {{ Resize "Decrease Right"; }} bind "=" "+" {{ Resize "Increase"; }} bind "-" {{ Resize "Decrease"; }} }} pane {{ bind "{primary_modifier} p" {{ SwitchToMode "Normal"; }} bind "h" "Left" {{ MoveFocus "Left"; }} bind "l" "Right" {{ MoveFocus "Right"; }} bind "j" "Down" {{ MoveFocus "Down"; }} bind "k" "Up" {{ MoveFocus "Up"; }} bind "p" {{ SwitchFocus; }} bind "n" {{ NewPane; SwitchToMode "Normal"; }} bind "d" {{ NewPane "Down"; SwitchToMode "Normal"; }} bind "r" {{ NewPane "Right"; SwitchToMode "Normal"; }} bind "s" {{ NewPane "stacked"; SwitchToMode "Normal"; }} bind "x" {{ CloseFocus; SwitchToMode "Normal"; }} bind "f" {{ ToggleFocusFullscreen; SwitchToMode "Normal"; }} bind "z" {{ TogglePaneFrames; SwitchToMode "Normal"; }} bind "w" {{ ToggleFloatingPanes; SwitchToMode "Normal"; }} bind "e" {{ TogglePaneEmbedOrFloating; SwitchToMode "Normal"; }} bind "c" {{ SwitchToMode "RenamePane"; PaneNameInput 0;}} bind "i" {{ TogglePanePinned; SwitchToMode "Normal"; }} }} move {{ bind "{primary_modifier} h" {{ SwitchToMode "Normal"; }} bind "n" "Tab" {{ MovePane; }} bind "p" {{ MovePaneBackwards; }} bind "h" "Left" {{ MovePane "Left"; }} bind "j" "Down" {{ MovePane "Down"; }} bind "k" "Up" {{ MovePane "Up"; }} bind "l" "Right" {{ MovePane "Right"; }} }} tab {{ bind "{primary_modifier} t" {{ SwitchToMode "Normal"; }} bind "r" {{ SwitchToMode "RenameTab"; TabNameInput 0; }} bind "h" "Left" "Up" "k" {{ GoToPreviousTab; }} bind "l" "Right" "Down" "j" {{ GoToNextTab; }} bind "n" {{ NewTab; SwitchToMode "Normal"; }} bind "x" {{ CloseTab; SwitchToMode "Normal"; }} bind "s" {{ ToggleActiveSyncTab; SwitchToMode "Normal"; }} bind "b" {{ BreakPane; SwitchToMode "Normal"; }} bind "]" {{ BreakPaneRight; SwitchToMode "Normal"; }} bind "[" {{ BreakPaneLeft; SwitchToMode "Normal"; }} bind "1" {{ GoToTab 1; SwitchToMode "Normal"; }} bind "2" {{ GoToTab 2; SwitchToMode "Normal"; }} bind "3" {{ GoToTab 3; SwitchToMode "Normal"; }} bind "4" {{ GoToTab 4; SwitchToMode "Normal"; }} bind "5" {{ GoToTab 5; SwitchToMode "Normal"; }} bind "6" {{ GoToTab 6; SwitchToMode "Normal"; }} bind "7" {{ GoToTab 7; SwitchToMode "Normal"; }} bind "8" {{ GoToTab 8; SwitchToMode "Normal"; }} bind "9" {{ GoToTab 9; SwitchToMode "Normal"; }} bind "Tab" {{ ToggleTab; }} }} scroll {{ bind "{primary_modifier} s" {{ SwitchToMode "Normal"; }} bind "e" {{ EditScrollback; SwitchToMode "Normal"; }} bind "s" {{ SwitchToMode "EnterSearch"; SearchInput 0; }} bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Normal"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }} bind "Ctrl f" "PageDown" "Right" "l" {{ PageScrollDown; }} bind "Ctrl b" "PageUp" "Left" "h" {{ PageScrollUp; }} bind "d" {{ HalfPageScrollDown; }} bind "u" {{ HalfPageScrollUp; }} }} search {{ bind "{primary_modifier} s" {{ SwitchToMode "Normal"; }} bind "Ctrl c" {{ ScrollToBottom; SwitchToMode "Normal"; }} bind "j" "Down" {{ ScrollDown; }} bind "k" "Up" {{ ScrollUp; }}
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/configuration/src/presets_screen.rs
default-plugins/configuration/src/presets_screen.rs
use zellij_tile::prelude::*; use crate::ui_components::info_line; use crate::rebind_leaders_screen::RebindLeadersScreen; use std::collections::BTreeSet; use crate::presets::{default_keybinds, unlock_first_keybinds}; #[derive(Debug)] pub struct PresetsScreen { selected_index: Option<usize>, latest_mode_info: Option<ModeInfo>, notification: Option<String>, primary_modifier: BTreeSet<KeyModifier>, secondary_modifier: BTreeSet<KeyModifier>, rebind_leaders_screen: Option<RebindLeadersScreen>, } impl Default for PresetsScreen { fn default() -> Self { let mut primary_modifier = BTreeSet::new(); primary_modifier.insert(KeyModifier::Ctrl); let mut secondary_modifier = BTreeSet::new(); secondary_modifier.insert(KeyModifier::Alt); PresetsScreen { primary_modifier, secondary_modifier, selected_index: None, latest_mode_info: None, notification: None, rebind_leaders_screen: None, } } } impl PresetsScreen { pub fn new(selected_index: Option<usize>) -> Self { PresetsScreen { selected_index, ..Default::default() } } pub fn rebinding_leaders(&self) -> bool { self.rebind_leaders_screen.is_some() } pub fn handle_presets_key(&mut self, key: KeyWithModifier) -> bool { if let Some(rebind_leaders_screen) = self.rebind_leaders_screen.as_mut() { match key.bare_key { BareKey::Esc if key.has_no_modifiers() => { // consume screen without applying its modifiers drop(self.rebind_leaders_screen.take()); return true; }, BareKey::Enter if key.has_no_modifiers() => { // consume screen and apply its modifiers let (primary_modifier, secondary_modifier) = rebind_leaders_screen.primary_and_secondary_modifiers(); self.primary_modifier = primary_modifier; self.secondary_modifier = secondary_modifier; drop(self.rebind_leaders_screen.take()); return true; }, _ => { return rebind_leaders_screen.handle_key(key); }, } } let mut should_render = false; if self.notification.is_some() { self.notification = None; should_render = true; } else if key.bare_key == BareKey::Down && key.has_no_modifiers() { self.move_selected_index_down(); should_render = true; } else if key.bare_key == BareKey::Up && key.has_no_modifiers() { self.move_selected_index_up(); should_render = true; } else if key.bare_key == BareKey::Enter && key.has_no_modifiers() { if let Some(selected_index) = self.selected_index.take() { let write_to_disk = false; self.reconfigure(selected_index, write_to_disk); self.notification = Some("Configuration applied to current session.".to_owned()); } else { self.reset_selected_index(); } should_render = true; } else if key.bare_key == BareKey::Char('a') && key.has_modifiers(&[KeyModifier::Ctrl]) { if let Some(selected_index) = self.take_selected_index() { let write_to_disk = true; self.reconfigure(selected_index, write_to_disk); self.notification = Some("Configuration applied and saved to disk.".to_owned()); should_render = true; } } else if key.bare_key == BareKey::Char('l') && key.has_no_modifiers() { // for the time being this screen has been disabled because it was deemed too confusing // and its use-cases are very limited (it's possible to achieve the same results by // applying a preset and then rebinding the leader keys) // // the code is left here in case someone feels strongly about implementing this on // their own, and because at the time of writing I'm a little ambiguous about this // decision. At some point it should be refactored away // self.rebind_leaders_screen = Some( // RebindLeadersScreen::default() // .with_rebinding_for_presets() // .with_mode_info(self.latest_mode_info.clone()), // ); // should_render = true; } else if (key.bare_key == BareKey::Esc && key.has_no_modifiers()) || key.is_key_with_ctrl_modifier(BareKey::Char('c')) { close_self(); should_render = true; } should_render } pub fn handle_setup_wizard_key(&mut self, key: KeyWithModifier) -> bool { if let Some(rebind_leaders_screen) = self.rebind_leaders_screen.as_mut() { match key.bare_key { BareKey::Esc if key.has_no_modifiers() => { // consume screen without applying its modifiers drop(self.rebind_leaders_screen.take()); return true; }, BareKey::Enter if key.has_no_modifiers() => { // consume screen and apply its modifiers let (primary_modifier, secondary_modifier) = rebind_leaders_screen.primary_and_secondary_modifiers(); self.primary_modifier = primary_modifier; self.secondary_modifier = secondary_modifier; drop(self.rebind_leaders_screen.take()); return true; }, _ => { return rebind_leaders_screen.handle_key(key); }, } } let mut should_render = false; if self.notification.is_some() { self.notification = None; should_render = true; } else if key.bare_key == BareKey::Down && key.has_no_modifiers() { self.move_selected_index_down(); should_render = true; } else if key.bare_key == BareKey::Up && key.has_no_modifiers() { self.move_selected_index_up(); should_render = true; } else if key.bare_key == BareKey::Enter && key.has_no_modifiers() { if let Some(selected_index) = self.take_selected_index() { let write_to_disk = true; self.reconfigure(selected_index, write_to_disk); close_self(); } else { self.reset_selected_index(); should_render = true; } } else if key.bare_key == BareKey::Char('l') && key.has_no_modifiers() { // for the time being this screen has been disabled because it was deemed too confusing // and its use-cases are very limited (it's possible to achieve the same results by // applying a preset and then rebinding the leader keys) // // the code is left here in case someone feels strongly about implementing this on // their own, and because at the time of writing I'm a little ambiguous about this // decision. At some point it should be refactored away // self.rebind_leaders_screen = // Some(RebindLeadersScreen::default().with_rebinding_for_presets()); // should_render = true; } else if (key.bare_key == BareKey::Esc && key.has_no_modifiers()) || key.is_key_with_ctrl_modifier(BareKey::Char('c')) { close_self(); should_render = true; } should_render } pub fn update_mode_info(&mut self, mode_info: ModeInfo) { if let Some(rebind_leaders_screen) = self.rebind_leaders_screen.as_mut() { rebind_leaders_screen.update_mode_info(mode_info.clone()); } self.latest_mode_info = Some(mode_info); } pub fn move_selected_index_down(&mut self) { if self.selected_index.is_none() { self.selected_index = Some(0); } else if self.selected_index < Some(1) { self.selected_index = Some(1); } else { self.selected_index = None; } } pub fn move_selected_index_up(&mut self) { if self.selected_index.is_none() { self.selected_index = Some(1); } else if self.selected_index == Some(1) { self.selected_index = Some(0); } else { self.selected_index = None; } } pub fn take_selected_index(&mut self) -> Option<usize> { self.selected_index.take() } pub fn reset_selected_index(&mut self) { self.selected_index = Some(0); } pub fn drain_notification(&mut self) -> Option<String> { self.notification.take() } pub fn set_notification(&mut self, notification: Option<String>) { self.notification = notification; } fn reconfigure(&self, selected: usize, write_to_disk: bool) { if selected == 0 { // TODO: these should be part of a "transaction" when they are // implemented reconfigure( default_keybinds( self.primary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" "), self.secondary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" "), ), write_to_disk, ); switch_to_input_mode(&InputMode::Normal); } else if selected == 1 { // TODO: these should be part of a "transaction" when they are // implemented reconfigure( unlock_first_keybinds( self.primary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" "), self.secondary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" "), ), write_to_disk, ); switch_to_input_mode(&InputMode::Locked); } } pub fn render_setup_wizard_screen( &mut self, rows: usize, cols: usize, ui_size: usize, notification: &Option<String>, ) { if let Some(rebind_leaders_screen) = self.rebind_leaders_screen.as_mut() { return rebind_leaders_screen.render(rows, cols, ui_size, notification); } let primary_modifier_key_text = self.primary_modifier_text(); let secondary_modifier_key_text = self.secondary_modifier_text(); self.render_setup_wizard_title(rows, cols, &primary_modifier_key_text, ui_size); self.render_first_bulletin(rows + 8, cols, &primary_modifier_key_text, ui_size); self.render_second_bulletin(rows + 8, cols, &primary_modifier_key_text, ui_size); self.render_leader_keys_indication( rows + 8, cols, &primary_modifier_key_text, &secondary_modifier_key_text, ui_size, ); info_line( rows + 8, cols, ui_size, &notification, &self.warning_text(cols), Some(self.main_screen_widths(&primary_modifier_key_text)), ); // self.render_info_line(rows + 8, cols); self.render_help_text_setup_wizard(rows + 8, cols); } pub fn render_reset_keybindings_screen( &mut self, rows: usize, cols: usize, ui_size: usize, notification: &Option<String>, ) { if let Some(rebind_leaders_screen) = self.rebind_leaders_screen.as_mut() { return rebind_leaders_screen.render(rows, cols, ui_size, notification); } let primary_modifier_key_text = self.primary_modifier_text(); let secondary_modifier_key_text = self.secondary_modifier_text(); self.render_override_title(rows, cols, &primary_modifier_key_text, ui_size); self.render_first_bulletin(rows, cols, &primary_modifier_key_text, ui_size); self.render_second_bulletin(rows, cols, &primary_modifier_key_text, ui_size); self.render_leader_keys_indication( rows, cols, &primary_modifier_key_text, &secondary_modifier_key_text, ui_size, ); let notification = notification.clone().or_else(|| self.notification.clone()); let warning_text = self.warning_text(cols); info_line( rows, cols, ui_size, &notification, &warning_text, Some(self.main_screen_widths(&primary_modifier_key_text)), ); self.render_help_text_main(rows, cols); } fn primary_modifier_text(&self) -> String { if self.primary_modifier.is_empty() { "<UNBOUND>".to_owned() } else { self.primary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") } } fn secondary_modifier_text(&self) -> String { if self.secondary_modifier.is_empty() { "<UNBOUND>".to_owned() } else { self.secondary_modifier .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join("-") } } fn render_setup_wizard_title( &self, rows: usize, cols: usize, primary_modifier_key_text: &str, ui_size: usize, ) { let widths = self.main_screen_widths(primary_modifier_key_text); if cols >= widths.0 { let title_text_1 = "Hi there! How would you like to interact with Zellij?"; let title_text_2 = "Not sure? Press <ENTER> to choose Default."; let title_text_3 = "Everything can always be changed later."; let title_text_4 = "Tips appear on screen - you don't need to remember anything."; let left_padding = cols.saturating_sub(widths.0) / 2; let first_row_coords = (rows.saturating_sub(ui_size) / 2).saturating_sub(1); print_text_with_coordinates( Text::new(title_text_1).color_range(2, ..), left_padding, first_row_coords, None, None, ); print_text_with_coordinates( Text::new(title_text_2) .color_range(0, ..10) .color_range(2, 16..23) .color_range(1, 34..41), left_padding, first_row_coords + 2, None, None, ); print_text_with_coordinates( Text::new(title_text_3), left_padding, first_row_coords + 4, None, None, ); print_text_with_coordinates( Text::new(title_text_4), left_padding, first_row_coords + 5, None, None, ); } else { let title_text_1 = "Hi there! Which do you prefer?"; let title_text_2 = "Not sure? Press <ENTER>"; let title_text_3 = "Can be changed later. Tips appear"; let title_text_4 = "on screen - no need to remember"; let left_padding = if cols >= widths.1 { cols.saturating_sub(widths.1) / 2 } else { cols.saturating_sub(widths.2) / 2 }; let first_row_coords = (rows.saturating_sub(ui_size) / 2).saturating_sub(1); print_text_with_coordinates( Text::new(title_text_1).color_range(2, ..), left_padding, first_row_coords, None, None, ); print_text_with_coordinates( Text::new(title_text_2) .color_range(0, ..10) .color_range(2, 16..23) .color_range(1, 40..49), left_padding, first_row_coords + 2, None, None, ); print_text_with_coordinates( Text::new(title_text_3), left_padding, first_row_coords + 4, None, None, ); print_text_with_coordinates( Text::new(title_text_4), left_padding, first_row_coords + 5, None, None, ); } } fn main_screen_widths(&self, primary_modifier_text: &str) -> (usize, usize, usize) { let primary_modifier_key_text_len = primary_modifier_text.chars().count(); let full_width = 61 + primary_modifier_key_text_len; let mid_width = 36 + primary_modifier_key_text_len; let min_width = 26 + primary_modifier_key_text_len; (full_width, mid_width, min_width) } fn render_first_bulletin( &self, rows: usize, cols: usize, primary_modifier_key_text: &str, ui_size: usize, ) { let widths = self.main_screen_widths(primary_modifier_key_text); let primary_modifier_key_text_len = primary_modifier_key_text.chars().count(); let default_text = "1. Default"; let (mut list_items, max_width) = if cols >= widths.0 { let list_items = vec![ NestedListItem::new(default_text).color_range(1, ..), NestedListItem::new("All modes available directly from the base mode, eg.:") .indent(1), NestedListItem::new(format!( "{} p - to enter PANE mode", primary_modifier_key_text )) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 2, primary_modifier_key_text_len + 14..primary_modifier_key_text_len + 18, ) .indent(1), NestedListItem::new(format!( "{} t - to enter TAB mode", primary_modifier_key_text )) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 2, primary_modifier_key_text_len + 14..primary_modifier_key_text_len + 17, ) .indent(1), ]; let max_width = widths.0; (list_items, max_width) } else if cols >= widths.1 { let list_items = vec![ NestedListItem::new(default_text).color_range(1, ..), NestedListItem::new("Modes available directly, eg.:").indent(1), NestedListItem::new(format!( "{} p - to enter PANE mode", primary_modifier_key_text )) .indent(1) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 2, primary_modifier_key_text_len + 14..primary_modifier_key_text_len + 18, ), NestedListItem::new(format!( "{} t - to enter TAB mode", primary_modifier_key_text )) .indent(1) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 2, primary_modifier_key_text_len + 14..primary_modifier_key_text_len + 17, ), ]; let max_width = widths.1; (list_items, max_width) } else { let list_items = vec![ NestedListItem::new(default_text).color_range(1, ..), NestedListItem::new("Directly, eg.:").indent(1), NestedListItem::new(format!("{} p - PANE mode", primary_modifier_key_text)) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 2, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 10, ) .indent(1), NestedListItem::new(format!("{} t - TAB mode", primary_modifier_key_text)) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 2, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 9, ) .indent(1), ]; let max_width = widths.2; (list_items, max_width) }; if self.selected_index == Some(0) { list_items = list_items.drain(..).map(|i| i.selected()).collect(); } let left_padding = cols.saturating_sub(max_width) / 2; let top_coordinates = if rows > 14 { (rows.saturating_sub(ui_size) / 2) + 3 } else { (rows.saturating_sub(ui_size) / 2) + 2 }; print_nested_list_with_coordinates(list_items, left_padding, top_coordinates, None, None); } fn render_second_bulletin( &self, rows: usize, cols: usize, primary_modifier_key_text: &str, ui_size: usize, ) { let unlock_first_text = "2. Unlock First (non-colliding)"; let widths = self.main_screen_widths(primary_modifier_key_text); let primary_modifier_key_text_len = primary_modifier_key_text.chars().count(); let (mut list_items, max_width) = if cols >= widths.0 { let list_items = vec![ NestedListItem::new(unlock_first_text).color_range(1, ..), NestedListItem::new(format!( "Single key modes available after unlocking with {} g, eg.:", primary_modifier_key_text )) .indent(1), NestedListItem::new(format!( "{} g + p to enter PANE mode", primary_modifier_key_text )) .indent(1) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 3, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 7, ) .color_range( 2, primary_modifier_key_text_len + 16..primary_modifier_key_text_len + 21, ), NestedListItem::new(format!( "{} g + t to enter TAB mode", primary_modifier_key_text )) .indent(1) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 3, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 7, ) .color_range( 2, primary_modifier_key_text_len + 16..primary_modifier_key_text_len + 20, ), ]; let max_width = widths.0; (list_items, max_width) } else if cols >= widths.1 { let list_items = vec![ NestedListItem::new(unlock_first_text).color_range(1, ..), NestedListItem::new(format!( "Single key modes after {} g, eg.:", primary_modifier_key_text )) .indent(1), NestedListItem::new(format!( "{} g + p to enter PANE mode", primary_modifier_key_text )) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 3, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 7, ) .color_range( 2, primary_modifier_key_text_len + 16..primary_modifier_key_text_len + 21, ) .indent(1), NestedListItem::new(format!( "{} g + t to enter TAB mode", primary_modifier_key_text )) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 3, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 7, ) .color_range( 2, primary_modifier_key_text_len + 16..primary_modifier_key_text_len + 20, ) .indent(1), ]; let max_width = widths.1; (list_items, max_width) } else { let list_items = vec![ NestedListItem::new("2. Unlock First").color_range(1, ..), NestedListItem::new(format!( "{} g + single key, eg.:", primary_modifier_key_text )) .indent(1), NestedListItem::new(format!("{} g + p PANE mode", primary_modifier_key_text)) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 3, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 7, ) .color_range( 2, primary_modifier_key_text_len + 7..primary_modifier_key_text_len + 11, ) .indent(1), NestedListItem::new(format!("{} g + t TAB mode", primary_modifier_key_text)) .color_range(3, ..primary_modifier_key_text_len + 3) .color_range( 3, primary_modifier_key_text_len + 5..primary_modifier_key_text_len + 7, ) .color_range( 2, primary_modifier_key_text_len + 7..primary_modifier_key_text_len + 10, ) .indent(1), ]; let max_width = widths.2; (list_items, max_width) }; if self.selected_index == Some(1) { list_items = list_items.drain(..).map(|i| i.selected()).collect(); } let left_padding = cols.saturating_sub(max_width) / 2; let top_coordinates = if rows > 14 { (rows.saturating_sub(ui_size) / 2) + 8 } else { (rows.saturating_sub(ui_size) / 2) + 6 }; print_nested_list_with_coordinates(list_items, left_padding, top_coordinates, None, None); } fn render_leader_keys_indication( &self, rows: usize, cols: usize, primary_modifier_key_text: &str, secondary_modifier_key_text: &str, ui_size: usize, ) { let widths = self.main_screen_widths(primary_modifier_key_text); let primary_modifier_key_text_len = primary_modifier_key_text.chars().count(); let secondary_modifier_key_text_len = secondary_modifier_key_text.chars().count(); let top_coordinates = if rows > 14 { (rows.saturating_sub(ui_size) / 2) + 13 } else { (rows.saturating_sub(ui_size) / 2) + 10 }; if cols >= widths.0 { let leader_key_text = format!( "Leader keys: {} - modes, {} - quicknav and shortcuts", primary_modifier_key_text, secondary_modifier_key_text ); let left_padding = cols.saturating_sub(widths.0) / 2; print_text_with_coordinates( Text::new(leader_key_text) .color_range(2, ..12) .color_range(3, 13..primary_modifier_key_text_len + 14) .color_range( 0, primary_modifier_key_text_len + 23 ..primary_modifier_key_text_len + 23 + secondary_modifier_key_text_len, ), left_padding, top_coordinates, None, None, ) } else { let leader_key_text = format!( "Leaders: {}, {}", primary_modifier_key_text, secondary_modifier_key_text ); let left_padding = if cols >= widths.1 { cols.saturating_sub(widths.1) / 2 } else { cols.saturating_sub(widths.2) / 2 }; print_text_with_coordinates( Text::new(leader_key_text) .color_range(2, ..8) .color_range(3, 9..primary_modifier_key_text_len + 10) .color_range( 0, primary_modifier_key_text_len + 11 ..primary_modifier_key_text_len + 12 + secondary_modifier_key_text_len, ), left_padding, top_coordinates, None, None, ) }; } fn render_help_text_setup_wizard(&self, rows: usize, cols: usize) { let full_help_text = "Help: <↓↑> - navigate, <ENTER> - apply & save, <ESC> - close"; let short_help_text = "Help: <↓↑> / <ENTER> / <ESC>"; if cols >= full_help_text.chars().count() { print_text_with_coordinates( Text::new(full_help_text) .color_range(2, 6..10) .color_range(2, 23..30) .color_range(2, 47..=50), 0, rows, None, None, ); } else { print_text_with_coordinates( Text::new(short_help_text) .color_range(2, 6..10) .color_range(2, 13..20) .color_range(2, 23..=27), 0, rows, None, None, ); } } fn render_override_title( &self, rows: usize, cols: usize, primary_modifier_key_text: &str, ui_size: usize, ) { let widths = self.main_screen_widths(primary_modifier_key_text); if cols >= widths.0 { let title_text = "Override keybindings with one of the following presets:"; let left_padding = cols.saturating_sub(widths.0) / 2; print_text_with_coordinates( Text::new(title_text).color_range(2, ..), left_padding, (rows.saturating_sub(ui_size) / 2) + 1, None, None, ); } else { let title_text = "Override keybindings:"; let left_padding = if cols >= widths.1 { cols.saturating_sub(widths.1) / 2 } else { cols.saturating_sub(widths.2) / 2 }; print_text_with_coordinates( Text::new(title_text).color_range(2, ..), left_padding, (rows.saturating_sub(ui_size) / 2) + 1, None, None, ); } } fn render_help_text_main(&self, rows: usize, cols: usize) { let full_help_text = "Help: <↓↑> - navigate, <ENTER> - apply, <Ctrl a> - apply & save, <ESC> - close"; let short_help_text = "Help: <↓↑> / <ENTER> / <Ctrl a> / <ESC>"; if cols >= full_help_text.chars().count() { print_text_with_coordinates( Text::new(full_help_text) .color_range(2, 6..10) .color_range(2, 23..30) .color_range(2, 40..48)
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/configuration/src/ui_components.rs
default-plugins/configuration/src/ui_components.rs
use crate::{Screen, WIDTH_BREAKPOINTS}; use zellij_tile::prelude::*; pub fn top_tab_menu(cols: usize, current_screen: &Screen, colors: &Styling) { let background = colors.text_unselected.background; let bg_color = match background { PaletteColor::Rgb((r, g, b)) => format!("\u{1b}[48;2;{};{};{}m\u{1b}[0K", r, g, b), PaletteColor::EightBit(color) => format!("\u{1b}[48;5;{}m\u{1b}[0K", color), }; let first_ribbon_text_long = "Rebind leader keys"; let second_ribbon_text_long = "Change mode behavior"; let first_ribbon_text_short = "Rebind keys"; let second_ribbon_text_short = "Mode behavior"; let (first_ribbon_is_selected, second_ribbon_is_selected) = match current_screen { Screen::RebindLeaders(_) => (true, false), Screen::Presets(_) => (false, true), }; let (first_ribbon_text, second_ribbon_text, starting_positions) = if cols >= first_ribbon_text_long.chars().count() + second_ribbon_text_long.chars().count() + 14 { (first_ribbon_text_long, second_ribbon_text_long, (6, 28)) } else { (first_ribbon_text_short, second_ribbon_text_short, (6, 21)) }; let mut first_ribbon = Text::new(first_ribbon_text); let mut second_ribbon = Text::new(second_ribbon_text); if first_ribbon_is_selected { first_ribbon = first_ribbon.selected(); } if second_ribbon_is_selected { second_ribbon = second_ribbon.selected(); } let switch_key = Text::new("<TAB>").color_range(3, ..).opaque(); print_text_with_coordinates(switch_key, 0, 0, None, None); print!("\u{1b}[{};{}H{}", 0, starting_positions.0, bg_color); print_ribbon_with_coordinates(first_ribbon, starting_positions.0, 0, None, None); print_ribbon_with_coordinates(second_ribbon, starting_positions.1, 0, None, None); } pub fn back_to_presets() { let esc = Text::new("<ESC>").color_range(3, ..); let first_ribbon = Text::new("Back to Presets"); print_text_with_coordinates(esc, 0, 0, None, None); print_ribbon_with_coordinates(first_ribbon, 6, 0, None, None); } pub fn info_line( rows: usize, cols: usize, ui_size: usize, notification: &Option<String>, warning_text: &Option<String>, widths: Option<(usize, usize, usize)>, ) { let top_coordinates = if rows > 14 { (rows.saturating_sub(ui_size) / 2) + 14 } else { (rows.saturating_sub(ui_size) / 2) + 10 }; let left_padding = if let Some(widths) = widths { if cols >= widths.0 { cols.saturating_sub(widths.0) / 2 } else if cols >= widths.1 { cols.saturating_sub(widths.1) / 2 } else { cols.saturating_sub(widths.2) / 2 } } else { if cols >= WIDTH_BREAKPOINTS.0 { cols.saturating_sub(WIDTH_BREAKPOINTS.0) / 2 } else { cols.saturating_sub(WIDTH_BREAKPOINTS.1) / 2 } }; if let Some(notification) = &notification { print_text_with_coordinates( Text::new(notification).color_range(3, ..), left_padding, top_coordinates, None, None, ); } else if let Some(warning_text) = warning_text { print_text_with_coordinates( Text::new(warning_text).color_range(3, ..), left_padding, top_coordinates, None, None, ); } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/configuration/src/main.rs
default-plugins/configuration/src/main.rs
mod presets; mod presets_screen; mod rebind_leaders_screen; mod ui_components; use zellij_tile::prelude::*; use presets_screen::PresetsScreen; use rebind_leaders_screen::RebindLeadersScreen; use ui_components::top_tab_menu; use std::collections::BTreeMap; pub static UI_SIZE: usize = 15; pub static WIDTH_BREAKPOINTS: (usize, usize) = (62, 35); pub static POSSIBLE_MODIFIERS: [KeyModifier; 4] = [ KeyModifier::Ctrl, KeyModifier::Alt, KeyModifier::Super, KeyModifier::Shift, ]; #[derive(Debug)] enum Screen { RebindLeaders(RebindLeadersScreen), Presets(PresetsScreen), } impl Screen { pub fn reset_state(&mut self, is_setup_wizard: bool) { if is_setup_wizard { Screen::new_reset_keybindings_screen(Some(0)); } else { match self { Screen::RebindLeaders(r) => { let notification = r.drain_notification(); *r = Default::default(); r.set_notification(notification); }, Screen::Presets(r) => { let notification = r.drain_notification(); *r = Default::default(); r.set_notification(notification); }, } } } pub fn update_mode_info(&mut self, latest_mode_info: ModeInfo) { match self { Screen::RebindLeaders(r) => r.update_mode_info(latest_mode_info), Screen::Presets(r) => r.update_mode_info(latest_mode_info), } } } impl Default for Screen { fn default() -> Self { Screen::RebindLeaders(Default::default()) } } impl Screen { pub fn new_reset_keybindings_screen(selected_index: Option<usize>) -> Self { Screen::Presets(PresetsScreen::new(selected_index)) } } struct State { notification: Option<String>, is_setup_wizard: bool, ui_size: usize, current_screen: Screen, latest_mode_info: Option<ModeInfo>, colors: Styling, } impl Default for State { fn default() -> Self { State { notification: None, is_setup_wizard: false, ui_size: UI_SIZE, current_screen: Screen::default(), latest_mode_info: None, colors: Palette::default().into(), } } } register_plugin!(State); impl ZellijPlugin for State { fn load(&mut self, configuration: BTreeMap<String, String>) { self.is_setup_wizard = configuration .get("is_setup_wizard") .map(|v| v == "true") .unwrap_or(false); subscribe(&[ EventType::Key, EventType::FailedToWriteConfigToDisk, EventType::ModeUpdate, ]); let own_plugin_id = get_plugin_ids().plugin_id; if self.is_setup_wizard { self.ui_size = 18; self.current_screen = Screen::new_reset_keybindings_screen(Some(0)); rename_plugin_pane(own_plugin_id, "First Run Setup Wizard (Step 1/1)"); resize_focused_pane(Resize::Increase); resize_focused_pane(Resize::Increase); resize_focused_pane(Resize::Increase); } else { rename_plugin_pane(own_plugin_id, "Configuration"); } } fn update(&mut self, event: Event) -> bool { let mut should_render = false; match event { Event::ModeUpdate(mode_info) => { self.colors = mode_info.style.colors; if self.latest_mode_info.as_ref().and_then(|l| l.base_mode) != mode_info.base_mode { // reset ui state self.current_screen.reset_state(self.is_setup_wizard); } self.latest_mode_info = Some(mode_info.clone()); self.current_screen.update_mode_info(mode_info.clone()); should_render = true; }, Event::Key(key) => { if self.notification.is_some() { self.notification = None; should_render = true; } else if key.bare_key == BareKey::Tab && key.has_no_modifiers() && !self.is_setup_wizard { self.switch_screen(); should_render = true; } else { should_render = match &mut self.current_screen { Screen::RebindLeaders(rebind_leaders_screen) => { rebind_leaders_screen.handle_key(key) }, Screen::Presets(presets_screen) => { if self.is_setup_wizard { presets_screen.handle_setup_wizard_key(key) } else { presets_screen.handle_presets_key(key) } }, }; } }, Event::FailedToWriteConfigToDisk(config_file_path) => { match config_file_path { Some(failed_path) => { self.notification = Some(format!( "Failed to write configuration file: {}", failed_path )); }, None => { self.notification = Some(format!("Failed to write configuration file.")); }, } should_render = true; }, _ => (), }; should_render } fn render(&mut self, rows: usize, cols: usize) { let notification = self.notification.clone(); if self.is_in_main_screen() { top_tab_menu(cols, &self.current_screen, &self.colors); } match &mut self.current_screen { Screen::RebindLeaders(rebind_leaders_screen) => { rebind_leaders_screen.render(rows, cols, self.ui_size, &notification); }, Screen::Presets(presets_screen) => { if self.is_setup_wizard { presets_screen.render_setup_wizard_screen( rows, cols, self.ui_size, &notification, ) } else { presets_screen.render_reset_keybindings_screen( rows, cols, self.ui_size, &notification, ) } }, }; } } impl State { fn is_in_main_screen(&self) -> bool { match &self.current_screen { Screen::RebindLeaders(_) => true, Screen::Presets(presets_screen) => { if self.is_setup_wizard || presets_screen.rebinding_leaders() { false } else { true } }, } } fn switch_screen(&mut self) { match &self.current_screen { Screen::RebindLeaders(_) => { self.current_screen = Screen::Presets(Default::default()); }, Screen::Presets(_) => { self.current_screen = Screen::RebindLeaders( RebindLeadersScreen::default().with_mode_info(self.latest_mode_info.clone()), ); }, } if let Some(mode_info) = &self.latest_mode_info { self.current_screen.update_mode_info(mode_info.clone()); } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/multiple-select/src/main.rs
default-plugins/multiple-select/src/main.rs
use std::collections::BTreeMap; use std::time::Instant; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; #[derive(Debug, Default)] pub struct App { own_plugin_id: Option<u32>, own_client_id: Option<ClientId>, own_tab_index: Option<usize>, total_tabs_in_session: Option<usize>, grouped_panes: Vec<PaneId>, grouped_panes_count: usize, all_client_grouped_panes: BTreeMap<ClientId, Vec<PaneId>>, mode_info: ModeInfo, closing: bool, highlighted_at: Option<Instant>, baseline_ui_width: usize, current_rows: usize, current_cols: usize, display_area_rows: usize, display_area_cols: usize, alternate_coordinates: bool, } register_plugin!(App); impl ZellijPlugin for App { fn load(&mut self, _configuration: BTreeMap<String, String>) { subscribe(&[ EventType::Key, EventType::InterceptedKeyPress, EventType::ModeUpdate, EventType::PaneUpdate, EventType::TabUpdate, EventType::Timer, ]); let plugin_ids = get_plugin_ids(); self.own_plugin_id = Some(plugin_ids.plugin_id); self.own_client_id = Some(plugin_ids.client_id); intercept_key_presses(); set_selectable(false); } fn update(&mut self, event: Event) -> bool { if self.closing { return false; } intercept_key_presses(); // we do this here so that all clients (even those connected after // load) will have their keys intercepted match event { Event::ModeUpdate(mode_info) => self.handle_mode_update(mode_info), Event::PaneUpdate(pane_manifest) => self.handle_pane_update(pane_manifest), Event::TabUpdate(tab_infos) => self.handle_tab_update(tab_infos), Event::InterceptedKeyPress(key) => self.handle_key_press(key), Event::Timer(_) => self.handle_timer(), _ => false, } } fn render(&mut self, rows: usize, cols: usize) { self.update_current_size(rows, cols); if self.grouped_panes_count == 0 { self.render_no_panes_message(rows, cols); } else { let ui_width = self.calculate_ui_width(); self.update_baseline_ui_width(ui_width); let base_x = cols.saturating_sub(self.baseline_ui_width) / 2; let base_y = rows.saturating_sub(8) / 2; self.render_header(base_x, base_y); self.render_shortcuts(base_x, base_y + 2); self.render_controls(base_x, base_y + 7); } } } impl App { fn update_current_size(&mut self, new_rows: usize, new_cols: usize) { let size_changed = new_rows != self.current_rows || new_cols != self.current_cols; self.current_rows = new_rows; self.current_cols = new_cols; if size_changed { self.baseline_ui_width = 0; } } fn update_baseline_ui_width(&mut self, current_ui_width: usize) { if current_ui_width > self.baseline_ui_width { self.baseline_ui_width = current_ui_width; } } fn calculate_ui_width(&self) -> usize { let controls_width = group_controls_length(&self.mode_info); let header_width = Self::header_text().0.len(); let shortcuts_max_width = self.shortcuts_max_width(); std::cmp::max( controls_width, std::cmp::max(header_width, shortcuts_max_width), ) } fn render_no_panes_message(&self, rows: usize, cols: usize) { let message = "PANES SELECTED FOR OTHER CLIENT"; let message_component = Text::new(message).color_all(2); let base_x = cols.saturating_sub(message.len()) / 2; let base_y = rows / 2; print_text_with_coordinates(message_component, base_x, base_y, None, None); let esc_message = "<ESC> - close"; let esc_message_component = Text::new(esc_message).color_substring(3, "<ESC>"); let esc_base_x = cols.saturating_sub(esc_message.len()) / 2; let esc_base_y = base_y + 2; print_text_with_coordinates(esc_message_component, esc_base_x, esc_base_y, None, None); } fn header_text() -> (&'static str, Text) { let header_text = "<ESC> - cancel, <TAB> - move"; let header_text_component = Text::new(header_text) .color_substring(3, "<ESC>") .color_substring(3, "<TAB>"); (header_text, header_text_component) } fn shortcuts_max_width(&self) -> usize { std::cmp::max( std::cmp::max( self.group_actions_text().0.len(), Self::shortcuts_line1_text().0.len(), ), std::cmp::max( Self::shortcuts_line2_text().0.len(), Self::shortcuts_line3_text().0.len(), ), ) } fn group_actions_text(&self) -> (&'static str, Text) { let count_text = if self.grouped_panes_count == 1 { format!("GROUP ACTIONS ({} SELECTED PANE)", self.grouped_panes_count) } else { format!( "GROUP ACTIONS ({} SELECTED PANES)", self.grouped_panes_count ) }; let component = Text::new(&count_text).color_all(2); (Box::leak(count_text.into_boxed_str()), component) } fn shortcuts_line1_text() -> (&'static str, Text) { let text = "<b> - break out, <s> - stack, <c> - close"; let component = Text::new(text) .color_substring(3, "<b>") .color_substring(3, "<s>") .color_substring(3, "<c>"); (text, component) } fn shortcuts_line2_text() -> (&'static str, Text) { let text = "<l> - break left, <r> - break right"; let component = Text::new(text) .color_substring(3, "<l>") .color_substring(3, "<r>"); (text, component) } fn shortcuts_line3_text() -> (&'static str, Text) { let text = "<e> - embed, <f> - float"; let component = Text::new(text) .color_substring(3, "<e>") .color_substring(3, "<f>"); (text, component) } fn handle_mode_update(&mut self, mode_info: ModeInfo) -> bool { if self.mode_info != mode_info { self.mode_info = mode_info; let ui_width = self.calculate_ui_width(); self.update_baseline_ui_width(ui_width); true } else { false } } fn handle_pane_update(&mut self, pane_manifest: PaneManifest) -> bool { let Some(own_client_id) = self.own_client_id else { return false; }; self.update_all_client_grouped_panes(&pane_manifest); self.update_own_grouped_panes(&pane_manifest, own_client_id); self.update_tab_info(&pane_manifest); self.total_tabs_in_session = Some(pane_manifest.panes.keys().count()); true } fn handle_tab_update(&mut self, tab_infos: Vec<TabInfo>) -> bool { for tab in tab_infos { if tab.active { self.display_area_rows = tab.display_area_rows; self.display_area_cols = tab.display_area_columns; break; } } false } fn update_all_client_grouped_panes(&mut self, pane_manifest: &PaneManifest) { self.all_client_grouped_panes.clear(); for (_tab_index, pane_infos) in &pane_manifest.panes { for pane_info in pane_infos { for (client_id, _index_in_pane_group) in &pane_info.index_in_pane_group { let pane_id = if pane_info.is_plugin { PaneId::Plugin(pane_info.id) } else { PaneId::Terminal(pane_info.id) }; self.all_client_grouped_panes .entry(*client_id) .or_insert_with(Vec::new) .push(pane_id); } } } } fn update_own_grouped_panes(&mut self, pane_manifest: &PaneManifest, own_client_id: ClientId) { self.grouped_panes.clear(); let mut count = 0; let mut panes_with_index = Vec::new(); for (_tab_index, pane_infos) in &pane_manifest.panes { for pane_info in pane_infos { if let Some(index_in_pane_group) = pane_info.index_in_pane_group.get(&own_client_id) { let pane_id = if pane_info.is_plugin { PaneId::Plugin(pane_info.id) } else { PaneId::Terminal(pane_info.id) }; panes_with_index.push((*index_in_pane_group, pane_id)); count += 1; } } } panes_with_index.sort_by_key(|(index, _)| *index); for (_, pane_id) in panes_with_index { self.grouped_panes.push(pane_id); } if self.all_clients_have_empty_groups() { self.close_self(); } let previous_count = self.grouped_panes_count; self.grouped_panes_count = count; if let Some(own_plugin_id) = self.own_plugin_id { if previous_count != count { rename_plugin_pane(own_plugin_id, "Multiple Pane Select".to_string()); } if previous_count != 0 && count != 0 && previous_count != count { if self.doherty_threshold_elapsed_since_highlight() { self.highlighted_at = Some(Instant::now()); highlight_and_unhighlight_panes(vec![PaneId::Plugin(own_plugin_id)], vec![]); set_timeout(0.4); } } } } fn all_clients_have_empty_groups(&self) -> bool { self.all_client_grouped_panes .values() .all(|panes| panes.is_empty()) } fn doherty_threshold_elapsed_since_highlight(&self) -> bool { self.highlighted_at .map(|h| h.elapsed() >= std::time::Duration::from_millis(400)) .unwrap_or(true) } fn update_tab_info(&mut self, pane_manifest: &PaneManifest) { for (tab_index, pane_infos) in &pane_manifest.panes { for pane_info in pane_infos { if pane_info.is_plugin && Some(pane_info.id) == self.own_plugin_id { self.own_tab_index = Some(*tab_index); return; } } } } fn handle_key_press(&mut self, key: KeyWithModifier) -> bool { if !key.has_no_modifiers() { return false; } match key.bare_key { BareKey::Char('b') => self.break_grouped_panes_to_new_tab(), BareKey::Char('s') => self.stack_grouped_panes(), BareKey::Char('f') => self.float_grouped_panes(), BareKey::Char('e') => self.embed_grouped_panes(), BareKey::Char('r') => self.break_grouped_panes_right(), BareKey::Char('l') => self.break_grouped_panes_left(), BareKey::Char('c') => self.close_grouped_panes(), BareKey::Tab => self.next_coordinates(), BareKey::Esc => { self.ungroup_panes_in_zellij(); self.close_self(); }, _ => return false, } false } fn handle_timer(&mut self) -> bool { if let Some(own_plugin_id) = self.own_plugin_id { if self.doherty_threshold_elapsed_since_highlight() { highlight_and_unhighlight_panes(vec![], vec![PaneId::Plugin(own_plugin_id)]); } } false } fn render_header(&self, base_x: usize, base_y: usize) { let header_text = Self::header_text(); print_text_with_coordinates(header_text.1, base_x, base_y, None, None); } fn render_shortcuts(&self, base_x: usize, base_y: usize) { let mut running_y = base_y; print_text_with_coordinates(self.group_actions_text().1, base_x, running_y, None, None); running_y += 1; print_text_with_coordinates( Self::shortcuts_line1_text().1, base_x, running_y, None, None, ); running_y += 1; print_text_with_coordinates( Self::shortcuts_line2_text().1, base_x, running_y, None, None, ); running_y += 1; print_text_with_coordinates( Self::shortcuts_line3_text().1, base_x, running_y, None, None, ); } fn render_controls(&self, base_x: usize, base_y: usize) { render_group_controls(&self.mode_info, base_x, base_y); } fn execute_action_and_close<F>(&mut self, action: F) where F: FnOnce(&[PaneId]), { let pane_ids = self.grouped_panes.clone(); action(&pane_ids); self.close_self(); } pub fn break_grouped_panes_to_new_tab(&mut self) { self.execute_action_and_close(|pane_ids| { break_panes_to_new_tab(pane_ids, None, true); }); self.ungroup_panes_in_zellij(); } pub fn stack_grouped_panes(&mut self) { self.execute_action_and_close(|pane_ids| { stack_panes(pane_ids.to_vec()); }); self.ungroup_panes_in_zellij(); } pub fn float_grouped_panes(&mut self) { self.execute_action_and_close(|pane_ids| { float_multiple_panes(pane_ids.to_vec()); }); self.ungroup_panes_in_zellij(); } pub fn embed_grouped_panes(&mut self) { self.execute_action_and_close(|pane_ids| { embed_multiple_panes(pane_ids.to_vec()); }); self.ungroup_panes_in_zellij(); } pub fn break_grouped_panes_right(&mut self) { let Some(own_tab_index) = self.own_tab_index else { return; }; let pane_ids = self.grouped_panes.clone(); if Some(own_tab_index + 1) < self.total_tabs_in_session { break_panes_to_tab_with_index(&pane_ids, own_tab_index + 1, true); } else { break_panes_to_new_tab(&pane_ids, None, true); } self.close_self(); } pub fn break_grouped_panes_left(&mut self) { let Some(own_tab_index) = self.own_tab_index else { return; }; let pane_ids = self.grouped_panes.clone(); if own_tab_index > 0 { break_panes_to_tab_with_index(&pane_ids, own_tab_index.saturating_sub(1), true); } else { break_panes_to_new_tab(&pane_ids, None, true); } self.close_self(); } pub fn close_grouped_panes(&mut self) { self.execute_action_and_close(|pane_ids| { close_multiple_panes(pane_ids.to_vec()); }); } pub fn ungroup_panes_in_zellij(&mut self) { let all_grouped_panes: Vec<PaneId> = self .all_client_grouped_panes .values() .flat_map(|panes| panes.iter().cloned()) .collect(); let for_all_clients = true; group_and_ungroup_panes(vec![], all_grouped_panes, for_all_clients); } pub fn close_self(&mut self) { self.closing = true; close_self(); } pub fn next_coordinates(&mut self) { let width_30_percent = (self.display_area_cols as f64 * 0.3) as usize; let height_30_percent = (self.display_area_rows as f64 * 0.3) as usize; let width = std::cmp::max(width_30_percent, 48); let height = std::cmp::max(height_30_percent, 10); let y_position = self.display_area_rows.saturating_sub(height + 2); if let Some(own_plugin_id) = self.own_plugin_id { if self.alternate_coordinates { let x_position = 2; let Some(next_coordinates) = FloatingPaneCoordinates::new( Some(format!("{}", x_position)), Some(format!("{}", y_position)), Some(format!("{}", width)), Some(format!("{}", height)), Some(true), ) else { return; }; change_floating_panes_coordinates(vec![( PaneId::Plugin(own_plugin_id), next_coordinates, )]); self.alternate_coordinates = false; } else { let x_position = self .display_area_cols .saturating_sub(width) .saturating_sub(2); let Some(next_coordinates) = FloatingPaneCoordinates::new( Some(format!("{}", x_position)), Some(format!("{}", y_position)), Some(format!("{}", width)), Some(format!("{}", height)), Some(true), ) else { return; }; change_floating_panes_coordinates(vec![( PaneId::Plugin(own_plugin_id), next_coordinates, )]); self.alternate_coordinates = true; } } } } fn render_group_controls(mode_info: &ModeInfo, base_x: usize, base_y: usize) { let keymap = mode_info.get_mode_keybinds(); let (common_modifiers, pane_group_key, group_mark_key) = extract_key_bindings(&keymap); let pane_group_bound = pane_group_key != "UNBOUND"; let group_mark_bound = group_mark_key != "UNBOUND"; if !pane_group_bound && !group_mark_bound { return; } render_common_modifiers(&common_modifiers, base_x, base_y); let mut next_x = base_x + render_common_modifiers(&common_modifiers, base_x, base_y); if pane_group_bound { next_x = render_toggle_group_ribbon(&pane_group_key, next_x, base_y); } if group_mark_bound { render_follow_focus_ribbon(&group_mark_key, next_x, base_y, mode_info); } } fn group_controls_length(mode_info: &ModeInfo) -> usize { let keymap = mode_info.get_mode_keybinds(); let (common_modifiers, pane_group_key, group_mark_key) = extract_key_bindings(&keymap); let pane_group_bound = pane_group_key != "UNBOUND"; let group_mark_bound = group_mark_key != "UNBOUND"; let mut length = 0; if !common_modifiers.is_empty() { let modifiers_text = format!( "{} + ", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" ") ); length += modifiers_text.chars().count(); } if pane_group_bound { let toggle_text = format!("<{}> Toggle", pane_group_key); length += toggle_text.chars().count() + 4; } if group_mark_bound { let follow_text = format!("<{}> Follow Focus", group_mark_key); length += follow_text.chars().count() + 4; } length } fn extract_key_bindings( keymap: &[(KeyWithModifier, Vec<Action>)], ) -> (Vec<KeyModifier>, String, String) { let pane_group_keys = get_key_for_action(keymap, &[Action::TogglePaneInGroup]); let group_mark_keys = get_key_for_action(keymap, &[Action::ToggleGroupMarking]); let key_refs: Vec<&KeyWithModifier> = [pane_group_keys.first(), group_mark_keys.first()] .into_iter() .flatten() .collect(); let common_modifiers = get_common_modifiers(key_refs); let pane_group_key = format_key_without_modifiers(&pane_group_keys, &common_modifiers); let group_mark_key = format_key_without_modifiers(&group_mark_keys, &common_modifiers); (common_modifiers, pane_group_key, group_mark_key) } fn format_key_without_modifiers( keys: &[KeyWithModifier], common_modifiers: &[KeyModifier], ) -> String { keys.first() .map(|key| format!("{}", key.strip_common_modifiers(&common_modifiers.to_vec()))) .unwrap_or_else(|| "UNBOUND".to_string()) } fn render_common_modifiers( common_modifiers: &[KeyModifier], base_x: usize, base_y: usize, ) -> usize { if !common_modifiers.is_empty() { let modifiers_text = format!( "{} + ", common_modifiers .iter() .map(|m| m.to_string()) .collect::<Vec<_>>() .join(" ") ); print_text_with_coordinates( Text::new(&modifiers_text).color_all(0), base_x, base_y, None, None, ); modifiers_text.chars().count() } else { 0 } } fn get_key_for_action( keymap: &[(KeyWithModifier, Vec<Action>)], target_action: &[Action], ) -> Vec<KeyWithModifier> { keymap .iter() .find_map(|(key, actions)| { if actions.first() == target_action.first() { Some(key.clone()) } else { None } }) .map(|key| vec![key]) .unwrap_or_default() } fn get_common_modifiers(keys: Vec<&KeyWithModifier>) -> Vec<KeyModifier> { if keys.is_empty() { return vec![]; } let mut common = keys[0].key_modifiers.clone(); for key in keys.iter().skip(1) { common = common.intersection(&key.key_modifiers).cloned().collect(); } common.into_iter().collect() } fn render_follow_focus_ribbon( group_mark_key: &str, x_position: usize, base_y: usize, mode_info: &ModeInfo, ) { let follow_text = format!("<{}> Follow Focus", group_mark_key); let key_highlight = format!("{}", group_mark_key); let mut ribbon = Text::new(&follow_text).color_substring(0, &key_highlight); if mode_info.currently_marking_pane_group.unwrap_or(false) { ribbon = ribbon.selected(); } print_ribbon_with_coordinates(ribbon, x_position, base_y, None, None); } fn render_toggle_group_ribbon(pane_group_key: &str, base_x: usize, base_y: usize) -> usize { let toggle_text = format!("<{}> Toggle", pane_group_key); let key_highlight = format!("{}", pane_group_key); print_ribbon_with_coordinates( Text::new(&toggle_text).color_substring(0, &key_highlight), base_x, base_y, None, None, ); base_x + toggle_text.len() + 4 }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/fixture-plugin-for-tests/src/main.rs
default-plugins/fixture-plugin-for-tests/src/main.rs
use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[allow(unused_imports)] use std::io::prelude::*; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; // This is a fixture plugin used only for tests in Zellij // it is not (and should not!) be included in the mainline executable // it's included here for convenience so that it will be built by the CI #[allow(dead_code)] #[derive(Default)] struct State { received_events: Vec<Event>, received_payload: Option<String>, configuration: BTreeMap<String, String>, message_to_plugin_payload: Option<String>, } #[derive(Default, Serialize, Deserialize)] struct TestWorker { number_of_messages_received: usize, } impl<'de> ZellijWorker<'de> for TestWorker { fn on_message(&mut self, message: String, payload: String) { if message == "ping" { self.number_of_messages_received += 1; post_message_to_plugin(PluginMessage { worker_name: None, name: "pong".into(), payload: format!( "{}, received {} messages", payload, self.number_of_messages_received ), }); } } } #[cfg(target_family = "wasm")] register_plugin!(State); #[cfg(target_family = "wasm")] register_worker!(TestWorker, test_worker, TEST_WORKER); #[cfg(target_family = "wasm")] impl ZellijPlugin for State { fn load(&mut self, configuration: BTreeMap<String, String>) { request_permission(&[ PermissionType::ChangeApplicationState, PermissionType::ReadApplicationState, PermissionType::ReadApplicationState, PermissionType::ChangeApplicationState, PermissionType::OpenFiles, PermissionType::RunCommands, PermissionType::OpenTerminalsOrPlugins, PermissionType::WriteToStdin, PermissionType::WebAccess, PermissionType::ReadCliPipes, PermissionType::MessageAndLaunchOtherPlugins, PermissionType::Reconfigure, PermissionType::WriteToClipboard, PermissionType::RunActionsAsUser, ]); self.configuration = configuration; subscribe(&[ EventType::InputReceived, EventType::Key, EventType::SystemClipboardFailure, EventType::CustomMessage, EventType::FileSystemCreate, EventType::FileSystemUpdate, EventType::FileSystemDelete, EventType::BeforeClose, ]); watch_filesystem(); } fn update(&mut self, event: Event) -> bool { match &event { Event::Key(key) => match key.bare_key { BareKey::Char('a') if key.has_no_modifiers() => { switch_to_input_mode(&InputMode::Tab); }, BareKey::Char('b') if key.has_no_modifiers() => { new_tabs_with_layout( "layout { tab { pane pane } tab split_direction=\"vertical\" { pane pane } }", ); }, BareKey::Char('c') if key.has_no_modifiers() => { new_tab(Some("new_tab_name"), Some("/path/to/my/cwd")) }, BareKey::Char('d') if key.has_no_modifiers() => go_to_next_tab(), BareKey::Char('e') if key.has_no_modifiers() => go_to_previous_tab(), BareKey::Char('f') if key.has_no_modifiers() => { let resize = Resize::Increase; resize_focused_pane(resize) }, BareKey::Char('g') if key.has_no_modifiers() => { let resize = Resize::Increase; let direction = Direction::Left; resize_focused_pane_with_direction(resize, direction); }, BareKey::Char('h') if key.has_no_modifiers() => focus_next_pane(), BareKey::Char('i') if key.has_no_modifiers() => focus_previous_pane(), BareKey::Char('j') if key.has_no_modifiers() => { let direction = Direction::Left; move_focus(direction) }, BareKey::Char('k') if key.has_no_modifiers() => { let direction = Direction::Left; move_focus_or_tab(direction) }, BareKey::Char('l') if key.has_no_modifiers() => detach(), BareKey::Char('m') if key.has_no_modifiers() => edit_scrollback(), BareKey::Char('n') if key.has_no_modifiers() => { let bytes = vec![102, 111, 111]; write(bytes) }, BareKey::Char('o') if key.has_no_modifiers() => { let chars = "foo"; write_chars(chars); }, BareKey::Char('p') if key.has_no_modifiers() => toggle_tab(), BareKey::Char('q') if key.has_no_modifiers() => move_pane(), BareKey::Char('r') if key.has_no_modifiers() => { let direction = Direction::Left; move_pane_with_direction(direction) }, BareKey::Char('s') if key.has_no_modifiers() => clear_screen(), BareKey::Char('t') if key.has_no_modifiers() => scroll_up(), BareKey::Char('u') if key.has_no_modifiers() => scroll_down(), BareKey::Char('v') if key.has_no_modifiers() => scroll_to_top(), BareKey::Char('w') if key.has_no_modifiers() => scroll_to_bottom(), BareKey::Char('x') if key.has_no_modifiers() => page_scroll_up(), BareKey::Char('y') if key.has_no_modifiers() => page_scroll_down(), BareKey::Char('z') if key.has_no_modifiers() => toggle_focus_fullscreen(), BareKey::Char('1') if key.has_no_modifiers() => toggle_pane_frames(), BareKey::Char('2') if key.has_no_modifiers() => toggle_pane_embed_or_eject(), BareKey::Char('3') if key.has_no_modifiers() => undo_rename_pane(), BareKey::Char('4') if key.has_no_modifiers() => close_focus(), BareKey::Char('5') if key.has_no_modifiers() => toggle_active_tab_sync(), BareKey::Char('6') if key.has_no_modifiers() => close_focused_tab(), BareKey::Char('7') if key.has_no_modifiers() => undo_rename_tab(), BareKey::Char('8') if key.has_no_modifiers() => quit_zellij(), BareKey::Char('a') if key.has_modifiers(&[KeyModifier::Ctrl]) => { previous_swap_layout() }, BareKey::Char('b') if key.has_modifiers(&[KeyModifier::Ctrl]) => next_swap_layout(), BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let tab_name = "my tab name"; go_to_tab_name(tab_name) }, BareKey::Char('d') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let tab_name = "my tab name"; focus_or_create_tab(tab_name) }, BareKey::Char('e') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let tab_index = 2; go_to_tab(tab_index) }, BareKey::Char('f') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let plugin_url = "file:/path/to/my/plugin.wasm"; start_or_reload_plugin(plugin_url) }, BareKey::Char('g') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_file( FileToOpen { path: std::path::PathBuf::from("/path/to/my/file.rs"), ..Default::default() }, BTreeMap::new(), ); }, BareKey::Char('h') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_file_floating( FileToOpen { path: std::path::PathBuf::from("/path/to/my/file.rs"), ..Default::default() }, None, BTreeMap::new(), ); }, BareKey::Char('i') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_file( FileToOpen { path: std::path::PathBuf::from("/path/to/my/file.rs"), line_number: Some(42), ..Default::default() }, BTreeMap::new(), ); }, BareKey::Char('j') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_file_floating( FileToOpen { path: std::path::PathBuf::from("/path/to/my/file.rs"), line_number: Some(42), ..Default::default() }, None, BTreeMap::new(), ); }, BareKey::Char('k') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_terminal(std::path::PathBuf::from("/path/to/my/file.rs").as_path()); }, BareKey::Char('l') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_terminal_floating( std::path::PathBuf::from("/path/to/my/file.rs").as_path(), None, ); }, BareKey::Char('m') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_command_pane( CommandToRun { path: std::path::PathBuf::from("/path/to/my/file.rs"), args: vec!["arg1".to_owned(), "arg2".to_owned()], ..Default::default() }, BTreeMap::new(), ); }, BareKey::Char('n') if key.has_modifiers(&[KeyModifier::Ctrl]) => { open_command_pane_floating( CommandToRun { path: std::path::PathBuf::from("/path/to/my/file.rs"), args: vec!["arg1".to_owned(), "arg2".to_owned()], ..Default::default() }, None, BTreeMap::new(), ); }, BareKey::Char('o') if key.has_modifiers(&[KeyModifier::Ctrl]) => { switch_tab_to(1); }, BareKey::Char('p') if key.has_modifiers(&[KeyModifier::Ctrl]) => { hide_self(); }, BareKey::Char('q') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let should_float_if_hidden = false; show_self(should_float_if_hidden); }, BareKey::Char('r') if key.has_modifiers(&[KeyModifier::Ctrl]) => { close_terminal_pane(1); }, BareKey::Char('s') if key.has_modifiers(&[KeyModifier::Ctrl]) => { close_plugin_pane(1); }, BareKey::Char('t') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let should_float_if_hidden = false; let should_be_in_place_if_hidden = false; focus_terminal_pane(1, should_float_if_hidden, should_be_in_place_if_hidden); }, BareKey::Char('u') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let should_float_if_hidden = false; let should_be_in_place_if_hidden = false; focus_plugin_pane(1, should_float_if_hidden, should_be_in_place_if_hidden); }, BareKey::Char('v') if key.has_modifiers(&[KeyModifier::Ctrl]) => { rename_terminal_pane(1, "new terminal_pane_name"); }, BareKey::Char('w') if key.has_modifiers(&[KeyModifier::Ctrl]) => { rename_plugin_pane(1, "new plugin_pane_name"); }, BareKey::Char('x') if key.has_modifiers(&[KeyModifier::Ctrl]) => { rename_tab(1, "new tab name"); }, BareKey::Char('z') if key.has_modifiers(&[KeyModifier::Ctrl]) => { go_to_tab_name(&format!("{:?}", self.configuration)); }, BareKey::Char('1') if key.has_modifiers(&[KeyModifier::Ctrl]) => { request_permission(&[PermissionType::ReadApplicationState]); }, BareKey::Char('2') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let mut context = BTreeMap::new(); context.insert("user_key_1".to_owned(), "user_value_1".to_owned()); run_command(&["ls", "-l"], context); }, BareKey::Char('3') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let mut context = BTreeMap::new(); context.insert("user_key_2".to_owned(), "user_value_2".to_owned()); let mut env_vars = BTreeMap::new(); env_vars.insert("VAR1".to_owned(), "some_value".to_owned()); run_command_with_env_variables_and_cwd( &["ls", "-l"], env_vars, std::path::PathBuf::from("/some/custom/folder"), context, ); }, BareKey::Char('4') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let mut headers = BTreeMap::new(); let mut context = BTreeMap::new(); let body = vec![1, 2, 3]; headers.insert("header1".to_owned(), "value1".to_owned()); headers.insert("header2".to_owned(), "value2".to_owned()); context.insert("user_key_1".to_owned(), "user_value1".to_owned()); context.insert("user_key_2".to_owned(), "user_value2".to_owned()); web_request( "https://example.com/foo?arg1=val1&arg2=val2", HttpVerb::Post, headers, body, context, ); }, BareKey::Char('5') if key.has_modifiers(&[KeyModifier::Ctrl]) => { switch_session(Some("my_new_session")); }, BareKey::Char('6') if key.has_modifiers(&[KeyModifier::Ctrl]) => { disconnect_other_clients() }, BareKey::Char('7') if key.has_modifiers(&[KeyModifier::Ctrl]) => { switch_session_with_layout( Some("my_other_new_session"), LayoutInfo::BuiltIn("compact".to_owned()), None, ); }, BareKey::Char('8') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let mut file = std::fs::File::create("/host/hi-from-plugin.txt").unwrap(); file.write_all(b"Hi there!").unwrap(); }, BareKey::Char('9') if key.has_modifiers(&[KeyModifier::Ctrl]) => { switch_session_with_layout( Some("my_other_new_session_with_cwd"), LayoutInfo::BuiltIn("compact".to_owned()), Some(std::path::PathBuf::from("/tmp")), ); }, BareKey::Char('0') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let write_to_disk = true; reconfigure( " keybinds { locked { bind \"a\" { NewTab; } } } " .to_owned(), write_to_disk, ); }, BareKey::Char('a') if key.has_modifiers(&[KeyModifier::Alt]) => { hide_pane_with_id(PaneId::Terminal(1)); }, BareKey::Char('b') if key.has_modifiers(&[KeyModifier::Alt]) => { show_pane_with_id(PaneId::Terminal(1), true, true); }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Alt]) => { open_command_pane_background( CommandToRun { path: std::path::PathBuf::from("/path/to/my/file.rs"), args: vec!["arg1".to_owned(), "arg2".to_owned()], ..Default::default() }, BTreeMap::new(), ); }, BareKey::Char('d') if key.has_modifiers(&[KeyModifier::Alt]) => { rerun_command_pane(1); }, BareKey::Char('e') if key.has_modifiers(&[KeyModifier::Alt]) => { resize_pane_with_id( ResizeStrategy::new(Resize::Increase, Some(Direction::Left)), PaneId::Terminal(2), ); }, BareKey::Char('f') if key.has_modifiers(&[KeyModifier::Alt]) => { edit_scrollback_for_pane_with_id(PaneId::Terminal(2)); }, BareKey::Char('g') if key.has_modifiers(&[KeyModifier::Alt]) => { write_to_pane_id(vec![102, 111, 111], PaneId::Terminal(2)); }, BareKey::Char('h') if key.has_modifiers(&[KeyModifier::Alt]) => { write_chars_to_pane_id("foo\n", PaneId::Terminal(2)); }, BareKey::Char('i') if key.has_modifiers(&[KeyModifier::Alt]) => { move_pane_with_pane_id(PaneId::Terminal(2)); }, BareKey::Char('j') if key.has_modifiers(&[KeyModifier::Alt]) => { move_pane_with_pane_id_in_direction(PaneId::Terminal(2), Direction::Left); }, BareKey::Char('k') if key.has_modifiers(&[KeyModifier::Alt]) => { clear_screen_for_pane_id(PaneId::Terminal(2)); }, BareKey::Char('l') if key.has_modifiers(&[KeyModifier::Alt]) => { scroll_up_in_pane_id(PaneId::Terminal(2)); }, BareKey::Char('m') if key.has_modifiers(&[KeyModifier::Alt]) => { scroll_down_in_pane_id(PaneId::Terminal(2)); }, BareKey::Char('n') if key.has_modifiers(&[KeyModifier::Alt]) => { scroll_to_top_in_pane_id(PaneId::Terminal(2)); }, BareKey::Char('o') if key.has_modifiers(&[KeyModifier::Alt]) => { scroll_to_bottom_in_pane_id(PaneId::Terminal(2)); }, BareKey::Char('p') if key.has_modifiers(&[KeyModifier::Alt]) => { page_scroll_up_in_pane_id(PaneId::Terminal(2)); }, BareKey::Char('q') if key.has_modifiers(&[KeyModifier::Alt]) => { page_scroll_down_in_pane_id(PaneId::Terminal(2)); }, BareKey::Char('r') if key.has_modifiers(&[KeyModifier::Alt]) => { toggle_pane_id_fullscreen(PaneId::Terminal(2)); }, BareKey::Char('s') if key.has_modifiers(&[KeyModifier::Alt]) => { toggle_pane_embed_or_eject_for_pane_id(PaneId::Terminal(2)); }, BareKey::Char('t') if key.has_modifiers(&[KeyModifier::Alt]) => { close_tab_with_index(2); }, BareKey::Char('u') if key.has_modifiers(&[KeyModifier::Alt]) => { let should_change_focus_to_new_tab = true; break_panes_to_new_tab( &[PaneId::Terminal(1), PaneId::Plugin(2)], Some("new_tab_name".to_owned()), should_change_focus_to_new_tab, ); }, BareKey::Char('v') if key.has_modifiers(&[KeyModifier::Alt]) => { let should_change_focus_to_target_tab = true; break_panes_to_tab_with_index( &[PaneId::Terminal(1), PaneId::Plugin(2)], 2, should_change_focus_to_target_tab, ); }, BareKey::Char('w') if key.has_modifiers(&[KeyModifier::Alt]) => { reload_plugin_with_id(0); }, BareKey::Char('x') if key.has_modifiers(&[KeyModifier::Alt]) => { let config = BTreeMap::new(); let load_in_background = true; let skip_plugin_cache = true; load_new_plugin( "zellij:OWN_URL", config, load_in_background, skip_plugin_cache, ) }, BareKey::Char('y') if key.has_modifiers(&[KeyModifier::Alt]) => { let write_to_disk = true; let keys_to_unbind = vec![ ( InputMode::Locked, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Normal, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Pane, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Tab, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Resize, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Move, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Search, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ( InputMode::Session, KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(), ), ]; let keys_to_rebind = vec![ ( InputMode::Locked, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Normal, }], ), ( InputMode::Normal, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ( InputMode::Pane, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ( InputMode::Tab, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ( InputMode::Resize, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ( InputMode::Move, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ( InputMode::Search, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ( InputMode::Session, KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier(), vec![actions::Action::SwitchToMode { input_mode: InputMode::Locked, }], ), ]; rebind_keys(keys_to_unbind, keys_to_rebind, write_to_disk); }, BareKey::Char('z') if key.has_modifiers(&[KeyModifier::Alt]) => { list_clients(); }, BareKey::Char('a') if key.has_modifiers(&[KeyModifier::Super]) => { // Test show_cursor with coordinates show_cursor(Some((5, 10))); }, BareKey::Char('b') if key.has_modifiers(&[KeyModifier::Super]) => { // Test hide_cursor show_cursor(None); }, BareKey::Char('c') if key.has_modifiers(&[KeyModifier::Super]) => { // Test copy_to_clipboard copy_to_clipboard("test clipboard text"); }, BareKey::Char('d') if key.has_modifiers(&[KeyModifier::Super]) => { // Test run_action with MoveFocus let mut context = BTreeMap::new(); context.insert("test_key".to_string(), "test_value".to_string()); run_action( Action::MoveFocus { direction: Direction::Left, }, context, ); }, BareKey::Char('e') if key.has_modifiers(&[KeyModifier::Super]) => { // Test send_sigint_to_pane_id send_sigint_to_pane_id(PaneId::Terminal(1)); }, BareKey::Char('f') if key.has_modifiers(&[KeyModifier::Super]) => { // Test send_sigkill_to_pane_id send_sigkill_to_pane_id(PaneId::Terminal(1)); }, _ => {}, }, Event::CustomMessage(message, payload) => { if message == "pong" { self.received_payload = Some(payload.clone()); } }, Event::BeforeClose => { // this is just to assert something to make sure this event was triggered highlight_and_unhighlight_panes(vec![PaneId::Terminal(1)], vec![PaneId::Plugin(1)]); }, Event::SystemClipboardFailure => { // this is just to trigger the worker message post_message_to(PluginMessage { worker_name: Some("test".into()), name: "ping".into(), payload: "gimme_back_my_payload".into(), }); }, _ => {}, } let should_render = true; self.received_events.push(event); should_render } fn pipe(&mut self, pipe_message: PipeMessage) -> bool { let input_pipe_id = match pipe_message.source { PipeSource::Cli(id) => id.clone(), PipeSource::Plugin(id) => format!("{}", id), PipeSource::Keybind => format!("keybind"), }; let name = pipe_message.name; let payload = pipe_message.payload; if name == "message_name" && payload == Some("message_payload".to_owned()) { unblock_cli_pipe_input(&input_pipe_id); } else if name == "message_name_block" { block_cli_pipe_input(&input_pipe_id); } else if name == "pipe_output" { cli_pipe_output(&name, "this_is_my_output"); } else if name == "pipe_message_to_plugin" { pipe_message_to_plugin( MessageToPlugin::new("message_to_plugin").with_payload("my_cool_payload"), ); } else if name == "message_to_plugin" { self.message_to_plugin_payload = payload.clone(); } let should_render = true; should_render } fn render(&mut self, rows: usize, cols: usize) { if let Some(payload) = self.received_payload.as_ref() { println!("Payload from worker: {:?}", payload); } else if let Some(payload) = self.message_to_plugin_payload.take() { println!("Payload from self: {:?}", payload); } else { println!( "Rows: {:?}, Cols: {:?}, Received events: {:?}", rows, cols, self.received_events ); } } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/plugin-manager/src/main.rs
default-plugins/plugin-manager/src/main.rs
use fuzzy_matcher::skim::SkimMatcherV2; use fuzzy_matcher::FuzzyMatcher; use uuid::Uuid; use zellij_tile::prelude::*; use std::collections::{BTreeMap, HashMap}; pub struct SearchResult { plugin_id: u32, plugin_info: PluginInfo, indices: Vec<usize>, score: i64, } impl SearchResult { pub fn new(plugin_id: u32, plugin_info: &PluginInfo, indices: Vec<usize>, score: i64) -> Self { SearchResult { plugin_id, plugin_info: plugin_info.clone(), indices, score, } } } pub struct NewPluginScreen { new_plugin_url: String, new_plugin_config: Vec<(String, String)>, // key/val for easy in-place manipulation new_config_key: String, new_config_val: String, entering_plugin_url: bool, entering_config_key: bool, entering_config_val: bool, selected_config_index: Option<usize>, request_ids: Vec<String>, load_in_background: bool, colors: Styling, } impl Default for NewPluginScreen { fn default() -> Self { NewPluginScreen { new_plugin_url: String::new(), new_plugin_config: vec![], new_config_key: String::new(), new_config_val: String::new(), entering_plugin_url: true, entering_config_key: false, entering_config_val: false, selected_config_index: None, request_ids: vec![], load_in_background: false, colors: Palette::default().into(), } } } impl NewPluginScreen { pub fn new(colors: Styling) -> Self { Self { colors, ..Default::default() } } pub fn render(&self, rows: usize, cols: usize) { self.render_title(cols); self.render_url_field(cols); self.render_configuration_title(); let config_list_len = self.render_config_list(cols, rows.saturating_sub(10)); // 10 - the rest self.render_background_toggle(6 + config_list_len + 1); if !self.editing_configuration() { self.render_help(rows); } } fn render_title(&self, cols: usize) { let title_text = format!("LOAD NEW PLUGIN"); let title_text_len = title_text.chars().count(); let title = Text::new(title_text); print_text_with_coordinates( title, (cols / 2).saturating_sub(title_text_len / 2), 0, None, None, ); } fn render_url_field(&self, cols: usize) { let url_field = if self.entering_plugin_url { let truncated_url = truncate_string_start(&self.new_plugin_url, cols.saturating_sub(19)); // 17 the length of the prompt + 2 for padding and cursor let text = format!("Enter Plugin URL: {}_", truncated_url); Text::new(text).color_range(2, ..=16).color_range(3, 18..) } else { let truncated_url = truncate_string_start(&self.new_plugin_url, cols.saturating_sub(18)); // 17 the length of the prompt + 1 for padding let text = format!("Enter Plugin URL: {}", truncated_url); Text::new(text).color_range(2, ..=16).color_range(0, 18..) }; print_text_with_coordinates(url_field, 0, 2, None, None); let url_helper = NestedListItem::new(format!("<Ctrl f> - Load from Disk")).color_range(3, ..=8); print_nested_list_with_coordinates(vec![url_helper], 0, 3, None, None); } fn render_configuration_title(&self) { let configuration_title = if !self.editing_configuration() && self.new_plugin_config.is_empty() { Text::new(format!("Plugin Configuration: <TAB> - Edit")) .color_range(2, ..=20) .color_range(3, 22..=26) } else if !self.editing_configuration() { Text::new(format!( "Plugin Configuration: <TAB> - Edit, <↓↑> - Navigate, <Del> - Delete" )) .color_range(2, ..=20) .color_range(3, 22..=26) .color_range(3, 36..=39) .color_range(3, 53..=57) } else { Text::new(format!( "Plugin Configuration: [Editing: <TAB> - Next, <ENTER> - Accept]" )) .color_range(2, ..=20) .color_range(3, 32..=36) .color_range(3, 46..=52) }; print_text_with_coordinates(configuration_title, 0, 5, None, None); } fn editing_configuration(&self) -> bool { self.entering_config_key || self.entering_config_val } fn render_config_list(&self, cols: usize, rows: usize) -> usize { let mut items = vec![]; let mut more_config_items = 0; for (i, (config_key, config_val)) in self.new_plugin_config.iter().enumerate() { let is_selected = Some(i) == self.selected_config_index; if i >= rows { more_config_items += 1; } else if is_selected && self.editing_config_line() { items.push(self.render_editing_config_line(config_key, config_val, cols)); } else { items.push(self.render_config_line(config_key, config_val, is_selected, cols)); } } if self.editing_new_config_line() { items.push(self.render_editing_config_line( &self.new_config_key, &self.new_config_val, cols, )); } else if items.is_empty() { items.push(NestedListItem::new("<NO CONFIGURATION>").color_range(0, ..)); } let config_list_len = items.len(); print_nested_list_with_coordinates(items, 0, 6, Some(cols), None); if more_config_items > 0 { let more_text = format!("[+{}]", more_config_items); print_text_with_coordinates( Text::new(more_text).color_range(1, ..), 0, 6 + config_list_len, None, None, ); } config_list_len } fn editing_config_line(&self) -> bool { self.entering_config_key || self.entering_config_val } fn editing_new_config_line(&self) -> bool { (self.entering_config_key || self.entering_config_val) && self.selected_config_index.is_none() } fn render_editing_config_line( &self, config_key: &str, config_val: &str, config_line_max_len: usize, ) -> NestedListItem { let config_line_max_len = config_line_max_len.saturating_sub(6); // 3 - line padding, 1 - // cursor, 2 ": " let config_key_max_len = config_line_max_len / 2; let config_val_max_len = config_line_max_len.saturating_sub(config_key_max_len); let config_key = if config_key.chars().count() > config_key_max_len { truncate_string_start(&config_key, config_key_max_len) } else { config_key.to_owned() }; let config_val = if config_val.chars().count() > config_val_max_len { truncate_string_start(&config_val, config_val_max_len) } else { config_val.to_owned() }; if self.entering_config_key { let val = if config_val.is_empty() { "<EMPTY>".to_owned() } else { config_val }; NestedListItem::new(format!("{}_: {}", config_key, val)) .color_range(3, ..=config_key.chars().count()) .color_range(1, config_key.chars().count() + 3..) } else { let key = if config_key.is_empty() { "<EMPTY>".to_owned() } else { config_key }; NestedListItem::new(format!("{}: {}_", key, config_val)) .color_range(0, ..key.chars().count()) .color_range(3, key.chars().count() + 2..) } } fn render_config_line( &self, config_key: &str, config_val: &str, is_selected: bool, config_line_max_len: usize, ) -> NestedListItem { let config_line_max_len = config_line_max_len.saturating_sub(5); // 3 - line padding, // 2 - ": " let config_key = if config_key.is_empty() { "<EMPTY>" } else { config_key }; let config_val = if config_val.is_empty() { "<EMPTY>" } else { config_val }; let config_key_max_len = config_line_max_len / 2; let config_val_max_len = config_line_max_len.saturating_sub(config_key_max_len); let config_key = if config_key.chars().count() > config_key_max_len { truncate_string_start(&config_key, config_key_max_len) } else { config_key.to_owned() }; let config_val = if config_val.chars().count() > config_val_max_len { truncate_string_start(&config_val, config_val_max_len) } else { config_val.to_owned() }; let mut item = NestedListItem::new(format!("{}: {}", config_key, config_val)) .color_range(0, ..config_key.chars().count()) .color_range(1, config_key.chars().count() + 2..); if is_selected { item = item.selected() } item } fn render_background_toggle(&self, y_coordinates: usize) { let key_shortcuts_text = format!("Ctrl l"); print_text_with_coordinates( Text::new(&key_shortcuts_text).color_range(3, ..).opaque(), 0, y_coordinates, None, None, ); let background = self.colors.text_unselected.background; let bg_color = match background { PaletteColor::Rgb((r, g, b)) => format!("\u{1b}[48;2;{};{};{}m\u{1b}[0K", r, g, b), PaletteColor::EightBit(color) => format!("\u{1b}[48;5;{}m\u{1b}[0K", color), }; println!( "\u{1b}[{};{}H{}", y_coordinates + 1, key_shortcuts_text.chars().count() + 1, bg_color ); let load_in_background_text = format!("Load in Background"); let load_in_foreground_text = format!("Load in Foreground"); let (load_in_background_ribbon, load_in_foreground_ribbon) = if self.load_in_background { ( Text::new(&load_in_background_text).selected(), Text::new(&load_in_foreground_text), ) } else { ( Text::new(&load_in_background_text), Text::new(&load_in_foreground_text).selected(), ) }; print_ribbon_with_coordinates( load_in_background_ribbon, key_shortcuts_text.chars().count() + 1, y_coordinates, None, None, ); print_ribbon_with_coordinates( load_in_foreground_ribbon, key_shortcuts_text.chars().count() + 1 + load_in_background_text.chars().count() + 4, y_coordinates, None, None, ); } fn render_help(&self, rows: usize) { let enter_line = Text::new(format!( "Help: <ENTER> - Accept and Load Plugin, <ESC> - Cancel" )) .color_range(3, 6..=12) .color_range(3, 40..=44); print_text_with_coordinates(enter_line, 0, rows, None, None); } fn get_field_being_edited_mut(&mut self) -> Option<&mut String> { if self.entering_plugin_url { Some(&mut self.new_plugin_url) } else { match self.selected_config_index { Some(selected_config_index) => { if self.entering_config_key { self.new_plugin_config .get_mut(selected_config_index) .map(|(key, _val)| key) } else if self.entering_config_val { self.new_plugin_config .get_mut(selected_config_index) .map(|(_key, val)| val) } else { None } }, None => { if self.entering_config_key { Some(&mut self.new_config_key) } else if self.entering_config_val { Some(&mut self.new_config_val) } else { None } }, } } } fn add_edit_buffer_to_config(&mut self) { if !self.new_config_key.is_empty() || !self.new_config_val.is_empty() { self.new_plugin_config.push(( self.new_config_key.drain(..).collect(), self.new_config_val.drain(..).collect(), )); } } pub fn handle_key(&mut self, key: KeyWithModifier) -> (bool, bool) { let (mut should_render, mut should_close) = (false, false); match key.bare_key { BareKey::Char(character) if key.has_no_modifiers() => { if let Some(field) = self.get_field_being_edited_mut() { field.push(character); } should_render = true; }, BareKey::Backspace if key.has_no_modifiers() => { if let Some(field) = self.get_field_being_edited_mut() { field.pop(); } should_render = true; }, BareKey::Enter if key.has_no_modifiers() => { if self.editing_configuration() { self.add_edit_buffer_to_config(); self.entering_config_key = false; self.entering_config_val = false; self.entering_plugin_url = true; should_render = true; } else { let plugin_url: String = self.new_plugin_url.drain(..).collect(); self.add_edit_buffer_to_config(); let config = self.new_plugin_config.drain(..).into_iter().collect(); let load_in_background = self.load_in_background; let skip_plugin_cache = true; load_new_plugin(plugin_url, config, load_in_background, skip_plugin_cache); should_render = true; should_close = true; } }, BareKey::Tab if key.has_no_modifiers() => { if self.entering_plugin_url { self.entering_plugin_url = false; self.entering_config_key = true; } else if self.entering_config_key { self.entering_config_key = false; self.entering_config_val = true; } else if self.entering_config_val { self.entering_config_val = false; if self.selected_config_index.is_none() { // new config, add it to the map self.add_edit_buffer_to_config(); self.entering_config_key = true; } else { self.entering_plugin_url = true; } self.selected_config_index = None; } else if self.selected_config_index.is_some() { self.entering_config_key = true; } else { self.entering_plugin_url = true; } should_render = true; }, BareKey::Esc if key.has_no_modifiers() => { if self.entering_config_key || self.entering_config_val || self.selected_config_index.is_some() { self.entering_plugin_url = true; self.entering_config_key = false; self.entering_config_val = false; self.selected_config_index = None; self.add_edit_buffer_to_config(); should_render = true; } else { should_close = true; } }, BareKey::Down if key.has_no_modifiers() => { if !self.editing_configuration() { let max_len = self.new_plugin_config.len().saturating_sub(1); let has_config_values = !self.new_plugin_config.is_empty(); if self.selected_config_index.is_none() && has_config_values { self.selected_config_index = Some(0); } else if self.selected_config_index == Some(max_len) { self.selected_config_index = None; } else { self.selected_config_index = self.selected_config_index.map(|s| s + 1); } } should_render = true; }, BareKey::Up if key.has_no_modifiers() => { if !self.editing_configuration() { let max_len = self.new_plugin_config.len().saturating_sub(1); let has_config_values = !self.new_plugin_config.is_empty(); if self.selected_config_index.is_none() && has_config_values { self.selected_config_index = Some(max_len); } else if self.selected_config_index == Some(0) { self.selected_config_index = None; } else { self.selected_config_index = self.selected_config_index.map(|s| s.saturating_sub(1)); } } should_render = true; }, BareKey::Delete if key.has_no_modifiers() => { if let Some(selected_config_index) = self.selected_config_index.take() { self.new_plugin_config.remove(selected_config_index); should_render = true; } }, BareKey::Char('f') if key.has_modifiers(&[KeyModifier::Ctrl]) => { let mut args = BTreeMap::new(); let request_id = Uuid::new_v4(); self.request_ids.push(request_id.to_string()); let mut config = BTreeMap::new(); config.insert("request_id".to_owned(), request_id.to_string()); args.insert("request_id".to_owned(), request_id.to_string()); pipe_message_to_plugin( MessageToPlugin::new("filepicker") .with_plugin_url("filepicker") .with_plugin_config(config) .new_plugin_instance_should_have_pane_title( "Select a .wasm file to load as a plugin...", ) .new_plugin_instance_should_be_focused() .with_args(args), ); }, BareKey::Char('l') if key.has_modifiers(&[KeyModifier::Ctrl]) => { self.load_in_background = !self.load_in_background; should_render = true; }, _ => {}, } (should_render, should_close) } } #[derive(Default)] struct State { userspace_configuration: BTreeMap<String, String>, plugins: BTreeMap<u32, PluginInfo>, search_results: Vec<SearchResult>, selected_index: Option<usize>, expanded_indices: Vec<usize>, tab_position_to_tab_name: HashMap<usize, String>, plugin_id_to_tab_position: HashMap<u32, usize>, search_term: String, new_plugin_screen: Option<NewPluginScreen>, colors: Styling, } register_plugin!(State); impl ZellijPlugin for State { fn load(&mut self, configuration: BTreeMap<String, String>) { self.userspace_configuration = configuration; subscribe(&[ EventType::ModeUpdate, EventType::PaneUpdate, EventType::TabUpdate, EventType::Key, EventType::SessionUpdate, ]); let own_plugin_id = get_plugin_ids().plugin_id; rename_plugin_pane(own_plugin_id, "Plugin Manager"); } fn pipe(&mut self, pipe_message: PipeMessage) -> bool { if pipe_message.name == "filepicker_result" { match (pipe_message.payload, pipe_message.args.get("request_id")) { (Some(payload), Some(request_id)) => { match self .new_plugin_screen .as_mut() .and_then(|n| n.request_ids.iter().position(|p| p == request_id)) { Some(request_id_position) => { self.new_plugin_screen .as_mut() .map(|n| n.request_ids.remove(request_id_position)); let chosen_plugin_location = std::path::PathBuf::from(payload); self.new_plugin_screen.as_mut().map(|n| { n.new_plugin_url = format!("file:{}", chosen_plugin_location.display()) }); }, None => { eprintln!("request id not found"); }, } }, _ => {}, } true } else { false } } fn update(&mut self, event: Event) -> bool { let mut should_render = false; match event { Event::ModeUpdate(mode_info) => { self.colors = mode_info.style.colors; should_render = true; }, Event::SessionUpdate(live_sessions, _dead_sessions) => { for session in live_sessions { if session.is_current_session { if session.plugins != self.plugins { self.plugins = session.plugins; self.reset_selection(); self.update_search_term(); } for tab in session.tabs { self.tab_position_to_tab_name.insert(tab.position, tab.name); } } } should_render = true; }, Event::PaneUpdate(pane_manifest) => { for (tab_position, panes) in pane_manifest.panes { for pane_info in panes { if pane_info.is_plugin { self.plugin_id_to_tab_position .insert(pane_info.id, tab_position); } } } }, Event::Key(key) => match self.new_plugin_screen.as_mut() { Some(new_plugin_screen) => { let (should_render_new_plugin_screen, should_close_new_plugin_screen) = new_plugin_screen.handle_key(key); if should_close_new_plugin_screen { self.new_plugin_screen = None; should_render = true; } else { should_render = should_render_new_plugin_screen; } }, None => should_render = self.handle_main_screen_key(key), }, _ => (), }; should_render } fn render(&mut self, rows: usize, cols: usize) { match &self.new_plugin_screen { Some(new_plugin_screen) => { new_plugin_screen.render(rows, cols); }, None => { self.render_search(cols); let list_y = 2; let max_list_items = rows.saturating_sub(4); // 2 top padding, 2 bottom padding let (selected_index_in_list, plugin_list) = if self.is_searching() { self.render_search_results(cols) } else { self.render_plugin_list(cols) }; let (more_above, more_below, truncated_list) = self.truncate_list_to_screen( selected_index_in_list, plugin_list, max_list_items, ); self.render_more_indication( more_above, more_below, cols, list_y, truncated_list.len(), ); print_nested_list_with_coordinates(truncated_list, 0, list_y, Some(cols), None); self.render_help(rows, cols); }, } } } impl State { fn render_search_results(&self, cols: usize) -> (Option<usize>, Vec<NestedListItem>) { let mut selected_index_in_list = None; let mut plugin_list = vec![]; for (i, search_result) in self.search_results.iter().enumerate() { let is_selected = Some(i) == self.selected_index; if is_selected { selected_index_in_list = Some(plugin_list.len()); } let is_expanded = self.expanded_indices.contains(&i); plugin_list.append(&mut self.render_search_result( search_result, is_selected, is_expanded, cols, None, )); } (selected_index_in_list, plugin_list) } fn render_plugin_list(&self, cols: usize) -> (Option<usize>, Vec<NestedListItem>) { let mut selected_index_in_list = None; let mut plugin_list = vec![]; for (i, (plugin_id, plugin_info)) in self.plugins.iter().enumerate() { let is_selected = Some(i) == self.selected_index; let is_expanded = self.expanded_indices.contains(&i); if is_selected { selected_index_in_list = Some(plugin_list.len()); } plugin_list.append(&mut self.render_plugin( *plugin_id, plugin_info, is_selected, is_expanded, cols, )); } (selected_index_in_list, plugin_list) } fn render_more_indication( &self, more_above: usize, more_below: usize, cols: usize, list_y: usize, list_len: usize, ) { if more_above > 0 { let text = format!("↑ [+{}]", more_above); let text_len = text.chars().count(); print_text_with_coordinates( Text::new(text).color_range(1, ..), cols.saturating_sub(text_len), list_y.saturating_sub(1), None, None, ); } if more_below > 0 { let text = format!("↓ [+{}]", more_below); let text_len = text.chars().count(); print_text_with_coordinates( Text::new(text).color_range(1, ..), cols.saturating_sub(text_len), list_y + list_len, None, None, ); } } pub fn render_search(&self, cols: usize) { let text = format!(" SEARCH: {}_", self.search_term); if text.chars().count() <= cols { let text = Text::new(text).color_range(3, 9..); print_text_with_coordinates(text, 0, 0, None, None); } else { let truncated_search_term = truncate_string_start(&self.search_term, cols.saturating_sub(10)); // 9 the length of the SEARCH prompt + 1 for the cursor let text = format!(" SEARCH: {}_", truncated_search_term); let text = Text::new(text).color_range(3, 9..); print_text_with_coordinates(text, 0, 0, None, None); } } pub fn render_plugin( &self, plugin_id: u32, plugin_info: &PluginInfo, is_selected: bool, is_expanded: bool, cols: usize, ) -> Vec<NestedListItem> { let mut items = vec![]; let plugin_location_len = plugin_info.location.chars().count(); let max_location_len = cols.saturating_sub(3); // 3 for the bulletin let location_string = if plugin_location_len > max_location_len { truncate_string_start(&plugin_info.location, max_location_len) } else { plugin_info.location.clone() }; let mut item = self.render_plugin_line(location_string, None); if is_selected { item = item.selected(); } items.push(item); if is_expanded { let tab_line = self.render_tab_line(plugin_id, cols); items.push(tab_line); if !plugin_info.configuration.is_empty() { let config_line = NestedListItem::new(format!("Configuration:")) .color_range(2, ..=13) .indent(1); items.push(config_line); for (config_key, config_val) in &plugin_info.configuration { items.push(self.render_config_line(config_key, config_val, cols)) } } } items } fn render_config_line( &self, config_key: &str, config_val: &str, cols: usize, ) -> NestedListItem { let config_line_padding = 9; // 7, left padding + 2 for the ": " between key/val let config_line_max_len = cols.saturating_sub(config_line_padding); let config_key_max_len = config_line_max_len / 2; let config_val_max_len = config_line_max_len.saturating_sub(config_key_max_len); let config_key = if config_key.chars().count() > config_key_max_len { truncate_string_start(&config_key, config_key_max_len) } else { config_key.to_owned() }; let config_val = if config_val.chars().count() > config_val_max_len { truncate_string_start(&config_val, config_val_max_len) } else { config_val.to_owned() }; NestedListItem::new(format!("{}: {}", config_key, config_val)) .indent(2) .color_range(0, ..config_key.chars().count()) .color_range(1, config_key.chars().count() + 2..) } pub fn render_search_result( &self, search_result: &SearchResult, is_selected: bool, is_expanded: bool, cols: usize, plus_indication: Option<usize>, ) -> Vec<NestedListItem> { let mut items = vec![]; let plugin_info = &search_result.plugin_info; let plugin_id = search_result.plugin_id; let indices = &search_result.indices; let plus_indication_len = plus_indication .map(|p| p.to_string().chars().count() + 4) .unwrap_or(0); // 4 for the plus indication decorators and space let max_location_len = cols.saturating_sub(plus_indication_len + 3); // 3 for the bulletin let (location_string, indices) = if plugin_info.location.chars().count() <= max_location_len { (plugin_info.location.clone(), indices.clone()) } else { truncate_search_result(&plugin_info.location, max_location_len, indices) }; let mut item = match plus_indication { Some(plus_indication) => self.render_plugin_line_with_plus_indication( location_string, plus_indication, Some(indices), ), None => self.render_plugin_line(location_string, Some(indices)), }; if is_selected { item = item.selected(); } items.push(item); if is_expanded { let tab_line = self.render_tab_line(plugin_id, cols); items.push(tab_line); if !plugin_info.configuration.is_empty() { let config_line = NestedListItem::new(format!("Configuration:")) .color_range(2, ..=13) .indent(1); items.push(config_line); for (config_key, config_value) in &plugin_info.configuration {
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/path_formatting.rs
default-plugins/sequence/src/path_formatting.rs
use std::path::PathBuf; /// Expand a path string to an absolute PathBuf /// Handles ~, ./, .., relative and absolute paths pub fn expand_path(path_str: &str, current_cwd: Option<&PathBuf>) -> Option<PathBuf> { let expanded = if path_str.starts_with("~/") || path_str == "~" { let home_dir = std::env::var("HOME").ok()?; if path_str == "~" { PathBuf::from(home_dir) } else { PathBuf::from(home_dir).join(&path_str[2..]) } } else if path_str.starts_with('/') { PathBuf::from(path_str) } else { let base = current_cwd?; base.join(path_str) }; let mut normalized = PathBuf::new(); for component in expanded.components() { match component { std::path::Component::ParentDir => { normalized.pop(); }, std::path::Component::CurDir => {}, _ => { normalized.push(component); }, } } Some(normalized) } /// Format a path for display in the prompt /// Example: /home/user/some/long/path -> ~/s/l/path pub fn format_cwd(cwd: &PathBuf) -> String { let path_str = cwd.to_string_lossy().to_string(); let home_dir = std::env::var("HOME").unwrap_or_default(); let path_str = if !home_dir.is_empty() && path_str.starts_with(&home_dir) { path_str.replacen(&home_dir, "~", 1) } else { path_str }; let parts: Vec<&str> = path_str.split('/').collect(); if parts.len() <= 1 { return path_str; } let mut formatted_parts = Vec::new(); for (i, part) in parts.iter().enumerate() { if i == parts.len() - 1 { formatted_parts.push(part.to_string()); } else if part.is_empty() { formatted_parts.push(String::new()); } else { formatted_parts.push(part.chars().next().unwrap_or_default().to_string()); } } formatted_parts.join("/") } /// Alias for expand_path for backwards compatibility pub fn resolve_path(current_cwd: Option<&PathBuf>, path_str: &str) -> Option<PathBuf> { expand_path(path_str, current_cwd) }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/lib.rs
default-plugins/sequence/src/lib.rs
pub mod path_formatting; pub mod state; pub mod ui; pub use state::State;
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/main.rs
default-plugins/sequence/src/main.rs
mod path_formatting; mod state; mod ui; use crate::state::CommandStatus; use crate::ui::components; use crate::ui::fuzzy_complete; use crate::ui::layout_calculations::calculate_viewport; use crate::ui::text_input::InputAction; use crate::ui::truncation::truncate_middle; use state::State; use zellij_tile::prelude::actions::Action; use zellij_tile::prelude::*; use std::collections::BTreeMap; use std::path::PathBuf; use unicode_width::UnicodeWidthStr; register_plugin!(State); impl ZellijPlugin for State { fn load(&mut self, _configuration: BTreeMap<String, String>) { subscribe(&[ EventType::ModeUpdate, EventType::SessionUpdate, EventType::Key, EventType::PermissionRequestResult, EventType::HostFolderChanged, EventType::RunCommandResult, EventType::ActionComplete, EventType::PaneUpdate, EventType::Timer, EventType::PastedText, EventType::TabUpdate, EventType::CommandPaneOpened, ]); // Store our own plugin ID and client ID let plugin_ids = get_plugin_ids(); self.plugin_id = Some(plugin_ids.plugin_id); self.client_id = Some(plugin_ids.client_id); self.cwd = Some(plugin_ids.initial_cwd); update_title(self); } fn update(&mut self, event: Event) -> bool { handle_event(self, event) } fn render(&mut self, rows: usize, cols: usize) { // Store dimensions for use in cursor calculations self.own_rows = Some(rows); self.own_columns = Some(cols); let max_visible_rows = rows.saturating_sub(5); let base_x = 1; let base_y = 0; let (offset, visible_count, hidden_above, hidden_below) = calculate_viewport( self.execution.all_commands.len(), max_visible_rows, self.selection.current_selected_command_index, self.execution.current_running_command_index, ); let mut table = components::build_table_header(hidden_above > 0 || hidden_below > 0); for index in offset..offset + visible_count { table = components::add_command_row( table, self, index, offset, visible_count, hidden_above, hidden_below, ); } print_table_with_coordinates( table, base_x, base_y, self.own_columns.map(|o| o.saturating_sub(base_x)), None, ); let help_y = base_y + visible_count + 2; let (first_help, _, second_help) = components::render_help_lines(self, Some(cols)); print_text_with_coordinates(first_help, base_x, help_y, None, None); if let Some((second_help_text, _)) = second_help { print_text_with_coordinates(second_help_text, base_x, help_y + 1, None, None); } } } pub fn handle_event(state: &mut State, event: Event) -> bool { use std::path::PathBuf; match event { Event::PermissionRequestResult(_) => { change_host_folder(PathBuf::from("/")); update_title(state); true }, Event::ModeUpdate(mode_info) => { state.shell = mode_info.shell.clone(); false }, Event::Key(key) => { let mut should_render = handle_key_event(state, key); let repositioned = state.reposition_plugin(); if repositioned { // we only want to render once we have repositioned, we will do this in TabUpdate should_render = false; } update_cursor(state); should_render }, Event::SessionUpdate(session_infos, _resurrectable_sessions) => { if state.is_first_run { // Find the current session let current_session = session_infos.iter().find(|s| s.is_current_session); if let Some(session) = current_session { // Get the pane history for this client if let Some(client_id) = state.client_id { if let Some(pane_history) = session.pane_history.get(&client_id) { let own_pane_id = state.plugin_id.map(|id| PaneId::Plugin(id)); state.primary_pane_id = select_primary_pane_from_history( pane_history, &session.panes, own_pane_id, ); state.original_pane_id = state.primary_pane_id; // pane id focused // before plugin // launched state.is_first_run = false; } } } } false }, Event::Timer(_elapsed) => { // Timer events are used for lock backoff let should_render = update_spinner(state); should_render }, Event::PastedText(pasted_text) => { // Split pasted text into lines let mut should_render = true; let lines: Vec<&str> = pasted_text .lines() .map(|line| line.trim()) .filter(|line| !line.is_empty()) .collect(); if lines.is_empty() { return false; } state.pasted_lines(lines); let repositioned = state.reposition_plugin(); if repositioned { // we only want to render once we have repositioned, we will do this in TabUpdate should_render = false; } update_cursor(state); should_render }, Event::TabUpdate(tab_infos) => { if let Some(tab_info) = tab_infos.iter().find(|t| t.active) { let new_cols = Some(tab_info.viewport_columns); let new_rows = Some(tab_info.viewport_rows); // Check if dimensions changed let dimensions_changed = new_cols != state.total_viewport_columns || new_rows != state.total_viewport_rows; state.total_viewport_columns = new_cols; state.total_viewport_rows = new_rows; if dimensions_changed { state.reposition_plugin(); } update_cursor(state); } false }, Event::PaneUpdate(pane_manifest) => handle_pane_update(state, pane_manifest), Event::ActionComplete(_action, pane_id, context) => { let should_render = handle_action_complete(state, pane_id, context); update_title(state); should_render }, Event::CommandPaneOpened(terminal_pane_id, context) => { // we get this event immediately as the pane opens, we use it to associate the // pane's id with our state if !is_running_sequence(&context, state.execution.sequence_id) { // action from previous sequence or unrelated return false; } if let Some(command_text) = context.get("command_text") { state.update_pane_id_for_command(PaneId::Terminal(terminal_pane_id), command_text); if !state.layout.spinner_timer_scheduled { set_timeout(0.1); state.layout.spinner_timer_scheduled = true; } update_title(state); } true }, _ => false, } } fn handle_key_event(state: &mut State, key: KeyWithModifier) -> bool { // Ctrl+Enter - Insert command after current with AND chain type if key.has_modifiers(&[KeyModifier::Ctrl]) && matches!(key.bare_key, BareKey::Enter) { let mut is_cd = false; if let Some(current_text) = state.editing_input_text() { if let Some(path) = state::detect_cd_command(&current_text) { if let Some(new_cwd) = path_formatting::resolve_path(state.cwd.as_ref(), &path) { state.current_selected_command_mut().map(|c| { c.set_cwd(Some(new_cwd)); c.set_text("".to_owned()); }); state.editing.editing_input.as_mut().map(|i| i.clear()); is_cd = true } } }; state.add_empty_command_after_current_selected(); if is_cd { state.start_editing_selected(); } return true; } // Ctrl+X - Cycle chain type if key.has_modifiers(&[KeyModifier::Ctrl]) && matches!(key.bare_key, BareKey::Char('x')) { // return state.ui.command_sequence.cycle_current_chain_type(); state.cycle_chain_type(); return true; } // Ctrl+Space, copy to clipboard if key.has_modifiers(&[KeyModifier::Ctrl]) && matches!(key.bare_key, BareKey::Char(' ')) { state.copy_to_clipboard(); return false; } // Ctrl+w, close all panes and clear sequence if key.has_modifiers(&[KeyModifier::Ctrl]) && matches!(key.bare_key, BareKey::Char('w')) { if !state.execution.is_running && !state.all_commands_are_pending() { close_panes_and_return_to_shell(state); } return true; } if matches!(key.bare_key, BareKey::Up) && !key.has_modifiers(&[KeyModifier::Ctrl]) && !key.has_modifiers(&[KeyModifier::Alt]) { state.move_selection_up(); return true; } if matches!(key.bare_key, BareKey::Down) && !key.has_modifiers(&[KeyModifier::Ctrl]) && !key.has_modifiers(&[KeyModifier::Alt]) { state.move_selection_down(); return true; } // Del - delete current command if matches!(key.bare_key, BareKey::Delete) && !key.has_modifiers(&[KeyModifier::Ctrl]) && !key.has_modifiers(&[KeyModifier::Alt]) { state.remove_current_selected_command(); return true; } // Ctrl+C - Clear currently focused command, or remove it if already empty if key.has_modifiers(&[KeyModifier::Ctrl]) && matches!(key.bare_key, BareKey::Char('c')) { if state.execution.is_running { interrupt_sequence(state); return true; } else if state.editing.editing_input.is_some() { let is_empty = state.current_selected_command_is_empty(); let has_more_than_one_command = state.execution.all_commands.len() > 1; if is_empty && has_more_than_one_command { state.remove_current_selected_command(); } else if is_empty { // last command, return to shell close_panes_and_return_to_shell(state); } else { // If not empty, clear it state.clear_current_selected_command(); } return true; } } if state.editing.editing_input.is_none() && key.has_no_modifiers() && matches!(key.bare_key, BareKey::Char('e')) { state.start_editing_selected(); return true; } if state.editing.editing_input.is_none() && key.has_no_modifiers() && matches!(key.bare_key, BareKey::Enter) { rerun_sequence(state); return true; } // Handle input actions from TextInput let is_backspace = matches!(key.bare_key, BareKey::Backspace); if let Some(action) = state .editing .editing_input .as_mut() .map(|i| i.handle_key(key)) { match action { InputAction::Submit => { return handle_submit(state); }, InputAction::Cancel => { state.cancel_editing_selected(); if state.all_commands_are_pending() { // we always want to stay in editing mode in main screen state.start_editing_selected(); } true }, InputAction::Complete => { state .editing_input_text() .map(|current_text| { if let Some(completed) = fuzzy_complete::fuzzy_complete( &current_text, &Default::default(), // TODO: get rid of this whoel thing? state.cwd.as_ref(), ) { state.set_editing_input_text(completed); true } else { false } }) .unwrap_or(false) }, InputAction::Continue => { if let Some(current_text) = state.editing_input_text() { if let Some((cmd_text, chain_type)) = state::detect_chain_operator_at_end(&current_text) { let mut should_add_empty_line = true; if let Some(path) = state::detect_cd_command(&cmd_text) { if let Some(new_cwd) = path_formatting::resolve_path(state.cwd.as_ref(), &path) { let remaining_text = state::get_remaining_after_first_segment(&current_text) .unwrap_or_else(|| "".to_owned()); if remaining_text.len() > 0 { should_add_empty_line = false; } state.current_selected_command_mut().map(|c| { c.set_cwd(Some(new_cwd)); c.set_text(remaining_text); }); } } else { state.current_selected_command_mut().map(|c| { c.set_text(cmd_text); c.set_chain_type(chain_type); }); }; state.cancel_editing_selected(); if should_add_empty_line { state.add_empty_command_after_current_selected(); } state.start_editing_selected(); } } // Handle backspace on empty command if is_backspace { let is_empty = state.current_selected_command_is_empty() || state .editing_input_text() .map(|i| i.is_empty()) .unwrap_or(false); let has_more_than_one_command = state.execution.all_commands.len() > 1; if is_empty && has_more_than_one_command { let current_index = state.selection.current_selected_command_index.unwrap_or(0); if current_index > 0 { state.remove_current_selected_command(); return true; } } else if is_empty { // last command close_panes_and_return_to_shell(state); } } true }, InputAction::NoAction => false, } } else { false } } /// Handle Enter key - submit and execute the command sequence fn handle_submit(state: &mut State) -> bool { let cwd = state.cwd.clone(); if state.handle_editing_submit(&cwd) { // handled the command internally (eg. cd) no need to run sequence return true; } if state.execution.all_commands.len() == 1 && state.can_run_sequence() { rerun_sequence(state); } else if state.execution.all_commands.len() == 1 { state.move_selection_down(); state.start_editing_selected(); } true } pub fn handle_pane_update(state: &mut State, pane_manifest: PaneManifest) -> bool { // Store the manifest for later use state.pane_manifest = Some(pane_manifest.clone()); let mut needs_rerender = false; if state.update_exited_command_statuses(&pane_manifest) { needs_rerender = true; } if state.update_sequence_stopped_state() { needs_rerender = true; } state.reposition_plugin(); update_primary_and_original_pane_ids(state, &pane_manifest); needs_rerender } pub fn calculate_cursor_position(state: &mut State) -> Option<(usize, usize)> { // Get pane dimensions from state (must be set by render) let Some(cols) = state.own_columns else { eprintln!("Warning: own_columns not set"); return None; }; let Some(rows) = state.own_rows else { eprintln!("Warning: own_rows not set"); return None; }; // Only show cursor if in edit mode let (text, cursor_pos) = if let Some(text_input) = &state.editing.editing_input { ( text_input.get_text().to_string(), text_input.cursor_position(), ) } else { return None; }; let Some(edit_index) = state.selection.current_selected_command_index else { return None; }; // Calculate folder column width using the longest cwd across all commands let longest_cwd_display = state.execution.longest_cwd_display(&state.cwd); let folder_display = format!("{} >", longest_cwd_display); let folder_col_width = folder_display.width().max(1); let base_x = 1; let base_y = 0; adjust_scroll_offset(state, rows); let max_visible_rows = state.own_rows.map(|r| r.saturating_sub(5)).unwrap_or(0); let (offset, visible_count, hidden_above, hidden_below) = calculate_viewport( state.execution.all_commands.len(), max_visible_rows, state.selection.current_selected_command_index, state.execution.current_running_command_index, ); let (max_chain_width, max_status_width) = components::calculate_max_widths(&state.execution.all_commands, state.layout.spinner_frame); let Some((_, available_cmd_width)) = components::calculate_row_layout_info( edit_index, offset, visible_count, hidden_above, hidden_below, cols, folder_col_width, max_chain_width, max_status_width, ) else { return None; }; // Get cursor position in truncated text let (_, cursor_in_truncated) = truncate_middle(&text, available_cmd_width, Some(cursor_pos)); let Some(cursor_in_truncated) = cursor_in_truncated else { return None; }; // Calculate relative coordinates within the visible table let relative_y = edit_index.saturating_sub(offset) + 1; // +1 for header row let relative_x = folder_col_width + 1 + cursor_in_truncated; let x = base_x + relative_x; let y = base_y + relative_y; Some((x, y)) } pub fn handle_action_complete( state: &mut State, pane_id: Option<PaneId>, context: BTreeMap<String, String>, ) -> bool { // Update primary_pane_id to the pane that just completed the action // This ensures we always have a valid pane to target for InPlace launches // But only if it's not a floating pane if let (Some(pane_id), Some(manifest)) = (pane_id, &state.pane_manifest) { if !is_pane_floating(pane_id, manifest) { state.primary_pane_id = Some(pane_id); } else { eprintln!("Not setting primary_pane_id to floating pane {:?}", pane_id); } } if !is_running_sequence(&context, state.execution.sequence_id) { // action from previous sequence or unrelated return false; } // If the sequence has been stopped (e.g., via Ctrl+C), don't continue if !state.execution.is_running { return true; // Re-render to show the stopped state } // Move to the next command let next_index = state.execution.current_running_command_index + 1; if next_index < state.execution.all_commands.len() { // Execute the next command // let (next_command, next_chain_type) = &state.execution.all_commands[next_index]; let Some(next_command) = state.execution.all_commands.get(next_index) else { // invalid state return true; }; let next_chain_type = next_command.get_chain_type(); let next_command_cwd = next_command.get_cwd(); let next_command_text = next_command.get_text(); let shell = state .shell .clone() .unwrap_or_else(|| PathBuf::from("/bin/bash")); let command = zellij_tile::prelude::actions::RunCommandAction { command: shell, args: vec!["-ic".to_string(), next_command_text.trim().to_string()], cwd: next_command_cwd, hold_on_close: true, ..Default::default() }; // Determine placement based on layout mode let placement = NewPanePlacement::Stacked(pane_id); // Update status: mark current command as completed // Use the pane_id from ActionComplete if the status is still Pending let pane_id_to_mark = state .execution .all_commands .get(state.execution.current_running_command_index) .and_then(|c| match c.get_status() { CommandStatus::Running(pid) => pid, CommandStatus::Pending => pane_id, // Use the pane from ActionComplete CommandStatus::Exited(_, pid) => pid, // Already marked, keep it CommandStatus::Interrupted(pid) => pid, // Already marked, keep it }); state .execution .all_commands .get_mut(state.execution.current_running_command_index) .map(|c| c.set_status(CommandStatus::Exited(None, pane_id_to_mark))); state.execution.current_running_command_index = next_index; // Determine unblock_condition based on whether this is the last command let unblock_condition = if next_index < state.execution.all_commands.len() - 1 { // Not the last command - use the chain type's unblock condition next_chain_type.to_unblock_condition() } else { // Last command - use UnblockCondition::OnAnyExit Some(UnblockCondition::OnAnyExit) }; let action = Action::NewBlockingPane { placement, command: Some(command), pane_name: Some(next_command_text.trim().to_string()), unblock_condition, near_current_pane: true, }; // Pass the sequence ID in the context let mut context = BTreeMap::new(); context.insert( "sequence_id".to_string(), state.execution.sequence_id.to_string(), ); context.insert("command_text".to_string(), next_command_text.to_string()); // Put the sequence back with updated index run_action(action, context); } else { // Sequence complete - mark the last command as Exited let pane_id_to_mark = state .execution .all_commands .get(state.execution.current_running_command_index) .and_then(|c| match c.get_status() { CommandStatus::Running(pid) => pid, CommandStatus::Pending => pane_id, // Use the pane from ActionComplete CommandStatus::Exited(_, pid) => pid, // Already marked, keep it CommandStatus::Interrupted(pid) => pid, // Already marked, keep it }); state .execution .all_commands .get_mut(state.execution.current_running_command_index) .map(|c| c.set_status(CommandStatus::Exited(None, pane_id_to_mark))); } true } /// Adjust scroll offset to keep selected or running command visible pub fn adjust_scroll_offset(sequence: &mut crate::state::State, rows: usize) { let max_visible = rows.saturating_sub(6); let total_commands = sequence.execution.all_commands.len(); if total_commands <= max_visible { sequence.selection.scroll_offset = 0; return; } let focus_index = sequence .selection .current_selected_command_index .unwrap_or(sequence.execution.current_running_command_index); let half_visible = max_visible / 2; if focus_index < half_visible { sequence.selection.scroll_offset = 0; } else if focus_index >= total_commands.saturating_sub(half_visible) { sequence.selection.scroll_offset = total_commands.saturating_sub(max_visible); } else { sequence.selection.scroll_offset = focus_index.saturating_sub(half_visible); } sequence.selection.scroll_offset = sequence .selection .scroll_offset .min(total_commands.saturating_sub(max_visible)); } pub fn is_pane_floating(pane_id: PaneId, pane_manifest: &PaneManifest) -> bool { pane_manifest .panes .iter() .flat_map(|(_, panes)| panes.iter()) .find(|pane_info| match pane_id { PaneId::Terminal(id) => !pane_info.is_plugin && pane_info.id == id, PaneId::Plugin(id) => pane_info.is_plugin && pane_info.id == id, }) .map(|pane_info| pane_info.is_floating) .unwrap_or(false) } fn is_running_sequence(context: &BTreeMap<String, String>, running_sequence_id: u64) -> bool { if let Some(context_sequence_id) = context.get("sequence_id") { if let Ok(context_id) = context_sequence_id.parse::<u64>() { if context_id != running_sequence_id { // This action is from a different sequence, ignore it return false; } else { return true; } } else { // Failed to parse sequence_id, ignore this action return false; } } else { return false; } } fn update_primary_and_original_pane_ids(state: &mut State, pane_manifest: &PaneManifest) { if let Some(primary_pane_id) = state.primary_pane_id { let mut primary_pane_found = false; // Check if the primary pane still exists for (_tab_index, panes) in &pane_manifest.panes { for pane_info in panes { let pane_matches = match primary_pane_id { PaneId::Terminal(id) => !pane_info.is_plugin && pane_info.id == id, PaneId::Plugin(id) => pane_info.is_plugin && pane_info.id == id, }; if pane_matches { primary_pane_found = true; break; } } if primary_pane_found { break; } } // If primary pane was not found, select a new one if !primary_pane_found { state.primary_pane_id = None; } } if let Some(original_pane_id) = state.original_pane_id { let mut original_pane_found = false; // Check if the original pane still exists for (_tab_index, panes) in &pane_manifest.panes { for pane_info in panes { let pane_matches = match original_pane_id { PaneId::Terminal(id) => !pane_info.is_plugin && pane_info.id == id, PaneId::Plugin(id) => pane_info.is_plugin && pane_info.id == id, }; if pane_matches { original_pane_found = true; break; } } if original_pane_found { break; } } // If original pane was not found, select a new one if !original_pane_found { state.original_pane_id = None; } } } pub fn select_primary_pane_from_history( pane_history: &[PaneId], pane_manifest: &PaneManifest, own_pane_id: Option<PaneId>, ) -> Option<PaneId> { pane_history .iter() .rev() // Most recent first .find(|&id| { // Skip self if Some(*id) == own_pane_id { return false; } // Skip floating panes !is_pane_floating(*id, pane_manifest) }) .copied() } fn close_panes_and_return_to_shell(state: &mut State) -> bool { // Close all panes in the sequence before clearing it // Handle the first pane: replace it with the primary_pane_id_before_sequence if available if let Some(first_pane_id) = state.execution.all_commands.iter().find_map(|command| { // we look for the first command in the sequence that has a pane that's // actually open match command.get_status() { CommandStatus::Running(pane_id) => pane_id, CommandStatus::Exited(_, pane_id) => pane_id, CommandStatus::Interrupted(pane_id) => pane_id, _ => None, } }) { if let Some(original_pane_id) = state.original_pane_id { replace_pane_with_existing_pane( first_pane_id, original_pane_id, true, // suppress_replaced_pane (closes the first pane) ); } else { // Fallback: if we don't have a saved primary pane, just close it close_pane_with_id(first_pane_id); } } // Close all other panes (starting from index 1) for (idx, command) in state.execution.all_commands.iter().skip(1).enumerate() { let pane_id = match command.get_status() { CommandStatus::Running(pane_id) => pane_id, CommandStatus::Exited(_, pane_id) => pane_id, CommandStatus::Interrupted(pane_id) => pane_id, _ => None, }; if let Some(pane_id) = pane_id { close_pane_with_id(pane_id); } else { eprintln!( "Warning: Cannot close pane at index {}: pane_id is None", idx + 1 ); } } state.clear_all_commands(); // Transition back to shell screen if let Some(plugin_id) = state.plugin_id { change_floating_pane_coordinates( plugin_id, Some(25), Some(25), Some(50), Some(50), false, // pinned (this should unpin it) ); } update_title(state); true } fn change_floating_pane_coordinates( own_plugin_id: u32, x: Option<usize>, y: Option<usize>, width: Option<usize>, height: Option<usize>, should_be_pinned: bool, ) { let coordinates = FloatingPaneCoordinates::new( x.map(|x| format!("{}%", x)), y.map(|y| format!("{}%", y)), width.map(|width| format!("{}%", width)), height.map(|height| format!("{}%", height)), Some(should_be_pinned), ); if let Some(coordinates) = coordinates { // TODO: better // show_self(true); change_floating_panes_coordinates(vec![(PaneId::Plugin(own_plugin_id), coordinates)]); } } fn update_spinner(state: &mut State) -> bool { // Advance spinner frame for RUNNING animation state.layout.spinner_frame = (state.layout.spinner_frame + 1) % 8; // Reset timer scheduled flag since this timer just fired state.layout.spinner_timer_scheduled = false; // If we have a running command, schedule next timer event let has_running = state .execution .all_commands .iter() .any(|command| matches!(command.get_status(), CommandStatus::Running(_))); if has_running && !state.layout.spinner_timer_scheduled { set_timeout(0.1); state.layout.spinner_timer_scheduled = true; } has_running } fn rerun_sequence(state: &mut State) { if !state.can_run_sequence() { return; } state.execution.all_commands.retain(|c| !c.is_empty()); if state.execution.all_commands.is_empty() { return; } let selected_index = state .selection
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
true
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/command_parser.rs
default-plugins/sequence/src/state/command_parser.rs
use super::ChainType; #[derive(Debug, Clone, Copy, PartialEq)] enum ParseState { Normal, InSingleQuote, InDoubleQuote, Escaped(EscapeContext), } #[derive(Debug, Clone, Copy, PartialEq)] enum EscapeContext { Normal, DoubleQuote, } pub fn split_by_chain_operators(text: &str) -> Vec<(String, Option<ChainType>)> { let mut segments = Vec::new(); let mut current_segment = String::new(); let mut state = ParseState::Normal; let chars: Vec<char> = text.chars().collect(); let mut i = 0; while i < chars.len() { let ch = chars[i]; match state { ParseState::Normal => { if ch == '\\' { state = ParseState::Escaped(EscapeContext::Normal); current_segment.push(ch); i += 1; } else if ch == '\'' { state = ParseState::InSingleQuote; current_segment.push(ch); i += 1; } else if ch == '"' { state = ParseState::InDoubleQuote; current_segment.push(ch); i += 1; } else if ch == '&' && i + 1 < chars.len() && chars[i + 1] == '&' { let segment_text = current_segment.trim().to_string(); if !segment_text.is_empty() { segments.push((segment_text, Some(ChainType::And))); } current_segment.clear(); i += 2; } else if ch == '|' && i + 1 < chars.len() && chars[i + 1] == '|' { let segment_text = current_segment.trim().to_string(); if !segment_text.is_empty() { segments.push((segment_text, Some(ChainType::Or))); } current_segment.clear(); i += 2; } else if ch == ';' { let segment_text = current_segment.trim().to_string(); if !segment_text.is_empty() { segments.push((segment_text, Some(ChainType::Then))); } current_segment.clear(); i += 1; } else { current_segment.push(ch); i += 1; } }, ParseState::InSingleQuote => { current_segment.push(ch); if ch == '\'' { state = ParseState::Normal; } i += 1; }, ParseState::InDoubleQuote => { if ch == '\\' { state = ParseState::Escaped(EscapeContext::DoubleQuote); current_segment.push(ch); i += 1; } else if ch == '"' { current_segment.push(ch); state = ParseState::Normal; i += 1; } else { current_segment.push(ch); i += 1; } }, ParseState::Escaped(context) => { current_segment.push(ch); state = match context { EscapeContext::Normal => ParseState::Normal, EscapeContext::DoubleQuote => ParseState::InDoubleQuote, }; i += 1; }, } } let final_segment = current_segment.trim().to_string(); if !final_segment.is_empty() { segments.push((final_segment, None)); } segments } pub fn detect_chain_operator_at_end(text: &str) -> Option<(String, ChainType)> { let segments = split_by_chain_operators(text); if segments.is_empty() { return None; } if segments.len() == 1 { if let Some((text, Some(chain_type))) = segments.first() { return Some((text.clone(), *chain_type)); } return None; } if let Some((first_text, Some(chain_type))) = segments.first() { return Some((first_text.clone(), *chain_type)); } None } pub fn get_remaining_after_first_segment(text: &str) -> Option<String> { let segments = split_by_chain_operators(text); if segments.len() <= 1 { return None; } let mut result = String::new(); for (i, (segment_text, chain_type_opt)) in segments.iter().enumerate().skip(1) { if i > 1 { if let Some(chain_type) = chain_type_opt { result.push_str(&format!(" {} ", chain_type.as_str())); } } result.push_str(segment_text); if let Some(chain_type) = chain_type_opt { result.push_str(&format!(" {} ", chain_type.as_str())); } } Some(result.trim().to_string()) } pub fn detect_cd_command(text: &str) -> Option<String> { let trimmed = text.trim(); if trimmed == "cd" { return Some("~".to_string()); } if trimmed.starts_with("cd ") { let path = trimmed[3..].trim(); return Some(path.to_string()); } None } #[cfg(test)] mod tests { use super::*; #[test] fn test_single_command_no_operator() { let result = split_by_chain_operators("ls"); assert_eq!(result, vec![("ls".to_string(), None)]); } #[test] fn test_two_commands_with_and() { let result = split_by_chain_operators("ls && pwd"); assert_eq!( result, vec![ ("ls".to_string(), Some(ChainType::And)), ("pwd".to_string(), None) ] ); } #[test] fn test_two_commands_with_or() { let result = split_by_chain_operators("cmd1 || cmd2"); assert_eq!( result, vec![ ("cmd1".to_string(), Some(ChainType::Or)), ("cmd2".to_string(), None) ] ); } #[test] fn test_two_commands_with_semicolon() { let result = split_by_chain_operators("echo hi ; ls"); assert_eq!( result, vec![ ("echo hi".to_string(), Some(ChainType::Then)), ("ls".to_string(), None) ] ); } #[test] fn test_three_commands_mixed() { let result = split_by_chain_operators("a && b || c"); assert_eq!( result, vec![ ("a".to_string(), Some(ChainType::And)), ("b".to_string(), Some(ChainType::Or)), ("c".to_string(), None) ] ); } #[test] fn test_operator_in_single_quotes() { let result = split_by_chain_operators("echo '&&' && ls"); assert_eq!( result, vec![ ("echo '&&'".to_string(), Some(ChainType::And)), ("ls".to_string(), None) ] ); } #[test] fn test_operator_in_double_quotes() { let result = split_by_chain_operators("echo \"||\" || pwd"); assert_eq!( result, vec![ ("echo \"||\"".to_string(), Some(ChainType::Or)), ("pwd".to_string(), None) ] ); } #[test] fn test_escaped_operator() { let result = split_by_chain_operators("echo \\&& test"); assert_eq!(result, vec![("echo \\&& test".to_string(), None)]); } #[test] fn test_complex_quoting() { let result = split_by_chain_operators("cmd1 && echo \"a || b\" && cmd2"); assert_eq!( result, vec![ ("cmd1".to_string(), Some(ChainType::And)), ("echo \"a || b\"".to_string(), Some(ChainType::And)), ("cmd2".to_string(), None) ] ); } #[test] fn test_empty_segments_filtered() { let result = split_by_chain_operators("cmd1 && && cmd2"); assert_eq!( result, vec![ ("cmd1".to_string(), Some(ChainType::And)), ("cmd2".to_string(), None) ] ); } #[test] fn test_detect_operator_just_typed_and() { let result = detect_chain_operator_at_end("ls &&"); assert_eq!(result, Some(("ls".to_string(), ChainType::And))); } #[test] fn test_detect_operator_just_typed_or() { let result = detect_chain_operator_at_end("cmd ||"); assert_eq!(result, Some(("cmd".to_string(), ChainType::Or))); } #[test] fn test_detect_operator_just_typed_semicolon() { let result = detect_chain_operator_at_end("echo ;"); assert_eq!(result, Some(("echo".to_string(), ChainType::Then))); } #[test] fn test_detect_operator_no_operator() { let result = detect_chain_operator_at_end("ls"); assert_eq!(result, None); } #[test] fn test_detect_operator_in_quotes() { let result = detect_chain_operator_at_end("echo '&&'"); assert_eq!(result, None); } #[test] fn test_whitespace_trimming() { let result = split_by_chain_operators(" cmd1 && cmd2 "); assert_eq!( result, vec![ ("cmd1".to_string(), Some(ChainType::And)), ("cmd2".to_string(), None) ] ); } #[test] fn test_trailing_operator_with_space() { let result = split_by_chain_operators("ls && "); assert_eq!(result, vec![("ls".to_string(), Some(ChainType::And))]); } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/chain_type.rs
default-plugins/sequence/src/state/chain_type.rs
use serde::{Deserialize, Serialize}; use zellij_tile::prelude::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ChainType { And, Or, Then, None, } impl Default for ChainType { fn default() -> Self { ChainType::None } } impl ChainType { pub fn to_unblock_condition(&self) -> Option<UnblockCondition> { match self { ChainType::And => Some(UnblockCondition::OnExitSuccess), ChainType::Or => Some(UnblockCondition::OnExitFailure), ChainType::Then => Some(UnblockCondition::OnAnyExit), ChainType::None => None, } } pub fn as_str(&self) -> &str { match self { ChainType::And => "&&", ChainType::Or => "||", ChainType::Then => ";", ChainType::None => "", } } pub fn cycle_next(&mut self) { *self = match self { ChainType::And => ChainType::Or, ChainType::Or => ChainType::Then, ChainType::Then => ChainType::And, ChainType::None => ChainType::And, }; } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/mod.rs
default-plugins/sequence/src/state/mod.rs
mod chain_type; mod command_entry; mod command_parser; mod command_status; mod editing; mod execution; mod layout; pub mod positioning; mod selection; pub use chain_type::ChainType; pub use command_entry::CommandEntry; pub use command_parser::{ detect_cd_command, detect_chain_operator_at_end, get_remaining_after_first_segment, split_by_chain_operators, }; pub use command_status::CommandStatus; pub use editing::Editing; pub use execution::Execution; pub use layout::Layout; pub use selection::Selection; use crate::ui::text_input::TextInput; use std::path::PathBuf; use zellij_tile::prelude::*; pub struct State { pub shell: Option<PathBuf>, pub plugin_id: Option<u32>, pub client_id: Option<u16>, pub own_rows: Option<usize>, pub own_columns: Option<usize>, pub cwd: Option<PathBuf>, pub original_pane_id: Option<PaneId>, pub primary_pane_id: Option<PaneId>, pub is_first_run: bool, pub pane_manifest: Option<PaneManifest>, pub total_viewport_columns: Option<usize>, pub total_viewport_rows: Option<usize>, pub selection: Selection, pub editing: Editing, pub execution: Execution, pub layout: Layout, pub current_position: Option<FloatingPaneCoordinates>, } impl State { pub fn new() -> Self { Self { shell: None, plugin_id: None, client_id: None, own_rows: None, own_columns: None, cwd: None, original_pane_id: None, primary_pane_id: None, is_first_run: true, pane_manifest: None, total_viewport_columns: None, total_viewport_rows: None, selection: Selection::new(), editing: Editing::new(), execution: Execution::new(), layout: Layout::new(), current_position: None, } } pub fn set_plugin_id(&mut self, plugin_id: u32) { self.plugin_id = Some(plugin_id); } /// Check if the sequence has finished executing (all commands are done) pub fn has_finished(&self) -> bool { self.execution .all_commands .iter() .all(|command| matches!(command.status, CommandStatus::Exited(_, _))) } pub fn add_empty_command_after_current_selected(&mut self) { self.selection.add_empty_command_after_current_selected( &mut self.execution.all_commands, &mut self.editing, &self.cwd, ); } pub fn current_selected_command_is_empty(&self) -> bool { self.selection .current_selected_command_is_empty(&self.execution.all_commands, &self.editing) } pub fn remove_current_selected_command(&mut self) { let removed_pane_id = self .selection .remove_current_selected_command(&mut self.execution.all_commands, &mut self.editing); if let Some(removed_pane_id) = removed_pane_id { close_pane_with_id(removed_pane_id); } } pub fn clear_current_selected_command(&mut self) { self.selection .clear_current_selected_command(&mut self.execution.all_commands, &mut self.editing); } pub fn move_selection_up(&mut self) { self.selection .move_up(&mut self.execution.all_commands, &mut self.editing); if let Some(pane_id) = self .current_selected_command() .and_then(|c| c.get_pane_id()) { show_pane_with_id(pane_id, true, false); } } pub fn move_selection_down(&mut self) { self.selection .move_down(&mut self.execution.all_commands, &mut self.editing); if let Some(pane_id) = self .current_selected_command() .and_then(|c| c.get_pane_id()) { show_pane_with_id(pane_id, true, false); } } pub fn start_editing_selected(&mut self) { if let Some(current_command_text) = self.current_selected_command().map(|c| c.get_text()) { self.editing.start_editing(current_command_text); } } pub fn cancel_editing_selected(&mut self) { self.editing.cancel_editing(); } pub fn editing_input_text(&self) -> Option<String> { self.editing.input_text() } pub fn set_editing_input_text(&mut self, text: String) { self.editing.set_input_text(text); } fn handle_first_pasted_segment( &mut self, current_text: &str, segment_text: &str, chain_type_opt: &Option<ChainType>, ) { let new_text = if current_text.trim().is_empty() { segment_text.to_string() } else { format!("{}{}", current_text, segment_text) }; if let Some(path) = detect_cd_command(&new_text) { use crate::path_formatting; if let Some(new_cwd) = path_formatting::resolve_path(self.cwd.as_ref(), &path) { self.current_selected_command_mut().map(|c| { c.set_cwd(Some(new_cwd)); c.set_text("".to_owned()); if let Some(chain_type) = chain_type_opt { c.set_chain_type(*chain_type); } }); return; } } self.current_selected_command_mut().map(|c| { c.set_text(new_text); if let Some(chain_type) = chain_type_opt { c.set_chain_type(*chain_type); } }); } fn insert_new_pasted_segment( &mut self, segment_text: &str, chain_type_opt: &Option<ChainType>, is_last_line: bool, ) { use crate::path_formatting; let cd_path = detect_cd_command(segment_text); if let Some(path) = cd_path { if let Some(new_cwd) = path_formatting::resolve_path(self.cwd.as_ref(), &path) { self.current_selected_command_mut().map(|c| { c.set_cwd(Some(new_cwd)); if let Some(chain_type) = chain_type_opt { c.set_chain_type(*chain_type); } }); return; } } let Some(new_selected_index) = self.selection.current_selected_command_index.map(|i| i + 1) else { return; }; let mut new_command = CommandEntry::new(segment_text, self.cwd.clone()); if let Some(chain_type) = chain_type_opt { new_command.set_chain_type(*chain_type); } else if !is_last_line { new_command.set_chain_type(ChainType::And); } self.execution .all_commands .insert(new_selected_index, new_command); self.selection.current_selected_command_index = Some(new_selected_index); } fn ensure_line_end_chain_type(&mut self) { if let Some(last_cmd_index) = self.selection.current_selected_command_index { self.execution .all_commands .get_mut(last_cmd_index) .map(|c| { if matches!(c.get_chain_type(), ChainType::None) { c.set_chain_type(ChainType::And); } }); } } pub fn pasted_lines(&mut self, lines: Vec<&str>) { let Some(current_text) = self.editing_input_text() else { return; }; for (line_index, line) in lines.iter().enumerate() { let segments = split_by_chain_operators(line); let is_last_line = line_index == lines.len().saturating_sub(1); for (seg_index, (segment_text, chain_type_opt)) in segments.iter().enumerate() { if line_index == 0 && seg_index == 0 { self.handle_first_pasted_segment(&current_text, segment_text, chain_type_opt); } else { self.insert_new_pasted_segment(segment_text, chain_type_opt, is_last_line); } } if !is_last_line { self.ensure_line_end_chain_type(); } } self.start_editing_selected(); } pub fn remove_empty_commands(&mut self) { self.execution.remove_empty_commands(); } pub fn get_first_command(&self) -> Option<CommandEntry> { self.execution.get_first_command() } pub fn set_command_status(&mut self, command_index: usize, status: CommandStatus) { self.execution.set_command_status(command_index, status); } pub fn set_current_running_command_status(&mut self, status: CommandStatus) { self.execution.set_current_running_command_status(status); } pub fn get_current_running_command_status(&mut self) -> Option<CommandStatus> { self.execution.get_current_running_command_status() } pub fn handle_editing_submit(&mut self, current_cwd: &Option<PathBuf>) -> bool { let (handled_internally, new_selection_index) = self.editing.handle_submit( self.selection.current_selected_command_index, &mut self.execution.all_commands, current_cwd, ); self.selection.current_selected_command_index = new_selection_index; handled_internally } pub fn update_pane_id_for_command(&mut self, pane_id: PaneId, command_text: &str) { self.execution .update_pane_id_for_command(pane_id, command_text); } pub fn update_exited_command_statuses(&mut self, pane_manifest: &PaneManifest) -> bool { self.execution.update_exited_command_statuses(pane_manifest) } pub fn update_sequence_stopped_state(&mut self) -> bool { self.execution.update_sequence_stopped_state() } pub fn cycle_chain_type(&mut self) { self.current_selected_command_mut() .map(|c| c.cycle_chain_type()); } pub fn set_primary_pane_id_before_sequence(&mut self, pane_id: Option<PaneId>) { if pane_id.is_some() { self.execution.primary_pane_id_before_sequence = pane_id; } } pub fn clear_all_commands(&mut self) { self.execution.all_commands = vec![CommandEntry::new("", self.cwd.clone())]; self.editing.editing_input = Some(TextInput::new("".to_owned())); self.selection.current_selected_command_index = Some(0); self.execution.current_running_command_index = 0; } pub fn update_running_state(&mut self, primary_pane_id: Option<PaneId>) { self.remove_empty_commands(); self.set_primary_pane_id_before_sequence(primary_pane_id); self.layout.needs_reposition = true; self.execution.is_running = true; } pub fn can_run_sequence(&self) -> bool { self.execution.can_run_sequence() } pub fn copy_to_clipboard(&mut self) { self.execution.copy_to_clipboard(); } pub fn current_selected_command_mut(&mut self) -> Option<&mut CommandEntry> { let Some(i) = self.selection.current_selected_command_index else { return None; }; self.execution.all_commands.get_mut(i) } pub fn reposition_plugin(&mut self) -> bool { let mut repositioned = false; let Some(plugin_id) = self.plugin_id else { return repositioned; }; let Some(total_viewport_rows) = self.total_viewport_rows else { return repositioned; }; let Some(total_viewport_columns) = self.total_viewport_columns else { return repositioned; }; let total_commands = std::cmp::max(self.execution.all_commands.iter().len(), 1); let height_padding = 7; if self.all_commands_are_pending() { let initial_height = total_commands + height_padding; let y = total_viewport_rows.saturating_sub(initial_height) / 2; let coordinates = FloatingPaneCoordinates::new( Some(format!("25%")), Some(format!("{}", y)), Some(format!("50%")), Some(format!("{}", initial_height)), Some(false), // should not be pinned when running sequence ); coordinates.map(|coordinates| { if Some(&coordinates) != self.current_position.as_ref() { repositioned = true; self.current_position = Some(coordinates.clone()); change_floating_panes_coordinates(vec![( PaneId::Plugin(plugin_id), coordinates, )]); } }); } else { // Calculate longest table row width let longest_cwd_display = self.execution.longest_cwd_display(&self.cwd); let longest_command = self .execution .all_commands .iter() .map(|cmd| cmd.get_text().chars().count()) .max() .unwrap_or(1); let (max_chain_width, max_status_width) = crate::ui::components::calculate_max_widths( &self.execution.all_commands, self.layout.spinner_frame, ); let longest_line = crate::ui::components::calculate_longest_line( &longest_cwd_display, longest_command, max_chain_width, max_status_width, ); let ui_width = std::cmp::max(longest_line, 50) + 4; // 2 for ui-padding, 2 for pane frame let width = std::cmp::min(ui_width, total_viewport_columns / 2); let height = (height_padding + total_commands).min((total_viewport_rows * 25) / 100); // Position: top-right with 1-space margins let x = total_viewport_columns.saturating_sub(width); let y = 1; let coordinates = FloatingPaneCoordinates::new( Some(x.to_string()), Some(y.to_string()), Some(width.to_string()), Some(height.to_string()), Some(true), // should be pinned for sequence ); coordinates.map(|coordinates| { if Some(&coordinates) != self.current_position.as_ref() { self.current_position = Some(coordinates.clone()); repositioned = true; change_floating_panes_coordinates(vec![( PaneId::Plugin(plugin_id), coordinates, )]); } }); } repositioned } pub fn all_commands_are_pending(&self) -> bool { self.execution .all_commands .iter() .all(|command| matches!(command.get_status(), CommandStatus::Pending)) } fn current_selected_command(&self) -> Option<&CommandEntry> { let Some(i) = self.selection.current_selected_command_index else { return None; }; self.execution.all_commands.get(i) } pub fn execute_command_sequence(&mut self) { self.execution .execute_command_sequence(&self.shell, &self.cwd, self.primary_pane_id); } } impl Default for State { fn default() -> Self { let mut state = Self::new(); state.is_first_run = true; state } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/layout.rs
default-plugins/sequence/src/state/layout.rs
use crate::state::positioning; use std::path::PathBuf; use zellij_tile::prelude::*; pub struct Layout { pub needs_reposition: bool, pub cached_cursor_position: Option<(usize, usize)>, pub spinner_frame: usize, pub spinner_timer_scheduled: bool, } impl Layout { pub fn new() -> Self { Self { needs_reposition: false, cached_cursor_position: None, spinner_frame: 0, spinner_timer_scheduled: false, } } pub fn reposition_plugin_based_on_sequence_state( &mut self, is_running: bool, first_command_pane_id: Option<PaneId>, pane_manifest: &PaneManifest, plugin_id: Option<u32>, total_viewport_columns: Option<usize>, total_viewport_rows: Option<usize>, total_commands: usize, _selected_index: Option<usize>, _running_index: usize, _cwd: &Option<PathBuf>, ) { let Some(plugin_id) = plugin_id else { return; }; let (Some(total_cols), Some(total_rows)) = (total_viewport_columns, total_viewport_rows) else { return; }; if !self.needs_reposition || !is_running { return; } let Some(first_pane_id) = first_command_pane_id else { return; }; for (_tab_index, panes) in &pane_manifest.panes { for pane in panes { if !pane.is_plugin && PaneId::Terminal(pane.id) == first_pane_id { positioning::reposition_plugin_for_sequence( plugin_id, total_cols, total_rows, total_commands, ); self.needs_reposition = false; return; } } } } } impl Default for Layout { fn default() -> Self { Self::new() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/selection.rs
default-plugins/sequence/src/state/selection.rs
use crate::state::{CommandEntry, Editing}; use std::path::PathBuf; use zellij_tile::prelude::*; pub struct Selection { pub current_selected_command_index: Option<usize>, pub scroll_offset: usize, } impl Selection { pub fn new() -> Self { Self { current_selected_command_index: Some(0), scroll_offset: 0, } } pub fn add_empty_command_after_current_selected( &mut self, all_commands: &mut Vec<CommandEntry>, editing: &mut Editing, cwd: &Option<PathBuf>, ) { self.save_editing_buffer_to_current_selected(all_commands, editing); editing.editing_input.as_mut().map(|i| i.clear()); if !self.current_selected_command_is_empty(all_commands, editing) { self.current_selected_command_mut(all_commands) .map(|c| c.fill_chain_type_if_empty()); if let Some(current_selected_command_index) = self.current_selected_command_index.take() { let new_command = CommandEntry::new("", cwd.clone()); if current_selected_command_index == all_commands.len().saturating_sub(1) { all_commands.push(new_command); } else { all_commands.insert(current_selected_command_index + 1, new_command); } self.current_selected_command_index = Some(current_selected_command_index + 1); } } } pub fn current_selected_command_is_empty( &self, all_commands: &[CommandEntry], editing: &Editing, ) -> bool { let text_input_is_empty = editing .editing_input .as_ref() .map(|i| i.is_empty()) .unwrap_or(true); let current_selected_command_is_empty = self .current_selected_command_index .and_then(|i| all_commands.get(i).map(|c| c.is_empty())) .unwrap_or(true); text_input_is_empty && current_selected_command_is_empty } pub fn remove_current_selected_command( &mut self, all_commands: &mut Vec<CommandEntry>, editing: &mut Editing, ) -> Option<PaneId> { // returns the pane_id of the removed command, if any let mut removed_pane_id = None; let Some(mut current_selected_command_index) = self.current_selected_command_index else { return removed_pane_id; }; if all_commands.len() > 1 && all_commands.len() > current_selected_command_index { let command = all_commands.remove(current_selected_command_index); removed_pane_id = command.get_pane_id(); } else { self.clear_current_selected_command(all_commands, editing); } if current_selected_command_index >= all_commands.len() && current_selected_command_index > 0 { current_selected_command_index -= 1; } self.update_current_selected_command_index( current_selected_command_index, all_commands, editing, ); if current_selected_command_index == all_commands.len().saturating_sub(1) { self.current_selected_command_mut(all_commands) .map(|c| c.clear_chain_type()); } removed_pane_id } pub fn clear_current_selected_command( &mut self, all_commands: &mut [CommandEntry], editing: &mut Editing, ) { let Some(current_selected_command_index) = self.current_selected_command_index else { return; }; self.current_selected_command_mut(all_commands) .map(|c| c.clear_text()); self.clear_editing_buffer(editing); if current_selected_command_index == all_commands.len().saturating_sub(1) { self.current_selected_command_mut(all_commands) .map(|c| c.clear_chain_type()); } } pub fn move_up(&mut self, all_commands: &mut [CommandEntry], editing: &mut Editing) { self.save_editing_buffer_to_current_selected(all_commands, editing); match self.current_selected_command_index.as_mut() { Some(i) if *i > 0 => { *i -= 1; }, None => { self.current_selected_command_index = Some(all_commands.len().saturating_sub(1)); }, _ => { self.current_selected_command_index = None; }, } self.update_editing_buffer_to_current_selected(all_commands, editing); } pub fn move_down(&mut self, all_commands: &mut [CommandEntry], editing: &mut Editing) { self.save_editing_buffer_to_current_selected(all_commands, editing); match self.current_selected_command_index.as_mut() { Some(i) if *i < all_commands.len().saturating_sub(1) => { *i += 1; }, None => { self.current_selected_command_index = Some(0); }, _ => { self.current_selected_command_index = None; }, } self.update_editing_buffer_to_current_selected(all_commands, editing); } fn current_selected_command_mut<'a>( &self, all_commands: &'a mut [CommandEntry], ) -> Option<&'a mut CommandEntry> { let Some(i) = self.current_selected_command_index else { return None; }; all_commands.get_mut(i) } fn current_selected_command<'a>( &self, all_commands: &'a [CommandEntry], ) -> Option<&'a CommandEntry> { let Some(i) = self.current_selected_command_index else { return None; }; all_commands.get(i) } fn clear_editing_buffer(&self, editing: &mut Editing) { editing.editing_input.as_mut().map(|c| c.clear()); } fn update_current_selected_command_index( &mut self, new_index: usize, all_commands: &[CommandEntry], editing: &mut Editing, ) { self.current_selected_command_index = Some(new_index); self.update_editing_buffer_to_current_selected(all_commands, editing); } fn get_text_of_current_selected_command( &self, all_commands: &[CommandEntry], ) -> Option<String> { self.current_selected_command(all_commands) .map(|c| c.get_text()) } fn save_editing_buffer_to_current_selected( &self, all_commands: &mut [CommandEntry], editing: &mut Editing, ) { if let Some(text_input) = editing.editing_input.as_ref().map(|i| i.get_text()) { self.current_selected_command_mut(all_commands) .map(|c| c.set_text(text_input.to_owned())); } } fn update_editing_buffer_to_current_selected( &self, all_commands: &[CommandEntry], editing: &mut Editing, ) { let new_text_of_current_selected_command = self .get_text_of_current_selected_command(all_commands) .unwrap_or_else(|| String::new()); if let Some(editing_input) = editing.editing_input.as_mut() { editing_input.set_text(new_text_of_current_selected_command); } } } impl Default for Selection { fn default() -> Self { Self::new() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/command_entry.rs
default-plugins/sequence/src/state/command_entry.rs
use super::{ChainType, CommandStatus}; use std::path::PathBuf; use std::time::Instant; use zellij_tile::prelude::PaneId; #[derive(Debug, Clone)] pub struct CommandEntry { text: String, cwd: Option<PathBuf>, pub(super) chain_type: ChainType, pub(super) status: CommandStatus, pub(super) start_time: std::time::Instant, } impl Default for CommandEntry { fn default() -> Self { CommandEntry { text: String::default(), cwd: None, chain_type: ChainType::default(), status: CommandStatus::default(), start_time: Instant::now(), } } } impl CommandEntry { pub fn new(text: &str, cwd: Option<PathBuf>) -> Self { CommandEntry { text: text.to_owned(), cwd, ..Default::default() } } pub fn with_and(mut self) -> Self { self.chain_type = ChainType::And; self } pub fn get_text(&self) -> String { self.text.clone() } pub fn set_text(&mut self, text: String) { self.text = text; } pub fn clear_text(&mut self) { self.text.clear(); } pub fn get_chain_type(&self) -> ChainType { self.chain_type } pub fn set_chain_type(&mut self, chain_type: ChainType) { self.chain_type = chain_type; } pub fn get_status(&self) -> CommandStatus { self.status.clone() } pub fn set_status(&mut self, status: CommandStatus) { self.status = status; } pub fn get_pane_id(&self) -> Option<PaneId> { self.status.get_pane_id() } pub fn is_empty(&self) -> bool { self.text.trim().is_empty() } pub fn fill_chain_type_if_empty(&mut self) { if let ChainType::None = self.chain_type { self.chain_type = ChainType::And; } } pub fn clear_chain_type(&mut self) { self.chain_type = ChainType::None; } pub fn clear_status(&mut self) { self.status = CommandStatus::Pending; } pub fn cycle_chain_type(&mut self) { self.chain_type.cycle_next(); } pub fn get_cwd(&self) -> Option<PathBuf> { self.cwd.clone() } pub fn set_cwd(&mut self, cwd: Option<PathBuf>) { self.cwd = cwd; } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false
zellij-org/zellij
https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/default-plugins/sequence/src/state/editing.rs
default-plugins/sequence/src/state/editing.rs
use crate::path_formatting; use crate::state::CommandEntry; use crate::ui::text_input::TextInput; use std::path::PathBuf; pub struct Editing { pub editing_input: Option<TextInput>, } impl Editing { pub fn new() -> Self { Self { editing_input: Some(TextInput::new("".to_owned())), } } pub fn start_editing(&mut self, text: String) { self.editing_input = Some(TextInput::new(text)); } pub fn cancel_editing(&mut self) { self.editing_input = None; } pub fn input_text(&self) -> Option<String> { self.editing_input.as_ref().map(|e| e.get_text().to_owned()) } pub fn set_input_text(&mut self, text: String) { self.editing_input.as_mut().map(|e| e.set_text(text)); } pub fn handle_submit( &mut self, selection_index: Option<usize>, all_commands: &mut Vec<CommandEntry>, current_cwd: &Option<PathBuf>, ) -> (bool, Option<usize>) { let mut handled_internally = false; let mut new_selection_index = None; if let Some(current_text) = self.editing_input.as_ref().map(|i| i.get_text()) { if let Some(index) = selection_index { if let Some(command) = all_commands.get_mut(index) { if current_text.starts_with("cd ") || current_text == "cd" { let path = if current_text == "cd" { "~" } else { current_text[3..].trim() }; if let Some(new_cwd) = path_formatting::resolve_path(current_cwd.as_ref(), path) { command.set_cwd(Some(new_cwd)); } command.set_text("".to_owned()); self.editing_input.as_mut().map(|c| c.clear()); new_selection_index = selection_index; // remain editing after a cd command handled_internally = true; return (handled_internally, new_selection_index); // avoid setting edit_input to None below, we // still want to be in editing mode after // changing directory with cd } else { command.set_text(current_text.to_owned()); } } } } self.editing_input = None; (handled_internally, new_selection_index) } } impl Default for Editing { fn default() -> Self { Self::new() } }
rust
MIT
3fe48a972c55537502128779116d38d8f8aedb7e
2026-01-04T15:35:12.838106Z
false