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

qaros/
error.rs

1use std::ffi::c_char;
2use std::fmt;
3
4use qaros_sys::{QarApi, QarResult, QarStatusCode};
5
6/// A `QarStatusCode` as returned by the C API.
7#[derive(Clone, Copy, PartialEq, Eq, Hash)]
8pub struct StatusCode(QarStatusCode);
9
10impl StatusCode {
11    pub const SUCCESS: Self = Self(QarStatusCode::QAR_STATUS_SUCCESS);
12    pub const UNCLASSIFIED: Self = Self(QarStatusCode::QAR_STATUS_UNCLASSIFIED);
13    pub const NOT_IMPLEMENTED: Self = Self(QarStatusCode::QAR_STATUS_NOT_IMPLEMENTED);
14    pub const ARGUMENT_NOT_SUPPORTED: Self = Self(QarStatusCode::QAR_STATUS_ARGUMENT_NOT_SUPPORTED);
15    pub const TIMEOUT: Self = Self(QarStatusCode::QAR_STATUS_TIMEOUT);
16    pub const LOGIC_ERROR: Self = Self(QarStatusCode::QAR_STATUS_LOGIC_ERROR);
17    pub const GUI_PANEL_INVALID_ID: Self = Self(QarStatusCode::QAR_STATUS_GUI_PANEL_INVALID_ID);
18    pub const APP_VOLUME_INVALID_ID: Self = Self(QarStatusCode::QAR_STATUS_APP_VOLUME_INVALID_ID);
19    /// No head pose has arrived from the viewer yet, so there is no pose to render with.
20    /// Recoverable: [`crate::RenderSender::next_render_pose`] succeeds once the viewer's first
21    /// pose is in.
22    pub const RENDERING_MISSING_POSE_DATA: Self =
23        Self(QarStatusCode::QAR_STATUS_RENDERING_PRODUCER_MISSING_POSE_DATA);
24    pub const RENDERING_UNABLE_TO_BEGIN_FRAME: Self =
25        Self(QarStatusCode::QAR_STATUS_RENDERING_PRODUCER_UNABLE_TO_DO_BEGIN_FRAME);
26    pub const RENDERING_STREAM_IS_CLOSED: Self =
27        Self(QarStatusCode::QAR_STATUS_RENDERING_PRODUCER_STREAM_IS_CLOSED);
28    /// The receiver paused the stream. Not a failure; a render sender's
29    /// begin-frame waits through a pause instead of reporting it.
30    pub const MEDIA_STREAMING_STREAM_IS_PAUSED: Self =
31        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_STREAM_IS_PAUSED);
32    pub const MEDIA_STREAMING_STREAM_IS_RECONNECTING: Self =
33        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_STREAM_IS_RECONNECTING);
34    pub const MEDIA_STREAMING_NO_ACTIVE_TRANSFERS: Self =
35        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_NO_ACTIVE_TRANSFERS);
36    /// The sender's app volume is not known (yet) where the receiver runs. Recoverable: keep
37    /// calling begin-frame; a volume that was removed never resolves.
38    pub const RENDERING_APP_VOLUME_UNRESOLVED: Self =
39        Self(QarStatusCode::QAR_STATUS_RENDERING_PRODUCER_APP_VOLUME_UNRESOLVED);
40    /// The render sender's depth format is one its graphics API cannot take; returned by the
41    /// creation before any receiver is waited for, with the accepted formats in the message.
42    pub const RENDERING_DEPTH_FORMAT_NOT_SUPPORTED: Self =
43        Self(QarStatusCode::QAR_STATUS_RENDERING_PRODUCER_DEPTH_FORMAT_NOT_SUPPORTED);
44    /// The device given for a Vulkan render sender lacks the external memory and semaphore
45    /// extensions sharing its images needs; returned by the creation before any receiver is
46    /// waited for, with what is missing in the message.
47    pub const RENDERING_EXTERNAL_DEVICE_NOT_SUPPORTED: Self =
48        Self(QarStatusCode::QAR_STATUS_RENDERING_PRODUCER_EXTERNAL_DEVICE_NOT_SUPPORTED);
49    pub const PAKE_ERROR: Self = Self(QarStatusCode::QAR_STATUS_PAKE_ERROR);
50    pub const ONBOARDING_SESSION_NOT_FOUND: Self =
51        Self(QarStatusCode::QAR_STATUS_ONBOARDING_SESSION_NOT_FOUND);
52    pub const ONBOARDING_FAILED: Self = Self(QarStatusCode::QAR_STATUS_ONBOARDING_FAILED);
53    pub const ONBOARDING_HUB_UNREACHABLE: Self =
54        Self(QarStatusCode::QAR_STATUS_ONBOARDING_HUB_UNREACHABLE);
55    pub const ONBOARDING_SESSION_STILL_ACTIVE: Self =
56        Self(QarStatusCode::QAR_STATUS_ONBOARDING_SESSION_STILL_ACTIVE);
57    pub const ONBOARDING_APPROVAL_DENIED: Self =
58        Self(QarStatusCode::QAR_STATUS_ONBOARDING_APPROVAL_DENIED);
59    pub const ONBOARDING_APPROVAL_TIMEOUT: Self =
60        Self(QarStatusCode::QAR_STATUS_ONBOARDING_APPROVAL_TIMEOUT);
61    pub const ONBOARDING_HUB_NOT_AUTHENTIC: Self =
62        Self(QarStatusCode::QAR_STATUS_ONBOARDING_HUB_NOT_AUTHENTIC);
63    pub const ONBOARDING_APP_IDENTITY_MISMATCH: Self =
64        Self(QarStatusCode::QAR_STATUS_ONBOARDING_APP_IDENTITY_MISMATCH);
65    /// The device's certificate expired or is no longer renewed, and the pairing credential given
66    /// did not replace it: pair the device again with a new code.
67    pub const ONBOARDING_RE_PAIR_REQUIRED: Self =
68        Self(QarStatusCode::QAR_STATUS_ONBOARDING_RE_PAIR_REQUIRED);
69    /// The hub refused to renew the certificate because the renewal did not prove it holds the
70    /// certificate's key: update to the current SDK, else pair again.
71    pub const ONBOARDING_RENEWAL_POSSESSION_UNPROVEN: Self =
72        Self(QarStatusCode::QAR_STATUS_ONBOARDING_RENEWAL_POSSESSION_UNPROVEN);
73    /// The hub refused to mint a co-process invite: this session did not join as a local app
74    /// (or as an app the QAROS launcher started). Final; nothing was minted.
75    pub const ONBOARDING_INVITE_REFUSED: Self =
76        Self(QarStatusCode::QAR_STATUS_ONBOARDING_INVITE_REFUSED);
77
78    pub const GUI_PANEL_CHANGE_NOT_PERMITTED: Self =
79        Self(QarStatusCode::QAR_STATUS_GUI_PANEL_CHANGE_NOT_PERMITTED);
80    /// A GUI panel display name was refused: more than 64 Unicode code points, not valid
81    /// UTF-8, or holding a control or bidirectional formatting character. The panel keeps its
82    /// previous name.
83    pub const GUI_PANEL_DISPLAY_NAME_INVALID: Self =
84        Self(QarStatusCode::QAR_STATUS_GUI_PANEL_DISPLAY_NAME_INVALID);
85    pub const PANEL_CONTENT_BUNDLE_REFUSED: Self =
86        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_BUNDLE_REFUSED);
87    pub const PANEL_CONTENT_PATH_REFUSED: Self =
88        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_PATH_REFUSED);
89    pub const PANEL_CONTENT_MIME_REFUSED: Self =
90        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_MIME_REFUSED);
91    pub const PANEL_CONTENT_SIZE_REFUSED: Self =
92        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_SIZE_REFUSED);
93    pub const PANEL_CONTENT_NOT_PUBLISHER: Self =
94        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_NOT_PUBLISHER);
95    pub const PANEL_CONTENT_NOT_FOUND: Self =
96        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_NOT_FOUND);
97    pub const PANEL_CONTENT_MESSAGE_REFUSED: Self =
98        Self(QarStatusCode::QAR_STATUS_PANEL_CONTENT_MESSAGE_REFUSED);
99    pub const APP_VOLUME_GESTURE_CONFIGURATION_INVALID: Self =
100        Self(QarStatusCode::QAR_STATUS_APP_VOLUME_GESTURE_CONFIGURATION_INVALID);
101    pub const APP_VOLUME_GESTURE_MODE_UNKNOWN: Self =
102        Self(QarStatusCode::QAR_STATUS_APP_VOLUME_GESTURE_MODE_UNKNOWN);
103    pub const MEDIA_STREAMING_DESTINATION_RESERVATION_FAILED: Self =
104        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_DESTINATION_RESERVATION_FAILED);
105    pub const MEDIA_STREAMING_SEND_PIPELINE_FAILED: Self =
106        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_SEND_PIPELINE_FAILED);
107    pub const MEDIA_STREAMING_LAYOUT_CHANGE_FAILED: Self =
108        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_LAYOUT_CHANGE_FAILED);
109    /// The application's own graphics device given to a sender or receiver is on another GPU
110    /// than the session's; nothing was created, and the message names both adapters. Create the
111    /// device on the adapter [`crate::Session::graphics_adapter`] reports.
112    pub const MEDIA_STREAMING_DEVICE_ON_ANOTHER_ADAPTER: Self =
113        Self(QarStatusCode::QAR_STATUS_MEDIA_STREAMING_DEVICE_ON_ANOTHER_ADAPTER);
114    /// The session was created without a graphics device
115    /// ([`crate::OnboardExtensions::without_graphics_device`]): it streams no media and reports
116    /// no adapter, so a render sender's creation, its render requests, a video sender and
117    /// [`crate::Session::graphics_adapter`] fail with this code. Nothing was created. Final for
118    /// the session; onboard without the extension to stream.
119    pub const GRAPHICS_DEVICE_NOT_INITIALIZED: Self =
120        Self(QarStatusCode::QAR_STATUS_GRAPHICS_DEVICE_NOT_INITIALIZED);
121    pub const HUB_TARGET_APP_DEVICE_NOT_INVITABLE: Self =
122        Self(QarStatusCode::QAR_STATUS_HUB_TARGET_APP_DEVICE_NOT_INVITABLE);
123    /// A declared device category other than desktop PC, server or camera.
124    pub const PEER_DEVICE_CATEGORY_NOT_ALLOWED: Self =
125        Self(QarStatusCode::QAR_STATUS_PEER_DEVICE_CATEGORY_NOT_ALLOWED);
126    /// The hub is in the middle of another session-wide operation; retry.
127    pub const HUB_LIFECYCLE_OPERATION_RUNNING: Self =
128        Self(QarStatusCode::QAR_STATUS_HUB_LIFECYCLE_OPERATION_RUNNING);
129    pub const MEMBER_JOIN_PENDING: Self = Self(QarStatusCode::QAR_STATUS_MEMBER_JOIN_PENDING);
130    pub const MEMBER_JOIN_DENIED: Self = Self(QarStatusCode::QAR_STATUS_MEMBER_JOIN_DENIED);
131    /// The hub on this PC hosts members of its own, is a member of another primary, or the
132    /// invitation does not permit the join; the message names the reason.
133    pub const MEMBER_JOIN_REFUSED: Self = Self(QarStatusCode::QAR_STATUS_MEMBER_JOIN_REFUSED);
134    pub const MEMBER_JOIN_REDIRECTED: Self = Self(QarStatusCode::QAR_STATUS_MEMBER_JOIN_REDIRECTED);
135    /// The primary removed this hub and the invitation does not permit readmitting it.
136    pub const MEMBER_REMOVED: Self = Self(QarStatusCode::QAR_STATUS_MEMBER_REMOVED);
137    /// None of the invitation's addresses of the primary hub answers.
138    pub const PRIMARY_UNREACHABLE: Self = Self(QarStatusCode::QAR_STATUS_PRIMARY_UNREACHABLE);
139    /// The hub on this PC is a member: create the member-hub invitation on its primary's PC.
140    pub const SESSION_WIDE_ACTION_ON_MEMBER: Self =
141        Self(QarStatusCode::QAR_STATUS_SESSION_WIDE_ACTION_ON_MEMBER);
142    /// The app's approval does not allow it to bring in member hubs.
143    pub const MEMBER_SPONSOR_NOT_ALLOWED: Self =
144        Self(QarStatusCode::QAR_STATUS_MEMBER_SPONSOR_NOT_ALLOWED);
145    /// The app's approval has used its quota of member hubs.
146    pub const MEMBER_SPONSOR_QUOTA_EXCEEDED: Self =
147        Self(QarStatusCode::QAR_STATUS_MEMBER_SPONSOR_QUOTA_EXCEEDED);
148    pub const AUDIT_LOG_CORRUPT: Self = Self(QarStatusCode::QAR_STATUS_AUDIT_LOG_CORRUPT);
149    pub const SECURE_STORAGE_ERROR: Self = Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_ERROR);
150    pub const SECURE_STORAGE_NOT_FOUND: Self =
151        Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_NOT_FOUND);
152    pub const SECURE_STORAGE_TAMPERED: Self =
153        Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_TAMPERED);
154    pub const SECURE_STORAGE_PROTECTOR_MISMATCH: Self =
155        Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_PROTECTOR_MISMATCH);
156    pub const SECURE_STORAGE_PROTECTOR_UNAVAILABLE: Self =
157        Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_PROTECTOR_UNAVAILABLE);
158    pub const SECURE_STORAGE_INVALID_KEY: Self =
159        Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_INVALID_KEY);
160    pub const SECURE_STORAGE_LOCKED: Self = Self(QarStatusCode::QAR_STATUS_SECURE_STORAGE_LOCKED);
161    /// The member-hub invitation's signature is wrong, its bytes are no invitation, or the
162    /// primary does not know it.
163    pub const MEMBER_INVITATION_INVALID: Self =
164        Self(QarStatusCode::QAR_STATUS_MEMBER_INVITATION_INVALID);
165    /// Ask the primary's app for a new member-hub invitation.
166    pub const MEMBER_INVITATION_EXPIRED: Self =
167        Self(QarStatusCode::QAR_STATUS_MEMBER_INVITATION_EXPIRED);
168    /// Ask the primary's app for a new member-hub invitation.
169    pub const MEMBER_INVITATION_USED_UP: Self =
170        Self(QarStatusCode::QAR_STATUS_MEMBER_INVITATION_USED_UP);
171    /// Ask the primary's app for a new member-hub invitation.
172    pub const MEMBER_INVITATION_REVOKED: Self =
173        Self(QarStatusCode::QAR_STATUS_MEMBER_INVITATION_REVOKED);
174    /// This PC does not trust the invitation's primary hub.
175    pub const MEMBER_INVITATION_PRIMARY_NOT_ALLOWED: Self =
176        Self(QarStatusCode::QAR_STATUS_MEMBER_INVITATION_PRIMARY_NOT_ALLOWED);
177    /// This PC's member-invitation policy can be written by a non-administrator.
178    pub const MEMBER_INVITATION_POLICY_NOT_PROTECTED: Self =
179        Self(QarStatusCode::QAR_STATUS_MEMBER_INVITATION_POLICY_NOT_PROTECTED);
180
181    pub(crate) fn from_raw(raw: QarStatusCode) -> Self {
182        Self(raw)
183    }
184
185    /// The raw `qaros_sys` code, for calls through [`crate::Library::raw_api`].
186    pub fn raw(self) -> QarStatusCode {
187        self.0
188    }
189
190    /// Numeric value of the code.
191    pub fn value(self) -> i64 {
192        i64::from(self.0.0)
193    }
194
195    /// The header's name without the `QAR_STATUS_` prefix, or `None` for a
196    /// code this crate does not name.
197    pub fn name(self) -> Option<&'static str> {
198        let name = match self {
199            Self::SUCCESS => "SUCCESS",
200            Self::UNCLASSIFIED => "UNCLASSIFIED",
201            Self::NOT_IMPLEMENTED => "NOT_IMPLEMENTED",
202            Self::ARGUMENT_NOT_SUPPORTED => "ARGUMENT_NOT_SUPPORTED",
203            Self::TIMEOUT => "TIMEOUT",
204            Self::LOGIC_ERROR => "LOGIC_ERROR",
205            Self::GUI_PANEL_INVALID_ID => "GUI_PANEL_INVALID_ID",
206            Self::APP_VOLUME_INVALID_ID => "APP_VOLUME_INVALID_ID",
207            Self::RENDERING_MISSING_POSE_DATA => "RENDERING_PRODUCER_MISSING_POSE_DATA",
208            Self::RENDERING_UNABLE_TO_BEGIN_FRAME => "RENDERING_PRODUCER_UNABLE_TO_DO_BEGIN_FRAME",
209            Self::RENDERING_STREAM_IS_CLOSED => "RENDERING_PRODUCER_STREAM_IS_CLOSED",
210            Self::MEDIA_STREAMING_STREAM_IS_PAUSED => "MEDIA_STREAMING_STREAM_IS_PAUSED",
211            Self::MEDIA_STREAMING_STREAM_IS_RECONNECTING => {
212                "MEDIA_STREAMING_STREAM_IS_RECONNECTING"
213            }
214            Self::MEDIA_STREAMING_NO_ACTIVE_TRANSFERS => "MEDIA_STREAMING_NO_ACTIVE_TRANSFERS",
215            Self::RENDERING_APP_VOLUME_UNRESOLVED => "RENDERING_PRODUCER_APP_VOLUME_UNRESOLVED",
216            Self::RENDERING_DEPTH_FORMAT_NOT_SUPPORTED => {
217                "RENDERING_PRODUCER_DEPTH_FORMAT_NOT_SUPPORTED"
218            }
219            Self::RENDERING_EXTERNAL_DEVICE_NOT_SUPPORTED => {
220                "RENDERING_PRODUCER_EXTERNAL_DEVICE_NOT_SUPPORTED"
221            }
222            Self::PAKE_ERROR => "PAKE_ERROR",
223            Self::ONBOARDING_SESSION_NOT_FOUND => "ONBOARDING_SESSION_NOT_FOUND",
224            Self::ONBOARDING_FAILED => "ONBOARDING_FAILED",
225            Self::ONBOARDING_HUB_UNREACHABLE => "ONBOARDING_HUB_UNREACHABLE",
226            Self::ONBOARDING_SESSION_STILL_ACTIVE => "ONBOARDING_SESSION_STILL_ACTIVE",
227            Self::ONBOARDING_APPROVAL_DENIED => "ONBOARDING_APPROVAL_DENIED",
228            Self::ONBOARDING_APPROVAL_TIMEOUT => "ONBOARDING_APPROVAL_TIMEOUT",
229            Self::ONBOARDING_HUB_NOT_AUTHENTIC => "ONBOARDING_HUB_NOT_AUTHENTIC",
230            Self::ONBOARDING_APP_IDENTITY_MISMATCH => "ONBOARDING_APP_IDENTITY_MISMATCH",
231            Self::ONBOARDING_RE_PAIR_REQUIRED => "ONBOARDING_RE_PAIR_REQUIRED",
232            Self::ONBOARDING_RENEWAL_POSSESSION_UNPROVEN => {
233                "ONBOARDING_RENEWAL_POSSESSION_UNPROVEN"
234            }
235            Self::ONBOARDING_INVITE_REFUSED => "ONBOARDING_INVITE_REFUSED",
236            Self::GUI_PANEL_CHANGE_NOT_PERMITTED => "GUI_PANEL_CHANGE_NOT_PERMITTED",
237            Self::GUI_PANEL_DISPLAY_NAME_INVALID => "GUI_PANEL_DISPLAY_NAME_INVALID",
238            Self::PANEL_CONTENT_BUNDLE_REFUSED => "PANEL_CONTENT_BUNDLE_REFUSED",
239            Self::PANEL_CONTENT_PATH_REFUSED => "PANEL_CONTENT_PATH_REFUSED",
240            Self::PANEL_CONTENT_MIME_REFUSED => "PANEL_CONTENT_MIME_REFUSED",
241            Self::PANEL_CONTENT_SIZE_REFUSED => "PANEL_CONTENT_SIZE_REFUSED",
242            Self::PANEL_CONTENT_NOT_PUBLISHER => "PANEL_CONTENT_NOT_PUBLISHER",
243            Self::PANEL_CONTENT_NOT_FOUND => "PANEL_CONTENT_NOT_FOUND",
244            Self::PANEL_CONTENT_MESSAGE_REFUSED => "PANEL_CONTENT_MESSAGE_REFUSED",
245            Self::APP_VOLUME_GESTURE_CONFIGURATION_INVALID => {
246                "APP_VOLUME_GESTURE_CONFIGURATION_INVALID"
247            }
248            Self::APP_VOLUME_GESTURE_MODE_UNKNOWN => "APP_VOLUME_GESTURE_MODE_UNKNOWN",
249            Self::MEDIA_STREAMING_DESTINATION_RESERVATION_FAILED => {
250                "MEDIA_STREAMING_DESTINATION_RESERVATION_FAILED"
251            }
252            Self::MEDIA_STREAMING_SEND_PIPELINE_FAILED => "MEDIA_STREAMING_SEND_PIPELINE_FAILED",
253            Self::MEDIA_STREAMING_LAYOUT_CHANGE_FAILED => "MEDIA_STREAMING_LAYOUT_CHANGE_FAILED",
254            Self::MEDIA_STREAMING_DEVICE_ON_ANOTHER_ADAPTER => {
255                "MEDIA_STREAMING_DEVICE_ON_ANOTHER_ADAPTER"
256            }
257            Self::GRAPHICS_DEVICE_NOT_INITIALIZED => "GRAPHICS_DEVICE_NOT_INITIALIZED",
258            Self::HUB_TARGET_APP_DEVICE_NOT_INVITABLE => "HUB_TARGET_APP_DEVICE_NOT_INVITABLE",
259            Self::PEER_DEVICE_CATEGORY_NOT_ALLOWED => "PEER_DEVICE_CATEGORY_NOT_ALLOWED",
260            Self::HUB_LIFECYCLE_OPERATION_RUNNING => "HUB_LIFECYCLE_OPERATION_RUNNING",
261            Self::MEMBER_JOIN_PENDING => "MEMBER_JOIN_PENDING",
262            Self::MEMBER_JOIN_DENIED => "MEMBER_JOIN_DENIED",
263            Self::MEMBER_JOIN_REFUSED => "MEMBER_JOIN_REFUSED",
264            Self::MEMBER_JOIN_REDIRECTED => "MEMBER_JOIN_REDIRECTED",
265            Self::MEMBER_REMOVED => "MEMBER_REMOVED",
266            Self::PRIMARY_UNREACHABLE => "PRIMARY_UNREACHABLE",
267            Self::SESSION_WIDE_ACTION_ON_MEMBER => "SESSION_WIDE_ACTION_ON_MEMBER",
268            Self::MEMBER_SPONSOR_NOT_ALLOWED => "MEMBER_SPONSOR_NOT_ALLOWED",
269            Self::MEMBER_SPONSOR_QUOTA_EXCEEDED => "MEMBER_SPONSOR_QUOTA_EXCEEDED",
270            Self::AUDIT_LOG_CORRUPT => "AUDIT_LOG_CORRUPT",
271            Self::SECURE_STORAGE_ERROR => "SECURE_STORAGE_ERROR",
272            Self::SECURE_STORAGE_NOT_FOUND => "SECURE_STORAGE_NOT_FOUND",
273            Self::SECURE_STORAGE_TAMPERED => "SECURE_STORAGE_TAMPERED",
274            Self::SECURE_STORAGE_PROTECTOR_MISMATCH => "SECURE_STORAGE_PROTECTOR_MISMATCH",
275            Self::SECURE_STORAGE_PROTECTOR_UNAVAILABLE => "SECURE_STORAGE_PROTECTOR_UNAVAILABLE",
276            Self::SECURE_STORAGE_INVALID_KEY => "SECURE_STORAGE_INVALID_KEY",
277            Self::SECURE_STORAGE_LOCKED => "SECURE_STORAGE_LOCKED",
278            Self::MEMBER_INVITATION_INVALID => "MEMBER_INVITATION_INVALID",
279            Self::MEMBER_INVITATION_EXPIRED => "MEMBER_INVITATION_EXPIRED",
280            Self::MEMBER_INVITATION_USED_UP => "MEMBER_INVITATION_USED_UP",
281            Self::MEMBER_INVITATION_REVOKED => "MEMBER_INVITATION_REVOKED",
282            Self::MEMBER_INVITATION_PRIMARY_NOT_ALLOWED => "MEMBER_INVITATION_PRIMARY_NOT_ALLOWED",
283            Self::MEMBER_INVITATION_POLICY_NOT_PROTECTED => {
284                "MEMBER_INVITATION_POLICY_NOT_PROTECTED"
285            }
286            _ => return None,
287        };
288        Some(name)
289    }
290
291    /// What the user has to do about a local-app enrollment refusal
292    /// ([`crate::OnboardMethod::LocalApp`]); `None` for every other code.
293    pub fn user_action(self) -> Option<&'static str> {
294        let action = match self {
295            Self::ONBOARDING_APPROVAL_DENIED => {
296                "the app was denied in the QAROS hub, or its approval was revoked; allow it in the hub, then start the app again"
297            }
298            Self::ONBOARDING_APPROVAL_TIMEOUT => {
299                "nobody answered the approval prompt in the QAROS hub in time; answer the prompt on the hub's PC and retry"
300            }
301            Self::ONBOARDING_HUB_NOT_AUTHENTIC => {
302                "the process serving the enrollment pipe is not the installed QAROS hub; check which hub runs on this PC, do not retry blindly"
303            }
304            Self::ONBOARDING_APP_IDENTITY_MISMATCH => {
305                "the app no longer matches what was approved (moved, rebuilt or re-signed); revoke it in the QAROS hub and approve it again"
306            }
307            _ => return None,
308        };
309        Some(action)
310    }
311}
312
313impl fmt::Debug for StatusCode {
314    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
315        fmt::Display::fmt(self, formatter)
316    }
317}
318
319impl fmt::Display for StatusCode {
320    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
321        match self.name() {
322            Some(name) => write!(formatter, "QAR_STATUS_{name} ({})", self.value()),
323            None => write!(formatter, "status {}", self.value()),
324        }
325    }
326}
327
328/// Every failure the safe API reports.
329#[derive(Debug)]
330pub enum Error {
331    /// The C API library could not be opened or lacks symbols.
332    Load(qaros_sys::LoadError),
333    /// A C API call returned an error result.
334    Api {
335        /// The public C name of the failed call, such as `qar_runtime_create`.
336        function: &'static str,
337        /// The status code of the result.
338        code: StatusCode,
339        /// The text of `qar_result_message`, empty when the library has none.
340        message: String,
341        /// The codes of [`StatusCode::WRAPPED_CAUSES`] that the result wraps under `code`,
342        /// as `qar_result_has_code` reports them.
343        causes: Vec<StatusCode>,
344    },
345    /// `qar_library_init` is process-wide; a second `Library` cannot coexist
346    /// with a live one.
347    LibraryAlreadyLoaded,
348    /// The argument cannot be passed to the C API (interior NUL, too many
349    /// views, ...).
350    InvalidArgument(String),
351}
352
353impl Error {
354    /// The status code of an [`Error::Api`].
355    pub fn code(&self) -> Option<StatusCode> {
356        match self {
357            Self::Api { code, .. } => Some(*code),
358            _ => None,
359        }
360    }
361
362    /// Whether this is an [`Error::Api`] with the `expected` code.
363    pub fn has_code(&self, expected: StatusCode) -> bool {
364        self.code() == Some(expected)
365    }
366
367    /// Whether the error is `expected` itself or wraps it as a cause, the C API's
368    /// `qar_result_has_code`. Wrapped causes are known for [`StatusCode::WRAPPED_CAUSES`] only:
369    /// begin-frame reports a paused, reconnecting or transfer-less stream inside
370    /// [`StatusCode::RENDERING_UNABLE_TO_BEGIN_FRAME`].
371    pub fn has_cause(&self, expected: StatusCode) -> bool {
372        match self {
373            Self::Api { code, causes, .. } => *code == expected || causes.contains(&expected),
374            _ => false,
375        }
376    }
377}
378
379impl StatusCode {
380    /// The causes an [`Error::Api`] records when the result wraps them, read at the failing
381    /// call because the C result's cause chain is not kept.
382    pub const WRAPPED_CAUSES: [Self; 5] = [
383        Self::MEDIA_STREAMING_STREAM_IS_PAUSED,
384        Self::MEDIA_STREAMING_STREAM_IS_RECONNECTING,
385        Self::MEDIA_STREAMING_NO_ACTIVE_TRANSFERS,
386        Self::RENDERING_APP_VOLUME_UNRESOLVED,
387        Self::RENDERING_STREAM_IS_CLOSED,
388    ];
389}
390
391impl fmt::Display for Error {
392    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
393        match self {
394            Self::Load(load_error) => write!(formatter, "loading the QAROS library: {load_error}"),
395            Self::Api {
396                function,
397                code,
398                message,
399                ..
400            } => {
401                if message.is_empty() {
402                    write!(formatter, "{function} failed with {code}")?;
403                } else {
404                    write!(formatter, "{function} failed with {code}: {message}")?;
405                }
406                match code.user_action() {
407                    Some(action) => write!(formatter, " ({action})"),
408                    None => Ok(()),
409                }
410            }
411            Self::LibraryAlreadyLoaded => {
412                formatter.write_str("a QAROS library is already initialized in this process")
413            }
414            Self::InvalidArgument(reason) => write!(formatter, "invalid argument: {reason}"),
415        }
416    }
417}
418
419impl std::error::Error for Error {
420    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
421        match self {
422            Self::Load(load_error) => Some(load_error),
423            _ => None,
424        }
425    }
426}
427
428impl From<qaros_sys::LoadError> for Error {
429    fn from(load_error: qaros_sys::LoadError) -> Self {
430        Self::Load(load_error)
431    }
432}
433
434/// The result type of every fallible call in this crate.
435pub type Result<T, E = Error> = std::result::Result<T, E>;
436
437const MESSAGE_BUFFER_SIZE: usize = 1024;
438
439/// Maps a `QarResult` to `Ok(())` or an [`Error::Api`] carrying the message
440/// from `qar_result_message` and the [`StatusCode::WRAPPED_CAUSES`] it wraps.
441pub(crate) fn check(api: &QarApi, function: &'static str, result: QarResult) -> Result<()> {
442    if result.code == QarStatusCode::QAR_STATUS_SUCCESS {
443        return Ok(());
444    }
445    let mut buffer = [0 as c_char; MESSAGE_BUFFER_SIZE];
446    // SAFETY: the buffer is writable for its full length, which is passed.
447    unsafe { (api.qar_impl_result_message)(result, buffer.as_mut_ptr(), buffer.len()) };
448    let code = StatusCode::from_raw(result.code);
449    let causes = StatusCode::WRAPPED_CAUSES
450        .into_iter()
451        .filter(|&cause| cause != code)
452        // SAFETY: plain value arguments.
453        .filter(|cause| unsafe { (api.qar_impl_result_has_code)(result, cause.raw()) })
454        .collect();
455    Err(Error::Api {
456        function,
457        code,
458        message: crate::strings::from_buffer(&buffer),
459        causes,
460    })
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    #[test]
468    fn a_wrapped_cause_is_found_but_not_taken_for_the_code() {
469        let error = Error::Api {
470            function: "qar_render_sender_try_begin_frame",
471            code: StatusCode::RENDERING_UNABLE_TO_BEGIN_FRAME,
472            message: String::new(),
473            causes: vec![StatusCode::MEDIA_STREAMING_STREAM_IS_RECONNECTING],
474        };
475        assert!(error.has_cause(StatusCode::MEDIA_STREAMING_STREAM_IS_RECONNECTING));
476        assert!(error.has_cause(StatusCode::RENDERING_UNABLE_TO_BEGIN_FRAME));
477        assert!(!error.has_code(StatusCode::MEDIA_STREAMING_STREAM_IS_RECONNECTING));
478        assert!(!error.has_cause(StatusCode::MEDIA_STREAMING_STREAM_IS_PAUSED));
479        assert!(!Error::LibraryAlreadyLoaded.has_cause(StatusCode::LOGIC_ERROR));
480    }
481
482    #[test]
483    fn codes_carry_the_headers_values_and_names() {
484        assert_eq!(
485            StatusCode::ONBOARDING_RE_PAIR_REQUIRED.to_string(),
486            "QAR_STATUS_ONBOARDING_RE_PAIR_REQUIRED (1809)"
487        );
488        assert_eq!(
489            StatusCode::ONBOARDING_RENEWAL_POSSESSION_UNPROVEN.to_string(),
490            "QAR_STATUS_ONBOARDING_RENEWAL_POSSESSION_UNPROVEN (1810)"
491        );
492        assert_eq!(
493            StatusCode::RENDERING_DEPTH_FORMAT_NOT_SUPPORTED.to_string(),
494            "QAR_STATUS_RENDERING_PRODUCER_DEPTH_FORMAT_NOT_SUPPORTED (806)"
495        );
496        assert_eq!(
497            StatusCode::MEMBER_INVITATION_EXPIRED.to_string(),
498            "QAR_STATUS_MEMBER_INVITATION_EXPIRED (3601)"
499        );
500        assert_eq!(
501            StatusCode::PEER_DEVICE_CATEGORY_NOT_ALLOWED.to_string(),
502            "QAR_STATUS_PEER_DEVICE_CATEGORY_NOT_ALLOWED (3101)"
503        );
504    }
505}