diff options
| author | Kunal Mohan <44079328+kunalmohan@users.noreply.github.com> | 2021-05-06 22:11:07 +0530 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-05-06 22:11:07 +0530 |
| commit | d5433f8f8995c155f231c823d49813882b6212bf (patch) | |
| tree | 529d5ee706ded18cd24f26a3b0372bf17ecb81ed /src/common | |
| parent | docs(changelog): Add Manpage #455 (diff) | |
| parent | explicitly set file and directory permissions (diff) | |
| download | sl0ppij-d5433f8f8995c155f231c823d49813882b6212bf.tar.gz sl0ppij-d5433f8f8995c155f231c823d49813882b6212bf.tar.xz sl0ppij-d5433f8f8995c155f231c823d49813882b6212bf.zip | |
Merge pull request #223 from zellij-org/isolate-pty
Psuedo Client-Server model
Diffstat (limited to 'src/common')
| -rw-r--r-- | src/common/command_is_executing.rs | 50 | ||||
| -rw-r--r-- | src/common/errors.rs | 92 | ||||
| -rw-r--r-- | src/common/input/handler.rs | 211 | ||||
| -rw-r--r-- | src/common/ipc.rs | 74 | ||||
| -rw-r--r-- | src/common/mod.rs | 648 | ||||
| -rw-r--r-- | src/common/os_input_output.rs | 237 | ||||
| -rw-r--r-- | src/common/pty_bus.rs | 48 | ||||
| -rw-r--r-- | src/common/screen.rs | 54 | ||||
| -rw-r--r-- | src/common/setup.rs | 8 | ||||
| -rw-r--r-- | src/common/utils/consts.rs | 37 | ||||
| -rw-r--r-- | src/common/utils/logging.rs | 29 | ||||
| -rw-r--r-- | src/common/wasm_vm.rs | 7 |
12 files changed, 482 insertions, 1013 deletions
diff --git a/src/common/command_is_executing.rs b/src/common/command_is_executing.rs index 775a7bfc..ad032557 100644 --- a/src/common/command_is_executing.rs +++ b/src/common/command_is_executing.rs @@ -3,51 +3,31 @@ use std::sync::{Arc, Condvar, Mutex}; #[derive(Clone)] pub struct CommandIsExecuting { - opening_new_pane: Arc<(Mutex<bool>, Condvar)>, - closing_pane: Arc<(Mutex<bool>, Condvar)>, + input_thread: Arc<(Mutex<bool>, Condvar)>, } impl CommandIsExecuting { pub fn new() -> Self { CommandIsExecuting { - opening_new_pane: Arc::new((Mutex::new(false), Condvar::new())), - closing_pane: Arc::new((Mutex::new(false), Condvar::new())), + input_thread: Arc::new((Mutex::new(false), Condvar::new())), } } - pub fn closing_pane(&mut self) { - let (lock, _cvar) = &*self.closing_pane; - let mut closing_pane = lock.lock().unwrap(); - *closing_pane = true; + pub fn blocking_input_thread(&mut self) { + let (lock, _cvar) = &*self.input_thread; + let mut input_thread = lock.lock().unwrap(); + *input_thread = true; } - pub fn done_closing_pane(&mut self) { - let (lock, cvar) = &*self.closing_pane; - let mut closing_pane = lock.lock().unwrap(); - *closing_pane = false; + pub fn unblock_input_thread(&mut self) { + let (lock, cvar) = &*self.input_thread; + let mut input_thread = lock.lock().unwrap(); + *input_thread = false; cvar.notify_all(); } - pub fn opening_new_pane(&mut self) { - let (lock, _cvar) = &*self.opening_new_pane; - let mut opening_new_pane = lock.lock().unwrap(); - *opening_new_pane = true; - } - pub fn done_opening_new_pane(&mut self) { - let (lock, cvar) = &*self.opening_new_pane; - let mut opening_new_pane = lock.lock().unwrap(); - *opening_new_pane = false; - cvar.notify_all(); - } - pub fn wait_until_pane_is_closed(&self) { - let (lock, cvar) = &*self.closing_pane; - let mut closing_pane = lock.lock().unwrap(); - while *closing_pane { - closing_pane = cvar.wait(closing_pane).unwrap(); - } - } - pub fn wait_until_new_pane_is_opened(&self) { - let (lock, cvar) = &*self.opening_new_pane; - let mut opening_new_pane = lock.lock().unwrap(); - while *opening_new_pane { - opening_new_pane = cvar.wait(opening_new_pane).unwrap(); + pub fn wait_until_input_thread_is_unblocked(&self) { + let (lock, cvar) = &*self.input_thread; + let mut input_thread = lock.lock().unwrap(); + while *input_thread { + input_thread = cvar.wait(input_thread).unwrap(); } } } diff --git a/src/common/errors.rs b/src/common/errors.rs index c1c6753f..411e0225 100644 --- a/src/common/errors.rs +++ b/src/common/errors.rs @@ -1,9 +1,11 @@ //! Error context system based on a thread-local representation of the call stack, itself based on //! the instructions that are sent between threads. -use super::{AppInstruction, ASYNCOPENCALLS, OPENCALLS}; +use super::{ServerInstruction, ASYNCOPENCALLS, OPENCALLS}; +use crate::client::ClientInstruction; use crate::pty_bus::PtyInstruction; use crate::screen::ScreenInstruction; +use serde::{Deserialize, Serialize}; use std::fmt::{Display, Error, Formatter}; @@ -19,7 +21,7 @@ use std::panic::PanicInfo; #[cfg(not(test))] pub fn handle_panic( info: &PanicInfo<'_>, - send_app_instructions: &SenderWithContext<AppInstruction>, + send_app_instructions: &SenderWithContext<ClientInstruction>, ) { use backtrace::Backtrace; use std::{process, thread}; @@ -66,9 +68,7 @@ pub fn handle_panic( println!("{}", backtrace); process::exit(1); } else { - send_app_instructions - .send(AppInstruction::Error(backtrace)) - .unwrap(); + let _ = send_app_instructions.send(ClientInstruction::Error(backtrace)); } } @@ -79,7 +79,7 @@ pub fn get_current_ctx() -> ErrorContext { } /// A representation of the call stack. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Serialize, Deserialize)] pub struct ErrorContext { calls: [ContextType; MAX_THREAD_CALL_STACK], } @@ -130,8 +130,8 @@ impl Display for ErrorContext { /// /// Complex variants store a variant of a related enum, whose variants can be built from /// the corresponding Zellij MSPC instruction enum variants ([`ScreenInstruction`], -/// [`PtyInstruction`], [`AppInstruction`], etc). -#[derive(Copy, Clone, PartialEq)] +/// [`PtyInstruction`], [`ClientInstruction`], etc). +#[derive(Copy, Clone, PartialEq, Serialize, Deserialize)] pub enum ContextType { /// A screen-related call. Screen(ScreenContext), @@ -140,8 +140,9 @@ pub enum ContextType { /// A plugin-related call. Plugin(PluginContext), /// An app-related call. - App(AppContext), - IpcServer, + Client(ClientContext), + /// A server-related call. + IPCServer(ServerContext), StdinHandler, AsyncTask, /// An empty, placeholder call. This should be thought of as representing no call at all. @@ -157,10 +158,9 @@ impl Display for ContextType { match *self { ContextType::Screen(c) => write!(f, "{}screen_thread: {}{:?}", purple, green, c), ContextType::Pty(c) => write!(f, "{}pty_thread: {}{:?}", purple, green, c), - ContextType::Plugin(c) => write!(f, "{}plugin_thread: {}{:?}", purple, green, c), - ContextType::App(c) => write!(f, "{}main_thread: {}{:?}", purple, green, c), - ContextType::IpcServer => write!(f, "{}ipc_server: {}AcceptInput", purple, green), + ContextType::Client(c) => write!(f, "{}main_thread: {}{:?}", purple, green, c), + ContextType::IPCServer(c) => write!(f, "{}ipc_server: {}{:?}", purple, green, c), ContextType::StdinHandler => { write!(f, "{}stdin_handler_thread: {}AcceptInput", purple, green) } @@ -174,7 +174,7 @@ impl Display for ContextType { // FIXME: Just deriving EnumDiscriminants from strum will remove the need for any of this!!! /// Stack call representations corresponding to the different types of [`ScreenInstruction`]s. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum ScreenContext { HandlePtyBytes, Render, @@ -193,7 +193,7 @@ pub enum ScreenContext { MoveFocusDown, MoveFocusUp, MoveFocusRight, - Quit, + Exit, ScrollUp, ScrollDown, PageScrollUp, @@ -238,7 +238,7 @@ impl From<&ScreenInstruction> for ScreenContext { ScreenInstruction::MoveFocusDown => ScreenContext::MoveFocusDown, ScreenInstruction::MoveFocusUp => ScreenContext::MoveFocusUp, ScreenInstruction::MoveFocusRight => ScreenContext::MoveFocusRight, - ScreenInstruction::Quit => ScreenContext::Quit, + ScreenInstruction::Exit => ScreenContext::Exit, ScreenInstruction::ScrollUp => ScreenContext::ScrollUp, ScreenInstruction::ScrollDown => ScreenContext::ScrollDown, ScreenInstruction::PageScrollUp => ScreenContext::PageScrollUp, @@ -252,14 +252,14 @@ impl From<&ScreenInstruction> for ScreenContext { ScreenInstruction::SetInvisibleBorders(..) => ScreenContext::SetInvisibleBorders, ScreenInstruction::SetMaxHeight(..) => ScreenContext::SetMaxHeight, ScreenInstruction::ClosePane(_) => ScreenContext::ClosePane, - ScreenInstruction::ApplyLayout(_) => ScreenContext::ApplyLayout, + ScreenInstruction::ApplyLayout(..) => ScreenContext::ApplyLayout, ScreenInstruction::NewTab(_) => ScreenContext::NewTab, ScreenInstruction::SwitchTabNext => ScreenContext::SwitchTabNext, ScreenInstruction::SwitchTabPrev => ScreenContext::SwitchTabPrev, ScreenInstruction::CloseTab => ScreenContext::CloseTab, ScreenInstruction::GoToTab(_) => ScreenContext::GoToTab, ScreenInstruction::UpdateTabName(_) => ScreenContext::UpdateTabName, - ScreenInstruction::TerminalResize => ScreenContext::TerminalResize, + ScreenInstruction::TerminalResize(_) => ScreenContext::TerminalResize, ScreenInstruction::ChangeMode(_) => ScreenContext::ChangeMode, ScreenInstruction::ToggleActiveSyncPanes => ScreenContext::ToggleActiveSyncPanes, } @@ -267,7 +267,7 @@ impl From<&ScreenInstruction> for ScreenContext { } /// Stack call representations corresponding to the different types of [`PtyInstruction`]s. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum PtyContext { SpawnTerminal, SpawnTerminalVertically, @@ -275,7 +275,7 @@ pub enum PtyContext { NewTab, ClosePane, CloseTab, - Quit, + Exit, } impl From<&PtyInstruction> for PtyContext { @@ -287,7 +287,7 @@ impl From<&PtyInstruction> for PtyContext { PtyInstruction::ClosePane(_) => PtyContext::ClosePane, PtyInstruction::CloseTab(_) => PtyContext::CloseTab, PtyInstruction::NewTab => PtyContext::NewTab, - PtyInstruction::Quit => PtyContext::Quit, + PtyInstruction::Exit => PtyContext::Exit, } } } @@ -297,13 +297,13 @@ impl From<&PtyInstruction> for PtyContext { use crate::wasm_vm::PluginInstruction; /// Stack call representations corresponding to the different types of [`PluginInstruction`]s. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum PluginContext { Load, Update, Render, Unload, - Quit, + Exit, } impl From<&PluginInstruction> for PluginContext { @@ -313,23 +313,51 @@ impl From<&PluginInstruction> for PluginContext { PluginInstruction::Update(..) => PluginContext::Update, PluginInstruction::Render(..) => PluginContext::Render, PluginInstruction::Unload(_) => PluginContext::Unload, - PluginInstruction::Quit => PluginContext::Quit, + PluginInstruction::Exit => PluginContext::Exit, } } } -/// Stack call representations corresponding to the different types of [`AppInstruction`]s. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum AppContext { +/// Stack call representations corresponding to the different types of [`ClientInstruction`]s. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub enum ClientContext { Exit, Error, + UnblockInputThread, + Render, +} + +impl From<&ClientInstruction> for ClientContext { + fn from(client_instruction: &ClientInstruction) -> Self { + match *client_instruction { + ClientInstruction::Exit => ClientContext::Exit, + ClientInstruction::Error(_) => ClientContext::Error, + ClientInstruction::Render(_) => ClientContext::Render, + ClientInstruction::UnblockInputThread => ClientContext::UnblockInputThread, + } + } +} + +/// Stack call representations corresponding to the different types of [`ServerInstruction`]s. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub enum ServerContext { + NewClient, + Action, + Render, + TerminalResize, + UnblockInputThread, + ClientExit, } -impl From<&AppInstruction> for AppContext { - fn from(app_instruction: &AppInstruction) -> Self { - match *app_instruction { - AppInstruction::Exit => AppContext::Exit, - AppInstruction::Error(_) => AppContext::Error, +impl From<&ServerInstruction> for ServerContext { + fn from(server_instruction: &ServerInstruction) -> Self { + match *server_instruction { + ServerInstruction::NewClient(..) => ServerContext::NewClient, + ServerInstruction::Action(_) => ServerContext::Action, + ServerInstruction::TerminalResize(_) => ServerContext::TerminalResize, + ServerInstruction::Render(_) => ServerContext::Render, + ServerInstruction::UnblockInputThread => ServerContext::UnblockInputThread, + ServerInstruction::ClientExit => ServerContext::ClientExit, } } } diff --git a/src/common/input/handler.rs b/src/common/input/handler.rs index 7304225c..75f9f8b1 100644 --- a/src/common/input/handler.rs +++ b/src/common/input/handler.rs @@ -2,53 +2,43 @@ use super::actions::Action; use super::keybinds::Keybinds; +use crate::client::ClientInstruction; use crate::common::input::config::Config; -use crate::common::{AppInstruction, SenderWithContext, OPENCALLS}; +use crate::common::{SenderWithContext, OPENCALLS}; use crate::errors::ContextType; -use crate::os_input_output::OsApi; -use crate::pty_bus::PtyInstruction; -use crate::screen::ScreenInstruction; -use crate::wasm_vm::PluginInstruction; +use crate::os_input_output::ClientOsApi; +use crate::server::ServerInstruction; use crate::CommandIsExecuting; use termion::input::{TermRead, TermReadEventsAndRaw}; -use zellij_tile::data::{Event, InputMode, Key, ModeInfo, Palette}; +use zellij_tile::data::{InputMode, Key, ModeInfo, Palette}; /// Handles the dispatching of [`Action`]s according to the current /// [`InputMode`], and keep tracks of the current [`InputMode`]. struct InputHandler { /// The current input mode mode: InputMode, - os_input: Box<dyn OsApi>, + os_input: Box<dyn ClientOsApi>, config: Config, command_is_executing: CommandIsExecuting, - send_screen_instructions: SenderWithContext<ScreenInstruction>, - send_pty_instructions: SenderWithContext<PtyInstruction>, - send_plugin_instructions: SenderWithContext<PluginInstruction>, - send_app_instructions: SenderWithContext<AppInstruction>, + send_client_instructions: SenderWithContext<ClientInstruction>, should_exit: bool, } impl InputHandler { /// Returns a new [`InputHandler`] with the attributes specified as arguments. fn new( - os_input: Box<dyn OsApi>, + os_input: Box<dyn ClientOsApi>, command_is_executing: CommandIsExecuting, config: Config, - send_screen_instructions: SenderWithContext<ScreenInstruction>, - send_pty_instructions: SenderWithContext<PtyInstruction>, - send_plugin_instructions: SenderWithContext<PluginInstruction>, - send_app_instructions: SenderWithContext<AppInstruction>, + send_client_instructions: SenderWithContext<ClientInstruction>, ) -> Self { InputHandler { mode: InputMode::Normal, os_input, config, command_is_executing, - send_screen_instructions, - send_pty_instructions, - send_plugin_instructions, - send_app_instructions, + send_client_instructions, should_exit: false, } } @@ -114,162 +104,31 @@ impl InputHandler { let mut should_break = false; match action { - Action::Write(val) => { - self.send_screen_instructions - .send(ScreenInstruction::ClearScroll) - .unwrap(); - self.send_screen_instructions - .send(ScreenInstruction::WriteCharacter(val)) - .unwrap(); - } Action::Quit => { self.exit(); should_break = true; } Action::SwitchToMode(mode) => { self.mode = mode; - self.send_plugin_instructions - .send(PluginInstruction::Update( - None, - Event::ModeUpdate(get_mode_info(mode, self.os_input.load_palette())), - )) - .unwrap(); - self.send_screen_instructions - .send(ScreenInstruction::ChangeMode(get_mode_info( - mode, - self.os_input.load_palette(), - ))) - .unwrap(); - self.send_screen_instructions - .send(ScreenInstruction::Render) - .unwrap(); - } - Action::Resize(direction) => { - let screen_instr = match direction { - super::actions::Direction::Left => ScreenInstruction::ResizeLeft, - super::actions::Direction::Right => ScreenInstruction::ResizeRight, - super::actions::Direction::Up => ScreenInstruction::ResizeUp, - super::actions::Direction::Down => ScreenInstruction::ResizeDown, - }; - self.send_screen_instructions.send(screen_instr).unwrap(); - } - Action::SwitchFocus => { - self.send_screen_instructions - .send(ScreenInstruction::SwitchFocus) - .unwrap(); - } - Action::FocusNextPane => { - self.send_screen_instructions - .send(ScreenInstruction::FocusNextPane) - .unwrap(); - } - Action::FocusPreviousPane => { - self.send_screen_instructions - .send(ScreenInstruction::FocusPreviousPane) - .unwrap(); - } - Action::MoveFocus(direction) => { - let screen_instr = match direction { - super::actions::Direction::Left => ScreenInstruction::MoveFocusLeft, - super::actions::Direction::Right => ScreenInstruction::MoveFocusRight, - super::actions::Direction::Up => ScreenInstruction::MoveFocusUp, - super::actions::Direction::Down => ScreenInstruction::MoveFocusDown, - }; - self.send_screen_instructions.send(screen_instr).unwrap(); - } - Action::ScrollUp => { - self.send_screen_instructions - .send(ScreenInstruction::ScrollUp) - .unwrap(); - } - Action::ScrollDown => { - self.send_screen_instructions - .send(ScreenInstruction::ScrollDown) - .unwrap(); - } - Action::PageScrollUp => { - self.send_screen_instructions - .send(ScreenInstruction::PageScrollUp) - .unwrap(); - } - Action::PageScrollDown => { - self.send_screen_instructions - .send(ScreenInstruction::PageScrollDown) - .unwrap(); - } - Action::ToggleFocusFullscreen => { - self.send_screen_instructions - .send(ScreenInstruction::ToggleActiveTerminalFullscreen) - .unwrap(); - } - Action::NewPane(direction) => { - let pty_instr = match direction { - Some(super::actions::Direction::Left) => { - PtyInstruction::SpawnTerminalVertically(None) - } - Some(super::actions::Direction::Right) => { - PtyInstruction::SpawnTerminalVertically(None) - } - Some(super::actions::Direction::Up) => { - PtyInstruction::SpawnTerminalHorizontally(None) - } - Some(super::actions::Direction::Down) => { - PtyInstruction::SpawnTerminalHorizontally(None) - } - // No direction specified - try to put it in the biggest available spot - None => PtyInstruction::SpawnTerminal(None), - }; - self.command_is_executing.opening_new_pane(); - self.send_pty_instructions.send(pty_instr).unwrap(); - self.command_is_executing.wait_until_new_pane_is_opened(); - } - Action::CloseFocus => { - self.command_is_executing.closing_pane(); - self.send_screen_instructions - .send(ScreenInstruction::CloseFocusedPane) - .unwrap(); - self.command_is_executing.wait_until_pane_is_closed(); - } - Action::NewTab => { - self.command_is_executing.opening_new_pane(); - self.send_pty_instructions - .send(PtyInstruction::NewTab) - .unwrap(); - self.command_is_executing.wait_until_new_pane_is_opened(); - } - Action::GoToNextTab => { - self.send_screen_instructions - .send(ScreenInstruction::SwitchTabNext) - .unwrap(); - } - Action::GoToPreviousTab => { - self.send_screen_instructions - .send(ScreenInstruction::SwitchTabPrev) - .unwrap(); - } - Action::ToggleActiveSyncPanes => { - self.send_screen_instructions - .send(ScreenInstruction::ToggleActiveSyncPanes) - .unwrap(); - } - Action::CloseTab => { - self.command_is_executing.closing_pane(); - self.send_screen_instructions - .send(ScreenInstruction::CloseTab) - .unwrap(); - self.command_is_executing.wait_until_pane_is_closed(); - } - Action::GoToTab(i) => { - self.send_screen_instructions - .send(ScreenInstruction::GoToTab(i)) - .unwrap(); + self.os_input + .send_to_server(ServerInstruction::Action(action)); } - Action::TabNameInput(c) => { - self.send_screen_instructions - .send(ScreenInstruction::UpdateTabName(c)) - .unwrap(); + Action::CloseFocus + | Action::NewPane(_) + | Action::NewTab + | Action::GoToNextTab + | Action::GoToPreviousTab + | Action::CloseTab + | Action::GoToTab(_) => { + self.command_is_executing.blocking_input_thread(); + self.os_input + .send_to_server(ServerInstruction::Action(action)); + self.command_is_executing + .wait_until_input_thread_is_unblocked(); } - Action::NoOp => {} + _ => self + .os_input + .send_to_server(ServerInstruction::Action(action)), } should_break @@ -278,8 +137,8 @@ impl InputHandler { /// Routine to be called when the input handler exits (at the moment this is the /// same as quitting Zellij). fn exit(&mut self) { - self.send_app_instructions - .send(AppInstruction::Exit) + self.send_client_instructions + .send(ClientInstruction::Exit) .unwrap(); } } @@ -328,22 +187,16 @@ pub fn get_mode_info(mode: InputMode, palette: Palette) -> ModeInfo { /// Entry point to the module. Instantiates an [`InputHandler`] and starts /// its [`InputHandler::handle_input()`] loop. pub fn input_loop( - os_input: Box<dyn OsApi>, + os_input: Box<dyn ClientOsApi>, config: Config, command_is_executing: CommandIsExecuting, - send_screen_instructions: SenderWithContext<ScreenInstruction>, - send_pty_instructions: SenderWithContext<PtyInstruction>, - send_plugin_instructions: SenderWithContext<PluginInstruction>, - send_app_instructions: SenderWithContext<AppInstruction>, + send_client_instructions: SenderWithContext<ClientInstruction>, ) { let _handler = InputHandler::new( os_input, command_is_executing, config, - send_screen_instructions, - send_pty_instructions, - send_plugin_instructions, - send_app_instructions, + send_client_instructions, ) .handle_input(); } diff --git a/src/common/ipc.rs b/src/common/ipc.rs index 81576b86..190680dc 100644 --- a/src/common/ipc.rs +++ b/src/common/ipc.rs @@ -1,7 +1,13 @@ //! IPC stuff for starting to split things into a client and server model. +use crate::common::errors::{get_current_ctx, ErrorContext}; +use interprocess::local_socket::LocalSocketStream; +use nix::unistd::dup; use serde::{Deserialize, Serialize}; use std::collections::HashSet; +use std::io::{self, Write}; +use std::marker::PhantomData; +use std::os::unix::io::{AsRawFd, FromRawFd}; type SessionId = u64; @@ -24,7 +30,7 @@ pub enum ClientType { // Types of messages sent from the client to the server #[derive(Serialize, Deserialize)] -pub enum ClientToServerMsg { +pub enum _ClientToServerMsg { // List which sessions are available ListSessions, // Create a new session @@ -45,3 +51,69 @@ pub enum _ServerToClientMsg { // A list of sessions SessionList(HashSet<Session>), } + +/// Sends messages on a stream socket, along with an [`ErrorContext`]. +pub struct IpcSenderWithContext<T: Serialize> { + sender: io::BufWriter<LocalSocketStream>, + _phantom: PhantomData<T>, +} + +impl<T: Serialize> IpcSenderWithContext<T> { + /// Returns a sender to the given [LocalSocketStream](interprocess::local_socket::LocalSocketStream). + pub fn new(sender: LocalSocketStream) -> Self { + Self { + sender: io::BufWriter::new(sender), + _phantom: PhantomData, + } + } + + /// Sends an event, along with the current [`ErrorContext`], on this [`IpcSenderWithContext`]'s socket. + pub fn send(&mut self, msg: T) { + let err_ctx = get_current_ctx(); + bincode::serialize_into(&mut self.sender, &(msg, err_ctx)).unwrap(); + self.sender.flush().unwrap(); + } + + /// Returns an [`IpcReceiverWithContext`] with the same socket as this sender. + pub fn get_receiver<F>(&self) -> IpcReceiverWithContext<F> + where + F: for<'de> Deserialize<'de> + Serialize, + { + let sock_fd = self.sender.get_ref().as_raw_fd(); + let dup_sock = dup(sock_fd).unwrap(); + let socket = unsafe { LocalSocketStream::from_raw_fd(dup_sock) }; + IpcReceiverWithContext::new(socket) + } +} + +/// Receives messages on a stream socket, along with an [`ErrorContext`]. +pub struct IpcReceiverWithContext<T> { + receiver: io::BufReader<LocalSocketStream>, + _phantom: PhantomData<T>, +} + +impl<T> IpcReceiverWithContext<T> +where + T: for<'de> Deserialize<'de> + Serialize, +{ + /// Returns a receiver to the given [LocalSocketStream](interprocess::local_socket::LocalSocketStream). + pub fn new(receiver: LocalSocketStream) -> Self { + Self { + receiver: io::BufReader::new(receiver), + _phantom: PhantomData, + } + } + + /// Receives an event, along with the current [`ErrorContext`], on this [`IpcReceiverWithContext`]'s socket. + pub fn recv(&mut self) -> (T, ErrorContext) { + bincode::deserialize_from(&mut self.receiver).unwrap() + } + + /// Returns an [`IpcSenderWithContext`] with the same socket as this receiver. + pub fn get_sender<F: Serialize>(&self) -> IpcSenderWithContext<F> { + let sock_fd = self.receiver.get_ref().as_raw_fd(); + let dup_sock = dup(sock_fd).unwrap(); + let socket = unsafe { LocalSocketStream::from_raw_fd(dup_sock) }; + IpcSenderWithContext::new(socket) + } +} diff --git a/src/common/mod.rs b/src/common/mod.rs index 17c1f4cb..6061f1a6 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -9,49 +9,12 @@ pub mod setup; pub mod utils; pub mod wasm_vm; -use std::cell::RefCell; -use std::path::PathBuf; -use std::sync::mpsc; -use std::thread; -use std::{collections::HashMap, fs}; -use std::{ - collections::HashSet, - env, - io::Write, - str::FromStr, - sync::{Arc, Mutex}, -}; - -use crate::cli::CliArgs; -use crate::common::input::config::Config; -use crate::layout::Layout; use crate::panes::PaneId; +use crate::server::ServerInstruction; use async_std::task_local; -use command_is_executing::CommandIsExecuting; -use directories_next::ProjectDirs; -use errors::{ - get_current_ctx, AppContext, ContextType, ErrorContext, PluginContext, PtyContext, - ScreenContext, -}; -use input::handler::input_loop; -use os_input_output::OsApi; -use pty_bus::{PtyBus, PtyInstruction}; -use screen::{Screen, ScreenInstruction}; -use serde::{Deserialize, Serialize}; -use setup::install; -use utils::consts::ZELLIJ_IPC_PIPE; -use wasm_vm::{wasi_read_string, wasi_write_object, zellij_exports, PluginEnv, PluginInstruction}; -use wasmer::{ChainableNamedResolver, Instance, Module, Store, Value}; -use wasmer_wasi::{Pipe, WasiState}; -use zellij_tile::data::{EventType, InputMode, ModeInfo}; - -#[derive(Serialize, Deserialize, Debug)] -pub enum ApiCommand { - OpenFile(PathBuf), - SplitHorizontally, - SplitVertically, - MoveFocus, -} +use errors::{get_current_ctx, ErrorContext}; +use std::cell::RefCell; +use std::sync::mpsc; /// An [MPSC](mpsc) asynchronous channel with added error context. pub type ChannelWithContext<T> = ( @@ -66,7 +29,7 @@ pub type SyncChannelWithContext<T> = ( /// Wrappers around the two standard [MPSC](mpsc) sender types, [`mpsc::Sender`] and [`mpsc::SyncSender`], with an additional [`ErrorContext`]. #[derive(Clone)] -enum SenderType<T: Clone> { +pub enum SenderType<T: Clone> { /// A wrapper around an [`mpsc::Sender`], adding an [`ErrorContext`]. Sender(mpsc::Sender<(T, ErrorContext)>), /// A wrapper around an [`mpsc::SyncSender`], adding an [`ErrorContext`]. @@ -81,7 +44,7 @@ pub struct SenderWithContext<T: Clone> { } impl<T: Clone> SenderWithContext<T> { - fn new(sender: SenderType<T>) -> Self { + pub fn new(sender: SenderType<T>) -> Self { Self { sender } } @@ -102,7 +65,7 @@ unsafe impl<T: Clone> Sync for SenderWithContext<T> {} thread_local!( /// A key to some thread local storage (TLS) that holds a representation of the thread's call /// stack in the form of an [`ErrorContext`]. - static OPENCALLS: RefCell<ErrorContext> = RefCell::default() + pub static OPENCALLS: RefCell<ErrorContext> = RefCell::default() ); task_local! { @@ -110,600 +73,3 @@ task_local! { /// stack in the form of an [`ErrorContext`]. static ASYNCOPENCALLS: RefCell<ErrorContext> = RefCell::default() } - -/// Instructions related to the entire application. -#[derive(Clone)] -pub enum AppInstruction { - Exit, - Error(String), -} - -/// Start Zellij with the specified [`OsApi`] and command-line arguments. -// FIXME this should definitely be modularized and split into different functions. -pub fn start(mut os_input: Box<dyn OsApi>, opts: CliArgs, config: Config) { - let take_snapshot = "\u{1b}[?1049h"; - os_input.unset_raw_mode(0); - let _ = os_input - .get_stdout_writer() - .write(take_snapshot.as_bytes()) - .unwrap(); - - env::set_var(&"ZELLIJ", "0"); - - let command_is_executing = CommandIsExecuting::new(); - - let full_screen_ws = os_input.get_terminal_size_using_fd(0); - os_input.set_raw_mode(0); - let (send_screen_instructions, receive_screen_instructions): ChannelWithContext< - ScreenInstruction, - > = mpsc::channel(); - let send_screen_instructions = - SenderWithContext::new(SenderType::Sender(send_screen_instructions)); - - let (send_pty_instructions, receive_pty_instructions): ChannelWithContext<PtyInstruction> = - mpsc::channel(); - let send_pty_instructions = SenderWithContext::new(SenderType::Sender(send_pty_instructions)); - - let (send_plugin_instructions, receive_plugin_instructions): ChannelWithContext< - PluginInstruction, - > = mpsc::channel(); - let send_plugin_instructions = - SenderWithContext::new(SenderType::Sender(send_plugin_instructions)); - - let (send_app_instructions, receive_app_instructions): SyncChannelWithContext<AppInstruction> = - mpsc::sync_channel(0); - let send_app_instructions = - SenderWithContext::new(SenderType::SyncSender(send_app_instructions)); - - let mut pty_bus = PtyBus::new( - receive_pty_instructions, - send_screen_instructions.clone(), - send_plugin_instructions.clone(), - os_input.clone(), - opts.debug, - ); - - // Determine and initialize the data directory - let project_dirs = ProjectDirs::from("org", "Zellij Contributors", "Zellij").unwrap(); - let data_dir = opts - .data_dir - .unwrap_or_else(|| project_dirs.data_dir().to_path_buf()); - install::populate_data_dir(&data_dir); - - // Don't use default layouts in tests, but do everywhere else - #[cfg(not(test))] - let default_layout = Some(PathBuf::from("default")); - #[cfg(test)] - let default_layout = None; - let maybe_layout = opts - .layout - .map(|p| Layout::new(&p, &data_dir)) - .or_else(|| default_layout.map(|p| Layout::from_defaults(&p, &data_dir))); - - #[cfg(not(test))] - std::panic::set_hook({ - use crate::errors::handle_panic; - let send_app_instructions = send_app_instructions.clone(); - Box::new(move |info| { - handle_panic(info, &send_app_instructions); - }) - }); - - let pty_thread = thread::Builder::new() - .name("pty".to_string()) - .spawn({ - let mut command_is_executing = command_is_executing.clone(); - send_pty_instructions.send(PtyInstruction::NewTab).unwrap(); - move || loop { - let (event, mut err_ctx) = pty_bus - .receive_pty_instructions - .recv() - .expect("failed to receive event on channel"); - err_ctx.add_call(ContextType::Pty(PtyContext::from(&event))); - match event { - PtyInstruction::SpawnTerminal(file_to_open) => { - let pid = pty_bus.spawn_terminal(file_to_open); - pty_bus - .send_screen_instructions - .send(ScreenInstruction::NewPane(PaneId::Terminal(pid))) - .unwrap(); - } - PtyInstruction::SpawnTerminalVertically(file_to_open) => { - let pid = pty_bus.spawn_terminal(file_to_open); - pty_bus - .send_screen_instructions - .send(ScreenInstruction::VerticalSplit(PaneId::Terminal(pid))) - .unwrap(); - } - PtyInstruction::SpawnTerminalHorizontally(file_to_open) => { - let pid = pty_bus.spawn_terminal(file_to_open); - pty_bus - .send_screen_instructions - .send(ScreenInstruction::HorizontalSplit(PaneId::Terminal(pid))) - .unwrap(); - } - PtyInstruction::NewTab => { - if let Some(layout) = maybe_layout.clone() { - pty_bus.spawn_terminals_for_layout(layout); - } else { - let pid = pty_bus.spawn_terminal(None); - pty_bus - .send_screen_instructions - .send(ScreenInstruction::NewTab(pid)) - .unwrap(); - } - } - PtyInstruction::ClosePane(id) => { - pty_bus.close_pane(id); - command_is_executing.done_closing_pane(); - } - PtyInstruction::CloseTab(ids) => { - pty_bus.close_tab(ids); - command_is_executing.done_closing_pane(); - } - PtyInstruction::Quit => { - break; - } - } - } - }) - .unwrap(); - - let screen_thread = thread::Builder::new() - .name("screen".to_string()) - .spawn({ - let mut command_is_executing = command_is_executing.clone(); - let os_input = os_input.clone(); - let send_pty_instructions = send_pty_instructions.clone(); - let send_plugin_instructions = send_plugin_instructions.clone(); - let send_app_instructions = send_app_instructions.clone(); - let max_panes = opts.max_panes; - let colors = os_input.load_palette(); - move || { - let mut screen = Screen::new( - receive_screen_instructions, - send_pty_instructions, - send_plugin_instructions, - send_app_instructions, - &full_screen_ws, - os_input, - max_panes, - ModeInfo { - palette: colors, - ..ModeInfo::default() - }, - InputMode::Normal, - colors, - ); - loop { - let (event, mut err_ctx) = screen - .receiver - .recv() - .expect("failed to receive event on channel"); - err_ctx.add_call(ContextType::Screen(ScreenContext::from(&event))); - match event { - ScreenInstruction::PtyBytes(pid, vte_bytes) => { - let active_tab = screen.get_active_tab_mut().unwrap(); - if active_tab.has_terminal_pid(pid) { - // it's most likely that this event is directed at the active tab - // look there first - active_tab.handle_pty_bytes(pid, vte_bytes); - } else { - // if this event wasn't directed at the active tab, start looking - // in other tabs - let all_tabs = screen.get_tabs_mut(); - for tab in all_tabs.values_mut() { - if tab.has_terminal_pid(pid) { - tab.handle_pty_bytes(pid, vte_bytes); - break; - } - } - } - } - ScreenInstruction::Render => { - screen.render(); - } - ScreenInstruction::NewPane(pid) => { - screen.get_active_tab_mut().unwrap().new_pane(pid); - command_is_executing.done_opening_new_pane(); - } - ScreenInstruction::HorizontalSplit(pid) => { - screen.get_active_tab_mut().unwrap().horizontal_split(pid); - command_is_executing.done_opening_new_pane(); - } - ScreenInstruction::VerticalSplit(pid) => { - screen.get_active_tab_mut().unwrap().vertical_split(pid); - command_is_executing.done_opening_new_pane(); - } - ScreenInstruction::WriteCharacter(bytes) => { - let active_tab = screen.get_active_tab_mut().unwrap(); - match active_tab.is_sync_panes_active() { - true => active_tab.write_to_terminals_on_current_tab(bytes), - false => active_tab.write_to_active_terminal(bytes), - } - } - ScreenInstruction::ResizeLeft => { - screen.get_active_tab_mut().unwrap().resize_left(); - } - ScreenInstruction::ResizeRight => { - screen.get_active_tab_mut().unwrap().resize_right(); - } - ScreenInstruction::ResizeDown => { - screen.get_active_tab_mut().unwrap().resize_down(); - } - ScreenInstruction::ResizeUp => { - screen.get_active_tab_mut().unwrap().resize_up(); - } - ScreenInstruction::SwitchFocus => { - screen.get_active_tab_mut().unwrap().move_focus(); - } - ScreenInstruction::FocusNextPane => { - screen.get_active_tab_mut().unwrap().focus_next_pane(); - } - ScreenInstruction::FocusPreviousPane => { - screen.get_active_tab_mut().unwrap().focus_previous_pane(); - } - ScreenInstruction::MoveFocusLeft => { - screen.get_active_tab_mut().unwrap().move_focus_left(); - } - ScreenInstruction::MoveFocusDown => { - screen.get_active_tab_mut().unwrap().move_focus_down(); - } - ScreenInstruction::MoveFocusRight => { - screen.get_active_tab_mut().unwrap().move_focus_right(); - } - ScreenInstruction::MoveFocusUp => { - screen.get_active_tab_mut().unwrap().move_focus_up(); - } - ScreenInstruction::ScrollUp => { - screen - .get_active_tab_mut() - .unwrap() - .scroll_active_terminal_up(); - } - ScreenInstruction::ScrollDown => { - screen - .get_active_tab_mut() - .unwrap() - .scroll_active_terminal_down(); - } - ScreenInstruction::PageScrollUp => { - screen - .get_active_tab_mut() - .unwrap() - .scroll_active_terminal_up_page(); - } - ScreenInstruction::PageScrollDown => { - screen - .get_active_tab_mut() - .unwrap() - .scroll_active_terminal_down_page(); - } - ScreenInstruction::ClearScroll => { - screen - .get_active_tab_mut() - .unwrap() - .clear_active_terminal_scroll(); - } - ScreenInstruction::CloseFocusedPane => { - screen.get_active_tab_mut().unwrap().close_focused_pane(); - screen.render(); - } - ScreenInstruction::SetSelectable(id, selectable) => { - screen - .get_active_tab_mut() - .unwrap() - .set_pane_selectable(id, selectable); - } - ScreenInstruction::SetMaxHeight(id, max_height) => { - screen - .get_active_tab_mut() - .unwrap() - .set_pane_max_height(id, max_height); - } - ScreenInstruction::SetInvisibleBorders(id, invisible_borders) => { - screen - .get_active_tab_mut() - .unwrap() - .set_pane_invisible_borders(id, invisible_borders); - screen.render(); - } - ScreenInstruction::ClosePane(id) => { - screen.get_active_tab_mut().unwrap().close_pane(id); - screen.render(); - } - ScreenInstruction::ToggleActiveTerminalFullscreen => { - screen - .get_active_tab_mut() - .unwrap() - .toggle_active_pane_fullscreen(); - } - ScreenInstruction::NewTab(pane_id) => { - screen.new_tab(pane_id); - command_is_executing.done_opening_new_pane(); - } - ScreenInstruction::SwitchTabNext => screen.switch_tab_next(), - ScreenInstruction::SwitchTabPrev => screen.switch_tab_prev(), - ScreenInstruction::CloseTab => screen.close_tab(), - ScreenInstruction::ApplyLayout((layout, new_pane_pids)) => { - screen.apply_layout(layout, new_pane_pids); - command_is_executing.done_opening_new_pane(); - } - ScreenInstruction::GoToTab(tab_index) => { - screen.go_to_tab(tab_index as usize) - } - ScreenInstruction::UpdateTabName(c) => { - screen.update_active_tab_name(c); - } - ScreenInstruction::TerminalResize => { - screen.resize_to_screen(); - } - ScreenInstruction::ChangeMode(mode_info) => { - screen.change_mode(mode_info); - } - ScreenInstruction::ToggleActiveSyncPanes => { - screen - .get_active_tab_mut() - .unwrap() - .toggle_sync_panes_is_active(); - screen.update_tabs(); - } - ScreenInstruction::Quit => { - break; - } - } - } - } - }) - .unwrap(); - - let wasm_thread = thread::Builder::new() - .name("wasm".to_string()) - .spawn({ - let send_pty_instructions = send_pty_instructions.clone(); - let send_screen_instructions = send_screen_instructions.clone(); - let send_app_instructions = send_app_instructions.clone(); - let send_plugin_instructions = send_plugin_instructions.clone(); - - let store = Store::default(); - let mut plugin_id = 0; - let mut plugin_map = HashMap::new(); - move || loop { - let (event, mut err_ctx) = receive_plugin_instructions - .recv() - .expect("failed to receive event on channel"); - err_ctx.add_call(ContextType::Plugin(PluginContext::from(&event))); - match event { - PluginInstruction::Load(pid_tx, path) => { - let plugin_dir = data_dir.join("plugins/"); - let wasm_bytes = fs::read(&path) - .or_else(|_| fs::read(&path.with_extension("wasm"))) - .or_else(|_| fs::read(&plugin_dir.join(&path).with_extension("wasm"))) - .unwrap_or_else(|_| panic!("cannot find plugin {}", &path.display())); - - // FIXME: Cache this compiled module on disk. I could use `(de)serialize_to_file()` for that - let module = Module::new(&store, &wasm_bytes).unwrap(); - - let output = Pipe::new(); - let input = Pipe::new(); - let mut wasi_env = WasiState::new("Zellij") - .env("CLICOLOR_FORCE", "1") - .preopen(|p| { - p.directory(".") // FIXME: Change this to a more meaningful dir - .alias(".") - .read(true) - .write(true) - .create(true) - }) - .unwrap() - .stdin(Box::new(input)) - .stdout(Box::new(output)) - .finalize() - .unwrap(); - - let wasi = wasi_env.import_object(&module).unwrap(); - - let plugin_env = PluginEnv { - plugin_id, - send_pty_instructions: send_pty_instructions.clone(), - send_screen_instructions: send_screen_instructions.clone(), - send_app_instructions: send_app_instructions.clone(), - send_plugin_instructions: send_plugin_instructions.clone(), - wasi_env, - subscriptions: Arc::new(Mutex::new(HashSet::new())), - }; - - let zellij = zellij_exports(&store, &plugin_env); - let instance = Instance::new(&module, &zellij.chain_back(wasi)).unwrap(); - - let start = instance.exports.get_function("_start").unwrap(); - - // This eventually calls the `.load()` method - start.call(&[]).unwrap(); - - plugin_map.insert(plugin_id, (instance, plugin_env)); - pid_tx.send(plugin_id).unwrap(); - plugin_id += 1; - } - PluginInstruction::Update(pid, event) => { - for (&i, (instance, plugin_env)) in &plugin_map { - let subs = plugin_env.subscriptions.lock().unwrap(); - // FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType? - let event_type = EventType::from_str(&event.to_string()).unwrap(); - if (pid.is_none() || pid == Some(i)) && subs.contains(&event_type) { - let update = instance.exports.get_function("update").unwrap(); - wasi_write_object(&plugin_env.wasi_env, &event); - update.call(&[]).unwrap(); - } - } - drop(send_screen_instructions.send(ScreenInstruction::Render)); - } - PluginInstruction::Render(buf_tx, pid, rows, cols) => { - let (instance, plugin_env) = plugin_map.get(&pid).unwrap(); - - let render = instance.exports.get_function("render").unwrap(); - - render - .call(&[Value::I32(rows as i32), Value::I32(cols as i32)]) - .unwrap(); - - buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap(); - } - PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)), - PluginInstruction::Quit => break, - } - } - }) - .unwrap(); - - let _signal_thread = thread::Builder::new() - .name("signal_listener".to_string()) - .spawn({ - let os_input = os_input.clone(); - let send_screen_instructions = send_screen_instructions.clone(); - move || { - os_input.receive_sigwinch(Box::new(move || { - let _ = send_screen_instructions.send(ScreenInstruction::TerminalResize); - })); - } - }) - .unwrap(); - - // TODO: currently we don't wait for this to quit - // because otherwise the app will hang. Need to fix this so it both - // listens to the ipc-bus and is able to quit cleanly - #[cfg(not(test))] - let _ipc_thread = thread::Builder::new() - .name("ipc_server".to_string()) - .spawn({ - use std::io::Read; - let send_pty_instructions = send_pty_instructions.clone(); - let send_screen_instructions = send_screen_instructions.clone(); - move || { - std::fs::remove_file(ZELLIJ_IPC_PIPE).ok(); - let listener = std::os::unix::net::UnixListener::bind(ZELLIJ_IPC_PIPE) - .expect("could not listen on ipc socket"); - let mut err_ctx = OPENCALLS.with(|ctx| *ctx.borrow()); - err_ctx.add_call(ContextType::IpcServer); - - for stream in listener.incoming() { - match stream { - Ok(mut stream) => { - let mut buffer = [0; 65535]; // TODO: more accurate - let _ = stream - .read(&mut buffer) - .expect("failed to parse ipc message"); - let decoded: ApiCommand = bincode::deserialize(&buffer) - .expect("failed to deserialize ipc message"); - match &decoded { - ApiCommand::OpenFile(file_name) => { - let path = PathBuf::from(file_name); - send_pty_instructions - .send(PtyInstruction::SpawnTerminal(Some(path))) - .unwrap(); - } - ApiCommand::SplitHorizontally => { - send_pty_instructions - .send(PtyInstruction::SpawnTerminalHorizontally(None)) - .unwrap(); - } - ApiCommand::SplitVertically => { - send_pty_instructions - .send(PtyInstruction::SpawnTerminalVertically(None)) - .unwrap(); - } - ApiCommand::MoveFocus => { - send_screen_instructions - .send(ScreenInstruction::FocusNextPane) - .unwrap(); - } - } - } - Err(err) => { - panic!("err {:?}", err); - } - } - } - } - }) - .unwrap(); - - let _stdin_thread = thread::Builder::new() - .name("stdin_handler".to_string()) - .spawn({ - let send_screen_instructions = send_screen_instructions.clone(); - let send_pty_instructions = send_pty_instructions.clone(); - let send_plugin_instructions = send_plugin_instructions.clone(); - let os_input = os_input.clone(); - let config = config; - move || { - input_loop( - os_input, - config, - command_is_executing, - send_screen_instructions, - send_pty_instructions, - send_plugin_instructions, - send_app_instructions, - ) - } - }); - - #[warn(clippy::never_loop)] - loop { - let (app_instruction, mut err_ctx) = receive_app_instructions - .recv() - .expect("failed to receive app instruction on channel"); - - err_ctx.add_call(ContextType::App(AppContext::from(&app_instruction))); - match app_instruction { - AppInstruction::Exit => { - break; - } - AppInstruction::Error(backtrace) => { - let _ = send_screen_instructions.send(ScreenInstruction::Quit); - let _ = screen_thread.join(); - let _ = send_pty_instructions.send(PtyInstruction::Quit); - let _ = pty_thread.join(); - let _ = send_plugin_instructions.send(PluginInstruction::Quit); - let _ = wasm_thread.join(); - os_input.unset_raw_mode(0); - let goto_start_of_last_line = format!("\u{1b}[{};{}H", full_screen_ws.rows, 1); - let restore_snapshot = "\u{1b}[?1049l"; - let error = format!( - "{}\n{}{}", - goto_start_of_last_line, restore_snapshot, backtrace - ); - let _ = os_input - .get_stdout_writer() - .write(error.as_bytes()) - .unwrap(); - std::process::exit(1); - } - } - } - - let _ = send_pty_instructions.send(PtyInstruction::Quit); - pty_thread.join().unwrap(); - let _ = send_screen_instructions.send(ScreenInstruction::Quit); - screen_thread.join().unwrap(); - let _ = send_plugin_instructions.send(PluginInstruction::Quit); - wasm_thread.join().unwrap(); - - // cleanup(); - let reset_style = "\u{1b}[m"; - let show_cursor = "\u{1b}[?25h"; - let restore_snapshot = "\u{1b}[?1049l"; - let goto_start_of_last_line = format!("\u{1b}[{};{}H", full_screen_ws.rows, 1); - let goodbye_message = format!( - "{}\n{}{}{}Bye from Zellij!\n", - goto_start_of_last_line, restore_snapshot, reset_style, show_cursor - ); - - os_input.unset_raw_mode(0); - let _ = os_input - .get_stdout_writer() - .write(goodbye_message.as_bytes()) - .unwrap(); - os_input.get_stdout_writer().flush().unwrap(); -} diff --git a/src/common/os_input_output.rs b/src/common/os_input_output.rs index 74d14036..5539ae70 100644 --- a/src/common/os_input_output.rs +++ b/src/common/os_input_output.rs @@ -1,23 +1,35 @@ +use crate::client::ClientInstruction; +use crate::common::{ + ipc::{IpcReceiverWithContext, IpcSenderWithContext}, + utils::consts::ZELLIJ_IPC_PIPE, +}; +use crate::errors::ErrorContext; use crate::panes::PositionAndSize; +use crate::server::ServerInstruction; use crate::utils::shared::default_palette; +use interprocess::local_socket::LocalSocketStream; use nix::fcntl::{fcntl, FcntlArg, OFlag}; use nix::pty::{forkpty, Winsize}; use nix::sys::signal::{kill, Signal}; use nix::sys::termios; use nix::sys::wait::waitpid; -use nix::unistd; -use nix::unistd::{ForkResult, Pid}; -use std::io; +use nix::unistd::{self, ForkResult, Pid}; +use signal_hook::{consts::signal::*, iterator::Signals}; use std::io::prelude::*; -use std::os::unix::io::RawFd; -use std::path::PathBuf; +use std::os::unix::{fs::PermissionsExt, io::RawFd}; +use std::path::{Path, PathBuf}; use std::process::{Child, Command}; use std::sync::{Arc, Mutex}; +use std::{env, fs, io}; use zellij_tile::data::Palette; -use signal_hook::{consts::signal::*, iterator::Signals}; +const UNIX_PERMISSIONS: u32 = 0o700; -use std::env; +pub fn set_permissions(path: &Path) { + let mut permissions = fs::metadata(path).unwrap().permissions(); + permissions.set_mode(UNIX_PERMISSIONS); + fs::set_permissions(path, permissions).unwrap(); +} fn into_raw_mode(pid: RawFd) { let mut tio = termios::tcgetattr(pid).expect("could not get terminal attribute"); @@ -156,23 +168,17 @@ fn spawn_terminal(file_to_open: Option<PathBuf>, orig_termios: termios::Termios) } #[derive(Clone)] -pub struct OsInputOutput { +pub struct ServerOsInputOutput { orig_termios: Arc<Mutex<termios::Termios>>, + receive_instructions_from_client: Option<Arc<Mutex<IpcReceiverWithContext<ServerInstruction>>>>, + send_instructions_to_client: Arc<Mutex<Option<IpcSenderWithContext<ClientInstruction>>>>, } -/// The `OsApi` trait represents an abstract interface to the features of an operating system that -/// Zellij requires. -pub trait OsApi: Send + Sync { - /// Returns the size of the terminal associated to file descriptor `fd`. - fn get_terminal_size_using_fd(&self, fd: RawFd) -> PositionAndSize; +/// The `ServerOsApi` trait represents an abstract interface to the features of an operating system that +/// Zellij server requires. +pub trait ServerOsApi: Send + Sync { /// Sets the size of the terminal associated to file descriptor `fd`. fn set_terminal_size_using_fd(&mut self, fd: RawFd, cols: u16, rows: u16); - /// Set the terminal associated to file descriptor `fd` to - /// [raw mode](https://en.wikipedia.org/wiki/Terminal_mode). - fn set_raw_mode(&mut self, fd: RawFd); - /// Set the terminal associated to file descriptor `fd` to - /// [cooked mode](https://en.wikipedia.org/wiki/Terminal_mode). - fn unset_raw_mode(&mut self, fd: RawFd); /// Spawn a new terminal, with an optional file to open in a terminal program. fn spawn_terminal(&mut self, file_to_open: Option<PathBuf>) -> (RawFd, RawFd); /// Read bytes from the standard output of the virtual terminal referred to by `fd`. @@ -186,30 +192,23 @@ pub trait OsApi: Send + Sync { // or a nix::unistd::Pid. See `man kill.3`, nix::sys::signal::kill (both take an argument // called `pid` and of type `pid_t`, and not `fd`) fn kill(&mut self, pid: RawFd) -> Result<(), nix::Error>; - /// Returns the raw contents of standard input. - fn read_from_stdin(&self) -> Vec<u8>; - /// Returns the writer that allows writing to standard output. - fn get_stdout_writer(&self) -> Box<dyn io::Write>; - /// Returns a [`Box`] pointer to this [`OsApi`] struct. - fn box_clone(&self) -> Box<dyn OsApi>; - fn receive_sigwinch(&self, cb: Box<dyn Fn()>); + /// Returns a [`Box`] pointer to this [`ServerOsApi`] struct. + fn box_clone(&self) -> Box<dyn ServerOsApi>; + /// Receives a message on server-side IPC channel + fn recv_from_client(&self) -> (ServerInstruction, ErrorContext); + /// Sends a message to client + fn send_to_client(&self, msg: ClientInstruction); + /// Adds a sender to client + fn add_client_sender(&mut self); + /// Update the receiver socket for the client + fn update_receiver(&mut self, stream: LocalSocketStream); fn load_palette(&self) -> Palette; } -impl OsApi for OsInputOutput { - fn get_terminal_size_using_fd(&self, fd: RawFd) -> PositionAndSize { - get_terminal_size_using_fd(fd) - } +impl ServerOsApi for ServerOsInputOutput { fn set_terminal_size_using_fd(&mut self, fd: RawFd, cols: u16, rows: u16) { set_terminal_size_using_fd(fd, cols, rows); } - fn set_raw_mode(&mut self, fd: RawFd) { - into_raw_mode(fd); - } - fn unset_raw_mode(&mut self, fd: RawFd) { - let orig_termios = self.orig_termios.lock().unwrap(); - unset_raw_mode(fd, orig_termios.clone()); - } fn spawn_terminal(&mut self, file_to_open: Option<PathBuf>) -> (RawFd, RawFd) { let orig_termios = self.orig_termios.lock().unwrap(); spawn_terminal(file_to_open, orig_termios.clone()) @@ -223,7 +222,118 @@ impl OsApi for OsInputOutput { fn tcdrain(&mut self, fd: RawFd) -> Result<(), nix::Error> { termios::tcdrain(fd) } - fn box_clone(&self) -> Box<dyn OsApi> { + fn box_clone(&self) -> Box<dyn ServerOsApi> { + Box::new((*self).clone()) + } + fn kill(&mut self, pid: RawFd) -> Result<(), nix::Error> { + // TODO: + // Ideally, we should be using SIGINT rather than SIGKILL here, but there are cases in which + // the terminal we're trying to kill hangs on SIGINT and so all the app gets stuck + // that's why we're sending SIGKILL here + // A better solution would be to send SIGINT here and not wait for it, and then have + // a background thread do the waitpid stuff and send SIGKILL if the process is stuck + kill(Pid::from_raw(pid), Some(Signal::SIGKILL)).unwrap(); + waitpid(Pid::from_raw(pid), None).unwrap(); + Ok(()) + } + fn recv_from_client(&self) -> (ServerInstruction, ErrorContext) { + self.receive_instructions_from_client + .as_ref() + .unwrap() + .lock() + .unwrap() + .recv() + } + fn send_to_client(&self, msg: ClientInstruction) { + self.send_instructions_to_client + .lock() + .unwrap() + .as_mut() + .unwrap() + .send(msg); + } + fn add_client_sender(&mut self) { + assert!(self.send_instructions_to_client.lock().unwrap().is_none()); + let sender = self + .receive_instructions_from_client + .as_ref() + .unwrap() + .lock() + .unwrap() + .get_sender(); + *self.send_instructions_to_client.lock().unwrap() = Some(sender); + } + fn update_receiver(&mut self, stream: LocalSocketStream) { + self.receive_instructions_from_client = + Some(Arc::new(Mutex::new(IpcReceiverWithContext::new(stream)))); + } + fn load_palette(&self) -> Palette { + default_palette() + } +} + +impl Clone for Box<dyn ServerOsApi> { + fn clone(&self) -> Box<dyn ServerOsApi> { + self.box_clone() + } +} + +pub fn get_server_os_input() -> ServerOsInputOutput { + let current_termios = termios::tcgetattr(0).unwrap(); + let orig_termios = Arc::new(Mutex::new(current_termios)); + ServerOsInputOutput { + orig_termios, + receive_instructions_from_client: None, + send_instructions_to_client: Arc::new(Mutex::new(None)), + } +} + +#[derive(Clone)] +pub struct ClientOsInputOutput { + orig_termios: Arc<Mutex<termios::Termios>>, + send_instructions_to_server: Arc<Mutex<Option<IpcSenderWithContext<ServerInstruction>>>>, + receive_instructions_from_server: Arc<Mutex<Option<IpcReceiverWithContext<ClientInstruction>>>>, +} + +/// The `ClientOsApi` trait represents an abstract interface to the features of an operating system that +/// Zellij client requires. +pub trait ClientOsApi: Send + Sync { + /// Returns the size of the terminal associated to file descriptor `fd`. + fn get_terminal_size_using_fd(&self, fd: RawFd) -> PositionAndSize; + /// Set the terminal associated to file descriptor `fd` to + /// [raw mode](https://en.wikipedia.org/wiki/Terminal_mode). + fn set_raw_mode(&mut self, fd: RawFd); + /// Set the terminal associated to file descriptor `fd` to + /// [cooked mode](https://en.wikipedia.org/wiki/Terminal_mode). + fn unset_raw_mode(&mut self, fd: RawFd); + /// Returns the writer that allows writing to standard output. + fn get_stdout_writer(&self) -> Box<dyn io::Write>; + /// Returns the raw contents of standard input. + fn read_from_stdin(&self) -> Vec<u8>; + /// Returns a [`Box`] pointer to this [`ClientOsApi`] struct. + fn box_clone(&self) -> Box<dyn ClientOsApi>; + /// Sends a message to the server. + fn send_to_server(&self, msg: ServerInstruction); + /// Receives a message on client-side IPC channel + // This should be called from the client-side router thread only. + fn recv_from_server(&self) -> (ClientInstruction, ErrorContext); + fn receive_sigwinch(&self, cb: Box<dyn Fn()>); + /// Establish a connection with the server socket. + fn connect_to_server(&self); +} + +impl ClientOsApi for ClientOsInputOutput { + fn get_terminal_size_using_fd(&self, fd: RawFd) -> PositionAndSize { + get_terminal_size_using_fd(fd) + } + fn set_raw_mode(&mut self, fd: RawFd) { + into_raw_mode(fd); + } + fn unset_raw_mode(&mut self, fd: RawFd) { + let orig_termios = self.orig_termios.lock().unwrap(); + unset_raw_mode(fd, orig_termios.clone()); + } + fn box_clone(&self) -> Box<dyn ClientOsApi> { Box::new((*self).clone()) } fn read_from_stdin(&self) -> Vec<u8> { @@ -239,16 +349,21 @@ impl OsApi for OsInputOutput { let stdout = ::std::io::stdout(); Box::new(stdout) } - fn kill(&mut self, pid: RawFd) -> Result<(), nix::Error> { - // TODO: - // Ideally, we should be using SIGINT rather than SIGKILL here, but there are cases in which - // the terminal we're trying to kill hangs on SIGINT and so all the app gets stuck - // that's why we're sending SIGKILL here - // A better solution would be to send SIGINT here and not wait for it, and then have - // a background thread do the waitpid stuff and send SIGKILL if the process is stuck - kill(Pid::from_raw(pid), Some(Signal::SIGKILL)).unwrap(); - waitpid(Pid::from_raw(pid), None).unwrap(); - Ok(()) + fn send_to_server(&self, msg: ServerInstruction) { + self.send_instructions_to_server + .lock() + .unwrap() + .as_mut() + .unwrap() + .send(msg); + } + fn recv_from_server(&self) -> (ClientInstruction, ErrorContext) { + self.receive_instructions_from_server + .lock() + .unwrap() + .as_mut() + .unwrap() + .recv() } fn receive_sigwinch(&self, cb: Box<dyn Fn()>) { let mut signals = Signals::new(&[SIGWINCH, SIGTERM, SIGINT, SIGQUIT]).unwrap(); @@ -264,19 +379,33 @@ impl OsApi for OsInputOutput { } } } - fn load_palette(&self) -> Palette { - default_palette() + fn connect_to_server(&self) { + let socket = match LocalSocketStream::connect(&**ZELLIJ_IPC_PIPE) { + Ok(sock) => sock, + Err(_) => { + std::thread::sleep(std::time::Duration::from_millis(20)); + LocalSocketStream::connect(&**ZELLIJ_IPC_PIPE).unwrap() + } + }; + let sender = IpcSenderWithContext::new(socket); + let receiver = sender.get_receiver(); + *self.send_instructions_to_server.lock().unwrap() = Some(sender); + *self.receive_instructions_from_server.lock().unwrap() = Some(receiver); } } -impl Clone for Box<dyn OsApi> { - fn clone(&self) -> Box<dyn OsApi> { +impl Clone for Box<dyn ClientOsApi> { + fn clone(&self) -> Box<dyn ClientOsApi> { self.box_clone() } } -pub fn get_os_input() -> OsInputOutput { +pub fn get_client_os_input() -> ClientOsInputOutput { let current_termios = termios::tcgetattr(0).unwrap(); let orig_termios = Arc::new(Mutex::new(current_termios)); - OsInputOutput { orig_termios } + ClientOsInputOutput { + orig_termios, + send_instructions_to_server: Arc::new(Mutex::new(None)), + receive_instructions_from_server: Arc::new(Mutex::new(None)), + } } diff --git a/src/common/pty_bus.rs b/src/common/pty_bus.rs index 2c132228..31696186 100644 --- a/src/common/pty_bus.rs +++ b/src/common/pty_bus.rs @@ -8,22 +8,24 @@ use ::std::sync::mpsc::Receiver; use ::std::time::{Duration, Instant}; use std::path::PathBuf; -use super::{ScreenInstruction, SenderWithContext}; -use crate::os_input_output::OsApi; +use super::SenderWithContext; +use crate::layout::Layout; +use crate::os_input_output::ServerOsApi; use crate::utils::logging::debug_to_file; use crate::{ errors::{get_current_ctx, ContextType, ErrorContext}, panes::PaneId, + screen::ScreenInstruction, + wasm_vm::PluginInstruction, }; -use crate::{layout::Layout, wasm_vm::PluginInstruction}; pub struct ReadFromPid { pid: RawFd, - os_input: Box<dyn OsApi>, + os_input: Box<dyn ServerOsApi>, } impl ReadFromPid { - pub fn new(pid: &RawFd, os_input: Box<dyn OsApi>) -> ReadFromPid { + pub fn new(pid: &RawFd, os_input: Box<dyn ServerOsApi>) -> ReadFromPid { ReadFromPid { pid: *pid, os_input, @@ -74,15 +76,15 @@ pub enum PtyInstruction { NewTab, ClosePane(PaneId), CloseTab(Vec<PaneId>), - Quit, + Exit, } pub struct PtyBus { - pub send_screen_instructions: SenderWithContext<ScreenInstruction>, - pub send_plugin_instructions: SenderWithContext<PluginInstruction>, pub receive_pty_instructions: Receiver<(PtyInstruction, ErrorContext)>, pub id_to_child_pid: HashMap<RawFd, RawFd>, - os_input: Box<dyn OsApi>, + pub send_screen_instructions: SenderWithContext<ScreenInstruction>, + send_plugin_instructions: SenderWithContext<PluginInstruction>, + os_input: Box<dyn ServerOsApi>, debug_to_file: bool, task_handles: HashMap<RawFd, JoinHandle<()>>, } @@ -90,7 +92,7 @@ pub struct PtyBus { fn stream_terminal_bytes( pid: RawFd, send_screen_instructions: SenderWithContext<ScreenInstruction>, - os_input: Box<dyn OsApi>, + os_input: Box<dyn ServerOsApi>, debug: bool, ) -> JoinHandle<()> { let mut err_ctx = get_current_ctx(); @@ -122,7 +124,9 @@ fn stream_terminal_bytes( Some(receive_time) => { if receive_time.elapsed() > max_render_pause { pending_render = false; - let _ = send_screen_instructions.send(ScreenInstruction::Render); + send_screen_instructions + .send(ScreenInstruction::Render) + .unwrap(); last_byte_receive_time = Some(Instant::now()); } else { pending_render = true; @@ -136,7 +140,9 @@ fn stream_terminal_bytes( } else { if pending_render { pending_render = false; - let _ = send_screen_instructions.send(ScreenInstruction::Render); + send_screen_instructions + .send(ScreenInstruction::Render) + .unwrap(); } last_byte_receive_time = None; task::sleep(::std::time::Duration::from_millis(10)).await; @@ -161,15 +167,15 @@ impl PtyBus { receive_pty_instructions: Receiver<(PtyInstruction, ErrorContext)>, send_screen_instructions: SenderWithContext<ScreenInstruction>, send_plugin_instructions: SenderWithContext<PluginInstruction>, - os_input: Box<dyn OsApi>, + os_input: Box<dyn ServerOsApi>, debug_to_file: bool, ) -> Self { PtyBus { - send_screen_instructions, - send_plugin_instructions, receive_pty_instructions, os_input, id_to_child_pid: HashMap::new(), + send_screen_instructions, + send_plugin_instructions, debug_to_file, task_handles: HashMap::new(), } @@ -196,10 +202,10 @@ impl PtyBus { new_pane_pids.push(pid_primary); } self.send_screen_instructions - .send(ScreenInstruction::ApplyLayout(( + .send(ScreenInstruction::ApplyLayout( layout, new_pane_pids.clone(), - ))) + )) .unwrap(); for id in new_pane_pids { let task_handle = stream_terminal_bytes( @@ -221,10 +227,10 @@ impl PtyBus { handle.cancel().await; }); } - PaneId::Plugin(pid) => drop( - self.send_plugin_instructions - .send(PluginInstruction::Unload(pid)), - ), + PaneId::Plugin(pid) => self + .send_plugin_instructions + .send(PluginInstruction::Unload(pid)) + .unwrap(), } } pub fn close_tab(&mut self, ids: Vec<PaneId>) { diff --git a/src/common/screen.rs b/src/common/screen.rs index e6cf73f5..562b0ffe 100644 --- a/src/common/screen.rs +++ b/src/common/screen.rs @@ -5,10 +5,11 @@ use std::os::unix::io::RawFd; use std::str; use std::sync::mpsc::Receiver; -use super::{AppInstruction, SenderWithContext}; -use crate::os_input_output::OsApi; +use crate::common::SenderWithContext; +use crate::os_input_output::ServerOsApi; use crate::panes::PositionAndSize; use crate::pty_bus::{PtyInstruction, VteBytes}; +use crate::server::ServerInstruction; use crate::tab::Tab; use crate::{errors::ErrorContext, wasm_vm::PluginInstruction}; use crate::{layout::Layout, panes::PaneId}; @@ -35,7 +36,7 @@ pub enum ScreenInstruction { MoveFocusDown, MoveFocusUp, MoveFocusRight, - Quit, + Exit, ScrollUp, ScrollDown, PageScrollUp, @@ -47,7 +48,7 @@ pub enum ScreenInstruction { SetMaxHeight(PaneId, usize), SetInvisibleBorders(PaneId, bool), ClosePane(PaneId), - ApplyLayout((Layout, Vec<RawFd>)), + ApplyLayout(Layout, Vec<RawFd>), NewTab(RawFd), SwitchTabNext, SwitchTabPrev, @@ -55,7 +56,7 @@ pub enum ScreenInstruction { CloseTab, GoToTab(u32), UpdateTabName(Vec<u8>), - TerminalResize, + TerminalResize(PositionAndSize), ChangeMode(ModeInfo), } @@ -68,18 +69,18 @@ pub struct Screen { max_panes: Option<usize>, /// A map between this [`Screen`]'s tabs and their ID/key. tabs: BTreeMap<usize, Tab>, - /// A [`PtyInstruction`] and [`ErrorContext`] sender. - pub send_pty_instructions: SenderWithContext<PtyInstruction>, /// A [`PluginInstruction`] and [`ErrorContext`] sender. pub send_plugin_instructions: SenderWithContext<PluginInstruction>, - /// An [`AppInstruction`] and [`ErrorContext`] sender. - pub send_app_instructions: SenderWithContext<AppInstruction>, + /// An [`PtyInstruction`] and [`ErrorContext`] sender. + pub send_pty_instructions: SenderWithContext<PtyInstruction>, + /// An [`ServerInstruction`] and [`ErrorContext`] sender. + pub send_server_instructions: SenderWithContext<ServerInstruction>, /// The full size of this [`Screen`]. full_screen_ws: PositionAndSize, /// The index of this [`Screen`]'s active [`Tab`]. active_tab_index: Option<usize>, - /// The [`OsApi`] this [`Screen`] uses. - os_api: Box<dyn OsApi>, + /// The [`ServerOsApi`] this [`Screen`] uses. + os_api: Box<dyn ServerOsApi>, mode_info: ModeInfo, input_mode: InputMode, colors: Palette, @@ -91,11 +92,11 @@ impl Screen { #[allow(clippy::too_many_arguments)] pub fn new( receive_screen_instructions: Receiver<(ScreenInstruction, ErrorContext)>, - send_pty_instructions: SenderWithContext<PtyInstruction>, send_plugin_instructions: SenderWithContext<PluginInstruction>, - send_app_instructions: SenderWithContext<AppInstruction>, + send_pty_instructions: SenderWithContext<PtyInstruction>, + send_server_instructions: SenderWithContext<ServerInstruction>, full_screen_ws: &PositionAndSize, - os_api: Box<dyn OsApi>, + os_api: Box<dyn ServerOsApi>, max_panes: Option<usize>, mode_info: ModeInfo, input_mode: InputMode, @@ -104,9 +105,9 @@ impl Screen { Screen { receiver: receive_screen_instructions, max_panes, - send_pty_instructions, send_plugin_instructions, - send_app_instructions, + send_pty_instructions, + send_server_instructions, full_screen_ws: *full_screen_ws, active_tab_index: None, tabs: BTreeMap::new(), @@ -128,9 +129,9 @@ impl Screen { String::new(), &self.full_screen_ws, self.os_api.clone(), - self.send_pty_instructions.clone(), self.send_plugin_instructions.clone(), - self.send_app_instructions.clone(), + self.send_pty_instructions.clone(), + self.send_server_instructions.clone(), self.max_panes, Some(PaneId::Terminal(pane_id)), self.mode_info.clone(), @@ -214,13 +215,13 @@ impl Screen { // below we don't check the result of sending the CloseTab instruction to the pty thread // because this might be happening when the app is closing, at which point the pty thread // has already closed and this would result in an error - let _ = self - .send_pty_instructions - .send(PtyInstruction::CloseTab(pane_ids)); + self.send_pty_instructions + .send(PtyInstruction::CloseTab(pane_ids)) + .unwrap(); if self.tabs.is_empty() { self.active_tab_index = None; - self.send_app_instructions - .send(AppInstruction::Exit) + self.send_server_instructions + .send(ServerInstruction::Render(None)) .unwrap(); } else { for t in self.tabs.values_mut() { @@ -232,8 +233,7 @@ impl Screen { } } - pub fn resize_to_screen(&mut self) { - let new_screen_size = self.os_api.get_terminal_size_using_fd(0); + pub fn resize_to_screen(&mut self, new_screen_size: PositionAndSize) { self.full_screen_ws = new_screen_size; for (_, tab) in self.tabs.iter_mut() { tab.resize_whole_tab(new_screen_size); @@ -285,9 +285,9 @@ impl Screen { String::new(), &self.full_screen_ws, self.os_api.clone(), - self.send_pty_instructions.clone(), self.send_plugin_instructions.clone(), - self.send_app_instructions.clone(), + self.send_pty_instructions.clone(), + self.send_server_instructions.clone(), self.max_panes, None, self.mode_info.clone(), diff --git a/src/common/setup.rs b/src/common/setup.rs index 70e0ded4..edfa858a 100644 --- a/src/common/setup.rs +++ b/src/common/setup.rs @@ -1,9 +1,9 @@ -use crate::common::utils::consts::SYSTEM_DEFAULT_CONFIG_DIR; +use crate::common::utils::consts::{SYSTEM_DEFAULT_CONFIG_DIR, VERSION}; +use crate::os_input_output::set_permissions; use directories_next::{BaseDirs, ProjectDirs}; use std::io::Write; use std::{fs, path::Path, path::PathBuf}; -const VERSION: &str = env!("CARGO_PKG_VERSION"); const CONFIG_LOCATION: &str = "/.config/zellij"; #[macro_export] @@ -40,7 +40,9 @@ pub mod install { for (path, bytes) in assets { let path = data_dir.join(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); + let parent_path = path.parent().unwrap(); + fs::create_dir_all(parent_path).unwrap(); + set_permissions(parent_path); if out_of_date || !path.exists() { fs::write(path, bytes).expect("Failed to install default assets!"); } diff --git a/src/common/utils/consts.rs b/src/common/utils/consts.rs index 4bd1b5b1..a46f8243 100644 --- a/src/common/utils/consts.rs +++ b/src/common/utils/consts.rs @@ -1,12 +1,41 @@ //! Zellij program-wide constants. -pub const ZELLIJ_TMP_DIR: &str = "/tmp/zellij"; -pub const ZELLIJ_TMP_LOG_DIR: &str = "/tmp/zellij/zellij-log"; -pub const ZELLIJ_TMP_LOG_FILE: &str = "/tmp/zellij/zellij-log/log.txt"; -pub const ZELLIJ_IPC_PIPE: &str = "/tmp/zellij/ipc"; +use crate::os_input_output::set_permissions; +use directories_next::ProjectDirs; +use lazy_static::lazy_static; +use nix::unistd::Uid; +use std::path::PathBuf; +use std::{env, fs}; pub const ZELLIJ_CONFIG_FILE_ENV: &str = "ZELLIJ_CONFIG_FILE"; pub const ZELLIJ_CONFIG_DIR_ENV: &str = "ZELLIJ_CONFIG_DIR"; +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); // TODO: ${PREFIX} argument in makefile pub const SYSTEM_DEFAULT_CONFIG_DIR: &str = "/etc/zellij"; + +lazy_static! { + static ref UID: Uid = Uid::current(); + pub static ref SESSION_NAME: String = names::Generator::default().next().unwrap(); + pub static ref ZELLIJ_PROJ_DIR: ProjectDirs = + ProjectDirs::from("org", "Zellij Contributors", "Zellij").unwrap(); + pub static ref ZELLIJ_IPC_PIPE: PathBuf = { + let mut ipc_dir = env::var("ZELLIJ_SOCKET_DIR").map_or_else( + |_| { + ZELLIJ_PROJ_DIR + .runtime_dir() + .map_or_else(|| ZELLIJ_TMP_DIR.clone(), |p| p.to_owned()) + }, + PathBuf::from, + ); + ipc_dir.push(VERSION); + fs::create_dir_all(&ipc_dir).unwrap(); + set_permissions(&ipc_dir); + ipc_dir.push(&*SESSION_NAME); + ipc_dir + }; + pub static ref ZELLIJ_TMP_DIR: PathBuf = + PathBuf::from("/tmp/zellij-".to_string() + &format!("{}", *UID)); + pub static ref ZELLIJ_TMP_LOG_DIR: PathBuf = ZELLIJ_TMP_DIR.join("zellij-log"); + pub static ref ZELLIJ_TMP_LOG_FILE: PathBuf = ZELLIJ_TMP_LOG_DIR.join("log.txt"); +} diff --git a/src/common/utils/logging.rs b/src/common/utils/logging.rs index 06827bfc..ff3fb44c 100644 --- a/src/common/utils/logging.rs +++ b/src/common/utils/logging.rs @@ -4,17 +4,20 @@ use std::{ fs, io::{self, prelude::*}, os::unix::io::RawFd, - path::PathBuf, + path::{Path, PathBuf}, }; +use crate::os_input_output::set_permissions; use crate::utils::consts::{ZELLIJ_TMP_LOG_DIR, ZELLIJ_TMP_LOG_FILE}; -pub fn atomic_create_file(file_name: &str) { +pub fn atomic_create_file(file_name: &Path) { let _ = fs::OpenOptions::new().create(true).open(file_name); + #[cfg(not(test))] + set_permissions(file_name); } -pub fn atomic_create_dir(dir_name: &str) -> io::Result<()> { - if let Err(e) = fs::create_dir(dir_name) { +pub fn atomic_create_dir(dir_name: &Path) -> io::Result<()> { + let result = if let Err(e) = fs::create_dir(dir_name) { if e.kind() == std::io::ErrorKind::AlreadyExists { Ok(()) } else { @@ -22,7 +25,11 @@ pub fn atomic_create_dir(dir_name: &str) -> io::Result<()> { } } else { Ok(()) + }; + if result.is_ok() { + set_permissions(dir_name); } + result } pub fn debug_log_to_file(mut message: String) -> io::Result<()> { @@ -31,11 +38,11 @@ pub fn debug_log_to_file(mut message: String) -> io::Result<()> { } pub fn debug_log_to_file_without_newline(message: String) -> io::Result<()> { - atomic_create_file(ZELLIJ_TMP_LOG_FILE); + atomic_create_file(&*ZELLIJ_TMP_LOG_FILE); let mut file = fs::OpenOptions::new() .append(true) .create(true) - .open(ZELLIJ_TMP_LOG_FILE)?; + .open(&*ZELLIJ_TMP_LOG_FILE)?; file.write_all(message.as_bytes()) } @@ -48,16 +55,16 @@ pub fn _debug_log_to_file_pid_3(message: String, pid: RawFd) -> io::Result<()> { } pub fn _delete_log_file() -> io::Result<()> { - if fs::metadata(ZELLIJ_TMP_LOG_FILE).is_ok() { - fs::remove_file(ZELLIJ_TMP_LOG_FILE) + if fs::metadata(&*ZELLIJ_TMP_LOG_FILE).is_ok() { + fs::remove_file(&*ZELLIJ_TMP_LOG_FILE) } else { Ok(()) } } pub fn _delete_log_dir() -> io::Result<()> { - if fs::metadata(ZELLIJ_TMP_LOG_DIR).is_ok() { - fs::remove_dir_all(ZELLIJ_TMP_LOG_DIR) + if fs::metadata(&*ZELLIJ_TMP_LOG_DIR).is_ok() { + fs::remove_dir_all(&*ZELLIJ_TMP_LOG_DIR) } else { Ok(()) } @@ -65,7 +72,7 @@ pub fn _delete_log_dir() -> io::Result<()> { pub fn debug_to_file(message: u8, pid: RawFd) -> io::Result<()> { let mut path = PathBuf::new(); - path.push(ZELLIJ_TMP_LOG_DIR); + path.push(&*ZELLIJ_TMP_LOG_DIR); path.push(format!("zellij-{}.log", pid.to_string())); let mut file = fs::OpenOptions::new() diff --git a/src/common/wasm_vm.rs b/src/common/wasm_vm.rs index bd98a85b..db52c2bb 100644 --- a/src/common/wasm_vm.rs +++ b/src/common/wasm_vm.rs @@ -11,9 +11,7 @@ use wasmer::{imports, Function, ImportObject, Store, WasmerEnv}; use wasmer_wasi::WasiEnv; use zellij_tile::data::{Event, EventType, PluginIds}; -use super::{ - pty_bus::PtyInstruction, screen::ScreenInstruction, AppInstruction, PaneId, SenderWithContext, -}; +use super::{pty_bus::PtyInstruction, screen::ScreenInstruction, PaneId, SenderWithContext}; #[derive(Clone, Debug)] pub enum PluginInstruction { @@ -21,7 +19,7 @@ pub enum PluginInstruction { Update(Option<u32>, Event), // Focused plugin / broadcast, event data Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols Unload(u32), - Quit, + Exit, } #[derive(WasmerEnv, Clone)] @@ -29,7 +27,6 @@ pub struct PluginEnv { pub plugin_id: u32, // FIXME: This should be a big bundle of all of the channels pub send_screen_instructions: SenderWithContext<ScreenInstruction>, - pub send_app_instructions: SenderWithContext<AppInstruction>, pub send_pty_instructions: SenderWithContext<PtyInstruction>, pub send_plugin_instructions: SenderWithContext<PluginInstruction>, pub wasi_env: WasiEnv, |
