Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ tower = "0.5"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
tracing-appender = "0.2"
url = "2"
url = "2.5.9"
uuid = { version = "1", features = ["v4"] }
vergen-git2 = { version = "10.0", features = ["build"] }
webbrowser = "1.2"
Expand Down
1 change: 1 addition & 0 deletions src-tauri/deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ ignore = [
{ id = "RUSTSEC-2026-0372", reason = "zvariant_derive merged into zbus 6, Tauri v2 plugins (notification, opener, single-instance) still on zbus 5" },
{ id = "RUSTSEC-2026-0459", reason = "libsqlite3-sys security vulnerability" },
{ id = "RUSTSEC-2026-0543", reason = "chrono is unmaintained" },
{ id = "RUSTSEC-2026-0594", reason = "expires 2026-12-24, cookie 0.18.2 is pulled in by reqwest and tauri with no fixed release yet, we never fork or use private cookie jars" },
]
# If this is true, then cargo deny will use the git executable to fetch advisory database.
# If this is false, then it uses a built-in git library.
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/enterprise/service-locations/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,8 +416,8 @@ impl ServiceLocationManager {
.load_service_location(instance_id, location_pubkey)?
.ok_or_else(|| {
ServiceLocationError::LoadError(format!(
"Service location with pubkey {} for instance {} not found",
location_pubkey, instance_id
"Service location with pubkey {location_pubkey} for instance {instance_id} \
not found"
))
})?;

Expand Down
39 changes: 14 additions & 25 deletions src-tauri/src/window_manager/macos.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use objc2_app_kit::{NSWindow, NSWindowButton, NSWindowStyleMask, NSWindowTitleVisibility};
use tauri::{
AppHandle, LogicalPosition, LogicalSize, Manager, Monitor, Position, Runtime, WebviewWindow,
};
use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, Position, Runtime, WebviewWindow};

use crate::{appstate::AppState, window_manager::WINDOW_GAP};
use crate::{
appstate::AppState,
window_manager::{monitor_for_point, WINDOW_GAP},
};

pub(crate) fn enable_rounded_corners<R: Runtime>(
window: &WebviewWindow<R>,
Expand Down Expand Up @@ -35,24 +36,10 @@ pub(crate) fn enable_rounded_corners<R: Runtime>(
.map_err(|err| err.to_string())
}

/// Try to get monitor at the given position, with a fall back to primary monitor, and then to the
/// first one on the list of available monitors.
fn get_monitor_for_position(app: &AppHandle, x: f64, y: f64) -> Option<Monitor> {
if let Ok(Some(monitor)) = app.monitor_from_point(x, y) {
return Some(monitor);
}

if let Ok(Some(monitor)) = app.primary_monitor() {
return Some(monitor);
}

// On macOS, it seems this is the only working method (as of Tauri 2.11), but fortunately it
// returns the current monitor as the first one.
if let Ok(mut monitors) = app.available_monitors() {
monitors.pop()
} else {
None
}
// f64::clamp panics and aborts the app when min > max (window larger than the display),
// here min wins so the window sticks to the top or left edge
fn clamp_pinned(value: f64, min: f64, max: f64) -> f64 {
value.min(max).max(min)
}

fn get_tray_window_position(
Expand All @@ -65,7 +52,7 @@ fn get_tray_window_position(

if let Some(tray_rect) = *app_state.tray_icon_rect.lock().unwrap() {
let tray_position = tray_rect.position;
let monitor = get_monitor_for_position(app, tray_position.x, tray_position.y)?;
let monitor = monitor_for_point(app, Some(tray_position))?;

let scale_factor = monitor.scale_factor();
let monitor_position = monitor.position().to_logical::<f64>(scale_factor);
Expand All @@ -75,11 +62,13 @@ fn get_tray_window_position(
x = tray_position.x;
y = tray_position.y;

x = x.clamp(
x = clamp_pinned(
x,
monitor_position.x,
monitor_position.x + monitor_size.width - window_size.width,
);
y = y.clamp(
y = clamp_pinned(
y,
monitor_position.y,
monitor_position.y + monitor_size.height - window_size.height,
);
Expand Down
202 changes: 184 additions & 18 deletions src-tauri/src/window_manager/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use defguard_client_core::version::mark_welcome_shown;
use tauri::{
async_runtime::block_on, AppHandle, Emitter, Manager, WebviewUrl, WebviewWindow,
async_runtime::block_on, AppHandle, Emitter, LogicalSize, Manager, WebviewUrl, WebviewWindow,
WebviewWindowBuilder,
};
#[cfg(not(windows))]
use tauri::{Monitor, PhysicalPosition};

use crate::{
appstate::AppState,
Expand Down Expand Up @@ -85,6 +87,147 @@ fn hide_shown_windows(app: &AppHandle, skip_label: &str) {
}
}

/// Display area without menu bar, Dock or taskbar, in physical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct WorkArea {
pub width: u32,
pub height: u32,
pub scale_factor: f64,
}

impl WorkArea {
#[cfg(not(windows))]
fn from_monitor(monitor: &Monitor) -> Self {
let size = monitor.work_area().size;
Self {
width: size.width,
height: size.height,
scale_factor: monitor.scale_factor(),
}
}

fn logical_size(&self) -> Option<(f64, f64)> {
if !self.scale_factor.is_finite()
|| self.scale_factor <= 0.0
|| self.width == 0
|| self.height == 0
{
return None;
}
Some((
f64::from(self.width) / self.scale_factor,
f64::from(self.height) / self.scale_factor,
))
}
}

/// Unusable display data counts as a fit, so a bad reading never takes the tray away.
#[must_use]
pub(crate) fn compact_window_fits(work: WorkArea) -> bool {
work.logical_size().is_none_or(|(width, height)| {
width >= COMPACT_WINDOW_WIDTH && height >= COMPACT_WINDOW_HEIGHT
})
}

#[must_use]
pub(crate) fn full_view_min_size((width, height): (f64, f64)) -> (f64, f64) {
let relax = |available: f64, default: f64| {
if available.is_finite() && available > 0.0 {
default.min(available)
} else {
default
}
};
(
relax(width, FULL_VIEW_WINDOW_WIDTH),
relax(height, FULL_VIEW_WINDOW_HEIGHT),
)
}

#[cfg(not(windows))]
pub(crate) fn monitor_for_point(
app: &AppHandle,
point: Option<PhysicalPosition<f64>>,
) -> Option<Monitor> {
if let Some(point) = point {
if let Ok(Some(monitor)) = app.monitor_from_point(point.x, point.y) {
return Some(monitor);
}
}
if let Ok(Some(monitor)) = app.primary_monitor() {
return Some(monitor);
}
// On macOS this is sometimes the only working method, and it lists the current monitor first.
app.available_monitors()
.ok()
.and_then(|monitors| monitors.into_iter().next())
}

#[cfg(not(windows))]
fn tray_work_area(app: &AppHandle) -> Option<WorkArea> {
let anchor = app
.state::<AppState>()
.tray_icon_rect
.lock()
.unwrap()
.map(|rect| rect.position);
monitor_for_point(app, anchor).map(|monitor| WorkArea::from_monitor(&monitor))
}

#[cfg(windows)]
fn tray_work_area(app: &AppHandle) -> Option<WorkArea> {
windows::tray_work_area(app)
}

pub(crate) fn tray_window_fits(app: &AppHandle) -> bool {
let Some(work) = tray_work_area(app) else {
debug!("No display found for the tray window, assuming it fits");
return true;
};
let fits = compact_window_fits(work);
if !fits {
info!(
"Tray window ({COMPACT_WINDOW_WIDTH}x{COMPACT_WINDOW_HEIGHT}) does not fit the display \
work area {work:?}, using the full view instead"
);
}
fits
}

pub(crate) fn fit_full_view_to_work_area(window: &WebviewWindow, work: WorkArea) {
let Some((work_width, work_height)) = work.logical_size() else {
return;
};
let scale = window
.scale_factor()
.ok()
.filter(|scale| scale.is_finite() && *scale > 0.0)
.unwrap_or(work.scale_factor);
let (Ok(inner), Ok(outer)) = (window.inner_size(), window.outer_size()) else {
return;
};
let inner = inner.to_logical::<f64>(scale);
let outer = outer.to_logical::<f64>(scale);
// Decorations (the Linux title bar) take part of the work area too.
let available = (
(work_width - (outer.width - inner.width).max(0.0)).max(0.0),
(work_height - (outer.height - inner.height).max(0.0)).max(0.0),
);

let (min_width, min_height) = full_view_min_size(available);
if let Err(err) = window.set_min_size(Some(LogicalSize::new(min_width, min_height))) {
warn!("Failed to set full view minimum size: {err}");
}
if inner.width > available.0 || inner.height > available.1 {
let width = inner.width.min(available.0).max(min_width);
let height = inner.height.min(available.1).max(min_height);
debug!("Shrinking full view to {width}x{height} to fit work area {work:?}");
if let Err(err) = window.set_size(LogicalSize::new(width, height)) {
warn!("Failed to shrink full view to the work area: {err}");
}
}
}

pub struct WindowManager;

impl WindowManager {
Expand Down Expand Up @@ -183,6 +326,14 @@ impl WindowManager {
} else {
Self::build_full_view_window(app)?
};
let monitor = window
.current_monitor()
.ok()
.flatten()
.or_else(|| monitor_for_point(app, None));
if let Some(monitor) = monitor {
fit_full_view_to_work_area(&window, WorkArea::from_monitor(&monitor));
}
#[cfg(target_os = "macos")]
{
let _ = app.set_activation_policy(tauri::ActivationPolicy::Regular);
Expand Down Expand Up @@ -222,9 +373,19 @@ pub mod windows;
#[cfg(target_os = "macos")]
pub mod macos;

// Export tauri commands so they can be registered in main.rs
pub(crate) fn show_tray_window(app: &AppHandle) {
let _ = WindowManager::open_tray(app);
/// Opens the full view instead when the tray window does not fit, returns the shown window label.
pub(crate) fn show_tray_window(app: &AppHandle) -> &'static str {
if tray_window_fits(app) {
if let Err(err) = WindowManager::open_tray(app) {
error!("Failed to open tray window: {err}");
}
COMPACT_WINDOW_ID
} else {
if let Err(err) = WindowManager::open_full_view(app) {
error!("Failed to open full view in place of the tray window: {err}");
}
FULL_VIEW_WINDOW_ID
}
}

fn prefers_full_view(app: &AppHandle) -> bool {
Expand All @@ -235,19 +396,17 @@ fn prefers_full_view(app: &AppHandle) -> bool {
.open_in_full_window
}

/// Show the compact (tray) window when there is tray content (a non-service
/// location or a tunnel) and the "open in full window" setting is off,
/// otherwise fall back to the full view.
pub fn show_tray_or_full_view(app: &AppHandle) {
if !prefers_full_view(app) && block_on(has_tray_content()) {
// Hide the full view if it is open and visible (not minimized) so only the compact window is shown.
if !prefers_full_view(app) && block_on(has_tray_content()) && tray_window_fits(app) {
if let Some(full_view) = app.get_webview_window(FULL_VIEW_WINDOW_ID) {
let full_view_visible = full_view.is_visible().ok().unwrap_or(false);
if full_view_visible {
let _ = full_view.hide();
}
}
show_tray_window(app);
if let Err(err) = WindowManager::open_tray(app) {
error!("Failed to open tray window: {err}");
}
} else {
let _ = WindowManager::open_full_view(app);
}
Expand All @@ -272,8 +431,7 @@ pub fn trigger_mfa(app: &AppHandle, location: &Location<Id>) {
let _ = window.set_focus();
FULL_VIEW_WINDOW_ID
} else {
show_tray_window(app);
COMPACT_WINDOW_ID
show_tray_window(app)
};
let payload = mfa_trigger_payload(location);
let _ = app.emit_to(target, EventKey::MfaTrigger.into(), &payload);
Expand Down Expand Up @@ -389,11 +547,13 @@ pub fn close_tray_window(app: AppHandle) {
pub fn close_welcome_window(app: AppHandle) {
info!("close_welcome_window called");

let config_dir = app
.path()
.app_data_dir()
.expect("Failed to access app data");
mark_welcome_shown(&config_dir, &app.package_info().version);
match app.path().app_data_dir() {
Ok(config_dir) => mark_welcome_shown(&config_dir, &app.package_info().version),
Err(err) => error!(
"close_welcome_window: Failed to access app data directory, the welcome screen will \
show again on next launch: {err}"
),
}

show_tray_or_full_view(&app);

Expand All @@ -416,7 +576,13 @@ pub fn close_welcome_window(app: AppHandle) {
#[tauri::command]
pub fn swap_to_tray(app: AppHandle) {
info!("swap_to_tray called");
show_tray_window(&app);
if !tray_window_fits(&app) {
info!("swap_to_tray: Tray window does not fit the display, keeping the full view");
return;
}
if let Err(err) = WindowManager::open_tray(&app) {
error!("swap_to_tray task: Failed to open tray window: {err:?}");
}
if let Some(window) = app.get_webview_window(FULL_VIEW_WINDOW_ID) {
if let Err(err) = window.hide() {
error!("swap_to_tray task: Failed to hide full-view window: {err:?}");
Expand Down
Loading
Loading