From 74b46cd0aa2d41d54edf207926c20ecdff7b664e Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Sat, 7 Oct 2023 11:18:34 +0200 Subject: [PATCH] lib: Cache the output of is_sandboxed --- src/lib.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6f5e59967..190048956 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,8 @@ compile_error!("You can't enable both async-std & tokio features at once"); /// Alias for a [`Result`] with the error type `ashpd::Error`. pub type Result = std::result::Result; +static IS_SANDBOXED: OnceCell = OnceCell::new(); + /// Interact with the user's desktop such as taking a screenshot, setting a /// background or querying the user's location. pub mod desktop; @@ -19,6 +21,7 @@ pub mod desktop; pub mod documents; mod error; mod window_identifier; + pub use self::window_identifier::WindowIdentifier; mod app_id; pub use self::app_id::AppID; @@ -32,6 +35,7 @@ mod proxy; pub mod flatpak; mod helpers; pub use enumflags2; +use once_cell::sync::OnceCell; pub use url; pub use zbus::{self, zvariant}; @@ -39,13 +43,19 @@ pub use zbus::{self, zvariant}; /// /// The function checks whether the file `/.flatpak-info` exists, or if the app /// is running as a snap, or if the environment variable `GTK_USE_PORTAL` is set -/// to `1`. +/// to `1`. As the return value of this function will not change during the +/// runtime of a program; it is cached for future calls. pub async fn is_sandboxed() -> bool { - crate::helpers::is_flatpak().await + if let Some(cached_value) = IS_SANDBOXED.get() { + return *cached_value; + } + let new_value = crate::helpers::is_flatpak().await || crate::helpers::is_snap().await || std::env::var("GTK_USE_PORTAL") .map(|v| v == "1") - .unwrap_or(false) + .unwrap_or(false); + IS_SANDBOXED.set(new_value).unwrap(); // Safe to unwrap here + new_value } pub use self::error::{Error, PortalError};