Skip to content

Commit

Permalink
plugins: Reimplement old API and handle errors
Browse files Browse the repository at this point in the history
by printing non-fatal errors to `stdout` and `stderr` (so they show up
in the logs).
  • Loading branch information
har7an committed Sep 4, 2022
1 parent f5ead76 commit 8cae215
Show file tree
Hide file tree
Showing 7 changed files with 107 additions and 70 deletions.
43 changes: 28 additions & 15 deletions default-plugins/compact-bar/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,16 @@ static ARROW_SEPARATOR: &str = "";
register_plugin!(State);

impl ZellijPlugin for State {
fn load(&mut self) -> Result<()> {
fn load(&mut self) {
set_selectable(false);
subscribe(&[
EventType::TabUpdate,
EventType::ModeUpdate,
EventType::Mouse,
])
.context("Failed to subscribe 'compact-bar' to events")?;
Ok(())
]);
}

fn update(&mut self, event: Event) -> Result<()> {
fn update(&mut self, event: Event) {
match event {
Event::ModeUpdate(mode_info) => self.mode_info = mode_info,
Event::TabUpdate(tabs) => {
Expand Down Expand Up @@ -69,12 +67,11 @@ impl ZellijPlugin for State {
eprintln!("Got unrecognized event: {:?}", event);
},
}
Ok(())
}

fn render(&mut self, _rows: usize, cols: usize) -> Result<()> {
fn render(&mut self, _rows: usize, cols: usize) {
if self.tabs.is_empty() {
return Ok(());
return;
}
let mut all_tabs: Vec<LinePart> = vec![];
let mut active_tab_index = 0;
Expand All @@ -101,16 +98,24 @@ impl ZellijPlugin for State {
is_alternate_tab = !is_alternate_tab;
all_tabs.push(tab);
}
let tab_line = tab_line(
let tab_line = match 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.mode,
)
.context("Failed to render compact bar plugin")?;
) {
Ok(line) => line,
err => {
err.context("Failed to render compact bar plugin")
.to_stdout()
.to_stderr()
.non_fatal();
return;
},
};
let mut s = String::new();
let mut len_cnt = 0;
for (idx, bar_part) in tab_line.iter().enumerate() {
Expand All @@ -124,9 +129,18 @@ impl ZellijPlugin for State {
// First three elements of tab_line are "Zellij", session name and mode, hence the idx > 3 condition.
// Tabs are indexed starting from 1, therefore we need subtract 3 below.
switch_tab_to(
TryInto::<u32>::try_into(idx).with_context(|| {
format!("Failed to get valid tab index from index {idx}")
})? - 3,
match TryInto::<u32>::try_into(idx) {
Ok(idx) => idx,
err => {
err.with_context(|| {
format!("Failed to get valid tab index from index {idx}")
})
.to_stdout()
.to_stderr()
.non_fatal();
return;
},
} - 3,
);
}
len_cnt += bar_part.len;
Expand All @@ -144,6 +158,5 @@ impl ZellijPlugin for State {
},
}
self.should_render = false;
Ok(())
}
}
28 changes: 17 additions & 11 deletions default-plugins/status-bar/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,21 +169,22 @@ fn color_elements(palette: Palette, different_color_alternates: bool) -> Colored
}

impl ZellijPlugin for State {
fn load(&mut self) -> Result<()> {
fn load(&mut self) {
// TODO: Should be able to choose whether to use the cache through config.
self.tip_name =
get_cached_tip_name().context("status bar: Failed to acquire a tip to display")?;
self.tip_name = get_cached_tip_name()
.context("status bar: Failed to acquire a tip to display")
.fatal();
set_selectable(false);
subscribe(&[
EventType::ModeUpdate,
EventType::TabUpdate,
EventType::CopyToClipboard,
EventType::InputReceived,
EventType::SystemClipboardFailure,
])
]);
}

fn update(&mut self, event: Event) -> Result<()> {
fn update(&mut self, event: Event) {
match event {
Event::ModeUpdate(mode_info) => {
self.mode_info = mode_info;
Expand All @@ -203,10 +204,9 @@ impl ZellijPlugin for State {
},
_ => {},
}
Ok(())
}

fn render(&mut self, _rows: usize, cols: usize) -> Result<()> {
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
Expand All @@ -215,9 +215,16 @@ impl ZellijPlugin for State {
};

let first_line = first_line(&self.mode_info, cols, separator);
let second_line = self
.second_line(cols)
.context("status bar: Failed to generate second line of output")?;
let second_line = match self.second_line(cols) {
Ok(line) => line,
err => {
err.context("status bar: Failed to generate second line of output")
.to_stdout()
.to_stderr()
.non_fatal();
return;
},
};

let background = match self.mode_info.style.colors.theme_hue {
ThemeHue::Dark => self.mode_info.style.colors.black,
Expand All @@ -235,7 +242,6 @@ impl ZellijPlugin for State {
},
}
println!("\u{1b}[m{}\u{1b}[0K", second_line);
Ok(())
}
}

Expand Down
2 changes: 1 addition & 1 deletion default-plugins/status-bar/src/tip/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl LocalCache {
Err(err) => {
if json_cache.is_empty() {
return Ok(Metadata {
zellij_version: get_zellij_version().map_err(LocalCacheError::Generic)?,
zellij_version: get_zellij_version(),
cached_data: HashMap::new(),
});
}
Expand Down
3 changes: 1 addition & 2 deletions default-plugins/status-bar/src/tip/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ pub fn get_cached_tip_name() -> Result<String> {
let mut local_cache = LocalCache::new(PathBuf::from(DEFAULT_CACHE_FILE_PATH))
.context("Failed to initialize tip cache")?;

let zellij_version = get_zellij_version()
.context("status bar: Failed to acquire zellij version to query cache")?;
let zellij_version = get_zellij_version();
if zellij_version.ne(local_cache.get_version()) {
local_cache.set_version(zellij_version);
local_cache.clear().context("Failed to clear tip cache")?;
Expand Down
44 changes: 26 additions & 18 deletions default-plugins/strider/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@ use zellij_tile::prelude::*;
register_plugin!(State);

impl ZellijPlugin for State {
fn load(&mut self) -> Result<()> {
refresh_directory(self)?;
subscribe(&[EventType::Key, EventType::Mouse])
.context("Failed to load plugin status bar")?;
Ok(())
fn load(&mut self) {
refresh_directory(self).fatal();
subscribe(&[EventType::Key, EventType::Mouse]);
}

fn update(&mut self, event: Event) -> Result<()> {
fn update(&mut self, event: Event) {
let prev_event = if self.ev_history.len() == 2 {
self.ev_history.pop_front()
} else {
Expand All @@ -33,7 +31,10 @@ impl ZellijPlugin for State {
},
Key::Right | Key::Char('\n') | Key::Char('l') if !self.files.is_empty() => {
self.traverse_dir_or_open_file()
.context("Failed to update file tree")?;
.context("Failed to update file tree")
.to_stdout()
.to_stderr()
.non_fatal();
self.ev_history.clear();
},
Key::Left | Key::Char('h') => {
Expand All @@ -43,12 +44,12 @@ impl ZellijPlugin for State {
// or some such is that there are certain cases in which self.path
// is empty and this will work then too
self.path.pop();
refresh_directory(self)?;
refresh_directory(self).to_stdout().to_stderr().non_fatal();
}
},
Key::Char('.') => {
self.toggle_hidden_files();
refresh_directory(self)?;
refresh_directory(self).to_stdout().to_stderr().non_fatal();
},

_ => (),
Expand All @@ -63,15 +64,18 @@ impl ZellijPlugin for State {
},
Mouse::Release(line, _) => {
if line < 0 {
return Ok(());
return;
}
let mut should_select = true;
if let Some((Event::Mouse(Mouse::Release(prev_line, _)), t)) = prev_event {
if prev_line == line
&& Instant::now().saturating_duration_since(t).as_millis() < 400
{
self.traverse_dir_or_open_file()
.context("Failed to update file tree")?;
.context("Failed to update file tree")
.to_stdout()
.to_stderr()
.non_fatal();
self.ev_history.clear();
should_select = false;
}
Expand All @@ -86,10 +90,9 @@ impl ZellijPlugin for State {
dbg!("Unknown event {:?}", event);
},
}
Ok(())
}

fn render(&mut self, rows: usize, cols: usize) -> Result<()> {
fn render(&mut self, rows: usize, cols: usize) {
for i in 0..rows {
if self.selected() < self.scroll() {
*self.scroll_mut() = self.selected();
Expand All @@ -100,10 +103,16 @@ impl ZellijPlugin for State {

let i = self.scroll() + i;
if let Some(entry) = self.files.get(i) {
let mut path = entry
.as_line(cols)
.context("Failed to render file list")?
.normal();
let mut path = match entry.as_line(cols) {
Ok(path) => path.normal(),
err => {
err.context("Failed to render file list")
.to_stdout()
.to_stderr()
.non_fatal();
return;
},
};

if let FsEntry::Dir(..) = entry {
path = path.dimmed().bold();
Expand All @@ -118,6 +127,5 @@ impl ZellijPlugin for State {
println!();
}
}
Ok(())
}
}
9 changes: 3 additions & 6 deletions default-plugins/strider/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,9 @@ impl State {
format!("Failed to traverse to directory '{}'", self.path.display())
})?;
},
FsEntry::File(p, _) => {
open_file(p.strip_prefix(ROOT).with_context(|| {
format!("Failed to strip path from file '{}'", p.display())
})?)
.with_context(|| format!("Failed to open file '{}'", p.display()))?;
},
FsEntry::File(p, _) => open_file(p.strip_prefix(ROOT).with_context(|| {
format!("Failed to strip path from file '{}'", p.display())
})?),
}
}
Ok(())
Expand Down
Loading

0 comments on commit 8cae215

Please sign in to comment.