Skip to content

Commit

Permalink
lib: Cache the output of is_sandboxed
Browse files Browse the repository at this point in the history
  • Loading branch information
bilelmoussaoui committed Oct 7, 2023
1 parent 606aac1 commit 74b46cd
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@ 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<T> = std::result::Result<T, Error>;

static IS_SANDBOXED: OnceCell<bool> = 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;
/// Interact with the documents store or transfer files across apps.
pub mod documents;
mod error;
mod window_identifier;

pub use self::window_identifier::WindowIdentifier;
mod app_id;
pub use self::app_id::AppID;
Expand All @@ -32,20 +35,27 @@ mod proxy;
pub mod flatpak;
mod helpers;
pub use enumflags2;
use once_cell::sync::OnceCell;
pub use url;
pub use zbus::{self, zvariant};

/// Check whether the application is running inside a sandbox.
///
/// 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};

0 comments on commit 74b46cd

Please sign in to comment.