diff --git a/apps/gpauth/Cargo.toml b/apps/gpauth/Cargo.toml index f62a191..1182614 100644 --- a/apps/gpauth/Cargo.toml +++ b/apps/gpauth/Cargo.toml @@ -28,7 +28,7 @@ compile-time.workspace = true home = "=0.5.11" # webview auth dependencies -tauri = { workspace = true, optional = true } +tauri = { workspace = true, optional = true, features = ["devtools"] } [features] default = ["webview-auth"] diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index 532cd7a..18ae3fc 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -1,5 +1,7 @@ use auth::{BrowserAuthenticator, auth_prelogin}; use clap::Parser; +#[cfg(feature = "webview-auth")] +use gpapi::auth::AuthWindowTheme; use gpapi::{ auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult}, clap::{Args, InfoLevelVerbosity, args::Os, handle_error}, @@ -96,6 +98,14 @@ struct Cli { #[arg(long, help = "Clean the cache of the embedded browser")] pub clean: bool, + #[cfg(feature = "webview-auth")] + #[arg(long, help = "Set the embedded authentication window title")] + window_title: Option, + + #[cfg(feature = "webview-auth")] + #[arg(long, value_enum, default_value_t = AuthWindowTheme::default(), help = "Set the embedded authentication window appearance")] + window_theme: AuthWindowTheme, + #[command(flatten)] verbose: InfoLevelVerbosity, } @@ -166,7 +176,16 @@ impl Cli { } #[cfg(feature = "webview-auth")] - crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?; + crate::webview_auth::authenticate( + server, + gp_params, + auth_request, + self.clean, + self.window_title.clone(), + self.window_theme, + openssl_conf, + ) + .await?; Ok(()) } @@ -314,4 +333,21 @@ mod tests { assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key")); assert_eq!(cli.key_password.as_deref(), Some("secret")); } + + #[cfg(feature = "webview-auth")] + #[test] + fn auth_window_options_parse() { + let cli = Cli::try_parse_from([ + "gpauth", + "portal.example.com", + "--window-title", + "GP Connect Login", + "--window-theme", + "dark", + ]) + .expect("gpauth window options should parse"); + + assert_eq!(cli.window_title.as_deref(), Some("GP Connect Login")); + assert_eq!(cli.window_theme, AuthWindowTheme::Dark); + } } diff --git a/apps/gpauth/src/webview_auth.rs b/apps/gpauth/src/webview_auth.rs index abdf48b..2add52a 100644 --- a/apps/gpauth/src/webview_auth.rs +++ b/apps/gpauth/src/webview_auth.rs @@ -1,5 +1,5 @@ -use auth::WebviewAuthenticator; -use gpapi::gp_params::GpParams; +use auth::{WebviewAuthenticator, apply_auth_theme}; +use gpapi::{auth::AuthWindowTheme, gp_params::GpParams}; use log::info; use tauri::RunEvent; use tempfile::NamedTempFile; @@ -11,19 +11,24 @@ pub async fn authenticate( gp_params: GpParams, auth_request: String, clean: bool, + window_title: Option, + window_theme: AuthWindowTheme, mut openssl_conf: Option, ) -> anyhow::Result<()> { let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string(); tauri::Builder::default() .setup(move |app| { + apply_auth_theme(app.handle(), window_theme); let app_handle = app.handle().clone(); tauri::async_runtime::spawn(async move { let authenticator = WebviewAuthenticator::new(&server, &gp_params) .with_auth_request(&auth_request) .with_webview_user_agent(gp_params.os_profile().webview_user_agent()) - .with_clean(clean); + .with_clean(clean) + .with_window_title(window_title.as_deref().unwrap_or("GlobalProtect Login")) + .with_window_theme(window_theme); let auth_result = authenticator.authenticate(&app_handle).await; print_auth_result(auth_result, Some(&auth_host_id)); diff --git a/apps/gpservice/src/cli.rs b/apps/gpservice/src/cli.rs index b8e81eb..a2f1c76 100644 --- a/apps/gpservice/src/cli.rs +++ b/apps/gpservice/src/cli.rs @@ -1,4 +1,3 @@ -#[cfg(debug_assertions)] use std::path::PathBuf; use std::sync::{ Arc, @@ -13,6 +12,8 @@ use clap::Parser; use common::constants::GP_SERVICE_LOCK_FILE; use gpapi::clap::InfoLevelVerbosity; use gpapi::logger; +#[cfg(debug_assertions)] +use gpapi::utils::lock_file::dev_service_lock_file_path; use gpapi::{ process::gui_launcher::GuiLauncher, service::{request::WsRequest, vpn_state::VpnState}, @@ -88,7 +89,7 @@ impl Cli { info!("gpservice started: {}", VERSION); let pid = std::process::id(); - let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid)); + let lock_file = Arc::new(LockFile::new(self.service_lock_file_path()?, pid)); if lock_file.check_health().await { bail!("Another instance of the service is already running"); @@ -230,6 +231,19 @@ impl Cli { false } + fn service_lock_file_path(&self) -> anyhow::Result { + #[cfg(debug_assertions)] + if self.dev_standalone { + let socket = self + .dev_bootstrap_socket + .as_ref() + .context("--dev-bootstrap-socket is required with --dev-standalone")?; + return Ok(dev_service_lock_file_path(socket)); + } + + Ok(PathBuf::from(GP_SERVICE_LOCK_FILE)) + } + fn init_logger(&self) -> Arc { let redaction = Arc::new(Redaction::new()); let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info); diff --git a/crates/auth/src/webview.rs b/crates/auth/src/webview.rs index bd15c88..071d14f 100644 --- a/crates/auth/src/webview.rs +++ b/crates/auth/src/webview.rs @@ -17,4 +17,4 @@ mod platform_impl; )))] compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets"); -pub use webview_auth::WebviewAuthenticator; +pub use webview_auth::{WebviewAuthenticator, apply_auth_theme}; diff --git a/crates/auth/src/webview/macos.rs b/crates/auth/src/webview/macos.rs index 5127c3d..ab0fb72 100644 --- a/crates/auth/src/webview/macos.rs +++ b/crates/auth/src/webview/macos.rs @@ -1,17 +1,147 @@ -use anyhow::bail; -use block2::RcBlock; -use log::warn; -use objc2::runtime::AnyObject; -use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest}; -use objc2_web_kit::WKWebView; +use std::{ffi::c_void, ptr}; + +use anyhow::{Context, bail}; +use block2::{DynBlock, RcBlock}; +use objc2::{ + DefinedClass, MainThreadOnly, define_class, + ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject}, + msg_send, + rc::Retained, + runtime::{AnyObject, ProtocolObject, Sel}, +}; +use objc2_foundation::{ + MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL, + NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest, + NSURLSessionAuthChallengeDisposition, +}; +use objc2_web_kit::{WKNavigationDelegate, WKWebView}; use tauri::webview::PlatformWebview; use super::webview_auth::PlatformWebviewExt; +static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0; + +struct TlsNavigationDelegateIvars { + original: Retained>, +} + +define_class!( + #[unsafe(super = NSObject)] + #[thread_kind = MainThreadOnly] + #[ivars = TlsNavigationDelegateIvars] + struct TlsNavigationDelegate; + + unsafe impl NSObjectProtocol for TlsNavigationDelegate {} + + #[allow(non_snake_case)] + unsafe impl WKNavigationDelegate for TlsNavigationDelegate { + #[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))] + unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler( + &self, + _webview: &WKWebView, + challenge: &NSURLAuthenticationChallenge, + completion_handler: &DynBlock, + ) { + let protection_space = challenge.protectionSpace(); + let is_server_trust = protection_space + .authenticationMethod() + .isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust }); + + if !is_server_trust { + completion_handler.call((challenge_disposition(false), ptr::null_mut())); + return; + } + + let server_trust: *mut AnyObject = msg_send![&*protection_space, serverTrust]; + if server_trust.is_null() { + completion_handler.call((challenge_disposition(false), ptr::null_mut())); + return; + } + + let credential: Retained = + msg_send![objc2::class!(NSURLCredential), credentialForTrust: server_trust]; + completion_handler.call((challenge_disposition(true), Retained::as_ptr(&credential).cast_mut())); + } + } + + impl TlsNavigationDelegate { + #[unsafe(method(respondsToSelector:))] + fn responds_to_selector(&self, selector: Sel) -> bool { + let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] }; + responds || self.ivars().original.respondsToSelector(selector) + } + + #[unsafe(method(forwardingTargetForSelector:))] + fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject { + if self.ivars().original.respondsToSelector(selector) { + Retained::as_ptr(&self.ivars().original).cast_mut().cast() + } else { + unsafe { msg_send![super(self), forwardingTargetForSelector: selector] } + } + } + } +); + +impl TlsNavigationDelegate { + fn new(original: Retained>, mtm: MainThreadMarker) -> Retained { + let this = Self::alloc(mtm).set_ivars(TlsNavigationDelegateIvars { original }); + unsafe { msg_send![super(this), init] } + } +} + +fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisposition { + if is_server_trust { + NSURLSessionAuthChallengeDisposition::UseCredential + } else { + NSURLSessionAuthChallengeDisposition::PerformDefaultHandling + } +} + +fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> { + let original = unsafe { webview.navigationDelegate() }.context("WebView navigation delegate is unavailable")?; + let mtm = MainThreadMarker::new().context("WebView must be configured on the main thread")?; + let delegate = TlsNavigationDelegate::new(original, mtm); + + unsafe { + objc_setAssociatedObject( + webview as *const WKWebView as *mut AnyObject, + &TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void, + Retained::as_ptr(&delegate).cast_mut().cast(), + OBJC_ASSOCIATION_RETAIN_NONATOMIC, + ); + webview.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate))); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use objc2_foundation::NSURLSessionAuthChallengeDisposition; + + use super::challenge_disposition; + + #[test] + fn accepts_server_trust_challenges() { + assert_eq!( + challenge_disposition(true), + NSURLSessionAuthChallengeDisposition::UseCredential + ); + } + + #[test] + fn preserves_default_handling_for_other_challenges() { + assert_eq!( + challenge_disposition(false), + NSURLSessionAuthChallengeDisposition::PerformDefaultHandling + ); + } +} + impl PlatformWebviewExt for PlatformWebview { fn ignore_tls_errors(&self) -> anyhow::Result<()> { - warn!("Ignoring TLS errors is not supported on macOS"); - Ok(()) + let webview: &WKWebView = unsafe { &*self.inner().cast() }; + install_tls_navigation_delegate(webview) } fn user_agent(&self) -> anyhow::Result { diff --git a/crates/auth/src/webview/webview_auth.rs b/crates/auth/src/webview/webview_auth.rs index e03da1f..1bc6d26 100644 --- a/crates/auth/src/webview/webview_auth.rs +++ b/crates/auth/src/webview/webview_auth.rs @@ -2,10 +2,10 @@ use std::{sync::Arc, time::Duration}; use anyhow::bail; use gpapi::{ - auth::{AuthenticationCancelled, SamlAuthData}, + auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData}, gp_params::GpParams, os_profile::{WebviewUserAgent, WebviewUserAgentTransform}, - utils::redact::redact_uri, + utils::{redact::redact_uri, window::get_title_bar_height}, }; use log::{info, warn}; use tauri::{ @@ -53,10 +53,28 @@ pub struct WebviewAuthenticator<'a> { auth_request: Option<&'a str>, webview_user_agent: Option, clean: bool, + window_title: &'a str, + window_theme: AuthWindowTheme, is_retrying: tokio::sync::RwLock, } +fn native_theme(theme: AuthWindowTheme) -> Option { + match theme { + AuthWindowTheme::System => None, + AuthWindowTheme::Light => Some(tauri::Theme::Light), + AuthWindowTheme::Dark => Some(tauri::Theme::Dark), + } +} + +pub fn apply_auth_theme(app_handle: &AppHandle, theme: AuthWindowTheme) { + app_handle.set_theme(native_theme(theme)); +} + +fn present_after_setup(clean: bool) -> bool { + clean +} + impl<'a> WebviewAuthenticator<'a> { pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self { Self { @@ -65,6 +83,8 @@ impl<'a> WebviewAuthenticator<'a> { auth_request: None, webview_user_agent: None, clean: false, + window_title: "GlobalProtect Login", + window_theme: AuthWindowTheme::System, is_retrying: Default::default(), } } @@ -84,6 +104,16 @@ impl<'a> WebviewAuthenticator<'a> { self } + pub fn with_window_title(mut self, window_title: &'a str) -> Self { + self.window_title = window_title; + self + } + + pub fn with_window_theme(mut self, window_theme: AuthWindowTheme) -> Self { + self.window_theme = window_theme; + self + } + pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result { let auth_messenger = Arc::new(AuthMessenger::new()); let auth_messenger_clone = Arc::clone(&auth_messenger); @@ -112,15 +142,15 @@ impl<'a> WebviewAuthenticator<'a> { }); }; - let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 }; - - let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default()) + let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default()) .on_page_load(on_page_load) - .title("GlobalProtect Login") - .inner_size(900.0, 650.0 + title_bar_height) + .title(self.window_title) + .theme(native_theme(self.window_theme)) + .devtools(true); + let auth_window = auth_window_builder + .inner_size(900.0, 650.0 + get_title_bar_height()) .focused(true) - // when clean is true, the window is expected to be shown because the cookies are cleared - .visible(self.clean) + .visible(false) .center() .build()?; @@ -128,6 +158,10 @@ impl<'a> WebviewAuthenticator<'a> { .setup_auth_window(&auth_window, Arc::clone(&auth_messenger)) .await?; + if present_after_setup(self.clean) { + self.raise_window(&auth_window); + } + loop { match auth_messenger.subscribe().await? { AuthEvent::Close => bail!(AuthenticationCancelled), @@ -284,14 +318,8 @@ impl<'a> WebviewAuthenticator<'a> { info!("Raising auth window..."); - #[cfg(target_os = "macos")] - let result = auth_window.show(); - - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] - let result = { - use gpapi::utils::window::WindowExt; - auth_window.raise() - }; + use gpapi::utils::window::WindowExt; + let result = auth_window.raise(); if let Err(err) = result { warn!("Failed to raise window: {}", err); @@ -377,6 +405,19 @@ fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) -> mod tests { use super::*; + #[test] + fn maps_auth_window_theme_to_native_theme() { + assert_eq!(native_theme(AuthWindowTheme::System), None); + assert_eq!(native_theme(AuthWindowTheme::Light), Some(tauri::Theme::Light)); + assert_eq!(native_theme(AuthWindowTheme::Dark), Some(tauri::Theme::Dark)); + } + + #[test] + fn presents_clean_auth_after_setup() { + assert!(present_after_setup(true)); + assert!(!present_after_setup(false)); + } + #[test] fn prepends_prefix_to_default_user_agent() { let user_agent = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "Mozilla/5.0").unwrap(); diff --git a/crates/gpapi/src/auth.rs b/crates/gpapi/src/auth.rs index 4657211..094b5f2 100644 --- a/crates/gpapi/src/auth.rs +++ b/crates/gpapi/src/auth.rs @@ -12,6 +12,25 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string}; pub type AuthDataParseResult = anyhow::Result; +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "clap", derive(clap::ValueEnum))] +pub enum AuthWindowTheme { + #[default] + System, + Light, + Dark, +} + +impl AuthWindowTheme { + pub fn as_str(self) -> &'static str { + match self { + Self::System => "system", + Self::Light => "light", + Self::Dark => "dark", + } + } +} + #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct SamlAuthData { diff --git a/crates/gpapi/src/process/auth_launcher.rs b/crates/gpapi/src/process/auth_launcher.rs index 1d477a5..fdd92b0 100644 --- a/crates/gpapi/src/process/auth_launcher.rs +++ b/crates/gpapi/src/process/auth_launcher.rs @@ -4,6 +4,8 @@ use anyhow::bail; use common::binary_paths; use tokio::process::Command; +#[cfg(feature = "webview-auth")] +use crate::auth::AuthWindowTheme; use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile}; use super::command_traits::CommandExt; @@ -27,6 +29,10 @@ pub struct SamlAuthLauncher<'a> { clean: bool, #[cfg(feature = "webview-auth")] default_browser: bool, + #[cfg(feature = "webview-auth")] + window_title: Option<&'a str>, + #[cfg(feature = "webview-auth")] + window_theme: Option, browser: Option<&'a str>, verbose: Option<&'a str>, } @@ -52,6 +58,10 @@ impl<'a> SamlAuthLauncher<'a> { clean: false, #[cfg(feature = "webview-auth")] default_browser: false, + #[cfg(feature = "webview-auth")] + window_title: None, + #[cfg(feature = "webview-auth")] + window_theme: None, browser: None, verbose: None, } @@ -122,6 +132,18 @@ impl<'a> SamlAuthLauncher<'a> { self } + #[cfg(feature = "webview-auth")] + pub fn window_title(mut self, window_title: &'a str) -> Self { + self.window_title = Some(window_title); + self + } + + #[cfg(feature = "webview-auth")] + pub fn window_theme(mut self, window_theme: AuthWindowTheme) -> Self { + self.window_theme = Some(window_theme); + self + } + pub fn browser(mut self, browser: Option<&'a str>) -> Self { self.browser = browser; self @@ -194,6 +216,14 @@ impl<'a> SamlAuthLauncher<'a> { if self.default_browser { auth_cmd.arg("--default-browser"); } + + if let Some(window_title) = self.window_title { + auth_cmd.arg("--window-title").arg(window_title); + } + + if let Some(window_theme) = self.window_theme { + auth_cmd.arg("--window-theme").arg(window_theme.as_str()); + } } if let Some(browser) = self.browser { diff --git a/crates/gpapi/src/utils/endpoint.rs b/crates/gpapi/src/utils/endpoint.rs index 6c0aa5a..242b15f 100644 --- a/crates/gpapi/src/utils/endpoint.rs +++ b/crates/gpapi/src/utils/endpoint.rs @@ -1,19 +1,38 @@ -use super::lock_file::gpservice_lock_info; +use std::path::Path; -async fn read_port() -> anyhow::Result { - let lock_info = gpservice_lock_info().await?; - - Ok(lock_info.port.to_string()) -} +use super::lock_file::{gpservice_lock_info, gpservice_lock_info_at}; pub async fn http_endpoint() -> anyhow::Result { - let port = read_port().await?; + let port = gpservice_lock_info().await?.port; Ok(format!("http://127.0.0.1:{}", port)) } pub async fn ws_endpoint() -> anyhow::Result { - let port = read_port().await?; + let port = gpservice_lock_info().await?.port; Ok(format!("ws://127.0.0.1:{}/ws", port)) } + +pub async fn ws_endpoint_from_lock_file(path: impl AsRef) -> anyhow::Result { + let port = gpservice_lock_info_at(path).await?.port; + + Ok(format!("ws://127.0.0.1:{}/ws", port)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn websocket_endpoint_uses_the_selected_lock_file() { + let temp = tempfile::tempdir().unwrap(); + let lock_file = temp.path().join("gpservice.lock"); + std::fs::write(&lock_file, "123:4242").unwrap(); + + assert_eq!( + ws_endpoint_from_lock_file(lock_file).await.unwrap(), + "ws://127.0.0.1:4242/ws" + ); + } +} diff --git a/crates/gpapi/src/utils/lock_file.rs b/crates/gpapi/src/utils/lock_file.rs index e742855..d723b41 100644 --- a/crates/gpapi/src/utils/lock_file.rs +++ b/crates/gpapi/src/utils/lock_file.rs @@ -1,4 +1,4 @@ -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use common::constants::GP_SERVICE_LOCK_FILE; use thiserror::Error; @@ -9,6 +9,10 @@ pub struct LockFile { pid: u32, } +pub fn dev_service_lock_file_path(bootstrap_socket: impl AsRef) -> PathBuf { + bootstrap_socket.as_ref().with_file_name("gpservice.lock") +} + impl LockFile { pub fn new>(path: P, pid: u32) -> Self { Self { path: path.into(), pid } @@ -95,7 +99,11 @@ impl LockInfo { } pub async fn gpservice_lock_info() -> Result { - LockInfo::from_file(GP_SERVICE_LOCK_FILE).await + gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await +} + +pub async fn gpservice_lock_info_at(path: impl AsRef) -> Result { + LockInfo::from_file(path).await } #[cfg(test)] @@ -126,4 +134,12 @@ mod tests { Err(LockFileError::InvalidPort(_)) )); } + + #[test] + fn dev_service_lock_file_is_next_to_the_bootstrap_socket() { + assert_eq!( + dev_service_lock_file_path("/var/run/gpservice-dev-123/dev-bootstrap.sock"), + PathBuf::from("/var/run/gpservice-dev-123/gpservice.lock") + ); + } } diff --git a/crates/gpapi/src/utils/window.rs b/crates/gpapi/src/utils/window.rs index b902256..9e6ff25 100644 --- a/crates/gpapi/src/utils/window.rs +++ b/crates/gpapi/src/utils/window.rs @@ -1,11 +1,40 @@ use tauri::WebviewWindow; +/// Returns the frame-to-content height difference for a standard titled macOS window. +/// This is nonzero only on macOS. +pub fn get_title_bar_height() -> f64 { + #[cfg(target_os = "macos")] + { + macos_title_bar_height(os_info::get().version()) + } + #[cfg(not(target_os = "macos"))] + { + 0.0 + } +} + +#[cfg(target_os = "macos")] +fn macos_title_bar_height(version: &os_info::Version) -> f64 { + if version.ge(&os_info::Version::from_string("26.0.0")) { + 32.0 + } else { + 28.0 + } +} + pub trait WindowExt { fn raise(&self) -> anyhow::Result<()>; } impl WindowExt for WebviewWindow { - #[cfg(any(target_os = "macos", target_os = "windows"))] + #[cfg(target_os = "macos")] + fn raise(&self) -> anyhow::Result<()> { + self.show()?; + self.set_focus()?; + Ok(()) + } + + #[cfg(target_os = "windows")] fn raise(&self) -> anyhow::Result<()> { self.show()?; Ok(()) @@ -17,6 +46,24 @@ impl WindowExt for WebviewWindow { } } +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(target_os = "macos")] + #[test] + fn uses_the_current_macos_title_bar_height() { + assert_eq!(macos_title_bar_height(&os_info::Version::from_string("25.9.0")), 28.0); + assert_eq!(macos_title_bar_height(&os_info::Version::from_string("26.0.0")), 32.0); + } + + #[cfg(not(target_os = "macos"))] + #[test] + fn native_title_bar_height_is_zero_without_a_native_macos_title_bar() { + assert_eq!(get_title_bar_height(), 0.0); + } +} + #[cfg(not(any(target_os = "macos", target_os = "windows")))] mod unix { use std::{process::ExitStatus, time::Duration};