Removed AppState and the unneeded get_help() function

This commit is contained in:
Brooks J Rady 2021-03-25 14:56:59 +00:00
parent 0ea8ce497d
commit 0371c111b7
6 changed files with 25 additions and 81 deletions

View file

@ -23,7 +23,9 @@ static ARROW_SEPARATOR: &str = "";
static MORE_MSG: &str = " ... ";
#[derive(Default)]
struct State {}
struct State {
mode_info: ModeInfo,
}
register_tile!(State);
@ -44,15 +46,21 @@ impl ZellijTile for State {
set_selectable(false);
set_invisible_borders(true);
set_max_height(2);
subscribe(&[EventType::ModeUpdate]);
}
fn update(&mut self, event: Event) {
if let Event::ModeUpdate(mode_info) = event {
self.mode_info = mode_info;
}
}
fn render(&mut self, _rows: usize, cols: usize) {
let help = get_help();
let superkey = superkey();
let ctrl_keys = ctrl_keys(&help, cols - superkey.len);
let ctrl_keys = ctrl_keys(&self.mode_info, cols - superkey.len);
let first_line = format!("{}{}", superkey, ctrl_keys);
let second_line = keybinds(&help, cols);
let second_line = keybinds(&self.mode_info, cols);
// [48;5;238m is gray background, [0K is so that it fills the rest of the line
// [48;5;16m is black background, [0K is so that it fills the rest of the line

View file

@ -305,8 +305,6 @@ impl From<&PluginInstruction> for PluginContext {
/// Stack call representations corresponding to the different types of [`AppInstruction`]s.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AppContext {
GetState,
SetState,
Exit,
Error,
}
@ -314,8 +312,6 @@ pub enum AppContext {
impl From<&AppInstruction> for AppContext {
fn from(app_instruction: &AppInstruction) -> Self {
match *app_instruction {
AppInstruction::GetState(_) => AppContext::GetState,
AppInstruction::SetState(_) => AppContext::SetState,
AppInstruction::Exit => AppContext::Exit,
AppInstruction::Error(_) => AppContext::Error,
}

View file

@ -2,7 +2,7 @@
use super::actions::Action;
use super::keybinds::get_default_keybinds;
use crate::common::{update_state, AppInstruction, AppState, SenderWithContext, OPENCALLS};
use crate::common::{AppInstruction, SenderWithContext, OPENCALLS};
use crate::errors::ContextType;
use crate::os_input_output::OsApi;
use crate::pty_bus::PtyInstruction;
@ -11,7 +11,7 @@ use crate::wasm_vm::{NaughtyEventType, PluginInputType, PluginInstruction};
use crate::CommandIsExecuting;
use termion::input::{TermRead, TermReadEventsAndRaw};
use zellij_tile::data::{InputMode, Key, ModeInfo};
use zellij_tile::data::{Event, InputMode, Key, ModeInfo};
use super::keybinds::key_to_actions;
@ -128,11 +128,14 @@ impl InputHandler {
}
Action::SwitchToMode(mode) => {
self.mode = mode;
update_state(&self.send_app_instructions, |_| AppState {
input_mode: self.mode,
});
self.send_plugin_instructions
.send(PluginInstruction::Update(
None,
Event::ModeUpdate(get_mode_info(mode)),
))
.unwrap();
self.send_screen_instructions
.send(ScreenInstruction::ChangeInputMode(self.mode))
.send(ScreenInstruction::ChangeInputMode(mode))
.unwrap();
self.send_screen_instructions
.send(ScreenInstruction::Render)
@ -273,7 +276,7 @@ impl InputHandler {
/// Creates a [`Help`] struct indicating the current [`InputMode`] and its keybinds
/// (as pairs of [`String`]s).
// TODO this should probably be automatically generated in some way
pub fn get_help(mode: InputMode) -> ModeInfo {
pub fn get_mode_info(mode: InputMode) -> ModeInfo {
let mut keybinds: Vec<(String, String)> = vec![];
match mode {
InputMode::Normal | InputMode::Locked => {}

View file

@ -9,10 +9,10 @@ pub mod screen;
pub mod utils;
pub mod wasm_vm;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread;
use std::{cell::RefCell, sync::mpsc::TrySendError};
use std::{collections::HashMap, fs};
use std::{
collections::HashSet,
@ -50,25 +50,6 @@ pub enum ApiCommand {
SplitVertically,
MoveFocus,
}
// FIXME: It would be good to add some more things to this over time
#[derive(Debug, Clone, Default)]
pub struct AppState {
pub input_mode: InputMode,
}
// FIXME: Make this a method on the big `Communication` struct, so that app_tx can be extracted
// from self instead of being explicitly passed here
pub fn update_state(
app_tx: &SenderWithContext<AppInstruction>,
update_fn: impl FnOnce(AppState) -> AppState,
) {
let (state_tx, state_rx) = mpsc::channel();
drop(app_tx.send(AppInstruction::GetState(state_tx)));
let state = state_rx.recv().unwrap();
drop(app_tx.send(AppInstruction::SetState(update_fn(state))))
}
/// An [MPSC](mpsc) asynchronous channel with added error context.
pub type ChannelWithContext<T> = (
@ -112,19 +93,6 @@ impl<T: Clone> SenderWithContext<T> {
}
}
/// Attempts to send an event on this sender's channel, terminating instead of blocking
/// if the event could not be sent (buffer full or connection closed).
///
/// This can only be called on [`SyncSender`](SenderType::SyncSender)s, and will
/// panic if called on an asynchronous [`Sender`](SenderType::Sender).
pub fn try_send(&self, event: T) -> Result<(), TrySendError<(T, ErrorContext)>> {
if let SenderType::SyncSender(ref s) = self.sender {
s.try_send((event, self.err_ctx))
} else {
panic!("try_send can only be called on SyncSenders!")
}
}
/// Updates this [`SenderWithContext`]'s [`ErrorContext`]. This is the way one adds
/// a call to the error context.
///
@ -147,8 +115,6 @@ thread_local!(
/// Instructions related to the entire application.
#[derive(Clone)]
pub enum AppInstruction {
GetState(mpsc::Sender<AppState>),
SetState(AppState),
Exit,
Error(String),
}
@ -162,7 +128,6 @@ pub fn start(mut os_input: Box<dyn OsApi>, opts: CliArgs) {
.get_stdout_writer()
.write(take_snapshot.as_bytes())
.unwrap();
let mut app_state = AppState::default();
let command_is_executing = CommandIsExecuting::new();
@ -715,8 +680,6 @@ pub fn start(mut os_input: Box<dyn OsApi>, opts: CliArgs) {
send_screen_instructions.update(err_ctx);
send_pty_instructions.update(err_ctx);
match app_instruction {
AppInstruction::GetState(state_tx) => drop(state_tx.send(app_state.clone())),
AppInstruction::SetState(state) => app_state = state,
AppInstruction::Exit => {
break;
}

View file

@ -2,18 +2,14 @@ use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
path::PathBuf,
sync::{
mpsc::{channel, Sender},
Arc, Mutex,
},
sync::{mpsc::Sender, Arc, Mutex},
};
use wasmer::{imports, Function, ImportObject, Store, WasmerEnv};
use wasmer_wasi::WasiEnv;
use zellij_tile::data::{Event, EventType, TabInfo};
use super::{
input::handler::get_help, pty_bus::PtyInstruction, screen::ScreenInstruction, AppInstruction,
PaneId, SenderWithContext,
pty_bus::PtyInstruction, screen::ScreenInstruction, AppInstruction, PaneId, SenderWithContext,
};
#[derive(Clone, Debug, PartialEq, Hash, Eq, Serialize, Deserialize)]
@ -59,7 +55,6 @@ pub fn zellij_imports(store: &Store, plugin_env: &PluginEnv) -> ImportObject {
"host_set_invisible_borders" => Function::new_native_with_env(store, plugin_env.clone(), host_set_invisible_borders),
"host_set_max_height" => Function::new_native_with_env(store, plugin_env.clone(), host_set_max_height),
"host_set_selectable" => Function::new_native_with_env(store, plugin_env.clone(), host_set_selectable),
"host_get_help" => Function::new_native_with_env(store, plugin_env.clone(), host_get_help),
}
}
}
@ -117,21 +112,6 @@ fn host_set_invisible_borders(plugin_env: &PluginEnv, invisible_borders: i32) {
.unwrap()
}
fn host_get_help(plugin_env: &PluginEnv) {
let (state_tx, state_rx) = channel();
// FIXME: If I changed the application so that threads were sent the termination
// signal and joined one at a time, there would be an order to shutdown, so I
// could get rid of this .is_ok() check and the .try_send()
if plugin_env
.send_app_instructions
.try_send(AppInstruction::GetState(state_tx))
.is_ok()
{
let help = get_help(state_rx.recv().unwrap().input_mode);
wasi_write_string(&plugin_env.wasi_env, &serde_json::to_string(&help).unwrap());
}
}
// Helper Functions ---------------------------------------------------------------------------------------------------
// FIXME: Unwrap city

View file

@ -36,11 +36,6 @@ pub fn set_selectable(selectable: bool) {
unsafe { host_set_selectable(selectable) };
}
pub fn get_help() -> ModeInfo {
unsafe { host_get_help() };
deserialize_from_stdin().unwrap_or_default()
}
pub fn get_tabs() -> Vec<TabInfo> {
deserialize_from_stdin().unwrap_or_default()
}
@ -61,5 +56,4 @@ extern "C" {
fn host_set_max_height(max_height: i32);
fn host_set_selectable(selectable: i32);
fn host_set_invisible_borders(invisible_borders: i32);
fn host_get_help();
}