diff --git a/Cargo.lock b/Cargo.lock index de80a9e..42111bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2262,8 +2262,10 @@ dependencies = [ "env_logger", "futures-util", "gpapi", + "gtk", "log", "reqwest", + "serde_json", "tauri", "tauri-build", "tempfile", diff --git a/README.md b/README.md index 60765e5..95c310d 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,12 @@ For the development version from the main branch, use the AUR package. yay -S globalprotect-openconnect-git ``` +To open GP Connect windows, including Settings, centered at their default sizes in i3, add the following line to your i3 config (usually `~/.config/i3/config`) and run `i3-msg reload`. The rule covers both Native Shell and Tauri. + +```i3 +include /usr/share/gpclient/i3.conf +``` + ### Debian / Ubuntu #### Ubuntu PPA diff --git a/apps/gpgui-helper/src-tauri/Cargo.toml b/apps/gpgui-helper/src-tauri/Cargo.toml index 720c66f..aae470c 100644 --- a/apps/gpgui-helper/src-tauri/Cargo.toml +++ b/apps/gpgui-helper/src-tauri/Cargo.toml @@ -26,5 +26,9 @@ tokio-tungstenite = "0.30" tempfile.workspace = true reqwest = { workspace = true, features = ["stream"] } +[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies] +gtk = "0.18" +serde_json.workspace = true + [features] default = ["tauri/custom-protocol"] diff --git a/apps/gpgui-helper/src-tauri/src/cli.rs b/apps/gpgui-helper/src-tauri/src/cli.rs index 7009d9b..11fa456 100644 --- a/apps/gpgui-helper/src-tauri/src/cli.rs +++ b/apps/gpgui-helper/src-tauri/src/cli.rs @@ -25,6 +25,10 @@ const VERSION: &str = concat!( #[derive(Parser)] #[command(version = VERSION)] struct Cli { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[arg(long, hide = true, conflicts_with = "service_credential_on_stdin")] + xembed_tray: bool, + #[arg(long, help = "Read the service credential from stdin")] service_credential_on_stdin: bool, @@ -42,6 +46,10 @@ struct Cli { impl Cli { fn run(&self) -> anyhow::Result<()> { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + if self.xembed_tray { + return crate::xembed_tray::run(); + } let credential = self.read_credential()?; let credential_lease = monitor_credential_lease().context("Failed to monitor service credential lifetime")?; anyhow::ensure!( diff --git a/apps/gpgui-helper/src-tauri/src/lib.rs b/apps/gpgui-helper/src-tauri/src/lib.rs index 4416c2f..3f946fa 100644 --- a/apps/gpgui-helper/src-tauri/src/lib.rs +++ b/apps/gpgui-helper/src-tauri/src/lib.rs @@ -3,3 +3,5 @@ pub(crate) mod downloader; pub(crate) mod updater; pub mod cli; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +mod xembed_tray; diff --git a/apps/gpgui-helper/src-tauri/src/xembed_tray.rs b/apps/gpgui-helper/src-tauri/src/xembed_tray.rs new file mode 100644 index 0000000..13de893 --- /dev/null +++ b/apps/gpgui-helper/src-tauri/src/xembed_tray.rs @@ -0,0 +1,187 @@ +//! GTK 3 owns the XEmbed plug and menu on the user session's X11 display. +use gpapi::process::xembed_tray::{MenuEntry, Request}; +use gtk::{ + glib::{self, translate::ToGlibPtr}, + prelude::*, +}; +use std::{ + cell::RefCell, + io::{self, BufRead, Cursor, Write}, + ptr, + rc::Rc, +}; + +glib::wrapper! { + struct StatusIcon(Object); + match fn { + type_ => || gtk::ffi::gtk_status_icon_get_type(), + } +} + +pub(crate) fn run() -> anyhow::Result<()> { + gtk::init()?; + let icon: StatusIcon = glib::Object::builder() + .property("title", "GP Connect") + .property("visible", false) + .build(); + let menu = Rc::new(RefCell::new(gtk::Menu::new())); + for signal in ["activate", "popup-menu"] { + let menu = menu.clone(); + icon.connect_local(signal, false, move |arguments| { + let icon = arguments[0].get::().expect("GtkStatusIcon signal instance"); + let button = arguments.get(1).and_then(|value| value.get::().ok()).unwrap_or(0); + let time = arguments + .get(2) + .and_then(|value| value.get::().ok()) + .unwrap_or_else(gtk::current_event_time); + popup(&icon, &menu.borrow(), button, time); + None + }); + } + + let (requests, mut input) = tokio::sync::mpsc::channel(8); + std::thread::Builder::new() + .name("xembed-tray-input".into()) + .spawn(move || { + for line in io::stdin().lock().lines() { + let request = line + .map_err(anyhow::Error::from) + .and_then(|line| Ok(serde_json::from_str::(&line)?)); + match request { + Ok(request) => { + if requests.blocking_send(request).is_err() { + break; + } + } + Err(error) => { + log::warn!("Could not read XEmbed tray request: {error:#}"); + break; + } + } + } + })?; + + let main_loop = glib::MainLoop::new(None, false); + let exit = main_loop.clone(); + glib::MainContext::default().spawn_local(async move { + while let Some(request) = input.recv().await { + if let Err(error) = apply(&icon, &menu, request) { + log::warn!("Could not update XEmbed tray: {error:#}"); + } + } + menu.borrow().popdown(); + icon.set_property("visible", false); + exit.quit(); + }); + main_loop.run(); + Ok(()) +} + +fn popup(icon: &StatusIcon, menu: >k::Menu, button: u32, time: u32) { + // GTK positions the menu against the plug on the panel's configured edge. + // The status icon outlives the popup and all of its positioning callbacks. + unsafe { + gtk::ffi::gtk_menu_popup( + menu.to_glib_none().0, + ptr::null_mut(), + ptr::null_mut(), + Some(position_menu), + icon.as_ptr().cast(), + button, + time, + ); + } +} + +unsafe extern "C" fn position_menu( + menu: *mut gtk::ffi::GtkMenu, + x: *mut i32, + y: *mut i32, + push_in: *mut glib::ffi::gboolean, + icon: glib::ffi::gpointer, +) { + // GtkMenu passes back the live GtkStatusIcon pointer supplied by popup. + unsafe { gtk::ffi::gtk_status_icon_position_menu(menu, x, y, push_in, icon.cast()) } +} + +fn apply(icon: &StatusIcon, menu: &RefCell, request: Request) -> anyhow::Result<()> { + let png = match request { + Request::Frame { + png, + tooltip, + menu: entries, + } => { + icon.set_property("tooltip-text", tooltip); + menu.borrow().popdown(); + *menu.borrow_mut() = build_menu(entries); + png + } + Request::Icon(png) => png, + }; + let pixbuf = gtk::gdk_pixbuf::Pixbuf::from_read(Cursor::new(png))?; + icon.set_property("pixbuf", pixbuf); + icon.set_property("visible", true); + Ok(()) +} + +fn build_menu(entries: Vec) -> gtk::Menu { + let menu = gtk::Menu::new(); + for entry in entries { + let item = match entry { + MenuEntry::Separator => gtk::SeparatorMenuItem::new().upcast(), + MenuEntry::Label(label) => { + let item = gtk::MenuItem::with_label(&label); + item.set_sensitive(false); + item + } + MenuEntry::Action { + id, + label, + enabled, + checked, + } => { + let item = if let Some(checked) = checked { + let item = gtk::CheckMenuItem::with_label(&label); + item.set_draw_as_radio(true); + item.set_active(checked); + item.upcast() + } else { + gtk::MenuItem::with_label(&label) + }; + item.set_sensitive(enabled); + item.connect_activate(move |item| { + if let Some(checked) = checked { + let item = item.downcast_ref::().expect("checkable tray item"); + // GTK toggles before this handler. Restoring the model's check emits + // activate again, so ignore the emission that restores the check. + if item.is_active() == checked { + return; + } + item.set_active(checked); + if checked { + return; + } + } + let mut output = io::stdout().lock(); + let sent = serde_json::to_writer(&mut output, &id) + .map_err(io::Error::other) + .and_then(|()| output.write_all(b"\n")) + .and_then(|()| output.flush()); + if let Err(error) = sent { + log::warn!("Could not send XEmbed tray action: {error}"); + } + }); + item + } + MenuEntry::Submenu { label, enabled, items } => { + let item = gtk::MenuItem::with_label(&label); + item.set_sensitive(enabled); + item.set_submenu(Some(&build_menu(items))); + item + } + }; + menu.append(&item); + } + menu.show_all(); + menu +} diff --git a/crates/gpapi/src/process/mod.rs b/crates/gpapi/src/process/mod.rs index 76331a6..7904317 100644 --- a/crates/gpapi/src/process/mod.rs +++ b/crates/gpapi/src/process/mod.rs @@ -39,6 +39,8 @@ pub mod rendering_recovery; #[cfg(windows)] #[path = "windows/user_process.rs"] pub mod user_process; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +pub mod xembed_tray; #[cfg(windows)] #[path = "windows/desktop_auth.rs"] diff --git a/crates/gpapi/src/process/xembed_tray.rs b/crates/gpapi/src/process/xembed_tray.rs new file mode 100644 index 0000000..c4c534d --- /dev/null +++ b/crates/gpapi/src/process/xembed_tray.rs @@ -0,0 +1,38 @@ +//! Private protocol between the desktop and its GTK 3 tray helper. +use serde::{Deserialize, Serialize}; +use std::process::Command; + +pub const OPTION: &str = "--xembed-tray"; + +pub fn command() -> Command { + let mut command = Command::new(common::binary_paths::gpgui_helper()); + command.arg(OPTION).env("GDK_BACKEND", "x11"); + command +} + +#[derive(Serialize, Deserialize)] +pub enum Request { + Frame { + png: Vec, + tooltip: String, + menu: Vec, + }, + Icon(Vec), +} + +#[derive(Serialize, Deserialize)] +pub enum MenuEntry { + Label(String), + Action { + id: String, + label: String, + enabled: bool, + checked: Option, + }, + Submenu { + label: String, + enabled: bool, + items: Vec, + }, + Separator, +} diff --git a/packaging/aur/globalprotect-openconnect-git/PKGBUILD b/packaging/aur/globalprotect-openconnect-git/PKGBUILD index 0891833..227426c 100644 --- a/packaging/aur/globalprotect-openconnect-git/PKGBUILD +++ b/packaging/aur/globalprotect-openconnect-git/PKGBUILD @@ -47,4 +47,6 @@ package() { cd "${_pkgname_prefix}" DESTDIR="$pkgdir" make install + install -d "$pkgdir/usr/share/gpclient" + install -m 644 packaging/files/usr/share/gpclient/i3.conf "$pkgdir/usr/share/gpclient/" } diff --git a/packaging/files/usr/share/gpclient/i3.conf b/packaging/files/usr/share/gpclient/i3.conf new file mode 100644 index 0000000..9bd22b3 --- /dev/null +++ b/packaging/files/usr/share/gpclient/i3.conf @@ -0,0 +1 @@ +for_window [class="^(gpgui-nsh|Gpgui)$"] floating enable, move position center diff --git a/packaging/pkgbuild/PKGBUILD.in b/packaging/pkgbuild/PKGBUILD.in index a868e97..b7785b7 100644 --- a/packaging/pkgbuild/PKGBUILD.in +++ b/packaging/pkgbuild/PKGBUILD.in @@ -34,4 +34,6 @@ package() { cd "$pkgname-$pkgver" make install DESTDIR="$pkgdir" + install -d "$pkgdir/usr/share/gpclient" + install -m 644 packaging/files/usr/share/gpclient/i3.conf "$pkgdir/usr/share/gpclient/" }