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

qaros/
panels.rs

1use std::ffi::{c_char, c_void};
2use std::rc::Rc;
3
4use qaros_sys::{self as sys, QarApi, QarResult, defaults};
5
6use crate::error::{Result, check};
7use crate::panel_content::{GuiPanelServedContent, PanelContentBundleId};
8use crate::session::{CallbackState, SessionInner, Subscription, query_owned_handles};
9use crate::strings;
10use crate::types::{GuiPanelContentType, GuiPanelId, GuiPanelState, PeerId, Pose};
11
12/// Physical size in meters and the scale mapping web content onto it.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct GuiPanelSize {
15    pub width: f32,
16    pub height: f32,
17    pub content_scale: f32,
18}
19
20impl Default for GuiPanelSize {
21    /// `qar_gui_panel_size_default()`: 1 m by 1 m, content scale 1.
22    fn default() -> Self {
23        Self::from_raw(defaults::qar_gui_panel_size_default())
24    }
25}
26
27impl GuiPanelSize {
28    fn to_raw(self) -> sys::QarGuiPanelSize {
29        sys::QarGuiPanelSize {
30            width_meters: self.width,
31            height_meters: self.height,
32            content_scale: self.content_scale,
33        }
34    }
35
36    fn from_raw(raw: sys::QarGuiPanelSize) -> Self {
37        Self {
38            width: raw.width_meters,
39            height: raw.height_meters,
40            content_scale: raw.content_scale,
41        }
42    }
43}
44
45/// Options for `qar_gui_panels_get_or_create`.
46#[derive(Clone, Debug)]
47pub struct GuiPanelConfig {
48    /// Stable identity, for example `status.myapp.example.com`; the panel id
49    /// derives from it.
50    pub common_name: String,
51    /// Label shown above the panel: UTF-8, emoji included, at most 64 Unicode code points
52    /// (not bytes), no control or bidirectional formatting characters. A refused name fails
53    /// [`GuiPanels::get_or_create`] with `GUI_PANEL_DISPLAY_NAME_INVALID`; `None` shows none.
54    pub display_name: Option<String>,
55    /// Pose of panel space in room space. Its origin is the midpoint of the
56    /// panel's top edge, and the surface hangs below it (x in ±width/2, y in
57    /// [-height, 0]). +X runs along the top edge to the viewer's left, +Y up,
58    /// and -Z is the front normal pointing at the viewer, so a panel with the
59    /// identity orientation faces room -Z (`qar_streaming.h` "Panel space").
60    pub pose: Pose,
61    pub size: GuiPanelSize,
62    /// Empty: visible to everyone.
63    pub visible_to: Vec<PeerId>,
64    /// A page of a content bundle this session published
65    /// ([`crate::PanelContent`]); `None` creates a website panel with the default URL. Only
66    /// the bundle's publisher may put it on a panel (`PANEL_CONTENT_NOT_PUBLISHER`).
67    pub served: Option<GuiPanelServedContent>,
68}
69
70impl GuiPanelConfig {
71    /// The values of `qar_gui_panel_init_default()` with this common name.
72    pub fn new(common_name: impl Into<String>) -> Self {
73        Self {
74            common_name: common_name.into(),
75            display_name: None,
76            pose: Pose::default(),
77            size: GuiPanelSize::default(),
78            visible_to: Vec::new(),
79            served: None,
80        }
81    }
82}
83
84/// Snapshot of a `QarGuiPanel`.
85#[derive(Clone, Debug, PartialEq)]
86pub struct GuiPanelInfo {
87    pub id: GuiPanelId,
88    pub display_name: String,
89    pub pose: Pose,
90    pub size: GuiPanelSize,
91    /// Which content the panel shows; fixed at creation.
92    pub content_type: GuiPanelContentType,
93    /// The page shown, for [`GuiPanelContentType::WebsiteUri`]; empty otherwise.
94    pub content_uri: String,
95    /// The bundle page shown, for [`GuiPanelContentType::Served`]; `None` otherwise.
96    pub served: Option<GuiPanelServedContent>,
97    pub state: GuiPanelState,
98    pub visible_to: Vec<PeerId>,
99}
100
101/// GUI panel operations of a session (`session.gui_panels()`).
102#[derive(Debug)]
103pub struct GuiPanels<'session> {
104    session: &'session Rc<SessionInner>,
105}
106
107impl<'session> GuiPanels<'session> {
108    pub(crate) fn new(session: &'session Rc<SessionInner>) -> Self {
109        Self { session }
110    }
111
112    /// Returns the panel named by `config.common_name`, creating it if
113    /// needed. Idempotent.
114    pub fn get_or_create(&self, config: &GuiPanelConfig) -> Result<GuiPanelId> {
115        let common_name = strings::to_c_string(&config.common_name, "common name")?;
116        let display_name =
117            strings::optional_c_string(config.display_name.as_deref(), "display name")?;
118        let visible_to: Vec<sys::QarPeerId> =
119            config.visible_to.iter().map(|peer| peer.to_raw()).collect();
120
121        let mut init = defaults::qar_gui_panel_init_default();
122        init.common_name = common_name.as_ptr();
123        init.display_name = strings::pointer_or_null(display_name.as_ref());
124        init.pose = config.pose.to_raw();
125        init.size = config.size.to_raw();
126        if !visible_to.is_empty() {
127            init.visible_to_peers = visible_to.as_ptr();
128            init.visible_to_peer_count = visible_to.len();
129        }
130        let served_entry = config
131            .served
132            .as_ref()
133            .map(|served| strings::to_c_string(&served.entry, "entry"))
134            .transpose()?;
135        let mut served_extension = match (&config.served, &served_entry) {
136            (Some(served), Some(entry)) => {
137                let mut extension = defaults::qar_gui_panel_served_content_ext_default();
138                extension.bundle = served.bundle.to_raw()?;
139                extension.entry = entry.as_ptr();
140                Some(extension)
141            }
142            _ => None,
143        };
144        if let Some(extension) = served_extension.as_mut() {
145            init.header.next = (&raw mut extension.header).cast();
146        }
147
148        let api = self.session.api();
149        let mut panel_id = defaults::qar_gui_panel_id_default();
150        // SAFETY: init and everything it points to live for the call.
151        let result = unsafe {
152            (api.qar_impl_gui_panels_get_or_create)(
153                self.session.handle.as_ptr(),
154                &raw const init,
155                &raw mut panel_id,
156            )
157        };
158        check(api, "qar_gui_panels_get_or_create", result)?;
159        Ok(GuiPanelId::from_raw(panel_id))
160    }
161
162    /// Moves the panel (top-edge midpoint, room space; see
163    /// [`GuiPanelConfig::pose`]).
164    pub fn set_pose(&self, panel: GuiPanelId, pose: Pose) -> Result<()> {
165        let api = self.session.api();
166        let panel_id = panel.to_raw();
167        let pose = pose.to_raw();
168        // SAFETY: live session; arguments live for the call.
169        let result = unsafe {
170            (api.qar_impl_gui_panels_update_pose)(
171                self.session.handle.as_ptr(),
172                &raw const panel_id,
173                &raw const pose,
174            )
175        };
176        check(api, "qar_gui_panels_update_pose", result)
177    }
178
179    /// Changes the panel's size and content scale (`qar_gui_panels_change_size`).
180    pub fn set_size(&self, panel: GuiPanelId, size: GuiPanelSize) -> Result<()> {
181        let api = self.session.api();
182        let panel_id = panel.to_raw();
183        let size = size.to_raw();
184        // SAFETY: live session; arguments live for the call.
185        let result = unsafe {
186            (api.qar_impl_gui_panels_change_size)(
187                self.session.handle.as_ptr(),
188                &raw const panel_id,
189                &raw const size,
190            )
191        };
192        check(api, "qar_gui_panels_change_size", result)
193    }
194
195    /// Sets the panel's state: visible, minimized or hidden (`qar_gui_panels_set_state`).
196    pub fn set_state(&self, panel: GuiPanelId, state: GuiPanelState) -> Result<()> {
197        let api = self.session.api();
198        let panel_id = panel.to_raw();
199        // SAFETY: live session; arguments live for the call.
200        let result = unsafe {
201            (api.qar_impl_gui_panels_set_state)(
202                self.session.handle.as_ptr(),
203                &raw const panel_id,
204                state.to_raw(),
205            )
206        };
207        check(api, "qar_gui_panels_set_state", result)
208    }
209
210    /// Points the panel at web content.
211    pub fn navigate_to_uri(&self, panel: GuiPanelId, uri: &str) -> Result<()> {
212        let api = self.session.api();
213        let panel_id = panel.to_raw();
214        let uri = strings::to_c_string(uri, "URI")?;
215        // SAFETY: live session; arguments live for the call.
216        let result = unsafe {
217            (api.qar_impl_gui_panels_navigate_to_uri)(
218                self.session.handle.as_ptr(),
219                &raw const panel_id,
220                uri.as_ptr(),
221            )
222        };
223        check(api, "qar_gui_panels_navigate_to_uri", result)
224    }
225
226    /// Replaces the label shown above the panel, any content type
227    /// (`qar_gui_panels_change_display_name`). The rules of [`GuiPanelConfig::display_name`]
228    /// apply: a refused name is `GUI_PANEL_DISPLAY_NAME_INVALID`, never shortened, and the
229    /// panel keeps its previous name. An empty string shows no name.
230    pub fn set_display_name(&self, panel: GuiPanelId, display_name: &str) -> Result<()> {
231        let api = self.session.api();
232        let panel_id = panel.to_raw();
233        let display_name = strings::to_c_string(display_name, "display name")?;
234        // SAFETY: live session; arguments live for the call.
235        let result = unsafe {
236            (api.qar_impl_gui_panels_change_display_name)(
237                self.session.handle.as_ptr(),
238                &raw const panel_id,
239                display_name.as_ptr(),
240            )
241        };
242        check(api, "qar_gui_panels_change_display_name", result)
243    }
244
245    /// Shows another page, or another bundle of this session, on a served panel
246    /// (`qar_gui_panels_set_served_content`). A bundle another session published is
247    /// `PANEL_CONTENT_NOT_PUBLISHER`; a website or stream panel is
248    /// `GUI_PANEL_CHANGE_NOT_PERMITTED`, since the content type is fixed at creation.
249    pub fn set_served_content(
250        &self,
251        panel: GuiPanelId,
252        content: &GuiPanelServedContent,
253    ) -> Result<()> {
254        let api = self.session.api();
255        let panel_id = panel.to_raw();
256        let bundle = content.bundle.to_raw()?;
257        let entry = strings::to_c_string(&content.entry, "entry")?;
258        // SAFETY: live session; arguments live for the call.
259        let result = unsafe {
260            (api.qar_impl_gui_panels_set_served_content)(
261                self.session.handle.as_ptr(),
262                &raw const panel_id,
263                &raw const bundle,
264                entry.as_ptr(),
265            )
266        };
267        check(api, "qar_gui_panels_set_served_content", result)
268    }
269
270    /// Closes and removes the panel (`qar_gui_panels_close_panel`).
271    pub fn close(&self, panel: GuiPanelId) -> Result<()> {
272        let api = self.session.api();
273        let panel_id = panel.to_raw();
274        // SAFETY: live session; argument lives for the call.
275        let result = unsafe {
276            (api.qar_impl_gui_panels_close_panel)(self.session.handle.as_ptr(), &raw const panel_id)
277        };
278        check(api, "qar_gui_panels_close_panel", result)
279    }
280
281    /// Snapshot of every panel in the session.
282    pub fn list(&self) -> Result<Vec<GuiPanelInfo>> {
283        let api = self.session.api();
284        let session = self.session.handle.as_ptr();
285        query_owned_handles(
286            api,
287            // SAFETY: live session; valid out-pointer.
288            |count| unsafe { (api.qar_impl_query_gui_panels_count)(session, count) },
289            // SAFETY: the buffer holds `capacity` handle slots.
290            |handles, capacity, written| unsafe {
291                (api.qar_impl_query_gui_panels)(session, handles, capacity, written)
292            },
293            api.qar_impl_gui_panel_handle_destroy,
294            "qar_query_gui_panels",
295            |handle| read_gui_panel_info(api, handle),
296        )
297    }
298
299    /// Calls `callback` with a snapshot whenever any panel changes. Runs on
300    /// library threads.
301    pub fn subscribe(
302        &self,
303        callback: impl Fn(GuiPanelInfo) + Send + Sync + 'static,
304    ) -> Result<Subscription> {
305        let session = self.session.handle.as_ptr();
306        self.session.subscribe(
307            Box::new(callback),
308            "qar_gui_panels_subscribe_updates",
309            |api, user_state, token| {
310                // SAFETY: live session; user_state stays valid until the
311                // session handle is destroyed.
312                unsafe {
313                    (api.qar_impl_gui_panels_subscribe_updates)(
314                        session,
315                        Some(gui_panel_update_trampoline),
316                        user_state,
317                        token,
318                    )
319                }
320            },
321        )
322    }
323
324    /// Like [`GuiPanels::subscribe`], for one panel.
325    pub fn subscribe_panel(
326        &self,
327        panel: GuiPanelId,
328        callback: impl Fn(GuiPanelInfo) + Send + Sync + 'static,
329    ) -> Result<Subscription> {
330        let session = self.session.handle.as_ptr();
331        let panel_id = panel.to_raw();
332        self.session.subscribe(
333            Box::new(callback),
334            "qar_gui_panels_subscribe_panel_updates",
335            |api, user_state, token| {
336                // SAFETY: as in subscribe; panel_id lives for the call.
337                unsafe {
338                    (api.qar_impl_gui_panels_subscribe_panel_updates)(
339                        session,
340                        &raw const panel_id,
341                        Some(gui_panel_update_trampoline),
342                        user_state,
343                        token,
344                    )
345                }
346            },
347        )
348    }
349}
350
351fn read_gui_panel_info(api: &QarApi, handle: *mut sys::QarGuiPanel) -> Result<GuiPanelInfo> {
352    let mut panel_id = defaults::qar_gui_panel_id_default();
353    let mut pose = defaults::qar_pose_default();
354    let mut size = defaults::qar_gui_panel_size_default();
355    let mut state = sys::QarGuiPanelState::QAR_GUI_PANEL_STATE_VISIBLE;
356    let mut content_type = sys::QarGuiPanelContentType::QAR_GUI_PANEL_CONTENT_TYPE_WEBSITE_URI;
357    let mut visible_count = 0_usize;
358    // SAFETY (all getters below): handle is live, out-pointers are valid.
359    let results: [(&'static str, QarResult); 6] = unsafe {
360        [
361            (
362                "qar_gui_panel_get_id",
363                (api.qar_impl_gui_panel_get_id)(handle, &raw mut panel_id),
364            ),
365            (
366                "qar_gui_panel_get_pose",
367                (api.qar_impl_gui_panel_get_pose)(handle, &raw mut pose),
368            ),
369            (
370                "qar_gui_panel_get_size",
371                (api.qar_impl_gui_panel_get_size)(handle, &raw mut size),
372            ),
373            (
374                "qar_gui_panel_get_state",
375                (api.qar_impl_gui_panel_get_state)(handle, &raw mut state),
376            ),
377            (
378                "qar_gui_panel_get_content_type",
379                (api.qar_impl_gui_panel_get_content_type)(handle, &raw mut content_type),
380            ),
381            (
382                "qar_gui_panel_get_visible_to_peers_count",
383                (api.qar_impl_gui_panel_get_visible_to_peers_count)(handle, &raw mut visible_count),
384            ),
385        ]
386    };
387    for (function, result) in results {
388        check(api, function, result)?;
389    }
390
391    let mut visible_to = vec![defaults::qar_peer_id_default(); visible_count];
392    let mut written = 0_usize;
393    if visible_count > 0 {
394        // SAFETY: the buffer holds visible_count ids.
395        let result = unsafe {
396            (api.qar_impl_gui_panel_get_visible_to_peers)(
397                handle,
398                visible_to.as_mut_ptr(),
399                visible_to.len(),
400                &raw mut written,
401            )
402        };
403        check(api, "qar_gui_panel_get_visible_to_peers", result)?;
404    }
405    visible_to.truncate(written);
406
407    let display_name = strings::read_string(|buffer: *mut c_char, buffer_size: usize| {
408        // SAFETY: handle is live; the buffer is writable for buffer_size bytes.
409        let result =
410            unsafe { (api.qar_impl_gui_panel_get_display_name)(handle, buffer, buffer_size) };
411        check(api, "qar_gui_panel_get_display_name", result)
412    })?;
413    let content_type = GuiPanelContentType::from_raw(content_type);
414    let content_uri = if content_type == GuiPanelContentType::WebsiteUri {
415        strings::read_string(|buffer: *mut c_char, buffer_size: usize| {
416            // SAFETY: as above.
417            let result =
418                unsafe { (api.qar_impl_gui_panel_get_content_uri)(handle, buffer, buffer_size) };
419            check(api, "qar_gui_panel_get_content_uri", result)
420        })?
421    } else {
422        String::new()
423    };
424    let served = if content_type == GuiPanelContentType::Served {
425        Some(read_served_content(api, handle)?)
426    } else {
427        None
428    };
429
430    Ok(GuiPanelInfo {
431        id: GuiPanelId::from_raw(panel_id),
432        display_name,
433        pose: Pose::from_raw(pose),
434        size: GuiPanelSize::from_raw(size),
435        content_type,
436        content_uri,
437        served,
438        state: GuiPanelState::from_raw(state),
439        visible_to: visible_to.into_iter().map(PeerId::from_raw).collect(),
440    })
441}
442
443/// An entry is at most 512 bytes, so one 513-byte buffer reads it whole.
444fn read_served_content(
445    api: &QarApi,
446    handle: *mut sys::QarGuiPanel,
447) -> Result<GuiPanelServedContent> {
448    let mut bundle = sys::QarPanelContentBundleId {
449        publisher: PeerId::default().to_raw(),
450        name: [0; crate::panel_content::PANEL_CONTENT_BUNDLE_NAME_MAX + 1],
451    };
452    let mut entry = [0_u8; 513];
453    let mut entry_size = 0_usize;
454    // SAFETY: handle is live; the out-pointers are valid for their sizes.
455    let result = unsafe {
456        (api.qar_impl_gui_panel_get_content_served)(
457            handle,
458            &raw mut bundle,
459            entry.as_mut_ptr().cast(),
460            entry.len(),
461            &raw mut entry_size,
462        )
463    };
464    check(api, "qar_gui_panel_get_content_served", result)?;
465    let entry = &entry[..entry_size.min(entry.len())];
466    Ok(GuiPanelServedContent {
467        bundle: PanelContentBundleId::from_raw(&bundle),
468        entry: String::from_utf8_lossy(entry).into_owned(),
469    })
470}
471
472unsafe extern "C" fn gui_panel_update_trampoline(
473    handle: *mut sys::QarGuiPanel,
474    user_state: *mut c_void,
475) {
476    // SAFETY: registered by GuiPanels::subscribe* with this event type.
477    let state = unsafe { CallbackState::<GuiPanelInfo>::from_user_state(user_state) };
478    if handle.is_null() {
479        return;
480    }
481    // Borrowed for the duration of the callback: read, never destroy.
482    match read_gui_panel_info(state.api(), handle) {
483        Ok(panel) => state.deliver(panel, "GUI panel update"),
484        Err(error) => log::warn!("reading a GUI panel update: {error}"),
485    }
486}