feat: support system and explicit themes in GUI download helper

This commit is contained in:
Kevin Yue committed 2026-11-05 14:24:02 +08:00
1 parent 0212b7ff91
commit b26a416f45
18 files changed
+338 -51

No files matched your search

+33 -4
View File
@@ -1,7 +1,36 @@
# Tauri + React + Typescript
# GP Connect download helper
This template should help get you started developing with Tauri, React and Typescript in Vite.
The desktop supervisor launches this window when the selected GUI is missing or
has an incompatible version. It downloads the selected Tauri or Native Shell
interface and requests installation through the service. Launches require the
existing service credential and lifetime channel on stdin.
## Recommended IDE Setup
## Appearance
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
`--theme system|light|dark` controls this window only. The default is `system`,
which follows system appearance and changes while the window is open. Explicit
`light` and `dark` modes override system appearance for that launch. Nothing is
saved by the helper.
Initial downloads follow the system. During Linux Tauri/Native Shell switches,
Desktop Core supplies the running app's saved theme choice to the supervisor,
which forwards it to the helper. There is no `--helper-theme` option on
`gpclient launch-gui`.
The native window and web content use the selected appearance before the window
is shown. Browser previews follow the system when no native mode is supplied.
## Development
```sh
pnpm build
pnpm test
```
The built `dist/` assets are tracked and must be rebuilt after frontend changes.
Run Rust checks and helper tests from the `gp` repository:
```sh
cargo check -p gpgui-helper
cargo test -p gpgui-helper --lib
```
+1
View File
@@ -0,0 +1 @@
:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--background:#f6f5f4;--foreground:#2e3436;--muted-foreground:#5e5c64;--progress-label:#3d3846;--progress-track:#d5d3d1;--progress-fill:#3584e4;--error:#9c2f2f;--button:#1c71d8;--button-hover:#1a5fb4;--button-active:#174a8b;--focus-ring:#1a5fb4}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--background:#242424;--foreground:#fff;--muted-foreground:#c0bfbc;--progress-label:#deddda;--progress-track:#454545;--progress-fill:#78aeed;--error:#ffb4ab;--button:#1c71d8;--button-hover:#3584e4;--button-active:#1a5fb4;--focus-ring:#78aeed}html,body,#root{box-sizing:border-box;-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0;overflow:hidden}body{background:var(--background);color:var(--foreground);font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}button{font:inherit}.update-window{box-sizing:border-box;background:var(--background);align-items:center;gap:15px;width:100%;height:100%;padding:16px 18px;display:flex}.update-logo{flex:none;width:48px;height:48px}.update-content,.update-status{width:100%;min-width:0}.update-title{color:var(--foreground);letter-spacing:-.01em;margin:0;font-size:16px;font-weight:600;line-height:1.25}.update-description{color:var(--muted-foreground);margin:3px 0 0;font-size:12px;line-height:1.4}.progress-summary{justify-content:space-between;align-items:baseline;gap:12px;margin-top:3px;display:flex}.progress-summary .update-description{margin:0}.progress-bar{background-color:var(--progress-track);border-radius:3px;width:100%;height:6px;margin-top:9px;position:relative;overflow:hidden}.progress-fill{background:var(--progress-fill);border-radius:3px;height:100%;transition:width .18s ease-out}.progress-bar-indeterminate .progress-fill{width:35%;animation:1.4s ease-in-out infinite progress-indeterminate}@keyframes progress-indeterminate{0%{transform:translate(-110%)}to{transform:translate(300%)}}@media (prefers-reduced-motion:reduce){.progress-fill{transition:none}.progress-bar-indeterminate .progress-fill{animation:none;transform:translate(90%)}}.progress-label{color:var(--progress-label);font-variant-numeric:tabular-nums;text-align:right;white-space:nowrap;flex:none;font-size:12px;font-weight:500}.error-status{justify-content:space-between;align-items:center;gap:16px;display:flex}.error-status .update-title{color:var(--error)}.error-copy{min-width:0}.retry-button{background:var(--button);color:#fff;cursor:default;border:0;border-radius:8px;min-width:68px;padding:4px 14px;font-size:12px;font-weight:600;line-height:1.5}.retry-button:hover{background:var(--button-hover)}.retry-button:active{background:var(--button-active)}.retry-button:focus-visible{outline:2px solid var(--focus-ring);outline-offset:2px}
-1
View File
@@ -1 +0,0 @@
html,body,#root{box-sizing:border-box;-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0;overflow:hidden}body{color:#2e3436;background:#f6f5f4;font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}button{font:inherit}.update-window{box-sizing:border-box;background:#f6f5f4;align-items:center;gap:15px;width:100%;height:100%;padding:16px 18px;display:flex}.update-logo{flex:none;width:48px;height:48px}.update-content,.update-status{width:100%;min-width:0}.update-title{color:#2e3436;letter-spacing:-.01em;margin:0;font-size:16px;font-weight:600;line-height:1.25}.update-description{color:#5e5c64;margin:3px 0 0;font-size:12px;line-height:1.4}.progress-summary{justify-content:space-between;align-items:baseline;gap:12px;margin-top:3px;display:flex}.progress-summary .update-description{margin:0}.progress-bar{background-color:#d5d3d1;border-radius:3px;width:100%;height:6px;margin-top:9px;position:relative;overflow:hidden}.progress-fill{background:#3584e4;border-radius:3px;height:100%;transition:width .18s ease-out}.progress-bar-indeterminate .progress-fill{width:35%;animation:1.4s ease-in-out infinite progress-indeterminate}@keyframes progress-indeterminate{0%{transform:translate(-110%)}to{transform:translate(300%)}}@media (prefers-reduced-motion:reduce){.progress-fill{transition:none}.progress-bar-indeterminate .progress-fill{animation:none;transform:translate(90%)}}.progress-label{color:#3d3846;font-variant-numeric:tabular-nums;text-align:right;white-space:nowrap;flex:none;font-size:12px;font-weight:500}.error-status{justify-content:space-between;align-items:center;gap:16px;display:flex}.error-status .update-title{color:#9c2f2f}.error-copy{min-width:0}.retry-button{color:#fff;cursor:pointer;background:#1c71d8;border:0;border-radius:8px;min-width:68px;padding:4px 14px;font-size:12px;font-weight:600;line-height:1.5}.retry-button:hover{background:#1a5fb4}.retry-button:active{background:#174a8b}.retry-button:focus-visible{outline-offset:2px;outline:2px solid #1a5fb4}
+12 -2
View File
@@ -2,11 +2,21 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
const theme = window.__GP_HELPER_THEME__ || "system";
const systemTheme = matchMedia("(prefers-color-scheme: dark)");
const applyTheme = () => {
document.documentElement.dataset.theme =
theme === "system" ? (systemTheme.matches ? "dark" : "light") : theme;
};
applyTheme();
if (theme === "system") systemTheme.addEventListener("change", applyTheme);
</script>
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-DFuJkDph.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPGUI Downloader</title>
<script type="module" crossorigin src="/assets/main-DZdDLhQH.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-DiWGniCh.css">
<script type="module" crossorigin src="/assets/main-BJvLW_Ih.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-CVTp2z3I.css">
</head>
<body>
<script>
+10
View File
@@ -2,6 +2,16 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
const theme = window.__GP_HELPER_THEME__ || "system";
const systemTheme = matchMedia("(prefers-color-scheme: dark)");
const applyTheme = () => {
document.documentElement.dataset.theme =
theme === "system" ? (systemTheme.matches ? "dark" : "light") : theme;
};
applyTheme();
if (theme === "system") systemTheme.addEventListener("change", applyTheme);
</script>
<link rel="icon" type="image/svg+xml" href="/src/assets/icon-small.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPGUI Downloader</title>
+1
View File
@@ -5,6 +5,7 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"test": "node --test tests/*.test.mjs",
"preview": "vite preview",
"tauri": "tauri"
},
+41 -2
View File
@@ -1,6 +1,6 @@
use std::sync::Arc;
use gpapi::service::transport::SessionCredential;
use gpapi::{gui::GuiTheme, service::transport::SessionCredential};
use log::info;
use tauri::{Listener, Manager};
use tokio::sync::watch;
@@ -12,6 +12,7 @@ pub struct App {
credential_lease: watch::Receiver<bool>,
gui_version: String,
variant: gpapi::gui::GuiVariant,
theme: GuiTheme,
}
impl App {
@@ -20,24 +21,53 @@ impl App {
credential_lease: watch::Receiver<bool>,
gui_version: &str,
variant: gpapi::gui::GuiVariant,
theme: GuiTheme,
) -> Self {
Self {
credential,
credential_lease,
gui_version: gui_version.to_string(),
variant,
theme,
}
}
pub fn run(&self) -> anyhow::Result<()> {
let gui_version = self.gui_version.clone();
let variant = self.variant;
let theme = self.theme;
let credential = Arc::clone(&self.credential);
let credential_lease = self.credential_lease.clone();
tauri::Builder::default()
.on_window_event(move |window, event| {
if theme == GuiTheme::System
&& let tauri::WindowEvent::ThemeChanged(theme) = event
&& let Some(win) = window.get_webview_window(window.label())
&& let Err(error) = win.set_background_color(Some(background_color(*theme)))
{
log::warn!("Could not update helper window background: {error}");
}
})
.setup(move |app| {
let win = app.get_webview_window("main").expect("no main window");
let native_theme = match theme {
GuiTheme::System => None,
GuiTheme::Light => Some(tauri::Theme::Light),
GuiTheme::Dark => Some(tauri::Theme::Dark),
};
let config = app
.config()
.app
.windows
.iter()
.find(|window| window.label == "main")
.expect("no main window");
let win = tauri::WebviewWindowBuilder::from_config(app, config)?
.theme(native_theme)
.initialization_script(format!("window.__GP_HELPER_THEME__ = {:?};", theme.as_str()))
.visible(false)
.build()?;
win.set_background_color(Some(background_color(win.theme()?)))?;
let _ = win.hide_menu();
let notifier = ProgressNotifier::new(win.clone());
@@ -74,6 +104,8 @@ impl App {
tokio::spawn(async move { updater.update().await });
});
win.show()?;
Ok(())
})
.run(tauri::generate_context!())?;
@@ -81,3 +113,10 @@ impl App {
Ok(())
}
}
fn background_color(theme: tauri::Theme) -> tauri::window::Color {
match theme {
tauri::Theme::Dark => tauri::window::Color(36, 36, 36, 255),
_ => tauri::window::Color(246, 245, 244, 255),
}
}
+27 -1
View File
@@ -4,6 +4,7 @@ use std::{io::Read, sync::Arc};
use anyhow::{Context, bail};
use gpapi::{
clap::InfoLevelVerbosity,
gui::GuiTheme,
service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential},
utils::env_utils,
};
@@ -32,6 +33,9 @@ struct Cli {
#[arg(long, default_value = "tauri", value_parser = ["tauri", "nsh"])]
gui_variant: String,
#[arg(long, value_enum, default_value = "system", help = "Window appearance")]
theme: GuiTheme,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
@@ -49,7 +53,13 @@ impl Cli {
variant != gpapi::gui::GuiVariant::Nsh || cfg!(target_os = "linux"),
"Native Shell is available only on Linux"
);
let app = App::new(Arc::new(credential), credential_lease, &self.gui_version, variant);
let app = App::new(
Arc::new(credential),
credential_lease,
&self.gui_version,
variant,
self.theme,
);
env_utils::patch_gui_runtime_env(false);
@@ -121,6 +131,22 @@ mod tests {
use super::*;
#[test]
fn theme_defaults_to_system_and_accepts_explicit_modes() {
assert_eq!(Cli::try_parse_from(["gpgui-helper"]).unwrap().theme, GuiTheme::System);
for (value, expected) in [
("system", GuiTheme::System),
("light", GuiTheme::Light),
("dark", GuiTheme::Dark),
] {
assert_eq!(
Cli::try_parse_from(["gpgui-helper", "--theme", value]).unwrap().theme,
expected
);
}
assert!(Cli::try_parse_from(["gpgui-helper", "--theme", "invalid"]).is_err());
}
#[test]
fn credential_lease_closes_at_eof() {
let (lease_tx, lease_rx) = watch::channel(true);
@@ -25,6 +25,7 @@
"maxWidth": 460,
"maxHeight": 104,
"label": "main",
"create": false,
"decorations": false
}
]
+44 -14
View File
@@ -1,3 +1,33 @@
:root {
color-scheme: light;
--background: #f6f5f4;
--foreground: #2e3436;
--muted-foreground: #5e5c64;
--progress-label: #3d3846;
--progress-track: #d5d3d1;
--progress-fill: #3584e4;
--error: #9c2f2f;
--button: #1c71d8;
--button-hover: #1a5fb4;
--button-active: #174a8b;
--focus-ring: #1a5fb4;
}
:root[data-theme="dark"] {
color-scheme: dark;
--background: #242424;
--foreground: #ffffff;
--muted-foreground: #c0bfbc;
--progress-label: #deddda;
--progress-track: #454545;
--progress-fill: #78aeed;
--error: #ffb4ab;
--button: #1c71d8;
--button-hover: #3584e4;
--button-active: #1a5fb4;
--focus-ring: #78aeed;
}
html,
body,
#root {
@@ -12,8 +42,8 @@ body,
}
body {
background: #f6f5f4;
color: #2e3436;
background: var(--background);
color: var(--foreground);
font-family:
Inter,
ui-sans-serif,
@@ -35,7 +65,7 @@ button {
height: 100%;
padding: 16px 18px;
gap: 15px;
background: #f6f5f4;
background: var(--background);
}
.update-logo {
@@ -52,7 +82,7 @@ button {
.update-title {
margin: 0;
color: #2e3436;
color: var(--foreground);
font-size: 16px;
font-weight: 600;
line-height: 1.25;
@@ -61,7 +91,7 @@ button {
.update-description {
margin: 3px 0 0;
color: #5e5c64;
color: var(--muted-foreground);
font-size: 12px;
line-height: 1.4;
}
@@ -85,13 +115,13 @@ button {
margin-top: 9px;
overflow: hidden;
border-radius: 3px;
background-color: #d5d3d1;
background-color: var(--progress-track);
}
.progress-fill {
height: 100%;
border-radius: 3px;
background: #3584e4;
background: var(--progress-fill);
transition: width 180ms ease-out;
}
@@ -123,7 +153,7 @@ button {
.progress-label {
flex: 0 0 auto;
color: #3d3846;
color: var(--progress-label);
font-size: 12px;
font-variant-numeric: tabular-nums;
font-weight: 500;
@@ -139,7 +169,7 @@ button {
}
.error-status .update-title {
color: #9c2f2f;
color: var(--error);
}
.error-copy {
@@ -151,23 +181,23 @@ button {
padding: 4px 14px;
border: 0;
border-radius: 8px;
background: #1c71d8;
background: var(--button);
color: #ffffff;
cursor: pointer;
cursor: default;
font-size: 12px;
font-weight: 600;
line-height: 1.5;
}
.retry-button:hover {
background: #1a5fb4;
background: var(--button-hover);
}
.retry-button:active {
background: #174a8b;
background: var(--button-active);
}
.retry-button:focus-visible {
outline: 2px solid #1a5fb4;
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
+48
View File
@@ -0,0 +1,48 @@
import { readFileSync } from "node:fs";
import { runInNewContext } from "node:vm";
import { test } from "node:test";
import assert from "node:assert/strict";
const html = readFileSync(new URL("../index.html", import.meta.url), "utf8");
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
function load(theme, dark) {
const root = { dataset: {} };
let changed;
const media = {
matches: dark,
addEventListener(event, listener) {
assert.equal(event, "change");
changed = listener;
},
};
runInNewContext(script, {
window: { __GP_HELPER_THEME__: theme },
document: { documentElement: root },
matchMedia(query) {
assert.equal(query, "(prefers-color-scheme: dark)");
return media;
},
});
return { root, change(dark) { media.matches = dark; changed?.(); } };
}
test("default and explicit system modes follow system changes before React starts", () => {
for (const theme of [undefined, "system"]) {
for (const dark of [false, true]) {
const page = load(theme, dark);
assert.equal(page.root.dataset.theme, dark ? "dark" : "light");
page.change(!dark);
assert.equal(page.root.dataset.theme, dark ? "light" : "dark");
}
}
});
test("explicit modes override opposite system appearance and ignore system changes", () => {
for (const theme of ["light", "dark"]) {
const page = load(theme, theme !== "dark");
assert.equal(page.root.dataset.theme, theme);
page.change(theme === "dark");
assert.equal(page.root.dataset.theme, theme);
}
});
+20
View File
@@ -11,6 +11,26 @@ pub enum GuiVariant {
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 {
+3 -1
View File
@@ -128,7 +128,9 @@ impl<'a> DesktopLauncher<'a> {
// the same cancellation, service ownership and recovery budget as gpgui.
let outcome = {
let attempt = async {
let program = launcher.resolve_program(&cancellation).await?;
let program = launcher
.resolve_program(&cancellation, crate::gui::GuiTheme::System)
.await?;
#[cfg(target_os = "linux")]
return launcher
.launch_with_switches(
@@ -13,6 +13,7 @@ pub struct GuiHelperLauncher<'a> {
credential: &'a SessionCredential,
gui_version: Option<&'a str>,
variant: crate::gui::GuiVariant,
theme: crate::gui::GuiTheme,
}
impl<'a> GuiHelperLauncher<'a> {
@@ -23,6 +24,7 @@ impl<'a> GuiHelperLauncher<'a> {
credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
}
}
@@ -41,6 +43,11 @@ impl<'a> GuiHelperLauncher<'a> {
self
}
pub fn theme(mut self, theme: crate::gui::GuiTheme) -> Self {
self.theme = theme;
self
}
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let mut cmd = Command::new(&self.program);
@@ -57,6 +64,9 @@ impl<'a> GuiHelperLauncher<'a> {
if let Some(gui_version) = self.gui_version {
cmd.arg("--gui-version").arg(gui_version);
}
if self.theme != crate::gui::GuiTheme::System {
cmd.arg("--theme").arg(self.theme.as_str());
}
info!("Launching gpgui-helper");
anyhow::ensure!(
@@ -93,6 +103,40 @@ mod tests {
path
}
#[tokio::test]
async fn forwards_explicit_themes_and_leaves_initial_downloads_on_system() {
use crate::gui::{GuiTheme, GuiVariant};
let dir = tempfile::TempDir::new().unwrap();
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let captured = dir.path().join("arguments");
for variant in [GuiVariant::Tauri, GuiVariant::Nsh] {
for theme in [GuiTheme::System, GuiTheme::Light, GuiTheme::Dark] {
let mut launcher = GuiHelperLauncher::new(&credential)
.variant(variant)
.gui_version(Some("test"))
.theme(theme);
launcher.program = fixture(
&dir,
&credential,
&format!("printf '%s\\n' \"$@\" > '{}'", captured.display()),
);
launcher.launch(&CancellationToken::new()).await.unwrap();
let mut expected = vec!["--service-credential-on-stdin"];
if variant == GuiVariant::Nsh {
expected.extend(["--gui-variant", "nsh"]);
}
expected.extend(["--gui-version", "test"]);
if theme != GuiTheme::System {
expected.extend(["--theme", theme.as_str()]);
}
assert_eq!(
std::fs::read_to_string(&captured).unwrap().lines().collect::<Vec<_>>(),
expected
);
}
}
}
#[tokio::test]
async fn propagates_helper_failure_and_preserves_stderr_in_desktop_log() {
let dir = tempfile::TempDir::new().unwrap();
@@ -107,6 +151,7 @@ mod tests {
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
@@ -134,6 +179,7 @@ mod tests {
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
let eligible =
@@ -156,6 +202,7 @@ mod tests {
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let cancellation = CancellationToken::new();
let attempt = launcher.launch(&cancellation);
+21 -7
View File
@@ -51,7 +51,11 @@ impl<'a> GuiLauncher<'a> {
self
}
pub(crate) async fn resolve_program(&self, cancellation: &CancellationToken) -> anyhow::Result<PathBuf> {
pub(crate) async fn resolve_program(
&self,
cancellation: &CancellationToken,
helper_theme: crate::gui::GuiTheme,
) -> anyhow::Result<PathBuf> {
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
@@ -59,7 +63,7 @@ impl<'a> GuiLauncher<'a> {
if let Some(program) = self.find_compatible_program(cancellation).await? {
return Ok(program);
}
self.download_program(cancellation).await?;
self.download_program(cancellation, helper_theme).await?;
let program = self.variant.update_target();
tokio::select! {
biased;
@@ -139,13 +143,18 @@ impl<'a> GuiLauncher<'a> {
Ok(())
}
async fn download_program(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
async fn download_program(
&self,
cancellation: &CancellationToken,
theme: crate::gui::GuiTheme,
) -> anyhow::Result<()> {
let gui_helper = GuiHelperLauncher::new(&self.credential);
gui_helper
.envs(self.envs.as_ref())
.gui_version(Some(self.version))
.variant(self.variant)
.theme(theme)
.launch(cancellation)
.await
}
@@ -177,7 +186,8 @@ impl<'a> GuiLauncher<'a> {
let (mut socket, _) = accepted?;
let mut pending = false;
let replacement = async {
let selection = gui_switch::receive(&mut socket).await?;
let command = gui_switch::receive(&mut socket).await?;
let selection = command.selection;
let variant = selection.variant;
let candidate = Self::new(self.version, self.credential.clone(), variant).envs(self.envs.clone());
let program = candidate.find_compatible_program(cancellation).await?;
@@ -210,7 +220,7 @@ impl<'a> GuiLauncher<'a> {
.minimized(false);
let program = match program {
Some(program) => program,
None => launcher.resolve_program(cancellation).await?,
None => launcher.resolve_program(cancellation, command.theme).await?,
};
let mut child = launcher.start_owned(program, cancellation.child_token());
let start_result = tokio::select! {
@@ -401,7 +411,7 @@ mod tests {
}
let launcher = launcher(VERSION, vec![first, second]);
let cancellation = CancellationToken::new();
let attempt = launcher.resolve_program(&cancellation);
let attempt = launcher.resolve_program(&cancellation, crate::gui::GuiTheme::System);
tokio::pin!(attempt);
tokio::select! {
result = &mut attempt => panic!("version probe exited early: {result:?}"),
@@ -602,7 +612,10 @@ mod tests {
crate::gui::save_preference(crate::gui::GuiVariant::Nsh).unwrap();
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap());
let selected = GuiLauncher::new(VERSION, credential, crate::gui::preferred().unwrap());
let program = selected.resolve_program(&CancellationToken::new()).await.unwrap();
let program = selected
.resolve_program(&CancellationToken::new(), crate::gui::GuiTheme::System)
.await
.unwrap();
assert_eq!(program.file_name().unwrap(), "gpgui-nsh");
}
@@ -707,6 +720,7 @@ mod tests {
variant: crate::gui::GuiVariant::Nsh,
allow_download: scenario == "runtime-too-old-confirmed",
},
crate::gui::GuiTheme::System,
)
.await;
if runtime_too_old {
+28 -18
View File
@@ -6,7 +6,15 @@ use tokio::{
net::{UnixListener, UnixStream},
};
use crate::gui::{GuiSwitchOutcome, GuiSwitchRequest};
use crate::gui::{GuiSwitchOutcome, GuiSwitchRequest, GuiTheme};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct SwitchCommand {
#[serde(flatten)]
pub selection: GuiSwitchRequest,
#[serde(default)]
pub theme: GuiTheme,
}
pub(crate) const SOCKET_ENV: &str = "GP_DESKTOP_CONTROL_SOCKET";
pub(crate) const READY_ENV: &str = "GP_DESKTOP_READY_SOCKET";
@@ -22,19 +30,22 @@ pub fn notify_ready() -> anyhow::Result<()> {
Ok(())
}
pub async fn request(selection: GuiSwitchRequest) -> anyhow::Result<GuiSwitchOutcome> {
pub async fn request(selection: GuiSwitchRequest, theme: GuiTheme) -> anyhow::Result<GuiSwitchOutcome> {
let path = std::env::var_os(SOCKET_ENV).context("GUI switching requires a desktop supervisor")?;
request_at(std::path::Path::new(&path), selection).await
request_at(std::path::Path::new(&path), selection, theme).await
}
pub(super) async fn request_at(
path: &std::path::Path,
selection: GuiSwitchRequest,
theme: GuiTheme,
) -> anyhow::Result<GuiSwitchOutcome> {
let mut socket = UnixStream::connect(path)
.await
.context("Could not contact the desktop supervisor")?;
socket.write_all(&serde_json::to_vec(&selection)?).await?;
socket
.write_all(&serde_json::to_vec(&SwitchCommand { selection, theme })?)
.await?;
socket.shutdown().await?;
let mut reply = Vec::new();
socket.take(4096).read_to_end(&mut reply).await?;
@@ -74,7 +85,7 @@ impl SwitchListener {
}
}
pub(crate) async fn receive(socket: &mut UnixStream) -> anyhow::Result<GuiSwitchRequest> {
pub(crate) async fn receive(socket: &mut UnixStream) -> anyhow::Result<SwitchCommand> {
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
@@ -107,22 +118,21 @@ mod tests {
let control = SwitchListener::new().unwrap();
let path = control.path();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let client = tokio::spawn(async move {
let mut socket = UnixStream::connect(path).await.unwrap();
socket
.write_all(&serde_json::to_vec(&selection).unwrap())
.await
.unwrap();
socket.shutdown().await.unwrap();
let mut reply = Vec::new();
socket.read_to_end(&mut reply).await.unwrap();
serde_json::from_slice::<Result<GuiSwitchOutcome, String>>(&reply).unwrap()
});
let client = tokio::spawn(async move { request_at(&path, selection, GuiTheme::Dark).await });
let (mut socket, _) = control.listener.accept().await.unwrap();
assert_eq!(receive(&mut socket).await.unwrap(), selection);
assert_eq!(
receive(&mut socket).await.unwrap(),
SwitchCommand {
selection,
theme: GuiTheme::Dark
}
);
reply(&mut socket, Err("Selected GUI could not start".into()))
.await
.unwrap();
assert_eq!(client.await.unwrap().unwrap_err(), "Selected GUI could not start");
assert_eq!(
client.await.unwrap().unwrap_err().to_string(),
"Selected GUI could not start"
);
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod desktop_launcher;
pub mod gui_launcher;
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", test))]
pub mod gui_switch;
#[cfg(any(target_os = "linux", test))]
mod nsh_runtime;