standard-plugin-sdk 0.1.5

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
//! What the viewer tells a UI plugin about the programs its pixels
//! surfaces host ([`Surface::bind_embed`]): each arrives as a plugin event
//! named `system.embed.*`.
//!
//! [`Surface::bind_embed`]: crate::surface::Surface::bind_embed

use alloc::string::String;

use serde::Deserialize;

/// The viewer opened the surface's socket and terminal.
pub const READY_EVENT: &str = "system.embed.ready";
/// The program joined the socket.
pub const JOINED_EVENT: &str = "system.embed.joined";
/// The program named its content.
pub const TITLE_EVENT: &str = "system.embed.title";
/// The program copied text; the viewer has written it to its clipboard.
pub const CLIPBOARD_EVENT: &str = "system.embed.clipboard";
/// The program left, or never joined before the viewer gave up on it.
pub const CLOSED_EVENT: &str = "system.embed.closed";

/// One event about an embedded program.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EmbedEvent {
    /// Start the program with `PIXEL_EMBED` set to `socket` and
    /// `PIXEL_TTY` to `tty`.
    Ready {
        surface: String,
        socket: String,
        tty: String,
    },
    Joined {
        surface: String,
    },
    Title {
        surface: String,
        text: String,
    },
    Clipboard {
        surface: String,
        text: String,
    },
    Closed {
        surface: String,
    },
}

#[derive(Deserialize)]
struct Payload {
    surface: String,
    #[serde(default)]
    socket: String,
    #[serde(default)]
    tty: String,
    #[serde(default)]
    text: String,
}

impl EmbedEvent {
    /// The embed event an event carries, if it is one.
    pub fn from_event(event: &crate::Event) -> Option<Self> {
        let crate::Event::Plugin { name, payload } = event else {
            return None;
        };
        if !name.starts_with("system.embed.") {
            return None;
        }
        let Payload {
            surface,
            socket,
            tty,
            text,
        } = payload.parse().ok()?;
        Some(match name.as_str() {
            READY_EVENT => Self::Ready {
                surface,
                socket,
                tty,
            },
            JOINED_EVENT => Self::Joined { surface },
            TITLE_EVENT => Self::Title { surface, text },
            CLIPBOARD_EVENT => Self::Clipboard { surface, text },
            CLOSED_EVENT => Self::Closed { surface },
            _ => return None,
        })
    }
}