summaryrefslogtreecommitdiffstats
path: root/zellij-server/src/wasm_vm.rs
blob: 53dceaa7534517bb239fca33ea294b3394ac1276 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::sync::{mpsc::Sender, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use zellij_utils::{serde, zellij_tile};

use serde::{de::DeserializeOwned, Serialize};
use wasmer::{
    imports, ChainableNamedResolver, Function, ImportObject, Instance, Module, Store, Value,
    WasmerEnv,
};
use wasmer_wasi::{Pipe, WasiEnv, WasiState};
use zellij_tile::data::{Event, EventType, PluginIds};

use crate::{
    panes::PaneId,
    pty::PtyInstruction,
    screen::ScreenInstruction,
    thread_bus::{Bus, ThreadSenders},
};
use zellij_utils::errors::{ContextType, PluginContext};

#[derive(Clone, Debug)]
pub(crate) enum PluginInstruction {
    Load(Sender<u32>, PathBuf),
    Update(Option<u32>, Event), // Focused plugin / broadcast, event data
    Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols
    Unload(u32),
    Exit,
}

impl From<&PluginInstruction> for PluginContext {
    fn from(plugin_instruction: &PluginInstruction) -> Self {
        match *plugin_instruction {
            PluginInstruction::Load(..) => PluginContext::Load,
            PluginInstruction::Update(..) => PluginContext::Update,
            PluginInstruction::Render(..) => PluginContext::Render,
            PluginInstruction::Unload(_) => PluginContext::Unload,
            PluginInstruction::Exit => PluginContext::Exit,
        }
    }
}

#[derive(WasmerEnv, Clone)]
pub(crate) struct PluginEnv {
    pub plugin_id: u32,
    pub senders: ThreadSenders,
    pub wasi_env: WasiEnv,
    pub subscriptions: Arc<Mutex<HashSet<EventType>>>,
}

// Thread main --------------------------------------------------------------------------------------------------------
pub(crate) fn wasm_thread_main(bus: Bus<PluginInstruction>, store: Store, data_dir: PathBuf) {
    let mut plugin_id = 0;
    let mut plugin_map = HashMap::new();
    loop {
        let (event, mut err_ctx) = bus.recv().expect("failed to receive event on channel");
        err_ctx.add_call(ContextType::Plugin((&event).into()));
        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,
                    senders: bus.senders.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(bus.senders.send_to_screen(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)),
            Plugin