дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Auxiliary windows (diff, comparison, editor, Sync with Deployed) boot a fixed set of features, so application actions they never register looked enabled in the menu but did nothing, some key equivalents were dropped because the page appeared to decline them, and Sync with Deployed had no menu bridge. Application actions now run in the project window (raised when it shows their result), Toggle Full Screen stays in the focused window, and menu enablement is cached per window so parent-routed items follow the destination window's state. Supersedes #7280. Co-authored-by: albince-mi <[email protected]> Co-authored-by: arookieofc-ai <[email protected]>
1192 рядки
45 KiB
Rust
1192 рядки
45 KiB
Rust
//! Desktop shell: project windows, native menu, quit flow, logs, updates.
|
||
|
||
use crate::menu::{self, MenuConfig, MenuState};
|
||
use crate::state::AppState;
|
||
use crate::windows::{self, Launch, OpenOutcome, WindowsState};
|
||
use ide_command::desktop_command;
|
||
use ide_core::{IdeError, IdeResult, RequestId};
|
||
use serde::{Deserialize, Serialize};
|
||
use specta::Type;
|
||
use std::collections::BTreeMap;
|
||
use std::path::PathBuf;
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
use tauri::ipc::Channel;
|
||
use tauri::{AppHandle, State, WebviewWindow, Window};
|
||
|
||
/// Opens `path` in a new window (`new_window`) or tells the caller to open it
|
||
/// itself (`current`). A project already open in some window is focused instead.
|
||
/// `files` then open in that project's editor. When `in_tab` is true, the opened
|
||
/// or focused window joins this window's tab group directly without flashing as
|
||
/// a separate window.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_project(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
path: PathBuf,
|
||
new_window: bool,
|
||
files: Vec<PathBuf>,
|
||
in_tab: bool,
|
||
) -> IdeResult<OpenOutcome> {
|
||
let tab_anchor = in_tab.then(|| window.label());
|
||
let outcome = windows::open_project_window(&app, &path, new_window, files, tab_anchor)?;
|
||
if tab_anchor.is_some() && !matches!(outcome, OpenOutcome::Current) {
|
||
crate::window_groups::persist(&app).await?;
|
||
}
|
||
Ok(outcome)
|
||
}
|
||
|
||
/// Loose `files` opened from a window without a local project: a file inside a local project
|
||
/// open in some window goes to that window, the others to the LightEdit window (this one,
|
||
/// another, or a new one from a remote project window). Returns the files this window opens
|
||
/// itself, in LightEdit.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_files(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
files: Vec<PathBuf>,
|
||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||
Ok(windows::open_files_window(&app, window.label(), files))
|
||
}
|
||
|
||
/// Detaches an editor tab: opens `file` in a forced new window (`project`, None
|
||
/// for LightEdit, decided by the caller), bypassing the focus-an-existing-window
|
||
/// routing of [`window_open_project`] / [`window_open_files`].
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_file_in_new_window(
|
||
app: AppHandle,
|
||
project: Option<PathBuf>,
|
||
file: PathBuf,
|
||
) -> IdeResult<OpenOutcome> {
|
||
windows::open_file_in_new_window(&app, project, file)
|
||
}
|
||
|
||
/// [`window_open_project`] for folder `path` of `target` (an SSH host or a WSL distribution;
|
||
/// Remote Development); a new window connects itself.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_remote(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
target: crate::remote_dev::RemoteTarget,
|
||
path: String,
|
||
new_window: bool,
|
||
in_tab: bool,
|
||
) -> IdeResult<OpenOutcome> {
|
||
let tab_anchor = in_tab.then(|| window.label());
|
||
let outcome = windows::open_remote_window(&app, &target, &path, new_window, tab_anchor)?;
|
||
if tab_anchor.is_some() && !matches!(outcome, OpenOutcome::Current) {
|
||
crate::window_groups::persist(&app).await?;
|
||
}
|
||
Ok(outcome)
|
||
}
|
||
|
||
/// Opens an empty (welcome) window; returns its label.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_new(app: AppHandle) -> IdeResult<String> {
|
||
windows::create_window(&app, None).map(|w| w.label().to_owned())
|
||
}
|
||
|
||
/// Opens this window's Settings window on `page` (or focuses it and navigates);
|
||
/// `new_projects` edits the global layer only ("Settings for New Projects").
|
||
/// `background` (`#rrggbb`) paints a new window until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_settings(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
page: Option<String>,
|
||
new_projects: bool,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_settings_window(&app, &window, page, new_projects, background)
|
||
}
|
||
|
||
/// Opens a window listing the files that differ between two revisions of this window's project.
|
||
/// `background` (`#rrggbb`) paints it until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_comparison(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
comparison: windows::ComparisonLaunch,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_comparison_window(&app, &window, comparison, background)
|
||
}
|
||
|
||
/// Opens a window showing `diff` next to this window ("Show Diff in New Window").
|
||
/// `background` (`#rrggbb`) paints it until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_diff(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
diff: windows::DiffLaunch,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_diff_window(&app, &window, diff, background)
|
||
}
|
||
|
||
/// Opens a lightweight editor window for `editor` next to this project window ("Open in New Window").
|
||
/// `background` (`#rrggbb`) paints it until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_editor(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
editor: windows::EditorLaunch,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_editor_window(&app, &window, editor, background)
|
||
}
|
||
|
||
/// Opens this window's Sync with Deployed window comparing `paths` with `server` (or hands them
|
||
/// to the open one). `background` (`#rrggbb`) paints a new window until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_deployment(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
server: String,
|
||
paths: Vec<PathBuf>,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_deployment_window(&app, &window, server, paths, background)
|
||
}
|
||
|
||
/// Opens this window's New Project window (or focuses it). `background` (`#rrggbb`) paints a new
|
||
/// window until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_new_project(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_new_project_window(&app, &window, background)
|
||
}
|
||
|
||
/// Opens this window's Get from VCS window (or focuses it), filling in `url` when given.
|
||
/// `background` (`#rrggbb`) paints a new window until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_clone(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
url: Option<String>,
|
||
background: Option<String>,
|
||
) -> IdeResult<()> {
|
||
windows::open_clone_window(&app, &window, url, background)
|
||
}
|
||
|
||
/// Opens this window's Remote Development window (or focuses it). `background` (`#rrggbb`)
|
||
/// paints a new window until its page has loaded.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_open_connect(app: AppHandle, window: WebviewWindow, background: Option<String>) -> IdeResult<()> {
|
||
windows::open_connect_window(&app, &window, background)
|
||
}
|
||
|
||
/// Focuses the next / previous window (⌘` / ⇧⌘`).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_cycle(app: AppHandle, window: WebviewWindow, forward: bool) {
|
||
windows::cycle(&app, window.label(), forward);
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
|
||
crate::window_groups::toggle_fullscreen(&window)
|
||
}
|
||
|
||
/// Fills the work area without the platform zoom animation. Returns whether it is filled now.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_toggle_zoom(window: WebviewWindow) -> IdeResult<bool> {
|
||
crate::window_zoom::toggle(&window)
|
||
}
|
||
|
||
/// Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a
|
||
/// breakpoint is hit while the window is in the background (macOS bounces the dock icon,
|
||
/// Linux sets the urgency hint). A focused window is never flashed: the user is already
|
||
/// looking at it, and re-flashing it would steal attention for nothing.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()> {
|
||
if flash && window.is_focused().unwrap_or(false) {
|
||
return Ok(());
|
||
}
|
||
window
|
||
.request_user_attention(flash.then_some(tauri::UserAttentionType::Critical))
|
||
.map_err(|e| IdeError::internal(e.to_string()))
|
||
}
|
||
|
||
/// Appearance › Smooth scrolling for this window's web view (Linux only)
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
|
||
#[cfg(target_os = "linux")]
|
||
#[allow(clippy::disallowed_methods)]
|
||
window
|
||
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
|
||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||
#[cfg(not(target_os = "linux"))]
|
||
let _ = (window, enabled);
|
||
Ok(())
|
||
}
|
||
|
||
/// Height of the web title bar in native logical pixels (CSS height × IDE zoom).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_set_titlebar_height(window: WebviewWindow, height: f64) -> IdeResult<()> {
|
||
if !height.is_finite() || !(1.0..=1000.0).contains(&height) {
|
||
return Err(IdeError::invalid("invalid title bar height"));
|
||
}
|
||
#[cfg(target_os = "macos")]
|
||
crate::titlebar::set_height(&window, height).map_err(|e| IdeError::internal(e.to_string()))?;
|
||
#[cfg(not(target_os = "macos"))]
|
||
let _ = window;
|
||
Ok(())
|
||
}
|
||
|
||
/// What this window was opened for (taken once).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> Option<Launch> {
|
||
windows.take_launch(window.label())
|
||
}
|
||
|
||
#[derive(Serialize, Deserialize, Type)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct SettingsWindowInit {
|
||
pub launch: Option<Launch>,
|
||
pub remote: Option<crate::remote_dev::RemoteSession>,
|
||
pub project: Option<ide_host::ops::project::ProjectInfo>,
|
||
pub global_settings: ide_core::settings::Settings,
|
||
pub updates: bool,
|
||
}
|
||
|
||
/// Local bootstrap snapshot for a `settings-<parent>` window, avoiding a sequential
|
||
/// startup IPC waterfall and any blocking SSH `project_current` round-trip before first paint.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_take_settings_init(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
windows: State<'_, WindowsState>,
|
||
state: State<'_, AppState>,
|
||
) -> SettingsWindowInit {
|
||
let owner = AppState::owner_window(window.label());
|
||
let launch = windows.take_launch(window.label());
|
||
let (remote, project) = if let Some(c) = state.remote_dev.get(owner) {
|
||
// Leave `project` empty on remote sessions: the Settings page tree renders immediately
|
||
// from local client settings, and `projectCurrent()` fills in project-scoped settings
|
||
// right after first paint without keeping a shadow cache in sync.
|
||
(Some(c.snapshot()), None)
|
||
} else {
|
||
let project = state.project(owner).ok().filter(|p| !p.light).map(|p| ide_host::ops::project::info(&p));
|
||
(None, project)
|
||
};
|
||
SettingsWindowInit {
|
||
launch,
|
||
remote,
|
||
project,
|
||
global_settings: state.host.with_proxy_password(state.global_settings.effective()),
|
||
updates: updates_configured(&app),
|
||
}
|
||
}
|
||
|
||
/// Release the opening window's reservation after navigation or cancellation.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_complete_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
|
||
windows.complete_launch(window.label());
|
||
Ok(())
|
||
}
|
||
|
||
#[derive(Serialize, Deserialize, Type)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct OpenProject {
|
||
pub name: String,
|
||
pub root: PathBuf,
|
||
/// Open in the calling window.
|
||
pub current: bool,
|
||
/// Where the project lives when the window is connected to a remote host (`root` is then a path there).
|
||
pub remote: Option<crate::remote_dev::RemoteTarget>,
|
||
}
|
||
|
||
/// Projects open in project windows, in window order (title bar project widget).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_open_projects(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
state: State<'_, AppState>,
|
||
) -> IdeResult<Vec<OpenProject>> {
|
||
Ok(windows::project_window_labels(&app)
|
||
.into_iter()
|
||
.filter_map(|label| {
|
||
let current = label == window.label();
|
||
// A remote window's project lives on the server: it has no local project here.
|
||
if let Some(c) = state.remote_dev.get(&label) {
|
||
let root = PathBuf::from(&c.root);
|
||
let name = c.root.trim_end_matches('/').rsplit('/').next().unwrap_or_default().to_owned();
|
||
return Some(OpenProject { name, root, current, remote: Some(c.target.clone()) });
|
||
}
|
||
let project = state.project(&label).ok().filter(|p| !p.light)?;
|
||
Some(OpenProject {
|
||
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||
root: project.root.clone(),
|
||
current,
|
||
remote: None,
|
||
})
|
||
})
|
||
.collect())
|
||
}
|
||
|
||
/// Whether this window is in native full screen (on macOS, also a tab of a fullscreen group).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_is_fullscreen(window: WebviewWindow) -> bool {
|
||
window.is_fullscreen().unwrap_or(false)
|
||
}
|
||
|
||
#[derive(Serialize, Deserialize, Type)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct CloseContext {
|
||
/// Quit is in progress (exit was already confirmed).
|
||
pub quitting: bool,
|
||
/// Number of open project windows (settings windows excluded), including the caller.
|
||
pub windows: u32,
|
||
/// Whether this window currently has auxiliary document windows that must settle first.
|
||
pub has_document_windows: bool,
|
||
/// Whether this close runs alongside other windows or on a background tab (prompts serialize and raise).
|
||
pub batch: bool,
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_close_context(app: AppHandle, window: Window, windows: State<'_, WindowsState>) -> CloseContext {
|
||
let all = windows::project_window_labels(&app);
|
||
let pending: Vec<String> = windows::sorted_labels(
|
||
windows.pending_closes().iter().map(String::as_str).filter(|l| all.iter().any(|a| a == l)),
|
||
);
|
||
// Members of a tab group asking to close together are one window closing: the first of them
|
||
// is the last window left (the frontend may return it to the welcome screen); the others just close.
|
||
let count = match pending.first() {
|
||
Some(keeper) if pending.len() > 1 && keeper == window.label() => all.len() - pending.len() + 1,
|
||
_ => all.len(),
|
||
};
|
||
let quitting = windows.quitting();
|
||
let has_document_windows = !windows::document_windows(&app, window.label()).is_empty();
|
||
// AppKit can deliver the selected tab's close before its siblings have registered theirs.
|
||
let grouped = windows.groups.lock().group(window.label()).is_some();
|
||
let batch = quitting || pending.len() > 1 || windows.in_tab_close_batch(window.label()) || grouped;
|
||
CloseContext { quitting, windows: count as u32, has_document_windows, batch }
|
||
}
|
||
|
||
/// Acquires the interactive prompt turn for a batch close and brings this window forward.
|
||
/// Returns `false` if the batch was cancelled while waiting.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_begin_prompt(app: AppHandle, window: WebviewWindow) -> bool {
|
||
crate::window_groups::begin_prompt(&app, &window).await
|
||
}
|
||
|
||
/// Releases the interactive prompt turn held by this window.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn window_end_prompt(app: AppHandle, window: Window) {
|
||
crate::window_groups::end_prompt(&app, window.label());
|
||
}
|
||
|
||
/// Signals that this window passed its close checks and waits for peers closing in the same
|
||
/// batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn window_ready_to_close(app: AppHandle, window: WebviewWindow) -> bool {
|
||
crate::window_groups::ready_to_close(&app, &window).await
|
||
}
|
||
|
||
/// Quits: closes every window in parallel, each of which runs its own unsaved-changes check.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_quit(app: AppHandle, windows: State<'_, WindowsState>) {
|
||
if windows.quitting() {
|
||
return;
|
||
}
|
||
windows.set_quitting(true);
|
||
windows::start_quit(&app);
|
||
}
|
||
|
||
/// A window vetoed the quit (user cancelled its unsaved-changes prompt).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_cancel_quit(app: AppHandle, window: Window, windows: State<'_, WindowsState>) {
|
||
windows.set_quitting(false);
|
||
windows.abort_all_closing(Some(window.label()));
|
||
windows.close_settled(window.label());
|
||
tauri::async_runtime::spawn(async move {
|
||
let _ = crate::window_groups::persist(&app).await;
|
||
});
|
||
}
|
||
|
||
/// Sets the menu's labels / accelerators and updates the menu when the visible
|
||
/// items changed. Accelerators of actions that are not on the menu must not call
|
||
/// `set_menu`, which redraws the macOS menu bar.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn menu_configure(
|
||
window: WebviewWindow,
|
||
app: AppHandle,
|
||
menu_state: State<'_, MenuState>,
|
||
state: State<'_, AppState>,
|
||
config: MenuConfig,
|
||
) {
|
||
if menu::native_menu_bar()
|
||
&& windows::target_window(&app).is_some_and(|target| !owns_menu_config(window.label(), target.label()))
|
||
{
|
||
return;
|
||
}
|
||
if menu::store_config(&menu_state, config) {
|
||
menu::install(&app, &menu_state, &state.recent.list());
|
||
}
|
||
}
|
||
|
||
fn owns_menu_config(source: &str, target: &str) -> bool {
|
||
let owner = match windows::auxiliary(target) {
|
||
Some((kind, parent)) if kind.runs_menu_in_parent() => parent,
|
||
_ => target,
|
||
};
|
||
source == owner
|
||
}
|
||
|
||
/// Updates the menu after the recent-projects list changed. Only the Open Recent
|
||
/// submenu is rewritten when the rest of the menu is unchanged.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn menu_refresh(app: AppHandle, menu_state: State<'_, MenuState>, state: State<'_, AppState>) {
|
||
menu::install(&app, &menu_state, &state.recent.list());
|
||
}
|
||
|
||
/// The menu bar for a title bar drawn by the frontend (Windows).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<'_, MenuState>) -> Vec<menu::MenuNode> {
|
||
let mut spec = menu::spec(menu::Os::current());
|
||
if !updates_configured(&app) {
|
||
spec = menu::without_action(spec, "app.checkForUpdates");
|
||
}
|
||
let home = dirs::home_dir();
|
||
let config = menu_state.config.lock().clone();
|
||
let spec = menu::without_hidden(spec, &config);
|
||
let remote = menu_state.remote_recent.lock().clone();
|
||
menu::model(&spec, &menu::recent_items(&state.recent.list(), &remote, home.as_deref()), &config)
|
||
}
|
||
|
||
/// The Remote Development projects of the frontend's recent list, for Open Recent.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn menu_set_remote_recent(
|
||
app: AppHandle,
|
||
menu_state: State<'_, MenuState>,
|
||
state: State<'_, AppState>,
|
||
projects: Vec<menu::RemoteRecent>,
|
||
) {
|
||
if menu::store_remote_recent(&menu_state, projects) {
|
||
menu::install(&app, &menu_state, &state.recent.list());
|
||
}
|
||
}
|
||
|
||
/// Action ids the focused window cannot run now: their native menu items are
|
||
/// disabled in place (no rebuild).
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn menu_set_disabled(window: WebviewWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
|
||
let source = window.label().to_owned();
|
||
let focused = windows::target_window(&app).map(|w| w.label().to_owned()).unwrap_or_else(|| source.clone());
|
||
let disabled = {
|
||
let mut by_window = menu_state.disabled_by_window.lock();
|
||
by_window.insert(source, ids.into_iter().collect());
|
||
windows::effective_menu_disabled(&focused, &by_window)
|
||
};
|
||
if *menu_state.disabled.lock() == disabled {
|
||
return;
|
||
}
|
||
*menu_state.disabled.lock() = disabled.clone();
|
||
if menu::native_menu_bar() {
|
||
menu::apply_disabled(&app, &disabled);
|
||
}
|
||
}
|
||
|
||
#[derive(Serialize, Deserialize, Type)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct LogLocation {
|
||
pub dir: ide_core::IpcPath,
|
||
/// Current log file, if one was written yet.
|
||
pub file: Option<ide_core::IpcPath>,
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_log_location() -> IdeResult<LogLocation> {
|
||
let dir = crate::logging::log_dir().ok_or_else(|| IdeError::unavailable("file logging is not active"))?;
|
||
Ok(LogLocation { dir: dir.into(), file: crate::logging::latest_log(dir).map(Into::into) })
|
||
}
|
||
|
||
#[derive(Serialize, Deserialize, Type)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct CliInstallation {
|
||
pub path: ide_core::IpcPath,
|
||
pub path_directory: Option<ide_core::IpcPath>,
|
||
}
|
||
|
||
/// Installs the `openidea` command for this user.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn app_cli_install() -> IdeResult<CliInstallation> {
|
||
tauri::async_runtime::spawn_blocking(crate::cli::install).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||
}
|
||
|
||
/// Removes the installed `openidea` command; returns the links removed.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn app_cli_uninstall() -> IdeResult<Vec<ide_core::IpcPath>> {
|
||
tauri::async_runtime::spawn_blocking(crate::cli::uninstall).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||
}
|
||
|
||
#[derive(Serialize, Deserialize, Type)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct BuildInfo {
|
||
pub version: String,
|
||
/// Build id from CI (`OPENIDEA_BUILD` at compile time), else `dev`.
|
||
pub build: String,
|
||
pub profile: String,
|
||
pub os: String,
|
||
pub arch: String,
|
||
pub tauri: String,
|
||
/// An update endpoint is configured ("Check for Updates…" is offered).
|
||
pub updates: bool,
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_build_info(app: AppHandle) -> BuildInfo {
|
||
BuildInfo {
|
||
version: env!("CARGO_PKG_VERSION").into(),
|
||
build: option_env!("OPENIDEA_BUILD").unwrap_or("dev").into(),
|
||
profile: if cfg!(debug_assertions) { "debug" } else { "release" }.into(),
|
||
os: std::env::consts::OS.into(),
|
||
arch: std::env::consts::ARCH.into(),
|
||
tauri: tauri::VERSION.into(),
|
||
updates: updates_configured(&app),
|
||
}
|
||
}
|
||
|
||
use ide_core::updates::UpdateInfo;
|
||
pub use ide_core::updates::{UpdateChannel, UpdateCheck, UpdateSource, UpdateStatus};
|
||
|
||
pub(crate) fn update_endpoint_env() -> Option<String> {
|
||
std::env::var("OPENIDEA_UPDATE_ENDPOINT").ok().filter(|s| !s.trim().is_empty())
|
||
}
|
||
|
||
/// Whether an update endpoint is configured: `plugins.updater.endpoints` in
|
||
/// tauri.conf.json, or the `OPENIDEA_UPDATE_ENDPOINT` environment variable. Empty by
|
||
/// default, and "Check for Updates…" is hidden then.
|
||
pub fn updates_configured<R: tauri::Runtime>(app: &AppHandle<R>) -> bool {
|
||
!config_endpoints(app).is_empty() || update_endpoint_env().is_some()
|
||
}
|
||
|
||
const CNB_ENDPOINT: &str = "https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json";
|
||
|
||
fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
|
||
app.config()
|
||
.plugins
|
||
.0
|
||
.get("updater")
|
||
.and_then(|u| u.get("endpoints"))
|
||
.and_then(|e| e.as_array())
|
||
.map(|e| e.iter().filter_map(|u| u.as_str().map(String::from)).collect())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
/// The Stable channel's GitHub manifest, `plugins.updater.endpoints` of a stable build.
|
||
const STABLE_ENDPOINT: &str = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json";
|
||
/// The Nightly channel's manifest, which `scripts/nightly-prepare.ts` writes into a nightly build.
|
||
const NIGHTLY_ENDPOINT: &str = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json";
|
||
|
||
/// The endpoints tried in order. The build's configured endpoint serves its own channel and
|
||
/// the other channel's manifest is the official one. Stable tries `source` first and the other
|
||
/// source when it fails or has no manifest; Nightly is on GitHub only, as the CNB mirror carries
|
||
/// stable releases. Bundles of both channels are signed with one key, so any of them verifies.
|
||
/// No configured endpoint (a build without updates) means no endpoint at all.
|
||
fn source_endpoints(official: Vec<String>, channel: UpdateChannel, source: UpdateSource, version: &str) -> Vec<String> {
|
||
if official.is_empty() {
|
||
return official;
|
||
}
|
||
let github = if channel == UpdateChannel::of_version(version) {
|
||
official
|
||
} else {
|
||
vec![
|
||
match channel {
|
||
UpdateChannel::Stable => STABLE_ENDPOINT,
|
||
UpdateChannel::Nightly => NIGHTLY_ENDPOINT,
|
||
}
|
||
.to_string(),
|
||
]
|
||
};
|
||
let mirror = vec![CNB_ENDPOINT.to_string()];
|
||
match (channel, source) {
|
||
(UpdateChannel::Nightly, _) => github,
|
||
(UpdateChannel::Stable, UpdateSource::Github) => [github, mirror].concat(),
|
||
(UpdateChannel::Stable, UpdateSource::Cnb) => [mirror, github].concat(),
|
||
}
|
||
}
|
||
|
||
/// `OPENIDEA_UPDATE_ENDPOINT` when set, which overrides both channels; else the endpoints of
|
||
/// the configured channel and `source`.
|
||
fn update_endpoints(app: &AppHandle, source: UpdateSource) -> Vec<String> {
|
||
use tauri::Manager;
|
||
match update_endpoint_env() {
|
||
Some(url) => vec![url],
|
||
None => source_endpoints(
|
||
config_endpoints(app),
|
||
crate::updates::configured_channel(&app.state::<AppState>()),
|
||
source,
|
||
env!("CARGO_PKG_VERSION"),
|
||
),
|
||
}
|
||
}
|
||
|
||
/// Bounds connection establishment (TCP and TLS) for the updater. reqwest divides this
|
||
/// across a host's resolved addresses, so a CDN hostname with four A records gets about
|
||
/// 3.75s each — enough for a slow link, while still leaving the 60s check budget intact.
|
||
const UPDATER_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||
|
||
fn configure_updater_client(
|
||
builder: reqwest::ClientBuilder,
|
||
proxy: &ide_core::proxy_settings::ProxySettings,
|
||
) -> reqwest::ClientBuilder {
|
||
ide_http::client::with_proxy(builder, proxy).connect_timeout(UPDATER_CONNECT_TIMEOUT)
|
||
}
|
||
|
||
pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
|
||
use tauri_plugin_updater::UpdaterExt;
|
||
if !updates_configured(app) {
|
||
return Ok(None);
|
||
}
|
||
let endpoints = update_endpoints(app, source)
|
||
.iter()
|
||
.map(|u| u.parse().map_err(|e| IdeError::invalid(format!("update endpoint {u}: {e}"))))
|
||
.collect::<IdeResult<Vec<_>>>()?;
|
||
let proxy = ide_core::proxy_settings::proxy();
|
||
let mut builder = app.updater_builder();
|
||
if let Some(target) = crate::updates::portable_target(
|
||
std::env::consts::OS,
|
||
std::env::consts::ARCH,
|
||
tauri::utils::platform::bundle_type(),
|
||
) {
|
||
builder = builder.target(target);
|
||
}
|
||
builder
|
||
.configure_client(move |b| configure_updater_client(b, &proxy))
|
||
.endpoints(endpoints)
|
||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||
.build()
|
||
.map(Some)
|
||
.map_err(|e| IdeError::unavailable(e.to_string()))
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn app_check_update(app: AppHandle, source: UpdateSource) -> IdeResult<UpdateCheck> {
|
||
crate::updates::check(&app, Some(source)).await
|
||
}
|
||
|
||
pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeResult<UpdateCheck> {
|
||
let Some(updater) = updater(app, source)? else {
|
||
return Ok(UpdateCheck { enabled: false, update: None });
|
||
};
|
||
let update = tokio::time::timeout(std::time::Duration::from_secs(60), updater.check())
|
||
.await
|
||
.map_err(|e| IdeError::unavailable(e.to_string()))?
|
||
.map_err(|e| IdeError::unavailable(e.to_string()))?;
|
||
Ok(UpdateCheck {
|
||
enabled: true,
|
||
update: update.map(|u| UpdateInfo {
|
||
version: u.version.clone(),
|
||
current_version: u.current_version.clone(),
|
||
notes: u.body.clone(),
|
||
date: u.date.map(|d| d.to_string()),
|
||
}),
|
||
})
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_update_window_ready(
|
||
app: AppHandle,
|
||
window: WebviewWindow,
|
||
ready: bool,
|
||
system_locale: String,
|
||
) -> IdeResult<()> {
|
||
crate::updates::window_ready(&app, window.label(), ready, system_locale);
|
||
Ok(())
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_update_status(state: State<'_, AppState>) -> IdeResult<UpdateStatus> {
|
||
Ok(state.updates.state.lock().policy.status.clone())
|
||
}
|
||
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub fn app_update_announcement(state: State<'_, AppState>, version: String, automatic: bool) -> IdeResult<bool> {
|
||
let claimed = state.updates.state.lock().policy.announce(&version);
|
||
Ok(!automatic || claimed)
|
||
}
|
||
|
||
/// Progress of [`app_install_update`], streamed to the UI's background task.
|
||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||
pub enum UpdateProgress {
|
||
/// Bytes received so far; `total` when the server sends a length.
|
||
Downloading { downloaded: f64, total: Option<f64> },
|
||
/// Download done; the new version is being written over this one.
|
||
Installing,
|
||
}
|
||
|
||
/// Limits download events to one per whole percent (or per 256 KiB without a length).
|
||
#[derive(Default)]
|
||
struct ProgressThrottle {
|
||
last_step: Option<u64>,
|
||
}
|
||
|
||
impl ProgressThrottle {
|
||
const UNKNOWN_STEP: u64 = 256 * 1024;
|
||
|
||
/// Converts the downloader's absolute byte count into a throttled event.
|
||
fn report(&mut self, downloaded: u64, total: Option<u64>) -> Option<UpdateProgress> {
|
||
let step = match total {
|
||
Some(t) if t > 0 => downloaded.min(t) * 100 / t,
|
||
_ => downloaded / Self::UNKNOWN_STEP,
|
||
};
|
||
if self.last_step == Some(step) {
|
||
return None;
|
||
}
|
||
self.last_step = Some(step);
|
||
Some(UpdateProgress::Downloading { downloaded: downloaded as f64, total: total.map(|t| t as f64) })
|
||
}
|
||
}
|
||
|
||
/// Set while an update is being downloaded or installed (by any window).
|
||
static INSTALLING: AtomicBool = AtomicBool::new(false);
|
||
|
||
struct InstallingGuard;
|
||
|
||
impl InstallingGuard {
|
||
fn acquire() -> Option<Self> {
|
||
(!INSTALLING.swap(true, Ordering::SeqCst)).then_some(Self)
|
||
}
|
||
}
|
||
|
||
impl Drop for InstallingGuard {
|
||
fn drop(&mut self) {
|
||
INSTALLING.store(false, Ordering::SeqCst);
|
||
}
|
||
}
|
||
|
||
/// Downloads and installs the available update, streaming progress to `on_progress`.
|
||
/// Cancellable through `request` until the download completes; the UI then restarts
|
||
/// with `app_restart`. One install runs at a time.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn app_install_update(
|
||
app: AppHandle,
|
||
state: State<'_, AppState>,
|
||
source: UpdateSource,
|
||
request: RequestId,
|
||
on_progress: Channel<UpdateProgress>,
|
||
) -> IdeResult<()> {
|
||
let _guard =
|
||
InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?;
|
||
let token = state.host.begin_request(request);
|
||
let result = async {
|
||
let mut throttle = ProgressThrottle::default();
|
||
let progress = on_progress.clone();
|
||
let downloaded = tokio::select! {
|
||
result = crate::updates::download_update(&app, source, &token, move |done, total| {
|
||
if let Some(p) = throttle.report(done, total) {
|
||
let _ = progress.send(p);
|
||
}
|
||
}) => result?,
|
||
_ = token.cancelled() => return Err(IdeError::cancelled()),
|
||
};
|
||
let crate::updates::DownloadedUpdate { update, bytes, path } = downloaded;
|
||
if token.is_cancelled() {
|
||
return Err(IdeError::cancelled());
|
||
}
|
||
let _ = on_progress.send(UpdateProgress::Installing);
|
||
let installed = tauri::async_runtime::spawn_blocking(move || {
|
||
#[cfg(windows)]
|
||
if update.target.ends_with("-portable") {
|
||
let exe = tauri::utils::platform::current_exe()?;
|
||
return ide_tools::portable_update::install(&exe, &bytes);
|
||
}
|
||
update.install(bytes).map_err(|e| IdeError::internal(e.to_string()))
|
||
})
|
||
.await
|
||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||
if installed.is_ok() {
|
||
let _ = tokio::fs::remove_file(path).await;
|
||
}
|
||
installed
|
||
}
|
||
.await;
|
||
state.host.end_request(request);
|
||
result
|
||
}
|
||
|
||
/// Release notes of `version` from the update manifest (`latest.json`), read
|
||
/// through the configured source: the `notes` text under `"en"` plus any
|
||
/// `notes.<lang>` translations keyed by their base language code, so the page
|
||
/// can show the UI's language and fall back to English. An install records the
|
||
/// notes it saw, so this is only for an update installed outside the app.
|
||
/// `Ok(None)` when the manifest covers another version or carries no notes.
|
||
/// Reads only the public manifest, like the update check: the page usually opens
|
||
/// in a window without a project.
|
||
#[desktop_command(trust = always)]
|
||
#[tauri::command]
|
||
#[specta::specta]
|
||
pub async fn app_release_notes(
|
||
app: AppHandle,
|
||
version: String,
|
||
source: UpdateSource,
|
||
) -> IdeResult<Option<BTreeMap<String, String>>> {
|
||
let endpoints = update_endpoints(&app, source);
|
||
let client = ide_http::client::shared()?;
|
||
for endpoint in endpoints {
|
||
// A hanging endpoint must not leave the page on "Fetching release notes…".
|
||
let fetched = tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||
let Ok(response) = client.get(&endpoint).send().await else {
|
||
return None;
|
||
};
|
||
if !response.status().is_success() {
|
||
return None;
|
||
}
|
||
response.text().await.ok()
|
||
})
|
||
.await;
|
||
let Ok(Some(text)) = fetched else { continue };
|
||
if let Some(notes) = notes_for(&text, &version) {
|
||
return Ok(Some(notes));
|
||
}
|
||
}
|
||
Ok(None)
|
||
}
|
||
|
||
/// The notes of `version` in a manifest, when that is the entry it lists: the
|
||
/// `notes` text as English and each `notes.<lang>` entry under its base language
|
||
/// code (`notes.zh-CN` → `zh`), the way the UI's locales are keyed.
|
||
fn notes_for(manifest: &str, version: &str) -> Option<BTreeMap<String, String>> {
|
||
let value: serde_json::Value = serde_json::from_str(manifest).ok()?;
|
||
if value.get("version")?.as_str()? != version {
|
||
return None;
|
||
}
|
||
let mut notes = BTreeMap::new();
|
||
let entry =
|
||
|text: &serde_json::Value| text.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_string);
|
||
if let Some(text) = value.get("notes").and_then(entry) {
|
||
notes.insert("en".to_owned(), text);
|
||
}
|
||
for (key, text) in value.as_object().into_iter().flatten() {
|
||
let Some(tag) = key.strip_prefix("notes.").and_then(|tag| tag.split(['-', '_']).next()) else {
|
||
continue;
|
||
};
|
||
if tag.is_empty() {
|
||
continue;
|
||
}
|
||
if let Some(text) = entry(text) {
|
||
notes.insert(tag.to_ascii_lowercase(), text);
|
||
}
|
||
}
|
||
(!notes.is_empty()).then_some(notes)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn release_notes_come_from_the_manifest_of_that_version() {
|
||
let manifest = serde_json::json!({
|
||
"version": "0.1.40",
|
||
"notes": "## What's new\n\n- dev containers",
|
||
"notes.zh": "## 新变化\n\n- 开发容器",
|
||
"notes.ko-KR": "## 새 소식",
|
||
"notes.pl": " ",
|
||
"pub_date": "2026-11-01T00:00:00Z",
|
||
})
|
||
.to_string();
|
||
assert_eq!(
|
||
notes_for(&manifest, "0.1.40"),
|
||
Some(BTreeMap::from([
|
||
("en".to_owned(), "## What's new\n\n- dev containers".to_owned()),
|
||
("zh".to_owned(), "## 新变化\n\n- 开发容器".to_owned()),
|
||
("ko".to_owned(), "## 새 소식".to_owned()),
|
||
]))
|
||
);
|
||
// Another version, empty notes, or not JSON: nothing to show.
|
||
assert_eq!(notes_for(&manifest, "0.1.41"), None);
|
||
assert_eq!(notes_for(r#"{ "version": "0.1.40", "notes": " " }"#, "0.1.40"), None);
|
||
assert_eq!(notes_for(r#"{ "version": "0.1.40" }"#, "0.1.40"), None);
|
||
assert_eq!(notes_for("not json", "0.1.40"), None);
|
||
}
|
||
|
||
#[test]
|
||
fn menu_configuration_follows_the_active_window_or_its_settings_parent() {
|
||
for (source, target, allowed) in [
|
||
("main", "main", true),
|
||
("project-1", "main", false),
|
||
("main", "settings-main", true),
|
||
("project-1", "settings-main", false),
|
||
("project-1", "settings-project-1", true),
|
||
("comparison-main-1", "comparison-main-1", true),
|
||
("main", "comparison-main-1", false),
|
||
] {
|
||
assert_eq!(super::owns_menu_config(source, target), allowed, "{source} → {target}");
|
||
}
|
||
}
|
||
|
||
use super::*;
|
||
|
||
fn downloading(p: Option<UpdateProgress>) -> Option<(f64, Option<f64>)> {
|
||
match p? {
|
||
UpdateProgress::Downloading { downloaded, total } => Some((downloaded, total)),
|
||
UpdateProgress::Installing => None,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn throttle_reports_each_whole_percent_once() {
|
||
let mut t = ProgressThrottle::default();
|
||
assert_eq!(downloading(t.report(1, Some(1000))), Some((1.0, Some(1000.0))));
|
||
assert_eq!(downloading(t.report(9, Some(1000))), None);
|
||
assert_eq!(downloading(t.report(10, Some(1000))), Some((10.0, Some(1000.0))));
|
||
let reported = (11..=100).filter(|percent| t.report(percent * 10, Some(1000)).is_some()).count();
|
||
assert_eq!(reported, 90);
|
||
}
|
||
|
||
#[test]
|
||
fn throttle_without_length_reports_per_step() {
|
||
let mut t = ProgressThrottle::default();
|
||
assert!(t.report(10, None).is_some());
|
||
assert!(t.report(1024, None).is_none());
|
||
assert_eq!(downloading(t.report(256 * 1024 + 1034, None)), Some(((256 * 1024 + 1034) as f64, None)));
|
||
// A zero length is treated as unknown, not divided by.
|
||
assert!(ProgressThrottle::default().report(1, Some(0)).is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn throttle_uses_absolute_bytes_after_a_full_download_restart() {
|
||
let mut t = ProgressThrottle::default();
|
||
let total = 100 * 1024 * 1024;
|
||
assert_eq!(downloading(t.report(40 * 1024 * 1024, None)), Some(((40 * 1024 * 1024) as f64, None)));
|
||
assert_eq!(downloading(t.report(1024, Some(total))), Some((1024.0, Some(total as f64))));
|
||
assert_eq!(
|
||
downloading(t.report(50 * 1024 * 1024, Some(total))),
|
||
Some(((50 * 1024 * 1024) as f64, Some(total as f64)))
|
||
);
|
||
}
|
||
|
||
/// Channel × source × build: a build's configured endpoint serves its own channel, the
|
||
/// other channel uses the official manifest, and only Stable has the CNB mirror.
|
||
#[test]
|
||
fn endpoints_follow_the_channel_and_source() {
|
||
use UpdateChannel::{Nightly, Stable};
|
||
use UpdateSource::{Cnb, Github};
|
||
let stable_build = "0.1.57";
|
||
let nightly_build = "0.1.58-nightly.20261203";
|
||
let stable = || vec![STABLE_ENDPOINT.to_string()];
|
||
let nightly = || vec![NIGHTLY_ENDPOINT.to_string()];
|
||
let cnb = CNB_ENDPOINT.to_string();
|
||
for (official, version, channel, source, expected) in [
|
||
(stable(), stable_build, Stable, Github, vec![STABLE_ENDPOINT.into(), cnb.clone()]),
|
||
(stable(), stable_build, Stable, Cnb, vec![cnb.clone(), STABLE_ENDPOINT.into()]),
|
||
(stable(), stable_build, Nightly, Github, nightly()),
|
||
(stable(), stable_build, Nightly, Cnb, nightly()),
|
||
(nightly(), nightly_build, Nightly, Github, nightly()),
|
||
(nightly(), nightly_build, Nightly, Cnb, nightly()),
|
||
(nightly(), nightly_build, Stable, Github, vec![STABLE_ENDPOINT.into(), cnb.clone()]),
|
||
(nightly(), nightly_build, Stable, Cnb, vec![cnb.clone(), STABLE_ENDPOINT.into()]),
|
||
] {
|
||
assert_eq!(
|
||
source_endpoints(official, channel, source, version),
|
||
expected,
|
||
"{version} on {channel:?} via {source:?}"
|
||
);
|
||
}
|
||
}
|
||
|
||
/// A fork's own endpoint keeps serving its own channel.
|
||
#[test]
|
||
fn a_custom_endpoint_serves_the_builds_own_channel() {
|
||
let custom = vec!["https://updates.example.test/latest.json".to_string()];
|
||
assert_eq!(
|
||
source_endpoints(custom.clone(), UpdateChannel::Stable, UpdateSource::Github, "0.1.57")[0],
|
||
custom[0]
|
||
);
|
||
assert_eq!(
|
||
source_endpoints(custom.clone(), UpdateChannel::Nightly, UpdateSource::Github, "0.1.58-nightly.1"),
|
||
custom
|
||
);
|
||
}
|
||
|
||
/// A build without an update endpoint stays without one on either channel.
|
||
#[test]
|
||
fn builds_without_updates_get_no_endpoint() {
|
||
for channel in [UpdateChannel::Stable, UpdateChannel::Nightly] {
|
||
for source in [UpdateSource::Github, UpdateSource::Cnb] {
|
||
for version in ["0.1.57", "0.1.58-nightly.20261203"] {
|
||
assert!(source_endpoints(Vec::new(), channel, source, version).is_empty());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The constants are the URLs the release and nightly scripts publish to.
|
||
#[test]
|
||
fn channel_endpoints_match_the_build_configuration() {
|
||
assert!(include_str!("../../tauri.conf.json").contains(STABLE_ENDPOINT));
|
||
assert!(include_str!("../../../scripts/nightly-prepare.ts").contains(NIGHTLY_ENDPOINT));
|
||
}
|
||
|
||
/// Switching a nightly back to Stable does not downgrade it: the updater installs only a
|
||
/// higher SemVer, and a release sorts after all of its own nightlies.
|
||
#[test]
|
||
fn stable_does_not_downgrade_a_nightly() {
|
||
use semver::Version;
|
||
let nightly = Version::parse("0.1.57-nightly.20261130").unwrap();
|
||
assert!(Version::parse("0.1.56").unwrap() < nightly);
|
||
assert!(Version::parse("0.1.57").unwrap() > nightly);
|
||
assert!(Version::parse("0.1.57-nightly.20261130.2").unwrap() > nightly);
|
||
assert!(Version::parse("0.1.58-nightly.20261201").unwrap() > Version::parse("0.1.57").unwrap());
|
||
}
|
||
|
||
#[test]
|
||
fn updater_client_bounds_connection_setup() {
|
||
let proxy = ide_core::proxy_settings::ProxySettings::default();
|
||
let builder = configure_updater_client(reqwest::ClientBuilder::new(), &proxy);
|
||
// reqwest has no getter for this; its ClientBuilder Debug prints non-default settings.
|
||
let debug = format!("{builder:?}");
|
||
assert!(
|
||
debug.contains(&format!("connect_timeout: {:?}", UPDATER_CONNECT_TIMEOUT)),
|
||
"the updater must not wait forever on an unreachable CDN address: {debug}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn only_one_install_at_a_time() {
|
||
let first = InstallingGuard::acquire().expect("first install starts");
|
||
assert!(InstallingGuard::acquire().is_none());
|
||
drop(first);
|
||
assert!(InstallingGuard::acquire().is_some());
|
||
}
|
||
}
|
||
|
||
ide_command::desktop_domain!(
|
||
app_build_info,
|
||
app_cancel_quit,
|
||
app_check_update,
|
||
app_cli_install,
|
||
app_cli_uninstall,
|
||
app_install_update,
|
||
app_log_location,
|
||
app_quit,
|
||
app_release_notes,
|
||
app_update_announcement,
|
||
app_update_status,
|
||
app_update_window_ready,
|
||
menu_configure,
|
||
menu_model,
|
||
menu_refresh,
|
||
menu_set_disabled,
|
||
menu_set_remote_recent,
|
||
window_begin_prompt,
|
||
window_close_context,
|
||
window_complete_launch,
|
||
window_cycle,
|
||
window_end_prompt,
|
||
window_flash_taskbar,
|
||
window_is_fullscreen,
|
||
window_new,
|
||
window_open_clone,
|
||
window_open_comparison,
|
||
window_open_connect,
|
||
window_open_deployment,
|
||
window_open_diff,
|
||
window_open_editor,
|
||
window_open_file_in_new_window,
|
||
window_open_new_project,
|
||
window_open_files,
|
||
window_open_project,
|
||
window_open_projects,
|
||
window_open_remote,
|
||
window_open_settings,
|
||
window_ready_to_close,
|
||
window_set_smooth_scrolling,
|
||
window_set_titlebar_height,
|
||
window_take_launch,
|
||
window_take_settings_init,
|
||
window_toggle_fullscreen,
|
||
window_toggle_zoom,
|
||
);
|