Files
GlobalProtect-openconnect/crates/gpapi/src/gui.rs
T
2026-11-21 02:41:00 +08:00

162 lines
4.8 KiB
Rust

//! Desktop GUI selection shared by launchers, installers and settings.
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
pub enum GuiVariant {
#[default]
Tauri,
Nsh,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
pub enum GuiTheme {
#[default]
System,
Light,
Dark,
}
impl GuiTheme {
pub fn as_str(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
Self::Dark => "dark",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GuiSwitchRequest {
pub variant: GuiVariant,
/// Permit a download only after the user accepts the confirmation dialog.
pub allow_download: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
pub enum GuiSwitchOutcome {
Switched,
DownloadRequired,
}
impl GuiVariant {
pub fn binary_name(self) -> &'static str {
match self {
Self::Tauri => "gpgui",
Self::Nsh => "gpgui-nsh",
}
}
pub fn update_target(self) -> PathBuf {
let target = common::binary_paths::gpgui_update_target();
match self {
Self::Tauri => target,
Self::Nsh => target.with_file_name(self.binary_name()),
}
}
pub fn primary(self) -> PathBuf {
match self {
Self::Tauri => common::binary_paths::gpgui(),
Self::Nsh => common::binary_paths::gpgui().with_file_name(self.binary_name()),
}
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn preference_path(name: &str) -> anyhow::Result<PathBuf> {
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
Ok(dirs.config_dir().join(name))
}
pub const NATIVE_SHELL_SUPPORTED: bool = cfg!(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64"),
any(target_env = "gnu", target_env = "musl")
));
#[cfg(target_os = "linux")]
pub(crate) fn saved_preference() -> anyhow::Result<Option<GuiVariant>> {
match std::fs::read_to_string(preference_path("gui")?) {
Ok(value) => match value.trim() {
"gpgui" => Ok(Some(GuiVariant::Tauri)),
"gpgui-nsh" => Ok(Some(GuiVariant::Nsh)),
_ => anyhow::bail!("Invalid GUI preference"),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error.into()),
}
}
#[cfg(target_os = "linux")]
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
save_launch_preference("gui", variant.binary_name())
}
pub const COMPATIBILITY_GRAPHICS_SUPPORTED: bool =
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
pub const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";
const COMPATIBILITY_GRAPHICS: &str = "compatibility-graphics";
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
fn preference_path(_: &str) -> anyhow::Result<PathBuf> {
anyhow::bail!("Compatibility graphics is unavailable")
}
pub fn compatibility_graphics_enabled() -> bool {
COMPATIBILITY_GRAPHICS_SUPPORTED && preference_path(COMPATIBILITY_GRAPHICS).is_ok_and(|path| path.is_file())
}
pub fn set_compatibility_graphics(enabled: bool) -> anyhow::Result<()> {
anyhow::ensure!(
COMPATIBILITY_GRAPHICS_SUPPORTED,
"Compatibility graphics is unavailable"
);
if enabled {
return save_launch_preference(COMPATIBILITY_GRAPHICS, "enabled");
}
match std::fs::remove_file(preference_path(COMPATIBILITY_GRAPHICS)?) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
result => result.map_err(Into::into),
}
}
fn save_launch_preference(name: &str, value: &str) -> anyhow::Result<()> {
use std::io::Write;
let path = preference_path(name)?;
let directory = path.parent().unwrap();
std::fs::create_dir_all(directory)?;
let mut file = tempfile::NamedTempFile::new_in(directory)?;
writeln!(file, "{value}")?;
file.persist(path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nsh_selection_keeps_both_launch_and_upgrade_paths_on_nsh() {
let variant = GuiVariant::Nsh;
assert_eq!(variant.primary().file_name().unwrap(), "gpgui-nsh");
assert_eq!(variant.update_target().file_name().unwrap(), "gpgui-nsh");
assert_eq!(
variant.update_target().parent(),
GuiVariant::Tauri.update_target().parent()
);
assert_eq!(serde_json::to_string(&variant).unwrap(), "\"nsh\"");
}
}