Skip to main content
QAROS Rust API Dev (main) · versions: Dev (main) · Developer Guide

qaros/
panel_content.rs

1//! Web pages a session serves to served GUI panels, and the JSON messages between those pages
2//! and the session (`qar_panel_content_*`).
3
4use std::ffi::{c_char, c_void};
5use std::path::Path;
6use std::rc::Rc;
7
8use qaros_sys as sys;
9
10use crate::error::{Error, Result, check};
11use crate::session::{CallbackState, SessionInner, Subscription};
12use crate::strings;
13use crate::types::{GuiPanelId, PeerId};
14
15/// Longest bundle name, in bytes (`QAR_PANEL_CONTENT_BUNDLE_NAME_MAX`).
16pub const PANEL_CONTENT_BUNDLE_NAME_MAX: usize = sys::QAR_PANEL_CONTENT_BUNDLE_NAME_MAX as usize;
17
18/// Names one content bundle (`QarPanelContentBundleId`): the session that published it and
19/// serves its files, and its name, unique per publisher.
20#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21pub struct PanelContentBundleId {
22    /// The publishing peer: the content's owner.
23    pub publisher: PeerId,
24    /// ASCII `A-Z a-z 0-9 . _ -`, not starting with `.`, at most
25    /// [`PANEL_CONTENT_BUNDLE_NAME_MAX`] bytes.
26    pub name: String,
27}
28
29impl PanelContentBundleId {
30    /// The C id. A name too long or holding NUL is `Error::InvalidArgument`; the C API checks
31    /// the remaining rules.
32    pub(crate) fn to_raw(&self) -> Result<sys::QarPanelContentBundleId> {
33        let bytes = self.name.as_bytes();
34        if bytes.len() > PANEL_CONTENT_BUNDLE_NAME_MAX || bytes.contains(&0) {
35            return Err(Error::InvalidArgument(format!(
36                "bundle name {:?} is longer than {PANEL_CONTENT_BUNDLE_NAME_MAX} bytes or holds NUL",
37                self.name
38            )));
39        }
40        let mut raw = sys::QarPanelContentBundleId {
41            publisher: self.publisher.to_raw(),
42            name: [0; PANEL_CONTENT_BUNDLE_NAME_MAX + 1],
43        };
44        for (slot, byte) in raw.name.iter_mut().zip(bytes) {
45            *slot = c_char::from_ne_bytes([*byte]);
46        }
47        Ok(raw)
48    }
49
50    pub(crate) fn from_raw(raw: &sys::QarPanelContentBundleId) -> Self {
51        let bytes: Vec<u8> = raw
52            .name
53            .iter()
54            .map(|byte| u8::from_ne_bytes(byte.to_ne_bytes()))
55            .take_while(|byte| *byte != 0)
56            .collect();
57        Self {
58            publisher: PeerId::from_raw(raw.publisher),
59            name: String::from_utf8_lossy(&bytes).into_owned(),
60        }
61    }
62}
63
64/// What a served GUI panel shows: one entry page of a content bundle.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct GuiPanelServedContent {
67    pub bundle: PanelContentBundleId,
68    /// Path of the page inside the bundle, for example `inspector/index.html`.
69    pub entry: String,
70}
71
72/// One file of [`PanelContent::publish_files`] (`QarPanelContentFile`).
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct PanelContentFile {
75    /// Relative, `/`-separated path inside the bundle.
76    pub path: String,
77    /// `None`: taken from the path's extension. Otherwise it must be the type that extension
78    /// is served as.
79    pub mime_type: Option<String>,
80    pub data: Vec<u8>,
81}
82
83/// A message a served panel sent to its content owner, stamped by the mixer showing it
84/// (`QarPanelContentMessage`).
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct PanelContentMessage {
87    pub panel: GuiPanelId,
88    /// The user (the mixer's target peer) whose panel sent it.
89    pub user: PeerId,
90    /// Counts up per sending mixer and panel, from 1.
91    pub sequence: u64,
92    /// One JSON value.
93    pub json: String,
94}
95
96/// Panel content operations of a session (`session.panel_content()`).
97///
98/// A served GUI panel shows a page of a content bundle this session publishes. Every user's
99/// mixer loads the page in its own browser and fetches the files over the session; the page
100/// sends with `qaros.panel.send(msg)` and receives with `qaros.panel.onMessage(cb)`. Publishing
101/// copies every byte, so an edit needs another publication, which reloads every panel showing
102/// the bundle. Only the publisher may put its bundle on a panel, receives the panels' messages
103/// and posts to them. Limits: 16 MiB per file, 64 MiB and 1024 files per bundle, 64 KiB per
104/// message.
105#[derive(Debug)]
106pub struct PanelContent<'session> {
107    session: &'session Rc<SessionInner>,
108}
109
110impl<'session> PanelContent<'session> {
111    pub(crate) fn new(session: &'session Rc<SessionInner>) -> Self {
112        Self { session }
113    }
114
115    /// Publishes `files` as bundle `name` (`qar_panel_content_publish_files`), replacing an
116    /// earlier publication of that name. Nothing is published when it fails:
117    /// `PANEL_CONTENT_BUNDLE_REFUSED`, `PANEL_CONTENT_PATH_REFUSED`,
118    /// `PANEL_CONTENT_MIME_REFUSED` or `PANEL_CONTENT_SIZE_REFUSED`.
119    pub fn publish_files(
120        &self,
121        name: &str,
122        files: &[PanelContentFile],
123    ) -> Result<PanelContentBundleId> {
124        let name = strings::to_c_string(name, "bundle name")?;
125        let paths = files
126            .iter()
127            .map(|file| strings::to_c_string(&file.path, "file path"))
128            .collect::<Result<Vec<_>>>()?;
129        let mime_types = files
130            .iter()
131            .map(|file| strings::optional_c_string(file.mime_type.as_deref(), "MIME type"))
132            .collect::<Result<Vec<_>>>()?;
133        let raw_files: Vec<sys::QarPanelContentFile> = files
134            .iter()
135            .zip(paths.iter().zip(&mime_types))
136            .map(|(file, (path, mime_type))| sys::QarPanelContentFile {
137                path: path.as_ptr(),
138                mime_type: strings::pointer_or_null(mime_type.as_ref()),
139                data: file.data.as_ptr(),
140                size: file.data.len(),
141            })
142            .collect();
143        let api = self.session.api();
144        let mut bundle = sys::QarPanelContentBundleId {
145            publisher: PeerId::default().to_raw(),
146            name: [0; PANEL_CONTENT_BUNDLE_NAME_MAX + 1],
147        };
148        // SAFETY: live session; the files, their strings and bytes live for the call.
149        let result = unsafe {
150            (api.qar_impl_panel_content_publish_files)(
151                self.session.handle.as_ptr(),
152                name.as_ptr(),
153                raw_files.as_ptr(),
154                raw_files.len(),
155                &raw mut bundle,
156            )
157        };
158        check(api, "qar_panel_content_publish_files", result)?;
159        Ok(PanelContentBundleId::from_raw(&bundle))
160    }
161
162    /// Publishes every regular file under `root` as bundle `name`
163    /// (`qar_panel_content_publish_directory`). A link inside the folder is refused, as is every
164    /// file [`PanelContent::publish_files`] refuses; a missing folder is
165    /// `PANEL_CONTENT_NOT_FOUND`.
166    pub fn publish_directory(&self, name: &str, root: &Path) -> Result<PanelContentBundleId> {
167        let name = strings::to_c_string(name, "bundle name")?;
168        let root_text = root.to_str().ok_or_else(|| {
169            Error::InvalidArgument(format!("folder {} is not valid UTF-8", root.display()))
170        })?;
171        let root = strings::to_c_string(root_text, "folder")?;
172        let api = self.session.api();
173        let mut bundle = sys::QarPanelContentBundleId {
174            publisher: PeerId::default().to_raw(),
175            name: [0; PANEL_CONTENT_BUNDLE_NAME_MAX + 1],
176        };
177        // SAFETY: live session; the strings live for the call.
178        let result = unsafe {
179            (api.qar_impl_panel_content_publish_directory)(
180                self.session.handle.as_ptr(),
181                name.as_ptr(),
182                root.as_ptr(),
183                &raw mut bundle,
184            )
185        };
186        check(api, "qar_panel_content_publish_directory", result)?;
187        Ok(PanelContentBundleId::from_raw(&bundle))
188    }
189
190    /// Stops serving a bundle this session published (`qar_panel_content_remove`). Panels
191    /// showing it stay and show nothing.
192    pub fn remove(&self, bundle: &PanelContentBundleId) -> Result<()> {
193        let raw = bundle.to_raw()?;
194        let api = self.session.api();
195        // SAFETY: live session; raw lives for the call.
196        let result = unsafe {
197            (api.qar_impl_panel_content_remove)(self.session.handle.as_ptr(), &raw const raw)
198        };
199        check(api, "qar_panel_content_remove", result)
200    }
201
202    /// Posts one JSON value to the panels showing a bundle this session published
203    /// (`qar_panel_content_post_message`): to one panel or all (`None`), for one user or all.
204    pub fn post_message(
205        &self,
206        bundle: &PanelContentBundleId,
207        json: &str,
208        panel: Option<GuiPanelId>,
209        user: Option<PeerId>,
210    ) -> Result<()> {
211        let raw = bundle.to_raw()?;
212        let json = strings::to_c_string(json, "message")?;
213        let panel = panel.map(GuiPanelId::to_raw);
214        let user = user.map(PeerId::to_raw);
215        let api = self.session.api();
216        // SAFETY: live session; every argument lives for the call.
217        let result = unsafe {
218            (api.qar_impl_panel_content_post_message)(
219                self.session.handle.as_ptr(),
220                &raw const raw,
221                panel.as_ref().map_or(std::ptr::null(), std::ptr::from_ref),
222                user.as_ref().map_or(std::ptr::null(), std::ptr::from_ref),
223                json.as_ptr(),
224            )
225        };
226        check(api, "qar_panel_content_post_message", result)
227    }
228
229    /// Calls `callback` with every message a panel showing the bundle sends
230    /// (`qar_panel_content_subscribe_messages`). Runs on library threads; validate each message
231    /// before acting on it and authorise per [`PanelContentMessage::user`].
232    pub fn subscribe_messages(
233        &self,
234        bundle: &PanelContentBundleId,
235        callback: impl Fn(PanelContentMessage) + Send + Sync + 'static,
236    ) -> Result<Subscription> {
237        let raw = bundle.to_raw()?;
238        let session = self.session.handle.as_ptr();
239        self.session.subscribe(
240            Box::new(callback),
241            "qar_panel_content_subscribe_messages",
242            |api, user_state, token| {
243                // SAFETY: live session; user_state stays valid until the session handle is
244                // destroyed; raw lives for the call.
245                unsafe {
246                    (api.qar_impl_panel_content_subscribe_messages)(
247                        session,
248                        &raw const raw,
249                        Some(panel_content_message_trampoline),
250                        user_state,
251                        token,
252                    )
253                }
254            },
255        )
256    }
257}
258
259unsafe extern "C" fn panel_content_message_trampoline(
260    message: *const sys::QarPanelContentMessage,
261    user_state: *mut c_void,
262) {
263    // SAFETY: registered by PanelContent::subscribe_messages with this event type.
264    let state = unsafe { CallbackState::<PanelContentMessage>::from_user_state(user_state) };
265    if message.is_null() {
266        return;
267    }
268    // SAFETY: the message is valid for the duration of the callback.
269    let message = unsafe { &*message };
270    let json = if message.json.is_null() {
271        String::new()
272    } else {
273        // SAFETY: json points at json_size bytes during the callback.
274        let bytes =
275            unsafe { std::slice::from_raw_parts(message.json.cast::<u8>(), message.json_size) };
276        String::from_utf8_lossy(bytes).into_owned()
277    };
278    state.deliver(
279        PanelContentMessage {
280            panel: GuiPanelId::from_raw(message.panel),
281            user: PeerId::from_raw(message.user),
282            sequence: message.sequence,
283            json,
284        },
285        "panel content message",
286    );
287}