Give plugins SDK APIs for terminals, granted folders, and plugin services
Plugins can now do through the SDK what they did with direct native calls. The SDK checks plugin shutdown, so these APIs can move to an isolated plugin context later. - api.pty opens shell sessions. pty_open accepts an optional channel. A channel session sends its output as raw bytes to its own webview and sends no pty-data or pty-exit events. Without a channel, the events stay, so the released Terminal plugin keeps working. The host closes the open sessions of a plugin when the plugin stops. - api.files gives folder grants. The user selects the folder, the host keeps the grants of each plugin in its retained data, and the plugin uses an opaque grant ID. The host rejects names with folder parts, links, and files over the size limit. Sidecar JSON files replace the per-image settings commands. - api.services lets one plugin offer data to another plugin in the same window. The host copies arguments and results. - The folder methods of api.backgrounds are deprecated. They stay for released Background Slideshow versions. - The plugin reference lists the native calls of each plugin and the SDK member that replaces each call.
This commit is contained in:
+109
-37
@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
||||
use serde::Serialize;
|
||||
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
@@ -72,6 +73,63 @@ pub struct PtyExit {
|
||||
pub code: Option<u32>,
|
||||
}
|
||||
|
||||
/// The destination of the output and the exit status of one terminal session.
|
||||
trait PtyOutput: Send {
|
||||
fn data(&self, bytes: &[u8]);
|
||||
fn exit(&self, code: Option<u32>);
|
||||
}
|
||||
|
||||
/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`.
|
||||
/// The events go to the window that opened the session. A global `listen` in that window
|
||||
/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows.
|
||||
struct EventOutput {
|
||||
app: AppHandle,
|
||||
owner: String,
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl PtyOutput for EventOutput {
|
||||
fn data(&self, bytes: &[u8]) {
|
||||
let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() });
|
||||
}
|
||||
fn exit(&self, code: Option<u32>) {
|
||||
let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code });
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel to the webview that opened the session. Output goes as raw bytes (an
|
||||
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
|
||||
struct ChannelOutput(Channel<InvokeResponseBody>);
|
||||
|
||||
impl PtyOutput for ChannelOutput {
|
||||
fn data(&self, bytes: &[u8]) {
|
||||
let _ = self.0.send(InvokeResponseBody::Raw(bytes.to_vec()));
|
||||
}
|
||||
fn exit(&self, code: Option<u32>) {
|
||||
let _ = self.0.send(InvokeResponseBody::Json(serde_json::json!({ "exit": code }).to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Use the channel when the caller supplies one. Without a channel, use window events.
|
||||
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
|
||||
match channel {
|
||||
Some(channel) => Box::new(ChannelOutput(channel)),
|
||||
None => events(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the output until the reader reaches EOF. Then send the exit status.
|
||||
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => output.data(&buf[..n]),
|
||||
}
|
||||
}
|
||||
output.exit(exit.recv().ok().flatten());
|
||||
}
|
||||
|
||||
type ShellProcess = (
|
||||
OpenPty,
|
||||
Box<dyn Read + Send>,
|
||||
@@ -223,6 +281,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
||||
pub async fn pty_open(
|
||||
app: AppHandle,
|
||||
window: tauri::Window,
|
||||
webview: tauri::Webview,
|
||||
workspace: State<'_, WorkspaceState>,
|
||||
id: String,
|
||||
cols: u16,
|
||||
@@ -230,13 +289,16 @@ pub async fn pty_open(
|
||||
cwd: String,
|
||||
profile: Option<String>,
|
||||
directory: Option<String>,
|
||||
channel: Option<JavaScriptChannelId>,
|
||||
) -> Result<()> {
|
||||
let root = current_root(&workspace, window.label())?;
|
||||
if root.to_string_lossy() != cwd {
|
||||
return Err(Error::new("workspace changed before the terminal started"));
|
||||
}
|
||||
let owner = window.label().to_owned();
|
||||
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory)).await?
|
||||
// A session with a channel sends no `pty-data` or `pty-exit` events.
|
||||
let channel = channel.map(|channel| channel.channel_on(webview));
|
||||
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -249,6 +311,7 @@ fn open(
|
||||
rows: u16,
|
||||
profile: Option<String>,
|
||||
directory: Option<String>,
|
||||
channel: Option<Channel<InvokeResponseBody>>,
|
||||
) -> Result<()> {
|
||||
let pty = app.state::<PtyState>();
|
||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||
@@ -257,7 +320,7 @@ fn open(
|
||||
}
|
||||
let directory = directory.map(PathBuf::from).unwrap_or(root);
|
||||
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
||||
let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
||||
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
||||
guard.insert(id.clone(), session);
|
||||
drop(guard);
|
||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||
@@ -275,41 +338,8 @@ fn open(
|
||||
drop(session);
|
||||
let _ = exit_tx.send(code);
|
||||
});
|
||||
let app_reader = app.clone();
|
||||
let reader_id = id.clone();
|
||||
thread::spawn(move || {
|
||||
let mut buf = [0u8; 4096];
|
||||
// Address the terminal events to the window that opened the session.
|
||||
// A global `listen` in that window receives them. Tauri 2 also delivers an addressed
|
||||
// event to a global `listen` in other windows. A listener with a window target does not
|
||||
// receive the events of other windows.
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
let data = buf[..n].to_vec();
|
||||
let _ = app_reader.emit_to(
|
||||
owner.as_str(),
|
||||
"pty-data",
|
||||
PtyData {
|
||||
id: reader_id.clone(),
|
||||
data,
|
||||
},
|
||||
);
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let code = exit_rx.recv().ok().flatten();
|
||||
let _ = app_reader.emit_to(
|
||||
owner.as_str(),
|
||||
"pty-exit",
|
||||
PtyExit {
|
||||
id: reader_id,
|
||||
code,
|
||||
},
|
||||
);
|
||||
});
|
||||
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
|
||||
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -403,8 +433,50 @@ pub fn pty_dictation() -> Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Records the window events that a session would send.
|
||||
struct FakeEvents(Arc<Mutex<Vec<String>>>);
|
||||
impl PtyOutput for FakeEvents {
|
||||
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
|
||||
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
|
||||
}
|
||||
|
||||
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) {
|
||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||
exit_tx.send(Some(3)).unwrap();
|
||||
let output = output(channel, move || Box::new(FakeEvents(events)));
|
||||
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let received = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = received.clone();
|
||||
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
||||
run_pump(Some(channel), events.clone());
|
||||
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
|
||||
let received = received.lock().unwrap();
|
||||
assert_eq!(received.len(), 2);
|
||||
match &received[0] {
|
||||
InvokeResponseBody::Raw(bytes) => assert_eq!(bytes, b"hello \xce\xbb"),
|
||||
InvokeResponseBody::Json(json) => panic!("output must be raw bytes, not JSON: {json}"),
|
||||
}
|
||||
match &received[1] {
|
||||
InvokeResponseBody::Json(json) => assert_eq!(serde_json::from_str::<serde_json::Value>(json).unwrap(), serde_json::json!({ "exit": 3 })),
|
||||
InvokeResponseBody::Raw(_) => panic!("the exit status must be JSON"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_without_a_channel_keeps_the_window_events() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
run_pump(None, events.clone());
|
||||
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_profiles_start_and_report_shell_prompts() {
|
||||
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user