diff options
| author | bjorn3 <17426603+bjorn3@users.noreply.github.com> | 2024-06-28 16:47:43 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-06-28 16:47:43 +0200 |
| commit | 7d7848cddcb303a8bdce6dd1431841345e9f6267 (patch) | |
| tree | 3353b66dfc8a18cdea5d006b57f0c05b9e277be1 /zellij-server/src/plugins | |
| parent | docs(changelog): mouse fix (diff) | |
| download | sl0ppij-7d7848cddcb303a8bdce6dd1431841345e9f6267.tar.gz sl0ppij-7d7848cddcb303a8bdce6dd1431841345e9f6267.tar.xz sl0ppij-7d7848cddcb303a8bdce6dd1431841345e9f6267.zip | |
dependencies: switch from Wasmer to Wasmtime (#3349)
* Remove ForeignFunctionEnv wrapper around PluginEnv
This will enable PluginEnv to be the Store context when migrating to
Wasmtime.
* Pass PluginEnv by value to load_plugin_instance
This will allow removing the Clone impl from PluginEnv when migrating to
Wasmtime as required by the missing Clone impl on Wasmtime's WasiCtx.
* Avoid passing a Store around when an Engine is enough
* Pass PluginEnv to the wasi read/write functions
Wasmtime requires storing the read/write end of the pipe outside of the
WasiCtx. Passing PluginEnv to these functions allows storing them in the
PluginEnv.
* Migrate to Wasmtime
* Switch from wasi-common to wasmtime-wasi
* Reduce verbosity of wasmtime_wasi logs
* Increase startup delay
To wait for all plugins to be compiled.
* Disable some wasmtime features
* Update to Wasmtime 21.0.1
Diffstat (limited to 'zellij-server/src/plugins')
| -rw-r--r-- | zellij-server/src/plugins/mod.rs | 8 | ||||
| -rw-r--r-- | zellij-server/src/plugins/pipes.rs | 39 | ||||
| -rw-r--r-- | zellij-server/src/plugins/plugin_loader.rs | 240 | ||||
| -rw-r--r-- | zellij-server/src/plugins/plugin_map.rs | 124 | ||||
| -rw-r--r-- | zellij-server/src/plugins/plugin_worker.rs | 16 | ||||
| -rw-r--r-- | zellij-server/src/plugins/unit/plugin_tests.rs | 18 | ||||
| -rw-r--r-- | zellij-server/src/plugins/wasm_bridge.rs | 81 | ||||
| -rw-r--r-- | zellij-server/src/plugins/zellij_exports.rs | 692 |
8 files changed, 529 insertions, 689 deletions
diff --git a/zellij-server/src/plugins/mod.rs b/zellij-server/src/plugins/mod.rs index 6beec9c6..7b9f7550 100644 --- a/zellij-server/src/plugins/mod.rs +++ b/zellij-server/src/plugins/mod.rs @@ -10,10 +10,9 @@ use std::{ collections::{BTreeMap, HashMap, HashSet}, fs, path::PathBuf, - sync::{Arc, Mutex}, time::Duration, }; -use wasmer::Store; +use wasmtime::Engine; use crate::panes::PaneId; use crate::screen::ScreenInstruction; @@ -189,7 +188,7 @@ impl From<&PluginInstruction> for PluginContext { pub(crate) fn plugin_thread_main( bus: Bus<PluginInstruction>, - store: Store, + engine: Engine, data_dir: PathBuf, mut layout: Box<Layout>, layout_dir: Option<PathBuf>, @@ -204,7 +203,6 @@ pub(crate) fn plugin_thread_main( let plugin_dir = data_dir.join("plugins/"); let plugin_global_data_dir = plugin_dir.join("data"); layout.populate_plugin_aliases_in_layout(&plugin_aliases); - let store = Arc::new(Mutex::new(store)); // use this channel to ensure that tasks spawned from this thread terminate before exiting // https://tokio.rs/tokio/topics/shutdown#waiting-for-things-to-finish-shutting-down @@ -212,7 +210,7 @@ pub(crate) fn plugin_thread_main( let mut wasm_bridge = WasmBridge::new( bus.senders.clone(), - store, + engine, plugin_dir, path_to_default_shell, zellij_cwd, diff --git a/zellij-server/src/plugins/pipes.rs b/zellij-server/src/plugins/pipes.rs index ba3fe99b..36cee46e 100644 --- a/zellij-server/src/plugins/pipes.rs +++ b/zellij-server/src/plugins/pipes.rs @@ -3,7 +3,6 @@ use crate::plugins::plugin_map::RunningPlugin; use crate::plugins::wasm_bridge::PluginRenderAsset; use crate::plugins::zellij_exports::{wasi_read_string, wasi_write_object}; use std::collections::{HashMap, HashSet}; -use wasmer::Value; use zellij_utils::data::{PipeMessage, PipeSource}; use zellij_utils::plugin_api::pipe_message::ProtobufPipeMessage; @@ -147,7 +146,6 @@ pub fn apply_pipe_message_to_plugin( senders: &ThreadSenders, ) -> Result<()> { let instance = &running_plugin.instance; - let plugin_env = &running_plugin.plugin_env; let rows = running_plugin.rows; let columns = running_plugin.columns; @@ -156,31 +154,24 @@ pub fn apply_pipe_message_to_plugin( .clone() .try_into() .map_err(|e| anyhow!("Failed to convert to protobuf: {:?}", e))?; - match instance.exports.get_function("pipe") { + match instance.get_typed_func::<(), i32>(&mut running_plugin.store, "pipe") { Ok(pipe) => { - wasi_write_object(&plugin_env.wasi_env, &protobuf_pipe_message.encode_to_vec()) - .with_context(err_context)?; - let pipe_return = pipe - .call(&mut running_plugin.store, &[]) + wasi_write_object( + running_plugin.store.data(), + &protobuf_pipe_message.encode_to_vec(), + ) + .with_context(err_context)?; + let should_render = pipe + .call(&mut running_plugin.store, ()) .with_context(err_context)?; - let should_render = match pipe_return.get(0) { - Some(Value::I32(n)) => *n == 1, - _ => false, - }; + let should_render = should_render == 1; if rows > 0 && columns > 0 && should_render { let rendered_bytes = instance - .exports - .get_function("render") - .map_err(anyError::new) + .get_typed_func::<(i32, i32), ()>(&mut running_plugin.store, "render") .and_then(|render| { - render - .call( - &mut running_plugin.store, - &[Value::I32(rows as i32), Value::I32(columns as i32)], - ) - .map_err(anyError::new) + render.call(&mut running_plugin.store, (rows as i32, columns as i32)) }) - .and_then(|_| wasi_read_string(&plugin_env.wasi_env)) + .and_then(|_| wasi_read_string(running_plugin.store.data())) .with_context(err_context)?; let pipes_to_block_or_unblock = pipes_to_block_or_unblock(running_plugin, Some(&pipe_message.source)); @@ -230,14 +221,16 @@ pub fn pipes_to_block_or_unblock( ) -> HashMap<String, PipeStateChange> { let mut pipe_state_changes = HashMap::new(); let mut input_pipes_to_unblock: HashSet<String> = running_plugin - .plugin_env + .store + .data() .input_pipes_to_unblock .lock() .unwrap() .drain() .collect(); let mut input_pipes_to_block: HashSet<String> = running_plugin - .plugin_env + .store + .data() .input_pipes_to_block .lock() .unwrap() diff --git a/zellij-server/src/plugins/plugin_loader.rs b/zellij-server/src/plugins/plugin_loader.rs index fafeeb22..0a839b65 100644 --- a/zellij-server/src/plugins/plugin_loader.rs +++ b/zellij-server/src/plugins/plugin_loader.rs @@ -1,19 +1,20 @@ -use crate::get_store; -use crate::plugins::plugin_map::{PluginEnv, PluginMap, RunningPlugin, Subscriptions}; +use crate::plugins::plugin_map::{ + PluginEnv, PluginMap, RunningPlugin, VecDequeInputStream, WriteOutputStream, +}; use crate::plugins::plugin_worker::{plugin_worker, RunningWorker}; use crate::plugins::zellij_exports::{wasi_write_object, zellij_exports}; use crate::plugins::PluginId; use highway::{HighwayHash, PortableHash}; use log::info; use std::{ - collections::{HashMap, HashSet}, + collections::{HashMap, HashSet, VecDeque}, fs, path::PathBuf, sync::{Arc, Mutex}, }; use url::Url; -use wasmer::{AsStoreRef, Instance, Module, Store}; -use wasmer_wasi::{Pipe, WasiState}; +use wasmtime::{Engine, Instance, Linker, Module, Store}; +use wasmtime_wasi::{DirPerms, FilePerms, WasiCtxBuilder}; use zellij_utils::consts::ZELLIJ_PLUGIN_ARTIFACT_DIR; use zellij_utils::prost::Message; @@ -53,7 +54,7 @@ pub struct PluginLoader<'a> { senders: ThreadSenders, plugin_id: PluginId, client_id: ClientId, - store: Arc<Mutex<Store>>, + engine: Engine, plugin: PluginConfig, plugin_dir: &'a PathBuf, tab_index: Option<usize>, @@ -75,7 +76,7 @@ impl<'a> PluginLoader<'a> { plugin_dir: PathBuf, plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>, senders: ThreadSenders, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_map: Arc<Mutex<PluginMap>>, connected_clients: Arc<Mutex<Vec<ClientId>>>, loading_indication: &mut LoadingIndication, @@ -102,7 +103,7 @@ impl<'a> PluginLoader<'a> { &senders, plugin_id, first_client_id, - store, + engine, &plugin_dir, path_to_default_shell, zellij_cwd, @@ -115,14 +116,8 @@ impl<'a> PluginLoader<'a> { plugin_loader .load_module_from_memory() .and_then(|module| plugin_loader.create_plugin_environment(module)) - .and_then(|(store, instance, plugin_env, subscriptions)| { - plugin_loader.load_plugin_instance( - store, - &instance, - &plugin_env, - &plugin_map, - &subscriptions, - ) + .and_then(|(store, instance)| { + plugin_loader.load_plugin_instance(store, &instance, &plugin_map) }) .and_then(|_| { plugin_loader.clone_instance_for_other_clients(&connected_clients, &plugin_map) @@ -140,7 +135,7 @@ impl<'a> PluginLoader<'a> { plugin_dir: PathBuf, plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>, senders: ThreadSenders, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_map: Arc<Mutex<PluginMap>>, size: Size, connected_clients: Arc<Mutex<Vec<ClientId>>>, @@ -161,7 +156,7 @@ impl<'a> PluginLoader<'a> { &senders, plugin_id, client_id, - store.clone(), + engine, plugin.clone(), &plugin_dir, tab_index, @@ -178,14 +173,8 @@ impl<'a> PluginLoader<'a> { plugin_loader .compile_module() .and_then(|module| plugin_loader.create_plugin_environment(module)) - .and_then(|(store, instance, plugin_env, subscriptions)| { - plugin_loader.load_plugin_instance( - store, - &instance, - &plugin_env, - &plugin_map, - &subscriptions, - ) + .and_then(|(store, instance)| { + plugin_loader.load_plugin_instance(store, &instance, &plugin_map) }) .and_then(|_| { plugin_loader.clone_instance_for_other_clients( @@ -200,14 +189,8 @@ impl<'a> PluginLoader<'a> { .or_else(|_e| plugin_loader.load_module_from_hd_cache()) .or_else(|_e| plugin_loader.compile_module()) .and_then(|module| plugin_loader.create_plugin_environment(module)) - .and_then(|(store, instance, plugin_env, subscriptions)| { - plugin_loader.load_plugin_instance( - store, - &instance, - &plugin_env, - &plugin_map, - &subscriptions, - ) + .and_then(|(store, instance)| { + plugin_loader.load_plugin_instance(store, &instance, &plugin_map) }) .and_then(|_| { plugin_loader.clone_instance_for_other_clients( @@ -226,7 +209,7 @@ impl<'a> PluginLoader<'a> { plugin_dir: PathBuf, plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>, senders: ThreadSenders, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_map: Arc<Mutex<PluginMap>>, connected_clients: Arc<Mutex<Vec<ClientId>>>, loading_indication: &mut LoadingIndication, @@ -250,7 +233,7 @@ impl<'a> PluginLoader<'a> { &senders, plugin_id, existing_client_id, - store.clone(), + engine.clone(), &plugin_dir, path_to_default_shell.clone(), zellij_cwd.clone(), @@ -263,14 +246,8 @@ impl<'a> PluginLoader<'a> { plugin_loader .load_module_from_memory() .and_then(|module| plugin_loader.create_plugin_environment(module)) - .and_then(|(store, instance, plugin_env, subscriptions)| { - plugin_loader.load_plugin_instance( - store, - &instance, - &plugin_env, - &plugin_map, - &subscriptions, - ) + .and_then(|(store, instance)| { + plugin_loader.load_plugin_instance(store, &instance, &plugin_map) })? } connected_clients.lock().unwrap().push(client_id); @@ -282,7 +259,7 @@ impl<'a> PluginLoader<'a> { plugin_dir: PathBuf, plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>, senders: ThreadSenders, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_map: Arc<Mutex<PluginMap>>, connected_clients: Arc<Mutex<Vec<ClientId>>>, loading_indication: &mut LoadingIndication, @@ -310,7 +287,7 @@ impl<'a> PluginLoader<'a> { &senders, plugin_id, first_client_id, - store.clone(), + engine, &plugin_dir, path_to_default_shell, zellij_cwd, @@ -323,14 +300,8 @@ impl<'a> PluginLoader<'a> { plugin_loader .compile_module() .and_then(|module| plugin_loader.create_plugin_environment(module)) - .and_then(|(store, instance, plugin_env, subscriptions)| { - plugin_loader.load_plugin_instance( - store, - &instance, - &plugin_env, - &plugin_map, - &subscriptions, - ) + .and_then(|(store, instance)| { + plugin_loader.load_plugin_instance(store, &instance, &plugin_map) }) .and_then(|_| { plugin_loader.clone_instance_for_other_clients(&connected_clients, &plugin_map) @@ -345,7 +316,7 @@ impl<'a> PluginLoader<'a> { senders: &ThreadSenders, plugin_id: PluginId, client_id: ClientId, - store: Arc<Mutex<Store>>, + engine: Engine, plugin: PluginConfig, plugin_dir: &'a PathBuf, tab_index: Option<usize>, @@ -370,7 +341,7 @@ impl<'a> PluginLoader<'a> { senders: senders.clone(), plugin_id, client_id, - store: store.clone(), + engine, plugin, plugin_dir, tab_index, @@ -393,7 +364,7 @@ impl<'a> PluginLoader<'a> { senders: &ThreadSenders, plugin_id: PluginId, client_id: ClientId, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_dir: &'a PathBuf, path_to_default_shell: PathBuf, zellij_cwd: PathBuf, @@ -411,20 +382,20 @@ impl<'a> PluginLoader<'a> { .with_context(err_context)? }; let running_plugin = running_plugin.lock().unwrap(); - let tab_index = running_plugin.plugin_env.tab_index; + let tab_index = running_plugin.store.data().tab_index; let size = Size { rows: running_plugin.rows, cols: running_plugin.columns, }; - let plugin_config = running_plugin.plugin_env.plugin.clone(); - loading_indication.set_name(running_plugin.plugin_env.name()); + let plugin_config = running_plugin.store.data().plugin.clone(); + loading_indication.set_name(running_plugin.store.data().name()); PluginLoader::new( plugin_cache, loading_indication, senders, plugin_id, client_id, - store, + engine, plugin_config, plugin_dir, tab_index, @@ -445,7 +416,7 @@ impl<'a> PluginLoader<'a> { senders: &ThreadSenders, plugin_id: PluginId, client_id: ClientId, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_dir: &'a PathBuf, path_to_default_shell: PathBuf, zellij_cwd: PathBuf, @@ -464,20 +435,20 @@ impl<'a> PluginLoader<'a> { .clone() }; let running_plugin = running_plugin.lock().unwrap(); - let tab_index = running_plugin.plugin_env.tab_index; + let tab_index = running_plugin.store.data().tab_index; let size = Size { rows: running_plugin.rows, cols: running_plugin.columns, }; - let plugin_config = running_plugin.plugin_env.plugin.clone(); - loading_indication.set_name(running_plugin.plugin_env.name()); + let plugin_config = running_plugin.store.data().plugin.clone(); + loading_indication.set_name(running_plugin.store.data().name()); PluginLoader::new( plugin_cache, loading_indication, senders, plugin_id, client_id, - store.clone(), + engine, plugin_config, plugin_dir, tab_index, @@ -527,9 +498,7 @@ impl<'a> PluginLoader<'a> { ); let (_wasm_bytes, cached_path) = self.plugin_bytes_and_cache_path()?; let timer = std::time::Instant::now(); - let module = unsafe { - Module::deserialize_from_file(&self.store.lock().unwrap().as_store_ref(), &cached_path)? - }; + let module = unsafe { Module::deserialize_file(&self.engine, &cached_path)? }; log::info!( "Loaded plugin '{}' from cache folder at '{}' in {:?}", self.plugin_path.display(), @@ -565,12 +534,11 @@ impl<'a> PluginLoader<'a> { .map_err(anyError::new) .and_then(|_| { // compile module - Module::new(&self.store.lock().unwrap().as_store_ref(), &wasm_bytes) - .map_err(anyError::new) + Module::new(&self.engine, &wasm_bytes) }) .and_then(|m| { // serialize module to HD cache for faster loading in the future - m.serialize_to_file(&cached_path).map_err(anyError::new)?; + fs::write(&cached_path, m.serialize()?).map_err(anyError::new)?; log::info!( "Compiled plugin '{}' in {:?}", self.plugin_path.display(), @@ -584,20 +552,19 @@ impl<'a> PluginLoader<'a> { pub fn create_plugin_environment( &mut self, module: Module, - ) -> Result<(Store, Instance, PluginEnv, Arc<Mutex<Subscriptions>>)> { - let (store, instance, plugin_env, subscriptions) = - self.create_plugin_instance_env_and_subscriptions(&module)?; + ) -> Result<(Store<PluginEnv>, Instance)> { + let (store, instance) = self.create_plugin_instance_env(&module)?; // Only do an insert when everything went well! let cloned_plugin = self.plugin.clone(); self.plugin_cache .lock() .unwrap() .insert(cloned_plugin.path, module); - Ok((store, instance, plugin_env, subscriptions)) + Ok((store, instance)) } pub fn create_plugin_instance_and_wasi_env_for_worker( &mut self, - ) -> Result<(Store, Instance, PluginEnv)> { + ) -> Result<(Store<PluginEnv>, Instance)> { let err_context = || { format!( "Failed to create instance and plugin env for worker {}", @@ -611,21 +578,17 @@ impl<'a> PluginLoader<'a> { .get(&self.plugin.path) .with_context(err_context)? .clone(); - let (store, instance, plugin_env, _subscriptions) = - self.create_plugin_instance_env_and_subscriptions(&module)?; - Ok((store, instance, plugin_env)) + let (store, instance) = self.create_plugin_instance_env(&module)?; + Ok((store, instance)) } pub fn load_plugin_instance( &mut self, - store: Store, + mut store: Store<PluginEnv>, instance: &Instance, - plugin_env: &PluginEnv, plugin_map: &Arc<Mutex<PluginMap>>, - subscriptions: &Arc<Mutex<Subscriptions>>, ) -> Result<()> { let err_context = || format!("failed to load plugin from instance {instance:#?}"); let main_user_instance = instance.clone(); - let main_user_env = plugin_env.clone(); display_loading_stage!( indicate_starting_plugin, self.loading_indication, @@ -633,39 +596,38 @@ impl<'a> PluginLoader<'a> { self.plugin_id ); let start_function = instance - .exports - .get_function("_start") + .get_typed_func::<(), ()>(&mut store, "_start") .with_context(err_context)?; let load_function = instance - .exports - .get_function("load") + .get_typed_func::<(), ()>(&mut store, "load") .with_context(err_context)?; let mut workers = HashMap::new(); - for (function_name, _exported_function) in instance.exports.iter().functions() { + for function_name in instance + .exports(&mut store) + .filter_map(|export| export.clone().into_func().map(|_| export.name())) + { if function_name.ends_with("_worker") { let plugin_config = self.plugin.clone(); - let (mut store, instance, plugin_env) = + let (mut store, instance) = self.create_plugin_instance_and_wasi_env_for_worker()?; let start_function_for_worker = instance - .exports - .get_function("_start") + .get_typed_func::<(), ()>(&mut store, "_start") .with_context(err_context)?; start_function_for_worker - .call(&mut store, &[]) + .call(&mut store, ()) .with_context(err_context)?; - let worker = - RunningWorker::new(store, instance, &function_name, plugin_config, plugin_env); + let worker = RunningWorker::new(store, instance, &function_name, plugin_config); let worker_sender = plugin_worker(worker); workers.insert(function_name.into(), worker_sender); } } + let subscriptions = store.data().subscriptions.clone(); let plugin = Arc::new(Mutex::new(RunningPlugin::new( store, main_user_instance, - main_user_env, self.size.rows, self.size.cols, ))); @@ -673,12 +635,12 @@ impl<'a> PluginLoader<'a> { self.plugin_id, self.client_id, plugin.clone(), - subscriptions.clone(), + subscriptions, workers, ); start_function - .call(&mut plugin.lock().unwrap().store, &[]) + .call(&mut plugin.lock().unwrap().store, ()) .with_context(err_context)?; let protobuf_plugin_configuration: ProtobufPluginConfiguration = self @@ -689,13 +651,13 @@ impl<'a> PluginLoader<'a> { .map_err(|e| anyhow!("Failed to serialize user configuration: {:?}", e))?; let protobuf_bytes = protobuf_plugin_configuration.encode_to_vec(); wasi_write_object( - &plugin_env.wasi_env, + plugin.lock().unwrap().store.data(), &protobuf_bytes, // &self.plugin.userspace_configuration.inner(), ) .with_context(err_context)?; load_function - .call(&mut plugin.lock().unwrap().store, &[]) + .call(&mut plugin.lock().unwrap().store, ()) .with_context(err_context)?; display_loading_stage!( @@ -744,7 +706,7 @@ impl<'a> PluginLoader<'a> { &self.senders.clone(), self.plugin_id, *client_id, - self.store.clone(), + self.engine.clone(), &self.plugin_dir, self.path_to_default_shell.clone(), self.zellij_cwd.clone(), @@ -757,14 +719,8 @@ impl<'a> PluginLoader<'a> { plugin_loader_for_client .load_module_from_memory() .and_then(|module| plugin_loader_for_client.create_plugin_environment(module)) - .and_then(|(store, instance, plugin_env, subscriptions)| { - plugin_loader_for_client.load_plugin_instance( - store, - &instance, - &plugin_env, - plugin_map, - &subscriptions, - ) + .and_then(|(store, instance)| { + plugin_loader_for_client.load_plugin_instance(store, &instance, plugin_map) })? } display_loading_stage!( @@ -799,18 +755,13 @@ impl<'a> PluginLoader<'a> { }, } } - fn create_plugin_instance_env_and_subscriptions( - &self, - module: &Module, - ) -> Result<(Store, Instance, PluginEnv, Arc<Mutex<Subscriptions>>)> { + fn create_plugin_instance_env(&self, module: &Module) -> Result<(Store<PluginEnv>, Instance)> { let err_context = || { format!( "Failed to create instance, plugin env and subscriptions for plugin {}", self.plugin_id ) }; - let mut store = get_store(); - let store_mut = &mut store; let dirs = vec![ ("/host".to_owned(), self.zellij_cwd.clone()), ("/data".to_owned(), self.plugin_own_data_dir.clone()), @@ -824,22 +775,23 @@ impl<'a> PluginLoader<'a> { // there's no built-in solution dir.try_exists().ok().unwrap_or(false) }); - let mut wasi_env = WasiState::new("Zellij") - .env("CLICOLOR_FORCE", "1") - .map_dirs(dirs) - .and_then(|wasi| { - wasi.stdin(Box::new(Pipe::new())) - .stdout(Box::new(Pipe::new())) - .stderr(Box::new(LoggingPipe::new( - &self.plugin.location.to_string(), - self.plugin_id, - ))) - .finalize(store_mut) - }) - .with_context(err_context)?; - let wasi = wasi_env - .import_object(store_mut, &module) - .with_context(err_context)?; + let mut wasi_ctx_builder = WasiCtxBuilder::new(); + wasi_ctx_builder.env("CLICOLOR_FORCE", "1"); + for (guest_path, host_path) in dirs { + wasi_ctx_builder + .preopened_dir(host_path, guest_path, DirPerms::all(), FilePerms::all()) + .with_context(err_context)?; + } + let stdin_pipe = Arc::new(Mutex::new(VecDeque::new())); + let stdout_pipe = Arc::new(Mutex::new(VecDeque::new())); + wasi_ctx_builder + .stdin(VecDequeInputStream(stdin_pipe.clone())) + .stdout(WriteOutputStream(stdout_pipe.clone())) + .stderr(WriteOutputStream(Arc::new(Mutex::new(LoggingPipe::new( + &self.plugin.location.to_string(), + self.plugin_id, + ))))); + let wasi_ctx = wasi_ctx_builder.build_p1(); let mut mut_plugin = self.plugin.clone(); if let Some(tab_index) = self.tab_index { mut_plugin.set_tab_index(tab_index); @@ -850,7 +802,7 @@ impl<'a> PluginLoader<'a> { plugin: mut_plugin, permissions: Arc::new(Mutex::new(None)), senders: self.senders.clone(), - wasi_env: wasi_env.data_mut(store_mut).clone(), + wasi_ctx, plugin_own_data_dir: self.plugin_own_data_dir.clone(), tab_index: self.tab_index, path_to_default_shell: self.path_to_default_shell.clone(), @@ -862,18 +814,28 @@ impl<'a> PluginLoader<'a> { input_pipes_to_unblock: Arc::new(Mutex::new(HashSet::new())), input_pipes_to_block: Arc::new(Mutex::new(HashSet::new())), layout_dir: self.layout_dir.clone(), + subscriptions: Arc::new(Mutex::new(HashSet::new())), + stdin_pipe, + stdout_pipe, }; + let mut store = Store::new(&self.engine, plugin_env); - let subscriptions = Arc::new(Mutex::new(HashSet::new())); - - let mut zellij = zellij_exports(store_mut, &plugin_env, &subscriptions); - zellij.extend(&wasi); + let mut linker = Linker::new(&self.engine); + wasmtime_wasi::preview1::add_to_linker_sync(&mut linker, |plugin_env: &mut PluginEnv| { + &mut plugin_env.wasi_ctx + }) + .unwrap(); + zellij_exports(&mut linker); - let instance = Instance::new(store_mut, &module, &zellij).with_context(err_context)?; + let instance = linker + .instantiate(&mut store, module) + .with_context(err_context)?; - wasi_env.initialize(store_mut, &instance)?; + if let Some(func) = instance.get_func(&mut store, "_initialize") { + func.typed::<(), ()>(&store)?.call(&mut store, ())?; + } - Ok((store, instance, plugin_env, subscriptions)) + Ok((store, instance)) } } diff --git a/zellij-server/src/plugins/plugin_map.rs b/zellij-server/src/plugins/plugin_map.rs index 1d400288..fb41c89e 100644 --- a/zellij-server/src/plugins/plugin_map.rs +++ b/zellij-server/src/plugins/plugin_map.rs @@ -1,12 +1,18 @@ use crate::plugins::plugin_worker::MessageToWorker; use crate::plugins::PluginId; +use bytes::Bytes; +use std::io::Write; use std::{ - collections::{HashMap, HashSet}, + collections::{HashMap, HashSet, VecDeque}, path::PathBuf, sync::{Arc, Mutex}, }; -use wasmer::{Instance, Store}; -use wasmer_wasi::WasiEnv; +use wasmtime::{Instance, Store}; +use wasmtime_wasi::preview1::WasiP1Ctx; +use wasmtime_wasi::{ + HostInputStream, HostOutputStream, StdinStream, StdoutStream, StreamError, StreamResult, + Subscribe, +}; use crate::{thread_bus::ThreadSenders, ClientId}; @@ -165,9 +171,9 @@ impl PluginMap { .iter() .filter(|(_, (running_plugin, _subscriptions, _workers))| { let running_plugin = running_plugin.lock().unwrap(); - let running_plugin_location = &running_plugin.plugin_env.plugin.location; - let running_plugin_configuration = - &running_plugin.plugin_env.plugin.userspace_configuration; + let plugin_config = &running_plugin.store.data().plugin; + let running_plugin_location = &plugin_config.location; + let running_plugin_configuration = &plugin_config.userspace_configuration; running_plugin_location == plugin_location && running_plugin_configuration == plugin_configuration }) @@ -188,9 +194,9 @@ impl PluginMap { > = HashMap::new(); for ((plugin_id, client_id), (running_plugin, _, _)) in self.plugin_assets.iter() { let running_plugin = running_plugin.lock().unwrap(); - let running_plugin_location = &running_plugin.plugin_env.plugin.location; - let running_plugin_configuration = - &running_plugin.plugin_env.plugin.userspace_configuration; + let plugin_config = &running_plugin.store.data().plugin; + let running_plugin_location = &plugin_config.location; + let running_plugin_configuration = &plugin_config.userspace_configuration; match cloned_plugin_assets.get_mut(running_plugin_location) { Some(location_map) => match location_map.get_mut(running_plugin_configuration) { Some(plugin_instances_info) => { @@ -240,13 +246,10 @@ impl PluginMap { .find_map(|((p_id, _), (running_plugin, _, _))| { if *p_id == plugin_id { let running_plugin = running_plugin.lock().unwrap(); - let run_plugin_location = running_plugin.plugin_env.plugin.location.clone(); - let run_plugin_configuration = running_plugin - .plugin_env - .plugin - .userspace_configuration - .clone(); - let initial_cwd = running_plugin.plugin_env.plugin.initial_cwd.clone(); + let plugin_config = &running_plugin.store.data().plugin; + let run_plugin_location = plugin_config.location.clone(); + let run_plugin_configuration = plugin_config.userspace_configuration.clone(); + let initial_cwd = plugin_config.initial_cwd.clone(); Some(RunPlugin { _allow_exec_host_cmd: false, location: run_plugin_location, @@ -262,13 +265,12 @@ impl PluginMap { pub type Subscriptions = HashSet<EventType>; -#[derive(Clone)] pub struct PluginEnv { pub plugin_id: PluginId, pub plugin: PluginConfig, pub permissions: Arc<Mutex<Option<HashSet<PermissionType>>>>, pub senders: ThreadSenders, - pub wasi_env: WasiEnv, + pub wasi_ctx: WasiP1Ctx, pub tab_index: Option<usize>, pub client_id: ClientId, #[allow(dead_code)] @@ -282,6 +284,80 @@ pub struct PluginEnv { pub plugin_cwd: PathBuf, pub input_pipes_to_unblock: Arc<Mutex<HashSet<String>>>, pub input_pipes_to_block: Arc<Mutex<HashSet<String>>>, + pub subscriptions: Arc<Mutex<Subscriptions>>, + pub stdin_pipe: Arc<Mutex<VecDeque<u8>>>, + pub stdout_pipe: Arc<Mutex<VecDeque<u8>>>, +} + +#[derive(Clone)] +pub struct VecDequeInputStream(pub Arc<Mutex<VecDeque<u8>>>); + +impl StdinStream for VecDequeInputStream { + fn stream(&self) -> Box<dyn wasmtime_wasi::HostInputStream> { + Box::new(self.clone()) + } + + fn isatty(&self) -> bool { + false + } +} + +impl HostInputStream for VecDequeInputStream { + fn read(&mut self, size: usize) -> StreamResult<Bytes> { + let mut inner = self.0.lock().unwrap(); + let len = std::cmp::min(size, inner.len()); + Ok(Bytes::from_iter(inner.drain(0..len))) + } +} + +#[async_trait::async_trait] +impl Subscribe for VecDequeInputStream { + async fn ready(&mut self) {} +} + +pub struct WriteOutputStream<T>(pub Arc<Mutex<T>>); + +impl<T> Clone for WriteOutputStream<T> { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl<T: Write + Send + 'static> StdoutStream for WriteOutputStream<T> { + fn stream(&self) -> Box<dyn HostOutputStream> { + Box::new((*self).clone()) + } + + fn isatty(&self) -> bool { + false + } +} + +impl<T: Write + Send + 'static> HostOutputStream for WriteOutputStream<T> { + fn write(&mut self, bytes: Bytes) -> StreamResult<()> { + self.0 + .lock() + .unwrap() + .write_all(&*bytes) + .map_err(|e| StreamError::LastOperationFailed(e.into())) + } + + fn flush(&mut self) -> StreamResult<()> { + self.0 + .lock() + .unwrap() + .flush() + .map_err(|e| StreamError::LastOperationFailed(e.into())) + } + + fn check_write(&mut self) -> StreamResult<usize> { + Ok(usize::MAX) + } +} + +#[async_trait::async_trait] +impl<T: Send + 'static> Subscribe for WriteOutputStream<T> { + async fn ready(&mut self) {} } impl PluginEnv { @@ -305,9 +381,8 @@ pub enum AtomicEvent { } pub struct RunningPlugin { - pub store: Store, + pub store: Store<PluginEnv>, pub instance: Instance, - pub plugin_env: PluginEnv, pub rows: usize, pub columns: usize, next_event_ids: HashMap<AtomicEvent, usize>, @@ -315,17 +390,10 @@ pub struct RunningPlugin { } impl RunningPlugin { - pub fn new( - store: Store, - instance: Instance, - plugin_env: PluginEnv, - rows: usize, - columns: usize, - ) -> Self { + pub fn new(store: Store<PluginEnv>, instance: Instance, rows: usize, columns: usize) -> Self { RunningPlugin { store, instance, - plugin_env, rows, columns, next_event_ids: HashMap::new(), diff --git a/zellij-server/src/plugins/plugin_worker.rs b/zellij-server/src/plugins/plugin_worker.rs index ec577102..3b630706 100644 --- a/zellij-server/src/plugins/plugin_worker.rs +++ b/zellij-server/src/plugins/plugin_worker.rs @@ -1,6 +1,6 @@ use crate::plugins::plugin_map::PluginEnv; use crate::plugins::zellij_exports::wasi_write_object; -use wasmer::{Instance, Store}; +use wasmtime::{Instance, Store}; use zellij_utils::async_channel::{unbounded, Receiver, Sender}; use zellij_utils::async_std::task; @@ -13,24 +13,21 @@ pub struct RunningWorker { pub instance: Instance, pub name: String, pub plugin_config: PluginConfig, - pub plugin_env: PluginEnv, - store: Store, + pub store: Store<PluginEnv>, } impl RunningWorker { pub fn new( - store: Store, + store: Store<PluginEnv>, instance: Instance, name: &str, plugin_config: PluginConfig, - plugin_env: PluginEnv, ) -> Self { RunningWorker { store, instance, name: name.into(), plugin_config, - plugin_env, } } pub fn send_message(&mut self, message: String, payload: String) -> Result<()> { @@ -43,12 +40,11 @@ impl RunningWorker { let protobuf_bytes = protobuf_message.encode_to_vec(); let work_function = self .instance - .exports - .get_function(&self.name) + .get_typed_func::<(), ()>(&mut self.store, &self.name) .with_context(err_context)?; - wasi_write_object(&self.plugin_env.wasi_env, &protobuf_bytes).with_context(err_context)?; + wasi_write_object(self.store.data(), &protobuf_bytes).with_context(err_context)?; work_function - .call(&mut self.store, &[]) + .call(&mut self.store, ()) .with_context(err_context)?; Ok(()) } diff --git a/zellij-server/src/plugins/unit/plugin_tests.rs b/zellij-server/src/plugins/unit/plugin_tests.rs index b644fe2f..6743d5e7 100644 --- a/zellij-server/src/plugins/unit/plugin_tests.rs +++ b/zellij-server/src/plugins/unit/plugin_tests.rs @@ -5,7 +5,7 @@ use insta::assert_snapshot; use std::collections::BTreeMap; use std::path::PathBuf; use tempfile::tempdir; -use wasmer::Store; +use wasmtime::Engine; use zellij_utils::data::{ BareKey, Event, KeyWithModifier, PermissionStatus, PermissionType, PluginCapabilities, }; @@ -247,7 +247,7 @@ fn create_plugin_thread( None, ) .should_silently_fail(); - let store = Store::new(wasmer::Singlepass::default()); + let engine = Engine::new(wasmtime::Config::new().strategy(wasmtime::Strategy::Winch)).unwrap(); let data_dir = PathBuf::from(tempdir().unwrap().path()); let default_shell = PathBuf::from("."); let plugin_capabilities = PluginCapabilities::default(); @@ -270,7 +270,7 @@ fn create_plugin_thread( set_var("ZELLIJ_SESSION_NAME", "zellij-test"); plugin_thread_main( plugin_bus, - store, + engine, data_dir, Box::new(Layout::default()), None, @@ -337,7 +337,7 @@ fn create_plugin_thread_with_server_receiver( None, ) .should_silently_fail(); - let store = Store::new(wasmer::Singlepass::default()); + let engine = Engine::new(wasmtime::Config::new().strategy(wasmtime::Strategy::Winch)).unwrap(); let data_dir = PathBuf::from(tempdir().unwrap().path()); let default_shell = PathBuf::from("."); let plugin_capabilities = PluginCapabilities::default(); @@ -349,7 +349,7 @@ fn create_plugin_thread_with_server_receiver( set_var("ZELLIJ_SESSION_NAME", "zellij-test"); plugin_thread_main( plugin_bus, - store, + engine, data_dir, Box::new(Layout::default()), None, @@ -422,7 +422,7 @@ fn create_plugin_thread_with_pty_receiver( None, ) .should_silently_fail(); - let store = Store::new(wasmer::Singlepass::default()); + let engine = Engine::new(wasmtime::Config::new().strategy(wasmtime::Strategy::Winch)).unwrap(); let data_dir = PathBuf::from(tempdir().unwrap().path()); let default_shell = PathBuf::from("."); let plugin_capabilities = PluginCapabilities::default(); @@ -434,7 +434,7 @@ fn create_plugin_thread_with_pty_receiver( set_var("ZELLIJ_SESSION_NAME", "zellij-test"); plugin_thread_main( plugin_bus, - store, + engine, data_dir, Box::new(Layout::default()), None, @@ -502,7 +502,7 @@ fn create_plugin_thread_with_background_jobs_receiver( None, ) .should_silently_fail(); - let store = Store::new(wasmer::Singlepass::default()); + let engine = Engine::new(wasmtime::Config::new().strategy(wasmtime::Strategy::Winch)).unwrap(); let data_dir = PathBuf::from(tempdir().unwrap().path()); let default_shell = PathBuf::from("."); let plugin_capabilities = PluginCapabilities::default(); @@ -514,7 +514,7 @@ fn create_plugin_thread_with_background_jobs_receiver( set_var("ZELLIJ_SESSION_NAME", "zellij-test"); plugin_thread_main( plugin_bus, - store, + engine, data_dir, Box::new(Layout::default()), None, diff --git a/zellij-server/src/plugins/wasm_bridge.rs b/zellij-server/src/plugins/wasm_bridge.rs index a9ba489c..764b757d 100644 --- a/zellij-server/src/plugins/wasm_bridge.rs +++ b/zellij-server/src/plugins/wasm_bridge.rs @@ -15,7 +15,7 @@ use std::{ str::FromStr, sync::{Arc, Mutex}, }; -use wasmer::{Module, Store, Value}; +use wasmtime::{Engine, Module}; use zellij_utils::async_channel::Sender; use zellij_utils::async_std::task::{self, JoinHandle}; use zellij_utils::consts::ZELLIJ_CACHE_DIR; @@ -77,7 +77,7 @@ impl PluginRenderAsset { pub struct WasmBridge { connected_clients: Arc<Mutex<Vec<ClientId>>>, senders: ThreadSenders, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_dir: PathBuf, plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>, plugin_map: Arc<Mutex<PluginMap>>, @@ -107,7 +107,7 @@ pub struct WasmBridge { impl WasmBridge { pub fn new( senders: ThreadSenders, - store: Arc<Mutex<Store>>, + engine: Engine, plugin_dir: PathBuf, path_to_default_shell: PathBuf, zellij_cwd: PathBuf, @@ -125,7 +125,7 @@ impl WasmBridge { WasmBridge { connected_clients, senders, - store, + engine, plugin_dir, plugin_cache, plugin_map, @@ -192,7 +192,7 @@ impl WasmBridge { let plugin_dir = self.plugin_dir.clone(); let plugin_cache = self.plugin_cache.clone(); let senders = self.senders.clone(); - let store = self.store.clone(); + let engine = self.engine.clone(); let plugin_map = self.plugin_map.clone(); let connected_clients = self.connected_clients.clone(); let path_to_default_shell = self.path_to_default_shell.clone(); @@ -236,7 +236,7 @@ impl WasmBridge { plugin_dir, plugin_cache, senders.clone(), - store, + engine, plugin_map, size, connected_clients.clone(), @@ -291,7 +291,7 @@ impl WasmBridge { drop(worker_sender.send(MessageToWorker::Exit)); } let running_plugin = running_plugin.lock().unwrap(); - let cache_dir = running_plugin.plugin_env.plugin_own_data_dir.clone(); + let cache_dir = running_plugin.store.data().plugin_own_data_dir.clone(); if let Err(e) = std::fs::remove_dir_all(cache_dir) { log::error!("Failed to remove cache dir for plugin: {:?}", e); } @@ -330,7 +330,7 @@ impl WasmBridge { let plugin_dir = self.plugin_dir.clone(); let plugin_cache = self.plugin_cache.clone(); let senders = self.senders.clone(); - let store = self.store.clone(); + let engine = self.engine.clone(); let plugin_map = self.plugin_map.clone(); let connected_clients = self.connected_clients.clone(); let path_to_default_shell = self.path_to_default_shell.clone(); @@ -346,7 +346,7 @@ impl WasmBridge { plugin_dir.clone(), plugin_cache.clone(), senders.clone(), - store.clone(), + engine.clone(), plugin_map.clone(), connected_clients.clone(), &mut loading_indication, @@ -371,7 +371,7 @@ impl WasmBridge { plugin_dir.clone(), plugin_cache.clone(), senders.clone(), - store.clone(), + engine.clone(), plugin_map.clone(), connected_clients.clone(), &mut loading_indication, @@ -423,7 +423,7 @@ impl WasmBridge { self.plugin_dir.clone(), self.plugin_cache.clone(), self.senders.clone(), - self.store.clone(), + self.engine.clone(), self.plugin_map.clone(), self.connected_clients.clone(), &mut loading_indication, @@ -491,23 +491,17 @@ impl WasmBridge { let rendered_bytes = running_plugin .instance .clone() - .exports - .get_function("render") - .map_err(anyError::new) + .get_typed_func::<(i32, i32), ()>( + &mut running_plugin.store, + "render", + ) .and_then(|render| { - render - .call( - &mut running_plugin.store, - &[ - Value::I32(new_rows as i32), - Value::I32(new_columns as i32), - ], - ) - .map_err(anyError::new) - }) - .and_then(|_| { - wasi_read_string(&running_plugin.plugin_env.wasi_env) + render.call( + &mut running_plugin.store, + (new_rows as i32, new_columns as i32), + ) }) + .and_then(|_| wasi_read_string(running_plugin.store.data())) .with_context(err_context); match rendered_bytes { Ok(rendered_bytes) => { @@ -1078,12 +1072,13 @@ impl WasmBridge { }; running_plugin - .plugin_env + .store + .data_mut() .set_permissions(HashSet::from_iter(permissions.clone())); let mut permission_cache = PermissionCache::from_path_or_default(cache_path); permission_cache.cache( - running_plugin.plugin_env.plugin.location.to_string(), + running_plugin.store.data().plugin.location.to_string(), permissions, ); @@ -1278,30 +1273,25 @@ pub fn apply_event_to_plugin( senders: ThreadSenders, ) -> Result<()> { let instance = &running_plugin.instance; - let plugin_env = &running_plugin.plugin_env; let rows = running_plugin.rows; let columns = running_plugin.columns; let err_context = || format!("Failed to apply event to plugin {plugin_id}"); - match check_event_permission(plugin_env, event) { + match check_event_permission(running_plugin.store.data(), event) { (PermissionStatus::Granted, _) => { let protobuf_event: ProtobufEvent = event .clone() .try_into() .map_err(|e| anyhow!("Failed to convert to protobuf: {:?}", e))?; let update = instance - .exports - .get_function("update") + .get_typed_func::<(), i32>(&mut running_plugin.store, "update") .with_context(err_context)?; - wasi_write_object(&plugin_env.wasi_env, &protobuf_event.encode_to_vec()) + wasi_write_object(running_plugin.store.data(), &protobuf_event.encode_to_vec()) .with_context(err_context)?; - let update_return = update - .call(&mut running_plugin.store, &[]) + let should_render = update + .call(&mut running_plugin.store, ()) .with_context(err_context)?; - let mut should_render = match update_return.get(0) { - Some(Value::I32(n)) => *n == 1, - _ => false, - }; + let mut should_render = should_render == 1; if let Event::PermissionRequestResult(..) = event { // we always render in this case, otherwise the request permission screen stays on // screen @@ -1309,18 +1299,11 @@ pub fn apply_event_to_plugin( } if rows > 0 && columns > 0 && should_render { let rendered_bytes = instance - .exports - .get_function("render") - .map_err(anyError::new) + .get_typed_func::<(i32, i32), ()>(&mut running_plugin.store, "render") .and_then(|render| { - render - .call( - &mut running_plugin.store, - &[Value::I32(rows as i32), Value::I32(columns as i32)], - ) - .map_err(anyError::new) + render.call(&mut running_plugin.store, (rows as i32, columns as i32)) }) - .and_then(|_| wasi_read_string(&plugin_env.wasi_env)) + .and_then(|_| wasi_read_string(running_plugin.store.data())) .with_context(err_context)?; let pipes_to_block_or_unblock = pipes_to_block_or_unblock(running_plugin, None); let plugin_render_asset = PluginRenderAsset::new( diff --git a/zellij-server/src/plugins/zellij_exports.rs b/zellij-server/src/plugins/zellij_exports.rs index 52ba0953..04569238 100644 --- a/zellij-server/src/plugins/zellij_exports.rs +++ b/zellij-server/src/plugins/zellij_exports.rs @@ -1,6 +1,6 @@ use super::PluginInstruction; use crate::background_jobs::BackgroundJob; -use crate::plugins::plugin_map::{PluginEnv, Subscriptions}; +use crate::plugins::plugin_map::PluginEnv; use crate::plugins::wasm_bridge::handle_plugin_crash; use crate::route::route_action; use crate::ServerInstruction; @@ -8,15 +8,14 @@ use log::{debug, warn}; use serde::Serialize; use std::{ collections::{BTreeMap, HashSet}, + io::{Read, Write}, path::PathBuf, process, str::FromStr, - sync::{Arc, Mutex}, thread, time::{Duration, Instant}, }; -use wasmer::{imports, AsStoreMut, Function, FunctionEnv, FunctionEnvMut, Imports}; -use wasmer_wasi::WasiEnv; +use wasmtime::{Caller, Linker}; use zellij_utils::data::{ CommandType, ConnectToSession, FloatingPaneCoordinates, HttpVerb, LayoutInfo, MessageToPlugin, PermissionStatus, PermissionType, PluginPermission, @@ -54,13 +53,13 @@ macro_rules! apply_action { ($action:ident, $error_message:ident, $env: ident) => { if let Err(e) = route_action( $action, - $env.plugin_env.client_id, - Some(PaneId::Plugin($env.plugin_env.plugin_id)), - $env.plugin_env.senders.clone(), - $env.plugin_env.capabilities.clone(), - $env.plugin_env.client_attributes.clone(), - $env.plugin_env.default_shell.clone(), - $env.plugin_env.default_layout.clone(), + $env.client_id, + Some(PaneId::Plugin($env.plugin_id)), + $env.senders.clone(), + $env.capabilities.clone(), + $env.client_attributes.clone(), + $env.default_shell.clone(), + $env.default_layout.clone(), None, ) { log::error!("{}: {:?}", $error_message(), e); @@ -68,46 +67,22 @@ macro_rules! apply_action { }; } -pub fn zellij_exports( - store: &mut impl AsStoreMut, - plugin_env: &PluginEnv, - subscriptions: &Arc<Mutex<Subscriptions>>, -) -> Imports { - let function_env = FunctionEnv::new(store, ForeignFunctionEnv::new(plugin_env, subscriptions)); - imports! { - "zellij" => { - "host_run_plugin_command" => { - Function::new_typed_with_env(store, &function_env, host_run_plugin_command) - } - } - } -} - -#[derive(Clone)] -pub struct ForeignFunctionEnv { - pub plugin_env: PluginEnv, - pub subscriptions: Arc<Mutex<Subscriptions>>, -} - -impl ForeignFunctionEnv { - pub fn new(plugin_env: &PluginEnv, subscriptions: &Arc<Mutex<Subscriptions>>) -> Self { - ForeignFunctionEnv { - plugin_env: plugin_env.clone(), - subscriptions: subscriptions.clone(), - } - } +pub fn zellij_exports(linker: &mut Linker<PluginEnv>) { + linker + .func_wrap("zellij", "host_run_plugin_command", host_run_plugin_command) + .unwrap(); } -fn host_run_plugin_command(env: FunctionEnvMut<ForeignFunctionEnv>) { - let env = env.data(); - let err_context = || format!("failed to run plugin command {}", env.plugin_env.name()); - wasi_read_bytes(&env.plugin_env.wasi_env) +fn host_run_plugin_command(caller: Caller<'_, PluginEnv>) { + let env = caller.data(); + let err_context = || format!("failed to run plugin command {}", env.name()); + wasi_read_bytes(env) .and_then(|bytes| { let command: ProtobufPluginCommand = ProtobufPluginCommand::decode(bytes.as_slice())?; let command: PluginCommand = command .try_into() .map_err(|e| anyhow!("failed to convert serialized command: {}", e))?; - match check_command_permission(&env.plugin_env, &command) { + match check_command_permission(&env, &command) { (PermissionStatus::Granted, _) => match command { PluginCommand::Subscribe(event_list) => subscribe(env, event_list)?, PluginCommand::Unsubscribe(event_list) => unsubscribe(env, event_list)?, @@ -273,7 +248,7 @@ fn host_run_plugin_command(env: FunctionEnvMut<ForeignFunctionEnv>) { (PermissionStatus::Denied, permission) => { log::error!( "Plugin '{}' permission '{}' denied - Command '{:?}' denied", - env.plugin_env.name(), + env.name(), permission .map(|p| p.to_string()) .unwrap_or("UNKNOWN".to_owned()), @@ -283,64 +258,50 @@ fn host_run_plugin_command(env: FunctionEnvMut<ForeignFunctionEnv>) { }; Ok(()) }) - .with_context(|| format!("failed to run plugin command {}", env.plugin_env.name())) + .with_context(|| format!("failed to run plugin command {}", env.name())) .non_fatal(); } -fn subscribe(env: &ForeignFunctionEnv, event_list: HashSet<EventType>) -> Result<()> { +fn subscribe(env: &PluginEnv, event_list: HashSet<EventType>) -> Result<()> { env.subscriptions .lock() .to_anyhow()? .extend(event_list.clone()); - env.plugin_env - .senders + env.senders .send_to_plugin(PluginInstruction::PluginSubscribedToEvents( - env.plugin_env.plugin_id, - env.plugin_env.client_id, + env.plugin_id, + env.client_id, event_list, )) } -fn unblock_cli_pipe_input(env: &ForeignFunctionEnv, pipe_name: String) { - env.plugin_env - .input_pipes_to_unblock - .lock() - .unwrap() - .insert(pipe_name); +fn unblock_cli_pipe_input(env: &PluginEnv, pipe_name: String) { + env.input_pipes_to_unblock.lock().unwrap().insert(pipe_name); } -fn block_cli_pipe_input(env: &ForeignFunctionEnv, pipe_name: String) { - env.plugin_env - .input_pipes_to_block - .lock() - .unwrap() - .insert(pipe_name); +fn block_cli_pipe_input(env: &PluginEnv, pipe_name: String) { + env.input_pipes_to_block.lock().unwrap().insert(pipe_name); } -fn cli_pipe_output(env: &ForeignFunctionEnv, pipe_name: String, output: String) -> Result<()> { - env.plugin_env - .senders +fn cli_pipe_output(env: &PluginEnv, pipe_name: String, output: String) -> Result<()> { + env.senders .send_to_server(ServerInstruction::CliPipeOutput(pipe_name, output)) .context("failed to send pipe output") } -fn message_to_plugin( - env: &ForeignFunctionEnv, - mut message_to_plugin: MessageToPlugin, -) -> Result<()> { +fn message_to_plugin(env: &PluginEnv, mut message_to_plugin: MessageToPlugin) -> Result<()> { if message_to_plugin.plugin_url.as_ref().map(|s| s.as_str()) == Some("zellij:OWN_URL") { - message_to_plugin.plugin_url = Some(env.plugin_env.plugin.location.display()); + message_to_plugin.plugin_url = Some(env.plugin.location.display()); } - env.plugin_env - .senders + env.senders .send_to_plugin(PluginInstruction::MessageFromPlugin { - source_plugin_id: env.plugin_env.plugin_id, + source_plugin_id: env.plugin_id, message: message_to_plugin, }) .context("failed to send message to plugin") } -fn unsubscribe(env: &ForeignFunctionEnv, event_list: HashSet<EventType>) -> Result<()> { +fn unsubscribe(env: &PluginEnv, event_list: HashSet<EventType>) -> Result<()> { env.subscriptions .lock() .to_anyhow()? @@ -348,14 +309,13 @@ fn unsubscribe(env: &ForeignFunctionEnv, event_list: HashSet<EventType>) -> Resu Ok(()) } -fn set_selectable(env: &ForeignFunctionEnv, selectable: bool) { - match env.plugin_env.plugin.run { +fn set_selectable(env: &PluginEnv, selectable: bool) { + match env.plugin.run { PluginType::Pane(Some(tab_index)) => { // let selectable = selectable != 0; - env.plugin_env - .senders + env.senders .send_to_screen(ScreenInstruction::SetSelectable( - PaneId::Plugin(env.plugin_env.plugin_id), + PaneId::Plugin(env.plugin_id), selectable, tab_index, )) @@ -363,7 +323,7 @@ fn set_selectable(env: &ForeignFunctionEnv, selectable: bool) { format!( "failed to set plugin {} selectable from plugin {}", selectable, - env.plugin_env.name() + env.name() ) }) .non_fatal(); @@ -371,22 +331,21 @@ fn set_selectable(env: &ForeignFunctionEnv, selectable: bool) { _ => { debug!( "{} - Calling method 'set_selectable' does nothing for headless plugins", - env.plugin_env.plugin.location + env.plugin.location ) }, } } -fn request_permission(env: &ForeignFunctionEnv, permissions: Vec<PermissionType>) -> Result<()> { +fn request_permission(env: &PluginEnv, permissions: Vec<PermissionType>) -> Result<()> { if PermissionCache::from_path_or_default(None) - .check_permissions(env.plugin_env.plugin.location.to_string(), &permissions) + .check_permissions(env.plugin.location.to_string(), &permissions) { return env - .plugin_env .senders .send_to_plugin(PluginInstruction::PermissionRequestResult( - env.plugin_env.plugin_id, - Some(env.plugin_env.client_id), + env.plugin_id, + Some(env.client_id), permissions.to_vec(), PermissionStatus::Granted, None, @@ -396,67 +355,62 @@ fn request_permission(env: &ForeignFunctionEnv, permissions: Vec<PermissionType> // we do this so that messages that have arrived while the user is seeing the permission screen // will be cached and reapplied once the permission is granted let _ = env - .plugin_env .senders .send_to_plugin(PluginInstruction::CachePluginEvents { - plugin_id: env.plugin_env.plugin_id, + plugin_id: env.plugin_id, }); - env.plugin_env - .senders + env.senders .send_to_screen(ScreenInstruction::RequestPluginPermissions( - env.plugin_env.plugin_id, - PluginPermission::new(env.plugin_env.plugin.location.to_string(), permissions), + env.plugin_id, + PluginPermission::new(env.plugin.location.to_string(), permissions), )) } -fn get_plugin_ids(env: &ForeignFunctionEnv) { +fn get_plugin_ids(env: &PluginEnv) { let ids = PluginIds { - plugin_id: env.plugin_env.plugin_id, + plugin_id: env.plugin_id, zellij_pid: process::id(), - initial_cwd: env.plugin_env.plugin_cwd.clone(), + initial_cwd: env.plugin_cwd.clone(), }; ProtobufPluginIds::try_from(ids) .map_err(|e| anyhow!("Failed to serialized plugin ids: {}", e)) .and_then(|serialized| { - wasi_write_object(&env.plugin_env.wasi_env, &serialized.encode_to_vec())?; + wasi_write_object(env, &serialized.encode_to_vec())?; Ok(()) }) .with_context(|| { format!( "failed to query plugin IDs from host for plugin {}", - env.plugin_env.name() + env.name() ) }) .non_fatal(); } -fn get_zellij_version(env: &ForeignFunctionEnv) { +fn get_zellij_version(env: &PluginEnv) { let protobuf_zellij_version = ProtobufZellijVersion { version: VERSION.to_owned(), }; - wasi_write_object( - &env.plugin_env.wasi_env, - &protobuf_zellij_version.encode_to_vec(), - ) - .with_context(|| { - format!( - "failed to request zellij version from host for plugin {}", - env.plugin_env.name() - ) - }) - .non_fatal(); + wasi_write_object(env, &protobuf_zellij_version.encode_to_vec()) + .with_context(|| { + format!( + "failed to request zellij version from host for plugin {}", + env.name() + ) + }) + .non_fatal(); } -fn open_file(env: &ForeignFunctionEnv, file_to_open: FileToOpen) { - let error_msg = || format!("failed to open file in plugin {}", env.plugin_env.name()); +fn open_file(env: &PluginEnv, file_to_open: FileToOpen) { + let error_msg = || format!("failed to open file in plugin {}", env.name()); let floating = false; let in_place = false; - let path = env.plugin_env.plugin_cwd.join(file_to_open.path); + let path = env.plugin_cwd.join(file_to_open.path); let cwd = file_to_open .cwd - .map(|cwd| env.plugin_env.plugin_cwd.join(cwd)) - .or_else(|| Some(env.plugin_env.plugin_cwd.clone())); + .map(|cwd| env.plugin_cwd.join(cwd)) + .or_else(|| Some(env.plugin_cwd.clone())); let action = Action::EditFile( path, file_to_open.line_number, @@ -470,18 +424,18 @@ fn open_file(env: &ForeignFunctionEnv, file_to_open: FileToOpen) { } fn open_file_floating( - env: &ForeignFunctionEnv, + env: &PluginEnv, file_to_open: FileToOpen, floating_pane_coordinates: Option<FloatingPaneCoordinates>, ) { - let error_msg = || format!("failed to open file in plugin {}", env.plugin_env.name()); + let error_msg = || format!("failed to open file in plugin {}", env.name()); let floating = true; let in_place = false; - let path = env.plugin_env.plugin_cwd.join(file_to_open.path); + let path = env.plugin_cwd.join(file_to_open.path); let cwd = file_to_open .cwd - .map(|cwd| env.plugin_env.plugin_cwd.join(cwd)) - .or_else(|| Some(env.plugin_env.plugin_cwd.clone())); + .map(|cwd| env.plugin_cwd.join(cwd)) + .or_else(|| Some(env.plugin_cwd.clone())); let action = Action::EditFile( path, file_to_open.line_number, @@ -494,15 +448,15 @@ fn open_file_floating( apply_action!(action, error_msg, env); } -fn open_file_in_place(env: &ForeignFunctionEnv, file_to_open: FileToOpen) { - let error_msg = || format!("failed to open file in plugin {}", env.plugin_env.name()); +fn open_file_in_place(env: &PluginEnv, file_to_open: FileToOpen) { + let error_msg = || format!("failed to open file in plugin {}", env.name()); let floating = false; let in_place = true; - let path = env.plugin_env.plugin_cwd.join(file_to_open.path); + let path = env.plugin_cwd.join(file_to_open.path); let cwd = file_to_open .cwd - .map(|cwd| env.plugin_env.plugin_cwd.join(cwd)) - .or_else(|| Some(env.plugin_env.plugin_cwd.clone())); + .map(|cwd| env.plugin_cwd.join(cwd)) + .or_else(|| Some(env.plugin_cwd.clone())); let action = Action::EditFile( path, @@ -516,12 +470,12 @@ fn open_file_in_place(env: &ForeignFunctionEnv, file_to_open: FileToOpen) { apply_action!(action, error_msg, env); } -fn open_terminal(env: &ForeignFunctionEnv, cwd: PathBuf) { - let error_msg = || format!("failed to open file in plugin {}", env.plugin_env.name()); - let cwd = env.plugin_env.plugin_cwd.join(cwd); - let mut default_shell = env.plugin_env.default_shell.clone().unwrap_or_else(|| { +fn open_terminal(env: &PluginEnv, cwd: PathBuf) { + let error_msg = || format!("failed to open file in plugin {}", env.name()); + let cwd = env.plugin_cwd.join(cwd); + let mut default_shell = env.default_shell.clone().unwrap_or_else(|| { TerminalAction::RunCommand(RunCommand { - command: env.plugin_env.path_to_default_shell.clone(), + command: env.path_to_default_shell.clone(), ..Default::default() }) }); @@ -535,15 +489,15 @@ fn open_terminal(env: &ForeignFunctionEnv, cwd: PathBuf) { } fn open_terminal_floating( - env: &ForeignFunctionEnv, + env: &PluginEnv, cwd: PathBuf, floating_pane_coordinates: Option<FloatingPaneCoordinates>, ) { - let error_msg = || format!("failed to open file in plugin {}", env.plugin_env.name()); - let cwd = env.plugin_env.plugin_cwd.join(cwd); - let mut default_shell = env.plugin_env.default_shell.clone().unwrap_or_else(|| { + let error_msg = || format!("failed to open file in plugin {}", env.name()); + let cwd = env.plugin_cwd.join(cwd); + let mut default_shell = env.default_shell.clone().unwrap_or_else(|| { TerminalAction::RunCommand(RunCommand { - command: env.plugin_env.path_to_default_shell.clone(), + command: env.path_to_default_shell.clone(), ..Default::default() }) }); @@ -556,12 +510,12 @@ fn open_terminal_floating( apply_action!(action, error_msg, env); } -fn open_terminal_in_place(env: &ForeignFunctionEnv, cwd: PathBuf) { - let error_msg = || format!("failed to open file in plugin {}", env.plugin_env.name()); - let cwd = env.plugin_env.plugin_cwd.join(cwd); - let mut default_shell = env.plugin_env.default_shell.clone().unwrap_or_else(|| { +fn open_terminal_in_place(env: &PluginEnv, cwd: PathBuf) { + let error_msg = || format!("failed to open file in plugin {}", env.name()); + let cwd = env.plugin_cwd.join(cwd); + let mut default_shell = env.default_shell.clone().unwrap_or_else(|| { TerminalAction::RunCommand(RunCommand { - command: env.plugin_env.path_to_default_shell.clone(), + command: env.path_to_default_shell.clone(), ..Default::default() }) }); @@ -574,12 +528,10 @@ fn open_terminal_in_place(env: &ForeignFunctionEnv, cwd: PathBuf) { apply_action!(action, error_msg, env); } -fn open_command_pane(env: &ForeignFunctionEnv, command_to_run: CommandToRun) { - let error_msg = || format!("failed to open command in plugin {}", env.plugin_env.name()); +fn open_command_pane(env: &PluginEnv, command_to_run: CommandToRun) { + let error_msg = || format!("failed to open command in plugin {}", env.name()); let command = command_to_run.path; - let cwd = command_to_run - .cwd - .map(|cwd| env.plugin_env.plugin_cwd.join(cwd)); + let cwd = command_to_run.cwd.map(|cwd| env.plugin_cwd.join(cwd)); let args = command_to_run.args; let direction = None; let hold_on_close = true; @@ -598,15 +550,13 @@ fn open_command_pane(env: &ForeignFunctionEnv, command_to_run: CommandToRun) { } fn open_command_pane_floating( - env: &ForeignFunctionEnv, + env: &PluginEnv, command_to_run: CommandToRun, floating_pane_coordinates: Option<FloatingPaneCoordinates>, ) { - let error_msg = || format!("failed to open command in plugin {}", env.plugin_env.name()); + let error_msg = || format!("failed to open command in plugin {}", env.name()); let command = command_to_run.path; - let cwd = command_to_run - .cwd - .map(|cwd| env.plugin_env.plugin_cwd.join(cwd)); + let cwd = command_to_run.cwd.map(|cwd| env.plugin_cwd.join(cwd)); let args = command_to_run.args; let direction = None; let hold_on_close = true; @@ -624,12 +574,10 @@ fn open_command_pane_floating( apply_action!(action, error_msg, env); } -fn open_command_pane_in_place(env: &ForeignFunctionEnv, command_to_run: CommandToRun) { - let error_msg = || format!("failed to open command in plugin {}", env.plugin_env.name()); +fn open_command_pane_in_place(env: &PluginEnv, command_to_run: CommandToRun) { + let error_msg = || format!("failed to open command in plugin {}", env.name()); let command = command_to_run.path; - let cwd = command_to_run - .cwd - .map(|cwd| env.plugin_env.plugin_cwd.join(cwd)); + let cwd = command_to_run.cwd.map(|cwd| env.plugin_cwd.join(cwd)); let args = command_to_run.args; let direction = None; let hold_on_close = true; @@ -647,23 +595,19 @@ fn open_command_pane_in_place(env: &ForeignFunctionEnv, command_to_run: CommandT apply_action!(action, error_msg, env); } -fn switch_tab_to(env: &ForeignFunctionEnv, tab_idx: u32) { - env.plugin_env - .senders - .send_to_screen(ScreenInstruction::GoToTab( - tab_idx, - Some(env.plugin_env.client_id), - )) +fn switch_tab_to(env: &PluginEnv, tab_idx: u32) { + env.senders + .send_to_screen(ScreenInstruction::GoToTab(tab_idx, Some(env.client_id))) .with_context(|| { format!( "failed to switch to tab {tab_idx} from plugin {}", - env.plugin_env.name() + env.name() ) }) .non_fatal(); } -fn set_timeout(env: &ForeignFunctionEnv, secs: f64) { +fn set_timeout(env: &PluginEnv, secs: f64) { // There is a fancy, high-performance way to do this with zero additional threads: // If the plugin thread keeps a BinaryHeap of timer structs, it can manage multiple and easily `.peek()` at the // next time to trigger in O(1) time. Once the wake-up time is known, the `wasm` thread can use `recv_timeout()` @@ -673,10 +617,10 @@ fn set_timeout(env: &ForeignFunctionEnv, secs: f64) { // timers as we'd like. // // But that's a lot of code, and this is a few lines: - let send_plugin_instructions = env.plugin_env.senders.to_plugin.clone(); - let update_target = Some(env.plugin_env.plugin_id); - let client_id = env.plugin_env.client_id; - let plugin_name = env.plugin_env.name(); + let send_plugin_instructions = env.senders.to_plugin.clone(); + let update_target = Some(env.plugin_id); + let client_id = env.client_id; + let plugin_name = env.name(); // TODO: we should really use an async task for this thread::spawn(move || { let start_time = Instant::now(); @@ -706,18 +650,18 @@ fn set_timeout(env: &ForeignFunctionEnv, secs: f64) { }); } -fn exec_cmd(env: &ForeignFunctionEnv, mut command_line: Vec<String>) { +fn exec_cmd(env: &PluginEnv, mut command_line: Vec<String>) { log::warn!("The ExecCmd plugin command is deprecated and will be removed in a future version. Please use RunCmd instead (it has all the things and can even show you STDOUT/STDERR and an exit code!)"); let err_context = || { format!( "failed to execute command on host for plugin '{}'", - env.plugin_env.name() + env.name() ) }; let command = command_line.remove(0); // Bail out if we're forbidden to run command - if !env.plugin_env.plugin._allow_exec_host_cmd { + if !env.plugin._allow_exec_host_cmd { warn!("This plugin isn't allow to run command in host side, skip running this command: '{cmd} {args}'.", cmd = command, args = command_line.join(" ")); return; @@ -732,7 +676,7 @@ fn exec_cmd(env: &ForeignFunctionEnv, mut command_line: Vec<String>) { } fn run_command( - env: &ForeignFunctionEnv, + env: &PluginEnv, mut command_line: Vec<String>, env_variables: BTreeMap<String, String>, cwd: PathBuf, @@ -742,13 +686,12 @@ fn run_command( log::error!("Command cannot be empty"); } else { let command = command_line.remove(0); - let cwd = env.plugin_env.plugin_cwd.join(cwd); + let cwd = env.plugin_cwd.join(cwd); let _ = env - .plugin_env .senders .send_to_background_jobs(BackgroundJob::RunCommand( - env.plugin_env.plugin_id, - env.plugin_env.client_id, + env.plugin_id, + env.client_id, command, command_line, env_variables, @@ -759,7 +702,7 @@ fn run_command( } fn web_request( - env: &ForeignFunctionEnv, + env: &PluginEnv, url: String, verb: HttpVerb, headers: BTreeMap<String, String>, @@ -767,11 +710,10 @@ fn web_request( context: BTreeMap<String, String>, ) { let _ = env - .plugin_env .senders .send_to_background_jobs(BackgroundJob::WebRequest( - env.plugin_env.plugin_id, - env.plugin_env.client_id, + env.plugin_id, + env.client_id, url, verb, headers, @@ -780,95 +722,84 @@ fn web_request( )); } -fn post_message_to(env: &ForeignFunctionEnv, plugin_message: PluginMessage) -> Result<()> { +fn post_message_to(env: &PluginEnv, plugin_message: PluginMessage) -> Result<()> { let worker_name = plugin_message .worker_name .ok_or(anyhow!("Worker name not specified in message to worker"))?; - env.plugin_env - .senders + env.senders .send_to_plugin(PluginInstruction::PostMessagesToPluginWorker( - env.plugin_env.plugin_id, - env.plugin_env.client_id, + env.plugin_id, + env.client_id, worker_name, vec![(plugin_message.name, plugin_message.payload)], )) } -fn post_message_to_plugin(env: &ForeignFunctionEnv, plugin_message: PluginMessage) -> Result<()> { +fn post_message_to_plugin(env: &PluginEnv, plugin_message: PluginMessage) -> Result<()> { if let Some(worker_name) = plugin_message.worker_name { return Err(anyhow!( "Worker name (\"{}\") should not be specified in message to plugin", worker_name )); } - env.plugin_env - .senders + env.senders .send_to_plugin(PluginInstruction::PostMessageToPlugin( - env.plugin_env.plugin_id, - env.plugin_env.client_id, + env.plugin_id, + env.client_id, plugin_message.name, plugin_message.payload, )) } -fn hide_self(env: &ForeignFunctionEnv) -> Result<()> { - env.plugin_env - .senders +fn hide_self(env: &PluginEnv) -> Result<()> { + env.senders .send_to_screen(ScreenInstruction::SuppressPane( - PaneId::Plugin(env.plugin_env.plugin_id), - env.plugin_env.client_id, + PaneId::Plugin(env.plugin_id), + env.client_id, )) .with_context(|| format!("failed to hide self")) } -fn show_self(env: &ForeignFunctionEnv, should_float_if_hidden: bool) { - let action = Action::FocusPluginPaneWithId(env.plugin_env.plugin_id, should_float_if_hidden); +fn show_self(env: &PluginEnv, should_float_if_hidden: bool) { + let action = Action::FocusPluginPaneWithId(env.plugin_id, should_float_if_hidden); let error_msg = || format!("Failed to show self for plugin"); apply_action!(action, error_msg, env); } -fn close_self(env: &ForeignFunctionEnv) { - env.plugin_env - .senders +fn close_self(env: &PluginEnv) { + env.senders .send_to_screen(ScreenInstruction::ClosePane( - PaneId::Plugin(env.plugin_env.plugin_id), + PaneId::Plugin(env.plugin_id), None, )) .with_context(|| format!("failed to close self")) .non_fatal(); - env.plugin_env - .senders - .send_to_plugin(PluginInstruction::Unload(env.plugin_env.plugin_id)) + env.senders + .send_to_plugin(PluginInstruction::Unload(env.plugin_id)) .with_context(|| format!("failed to close self")) .non_fatal(); } -fn rebind_keys(env: &ForeignFunctionEnv, new_keybinds: String) -> Result<()> { +fn rebind_keys(env: &PluginEnv, new_keybinds: String) -> Result<()> { let err_context = || "Failed to rebind keys"; - let client_id = env.plugin_env.client_id; - env.plugin_env - .senders + let client_id = env.client_id; + env.senders .send_to_server(ServerInstruction::RebindKeys(client_id, new_keybinds)) .with_context(err_context)?; Ok(()) } -fn switch_to_mode(env: &ForeignFunctionEnv, input_mode: InputMode) { +fn switch_to_mode(env: &PluginEnv, input_mode: InputMode) { let action = Action::SwitchToMode(input_mode); - let error_msg = || { - format!( - "failed to switch to mode in plugin {}", - env.plugin_env.name() - ) - }; + let error_msg = || format!("failed to switch to mode in plugin {}", env.name()); apply_action!(action, error_msg, env); } -fn new_tabs_with_layout(env: &ForeignFunctionEnv, raw_layout: &str) -> Result<()> { +fn new_tabs_with_layout(env: &PluginEnv, raw_layout: &str) -> Result<()> { // TODO: cwd let layout = Layout::from_str( &raw_layout, - format!("Layout from plugin: {}", env.plugin_env.name()), + format!("Layout from plugin: {}", env.name()), None, None, ) @@ -877,15 +808,15 @@ fn new_tabs_with_layout(env: &ForeignFunctionEnv, raw_layout: &str) -> Result<() Ok(()) } -fn new_tabs_with_layout_info(env: &ForeignFunctionEnv, layout_info: LayoutInfo) -> Result<()> { +fn new_tabs_with_layout_info(env: &PluginEnv, layout_info: LayoutInfo) -> Result<()> { // TODO: cwd - let layout = Layout::from_layout_info(&env.plugin_env.layout_dir, layout_info) + let layout = Layout::from_layout_info(&env.layout_dir, layout_info) .map_err(|e| anyhow!("Failed to parse layout: {:?}", e))?; apply_layout(env, layout); Ok(()) } -fn apply_layout(env: &ForeignFunctionEnv, layout: Layout) { +fn apply_layout(env: &PluginEnv, layout: Layout) { let mut tabs_to_open = vec![]; let tabs = layout.tabs(); if tabs.is_empty() { @@ -919,68 +850,68 @@ fn apply_layout(env: &ForeignFunctionEnv, layout: Layout) { } } -fn new_tab(env: &ForeignFunctionEnv) { +fn new_tab(env: &PluginEnv) { let action = Action::NewTab(None, vec![], None, None, None); let error_msg = || format!("Failed to open new tab"); apply_action!(action, error_msg, env); } -fn go_to_next_tab(env: &ForeignFunctionEnv) { +fn go_to_next_tab(env: &PluginEnv) { let action = Action::GoToNextTab; let error_msg = || format!("Failed to go to next tab"); apply_action!(action, error_msg, env); } -fn go_to_previous_tab(env: &ForeignFunctionEnv) { +fn go_to_previous_tab(env: &PluginEnv) { let action = Action::GoToPreviousTab; let error_msg = || format!("Failed to go to previous tab"); apply_action!(action, error_msg, env); } -fn resize(env: &ForeignFunctionEnv, resize: Resize) { - let error_msg = || format!("failed to resize in plugin {}", env.plugin_env.name()); +fn resize(env: &PluginEnv, resize: Resize) { + let error_msg = || format!("failed to resize in plugin {}", env.name()); let action = Action::Resize(resize, None); apply_action!(action, error_msg, env); } -fn resize_with_direction(env: &ForeignFunctionEnv, resize: ResizeStrategy) { - let error_msg = || format!("failed to resize in plugin {}", env.plugin_env.name()); +fn resize_with_direction(env: &PluginEnv, resize: ResizeStrategy) { + let error_msg = || format!("failed to resize in plugin {}", env.name()); let action = Action::Resize(resize.resize, resize.direction); apply_action!(action, error_msg, env); } -fn focus_next_pane(env: &ForeignFunctionEnv) { +fn focus_next_pane(env: &PluginEnv) { let action = Action::FocusNextPane; let error_msg = || format!("Failed to focus next pane"); apply_action!(action, error_msg, env); } -fn focus_previous_pane(env: &ForeignFunctionEnv) { +fn focus_previous_pane(env: &PluginEnv) { let action = Action::FocusPreviousPane; let error_msg = || format!("Failed to focus previous pane"); apply_action!(action, error_msg, env); } -fn move_focus(env: &ForeignFunctionEnv, direction: Direction) { - let error_msg = || format!("failed to move focus in plugin {}", env.plugin_env.name()); +fn move_focus(env: &PluginEnv, direction: Direction) { + let error_msg = || format!("failed to move focus in plugin {}", env.name()); let action = Action::MoveFocus(direction); apply_action!(action, error_msg, env); } -fn move_focus_or_tab(env: &ForeignFunctionEnv, direction: Direction) { - let error_msg = || format!("failed to move focus in plugin {}", env.plugin_env.name()); +fn move_focus_or_tab(env: &PluginEnv, direction: Direction) { + let error_msg = || format!("failed to move focus in plugin {}", env.name()); let action = Action::MoveFocusOrTab(direction); apply_action!(action, error_msg, env); } -fn detach(env: &ForeignFunctionEnv) { +fn detach(env: &PluginEnv) { let action = Action::Detach; let error_msg = || format!("Failed to detach"); apply_action!(action, error_msg, env); } fn switch_session( - env: &ForeignFunctionEnv, + env: &PluginEnv, session_name: Option<String>, tab_position: Option<usize>, pane_id: Option<(u32, bool)>, @@ -989,7 +920,7 @@ fn switch_session( ) -> Result<()> { // pane_id is (id, is_plugin) let err_context = || format!("Failed to switch session"); - let client_id = env.plugin_env.client_id; + let client_id = env.client_id; let tab_position = tab_position.map(|p| p + 1); // ¯\_()_/¯ let connect_to_session = ConnectToSession { name: session_name, @@ -998,8 +929,7 @@ fn switch_session( layout, cwd, }; - env.plugin_env - .senders + env.senders .send_to_server(ServerInstruction::SwitchSession( connect_to_session, client_id, @@ -1054,236 +984,176 @@ fn delete_all_dead_sessions() -> Result<()> { Ok(()) } -fn edit_scrollback(env: &ForeignFunctionEnv) { +fn edit_scrollback(env: &PluginEnv) { let action = Action::EditScrollback; let error_msg = || format!("Failed to edit scrollback"); apply_action!(action, error_msg, env); } -fn write(env: &ForeignFunctionEnv, bytes: Vec<u8>) { - let error_msg = || format!("failed to write in plugin {}", env.plugin_env.name()); +fn write(env: &PluginEnv, bytes: Vec<u8>) { + let error_msg = || format!("failed to write in plugin {}", env.name()); let action = Action::Write(None, bytes, false); apply_action!(action, error_msg, env); } -fn write_chars(env: &ForeignFunctionEnv, chars_to_write: String) { - let error_msg = || format!("failed to write in plugin {}", env.plugin_env.name()); +fn write_chars(env: &PluginEnv, chars_to_write: String) { + let error_msg = || format!("failed to write in plugin {}", env.name()); let action = Action::WriteChars(chars_to_write); apply_action!(action, error_msg, env); } -fn toggle_tab(env: &ForeignFunctionEnv) { +fn toggle_tab(env: &PluginEnv) { let error_msg = || format!("Failed to toggle tab"); let action = Action::ToggleTab; apply_action!(action, error_msg, env); } -fn move_pane(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to move pane in plugin {}", env.plugin_env.name()); +fn move_pane(env: &PluginEnv) { + let error_msg = || format!("failed to move pane in plugin {}", env.name()); let action = Action::MovePane(None); apply_action!(action, error_msg, env); } -fn move_pane_with_direction(env: &ForeignFunctionEnv, direction: Direction) { - let error_msg = || format!("failed to move pane in plugin {}", env.plugin_env.name()); +fn move_pane_with_direction(env: &PluginEnv, direction: Direction) { + let error_msg = || format!("failed to move pane in plugin {}", env.name()); let action = Action::MovePane(Some(direction)); apply_action!(action, error_msg, env); } -fn clear_screen(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to clear screen in plugin {}", env.plugin_env.name()); +fn clear_screen(env: &PluginEnv) { + let error_msg = || format!("failed to clear screen in plugin {}", env.name()); let action = Action::ClearScreen; apply_action!(action, error_msg, env); } -fn scroll_up(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to scroll up in plugin {}", env.plugin_env.name()); +fn scroll_up(env: &PluginEnv) { + let error_msg = || format!("failed to scroll up in plugin {}", env.name()); let action = Action::ScrollUp; apply_action!(action, error_msg, env); } -fn scroll_down(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to scroll down in plugin {}", env.plugin_env.name()); +fn scroll_down(env: &PluginEnv) { + let error_msg = || format!("failed to scroll down in plugin {}", env.name()); let action = Action::ScrollDown; apply_action!(action, error_msg, env); } -fn scroll_to_top(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to scroll in plugin {}", env.plugin_env.name()); +fn scroll_to_top(env: &PluginEnv) { + let error_msg = || format!("failed to scroll in plugin {}", env.name()); let action = Action::ScrollToTop; apply_action!(action, error_msg, env); } -fn scroll_to_bottom(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to scroll in plugin {}", env.plugin_env.name()); +fn scroll_to_bottom(env: &PluginEnv) { + let error_msg = || format!("failed to scroll in plugin {}", env.name()); let action = Action::ScrollToBottom; apply_action!(action, error_msg, env); } -fn page_scroll_up(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to scroll in plugin {}", env.plugin_env.name()); +fn page_scroll_up(env: &PluginEnv) { + let error_msg = || format!("failed to scroll in plugin {}", env.name()); let action = Action::PageScrollUp; apply_action!(action, error_msg, env); } -fn page_scroll_down(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to scroll in plugin {}", env.plugin_env.name()); +fn page_scroll_down(env: &PluginEnv) { + let error_msg = || format!("failed to scroll in plugin {}", env.name()); let action = Action::PageScrollDown; apply_action!(action, error_msg, env); } -fn toggle_focus_fullscreen(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to toggle full screen in plugin {}", - env.plugin_env.name() - ) - }; +fn toggle_focus_fullscreen(env: &PluginEnv) { + let error_msg = || format!("failed to toggle full screen in plugin {}", env.name()); let action = Action::ToggleFocusFullscreen; apply_action!(action, error_msg, env); } -fn toggle_pane_frames(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to toggle full screen in plugin {}", - env.plugin_env.name() - ) - }; +fn toggle_pane_frames(env: &PluginEnv) { + let error_msg = || format!("failed to toggle full screen in plugin {}", env.name()); let action = Action::TogglePaneFrames; apply_action!(action, error_msg, env); } -fn toggle_pane_embed_or_eject(env: &ForeignFunctionEnv) { +fn toggle_pane_embed_or_eject(env: &PluginEnv) { let error_msg = || { format!( "failed to toggle pane embed or eject in plugin {}", - env.plugin_env.name() + env.name() ) }; let action = Action::TogglePaneEmbedOrFloating; apply_action!(action, error_msg, env); } -fn undo_rename_pane(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to undo rename pane in plugin {}", - env.plugin_env.name() - ) - }; +fn undo_rename_pane(env: &PluginEnv) { + let error_msg = || format!("failed to undo rename pane in plugin {}", env.name()); let action = Action::UndoRenamePane; apply_action!(action, error_msg, env); } -fn close_focus(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to close focused pane in plugin {}", - env.plugin_env.name() - ) - }; +fn close_focus(env: &PluginEnv) { + let error_msg = || format!("failed to close focused pane in plugin {}", env.name()); let action = Action::CloseFocus; apply_action!(action, error_msg, env); } -fn toggle_active_tab_sync(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to toggle active tab sync in plugin {}", - env.plugin_env.name() - ) - }; +fn toggle_active_tab_sync(env: &PluginEnv) { + let error_msg = || format!("failed to toggle active tab sync in plugin {}", env.name()); let action = Action::ToggleActiveSyncTab; apply_action!(action, error_msg, env); } -fn close_focused_tab(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to close active tab in plugin {}", - env.plugin_env.name() - ) - }; +fn close_focused_tab(env: &PluginEnv) { + let error_msg = || format!("failed to close active tab in plugin {}", env.name()); let action = Action::CloseTab; apply_action!(action, error_msg, env); } -fn undo_rename_tab(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to undo rename tab in plugin {}", - env.plugin_env.name() - ) - }; +fn undo_rename_tab(env: &PluginEnv) { + let error_msg = || format!("failed to undo rename tab in plugin {}", env.name()); let action = Action::UndoRenameTab; apply_action!(action, error_msg, env); } -fn quit_zellij(env: &ForeignFunctionEnv) { - let error_msg = || format!("failed to quit zellij in plugin {}", env.plugin_env.name()); +fn quit_zellij(env: &PluginEnv) { + let error_msg = || format!("failed to quit zellij in plugin {}", env.name()); let action = Action::Quit; apply_action!(action, error_msg, env); } -fn previous_swap_layout(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to switch swap layout in plugin {}", - env.plugin_env.name() - ) - }; +fn previous_swap_layout(env: &PluginEnv) { + let error_msg = || format!("failed to switch swap layout in plugin {}", env.name()); let action = Action::PreviousSwapLayout; apply_action!(action, error_msg, env); } -fn next_swap_layout(env: &ForeignFunctionEnv) { - let error_msg = || { - format!( - "failed to switch swap layout in plugin {}", - env.plugin_env.name() - ) - }; +fn next_swap_layout(env: &PluginEnv) { + let error_msg = || format!("failed to switch swap layout in plugin {}", env.name()); let action = Action::NextSwapLayout; apply_action!(action, error_msg, env); } -fn go_to_tab_name(env: &ForeignFunctionEnv, tab_name: String) { - let error_msg = || format!("failed to change tab in plugin {}", env.plugin_env.name()); +fn go_to_tab_name(env: &PluginEnv, tab_name: String) { + let error_msg = || format!("failed to change tab in plugin {}", env.name()); let create = false; let action = Action::GoToTabName(tab_name, create); apply_action!(action, error_msg, env); } -fn focus_or_create_tab(env: &ForeignFunctionEnv, tab_name: String) { - let error_msg = || { - format!( - "failed to change or create tab in plugin {}", - env.plugin_env.name() - ) - }; +fn focus_or_create_tab(env: &PluginEnv, tab_name: String) { + let error_msg = || format!("failed to change or create tab in plugin {}", env.name()); let create = true; let action = Action::GoToTabName(tab_name, create); apply_action!(action, error_msg, env); } -fn go_to_tab(env: &ForeignFunctionEnv, tab_index: u32) { - let error_msg = || { - format!( - "failed to change tab focus in plugin {}", - env.plugin_env.name() - ) - }; +fn go_to_tab(env: &PluginEnv, tab_index: u32) { + let error_msg = || format!("failed to change tab focus in plugin {}", env.name()); let action = Action::GoToTab(tab_index + 1); apply_action!(action, error_msg, env); } -fn start_or_reload_plugin(env: &ForeignFunctionEnv, url: &str) -> Result<()> { - let error_msg = || { - format!( - "failed to start or reload plugin in plugin {}", - env.plugin_env.name() - ) - }; +fn start_or_reload_plugin(env: &PluginEnv, url: &str) -> Result<()> { + let error_msg = || format!("failed to start or reload plugin in plugin {}", env.name()); let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); let run_plugin_or_alias = RunPluginOrAlias::from_url(url, &None, None, Some(cwd)) .map_err(|e| anyhow!("Failed to parse plugin location: {}", e))?; @@ -1292,81 +1162,59 @@ fn start_or_reload_plugin(env: &ForeignFunctionEnv, url: &str) -> Result<()> { Ok(()) } -fn close_terminal_pane(env: &ForeignFunctionEnv, terminal_pane_id: u32) { - let error_msg = || { - format!( - "failed to change tab focus in plugin {}", - env.plugin_env.name() - ) - }; +fn close_terminal_pane(env: &PluginEnv, terminal_pane_id: u32) { + let error_msg = || format!("failed to change tab focus in plugin {}", env.name()); let action = Action::CloseTerminalPane(terminal_pane_id); apply_action!(action, error_msg, env); } -fn close_plugin_pane(env: &ForeignFunctionEnv, plugin_pane_id: u32) { - let error_msg = || { - format!( - "failed to change tab focus in plugin {}", - env.plugin_env.name() - ) - }; +fn close_plugin_pane(env: &PluginEnv, plugin_pane_id: u32) { + let error_msg = || format!("failed to change tab focus in plugin {}", env.name()); let action = Action::ClosePluginPane(plugin_pane_id); apply_action!(action, error_msg, env); } -fn focus_terminal_pane( - env: &ForeignFunctionEnv, - terminal_pane_id: u32, - should_float_if_hidden: bool, -) { +fn focus_terminal_pane(env: &PluginEnv, terminal_pane_id: u32, should_float_if_hidden: bool) { let action = Action::FocusTerminalPaneWithId(terminal_pane_id, should_float_if_hidden); let error_msg = || format!("Failed to focus terminal pane"); apply_action!(action, error_msg, env); } -fn focus_plugin_pane(env: &ForeignFunctionEnv, plugin_pane_id: u32, should_float_if_hidden: bool) { +fn focus_plugin_pane(env: &PluginEnv, plugin_pane_id: u32, should_float_if_hidden: bool) { let action = Action::FocusPluginPaneWithId(plugin_pane_id, should_float_if_hidden); let error_msg = || format!("Failed to focus plugin pane"); apply_action!(action, error_msg, env); } -fn rename_terminal_pane(env: &ForeignFunctionEnv, terminal_pane_id: u32, new_name: &str) { +fn rename_terminal_pane(env: &PluginEnv, terminal_pane_id: u32, new_name: &str) { let error_msg = || format!("Failed to rename terminal pane"); let rename_pane_action = Action::RenameTerminalPane(terminal_pane_id, new_name.as_bytes().to_vec()); apply_action!(rename_pane_action, error_msg, env); } -fn rename_plugin_pane(env: &ForeignFunctionEnv, plugin_pane_id: u32, new_name: &str) { +fn rename_plugin_pane(env: &PluginEnv, plugin_pane_id: u32, new_name: &str) { let error_msg = || format!("Failed to rename plugin pane"); let rename_pane_action = Action::RenamePluginPane(plugin_pane_id, new_name.as_bytes().to_vec()); apply_action!(rename_pane_action, error_msg, env); } -fn rename_tab(env: &ForeignFunctionEnv, tab_index: u32, new_name: &str) { +fn rename_tab(env: &PluginEnv, tab_index: u32, new_name: &str) { let error_msg = || format!("Failed to rename tab"); let rename_tab_action = Action::RenameTab(tab_index, new_name.as_bytes().to_vec()); apply_action!(rename_tab_action, error_msg, env); } -fn rename_session(env: &ForeignFunctionEnv, new_session_name: String) { - let error_msg = || { - format!( - "failed to rename session in plugin {}", - env.plugin_env.name() - ) - }; +fn rename_session(env: &PluginEnv, new_session_name: String) { + let error_msg = || format!("failed to rename session in plugin {}", env.name()); let action = Action::RenameSession(new_session_name); apply_action!(action, error_msg, env); } -fn disconnect_other_clients(env: &ForeignFunctionEnv) { +fn disconnect_other_clients(env: &PluginEnv) { let _ = env - .plugin_env .senders - .send_to_server(ServerInstruction::DisconnectAllClientsExcept( - env.plugin_env.client_id, - )) + .send_to_server(ServerInstruction::DisconnectAllClientsExcept(env.client_id)) .context("failed to send disconnect other clients instruction"); } @@ -1384,24 +1232,23 @@ fn kill_sessions(session_names: Vec<String>) { } } -fn watch_filesystem(env: &ForeignFunctionEnv) { +fn watch_filesystem(env: &PluginEnv) { let _ = env - .plugin_env .senders .to_plugin .as_ref() .map(|sender| sender.send(PluginInstruction::WatchFilesystem)); } -fn dump_session_layout(env: &ForeignFunctionEnv) { - let _ = env.plugin_env.senders.to_screen.as_ref().map(|sender| { - sender.send(ScreenInstruction::DumpLayoutToPlugin( - env.plugin_env.plugin_id, - )) - }); +fn dump_session_layout(env: &PluginEnv) { + let _ = env + .senders + .to_screen + .as_ref() + .map(|sender| sender.send(ScreenInstruction::DumpLayoutToPlugin(env.plugin_id))); } -fn scan_host_folder(env: &ForeignFunctionEnv, folder_to_scan: PathBuf) { +fn scan_host_folder(env: &PluginEnv, folder_to_scan: PathBuf) { if !folder_to_scan.starts_with("/host") { log::error!( "Can only scan files in the /host filesystem, found: {}", @@ -1409,7 +1256,7 @@ fn scan_host_folder(env: &ForeignFunctionEnv, folder_to_scan: PathBuf) { ); return; } - let plugin_host_folder = env.plugin_env.plugin_cwd.clone(); + let plugin_host_folder = env.plugin_cwd.clone(); let folder_to_scan = plugin_host_folder.join(folder_to_scan.strip_prefix("/host").unwrap()); match folder_to_scan.canonicalize() { Ok(folder_to_scan) => { @@ -1424,9 +1271,9 @@ fn scan_host_folder(env: &ForeignFunctionEnv, folder_to_scan: PathBuf) { let reading_folder = std::fs::read_dir(&folder_to_scan); match reading_folder { Ok(reading_folder) => { - let send_plugin_instructions = env.plugin_env.senders.to_plugin.clone(); - let update_target = Some(env.plugin_env.plugin_id); - let client_id = env.plugin_env.client_id; + let send_plugin_instructions = env.senders.to_plugin.clone(); + let update_target = Some(env.plugin_id); + let client_id = env.client_id; thread::spawn({ move || { let mut paths_in_folder = vec![]; @@ -1473,27 +1320,23 @@ fn scan_host_folder(env: &ForeignFunctionEnv, folder_to_scan: PathBuf) { // This is called when a panic occurs in a plugin. Since most panics will likely originate in the // code trying to deserialize an `Event` upon a plugin state update, we read some panic message, // formatted as string from the plugin. -fn report_panic(env: &ForeignFunctionEnv, msg: &str) { +fn report_panic(env: &PluginEnv, msg: &str) { log::error!("PANIC IN PLUGIN!\n\r{}", msg); - handle_plugin_crash( - env.plugin_env.plugin_id, - msg.to_owned(), - env.plugin_env.senders.clone(), - ); + handle_plugin_crash(env.plugin_id, msg.to_owned(), env.senders.clone()); } // Helper Functions --------------------------------------------------------------------------------------------------- -pub fn wasi_read_string(wasi_env: &WasiEnv) -> Result<String> { - let err_context = || format!("failed to read string from WASI env '{wasi_env:?}'"); +pub fn wasi_read_string(plugin_env: &PluginEnv) -> Result<String> { + let err_context = || format!("failed to read string from WASI env"); let mut buf = vec![]; - wasi_env - .state() - .stdout() + plugin_env + .stdout_pipe + .lock() + .unwrap() + .read_to_end(&mut buf) .map_err(anyError::new) - .and_then(|stdout| stdout.ok_or(anyhow!("failed to get mutable reference to stdout"))) - .and_then(|mut wasi_file| wasi_file.read_to_end(&mut buf).map_err(anyError::new)) .with_context(err_context)?; let buf = String::from_utf8_lossy(&buf); @@ -1501,27 +1344,24 @@ pub fn wasi_read_string(wasi_env: &WasiEnv) -> Result<String> { Ok(buf.replace("\n", "\n\r")) } -pub fn wasi_write_string(wasi_env: &WasiEnv, buf: &str) -> Result<()> { - wasi_env - .state() - .stdin() +pub fn wasi_write_string(plugin_env: &PluginEnv, buf: &str) -> Result<()> { + let mut stdin = plugin_env.stdin_pipe.lock().unwrap(); + writeln!(stdin, "{}\r", buf) .map_err(anyError::new) - .and_then(|stdin| stdin.ok_or(anyhow!("failed to get mutable reference to stdin"))) - .and_then(|mut stdin| writeln!(stdin, "{}\r", buf).map_err(anyError::new)) - .with_context(|| format!("failed to write string to WASI env '{wasi_env:?}'")) + .with_context(|| format!("failed to write string to WASI env")) } -pub fn wasi_write_object(wasi_env: &WasiEnv, object: &(impl Serialize + ?Sized)) -> Result<()> { +pub fn wasi_write_object(plugin_env: &PluginEnv, object: &(impl Serialize + ?Sized)) -> Result<()> { serde_json::to_string(&object) .map_err(anyError::new) - .and_then(|string| wasi_write_string(wasi_env, &string)) - .with_context(|| format!("failed to serialize object for WASI env '{wasi_env:?}'")) + .and_then(|string| wasi_write_string(plugin_env, &string)) + .with_context(|| format!("failed to serialize object for WASI env")) } -pub fn wasi_read_bytes(wasi_env: &WasiEnv) -> Result<Vec<u8>> { - wasi_read_string(wasi_env) +pub fn wasi_read_bytes(plugin_env: &PluginEnv) -> Result<Vec<u8>> { + wasi_read_string(plugin_env) .and_then(|string| serde_json::from_str(&string).map_err(anyError::new)) - .with_context(|| format!("failed to deserialize object from WASI env '{wasi_env:?}'")) + .with_context(|| format!("failed to deserialize object from WASI env")) } // TODO: move to permissions? |
