дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
feat(run): choose the iOS simulator for Xcode projects in the toolbar (#6821)
Native Xcode projects get an iOS Simulator chooser next to the run widget on macOS, shown when the project root holds an .xcodeproj or .xcworkspace and no pubspec.yaml (Flutter lists simulators through its own daemon). ide_run::simulator lists available iOS simulators from simctl, booted first, then newest runtime, then name; the menu has Booted and Available sections with Boot / Shut Down per row and Open Simulator, refreshes on open and after each boot or shutdown, and the choice is kept per project root. Xcode run configurations without a pinned simulator launch on the chooser's selection. Closes #6797 Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
5cb73c5fd1
коміт
fca497d246
14 files changed
+501
-1
No files matched your search
@@ -0,0 +1,40 @@
|
||||
//! iOS Simulators for Xcode projects, through `xcrun simctl` on the project host.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_run::simulator::{self, IosSimulator};
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
/// no change feed, and one listing takes a fraction of a second.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
|
||||
return Ok(None);
|
||||
}
|
||||
blocking(simulator::list).await.map(Some)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once it is booted.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_boot(_host: &Host, udid: String) -> IdeResult<()> {
|
||||
blocking(move || simulator::boot(&udid)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_shutdown(_host: &Host, udid: String) -> IdeResult<()> {
|
||||
blocking(move || simulator::shutdown(&udid)).await
|
||||
}
|
||||
|
||||
/// Opens Simulator.app.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_open_app(_host: &Host) -> IdeResult<()> {
|
||||
blocking(simulator::open_app).await
|
||||
}
|
||||
|
||||
ide_command::domain!(ios: ios_simulators, ios_simulator_boot, ios_simulator_shutdown, ios_simulator_open_app);
|
||||
@@ -22,6 +22,7 @@ pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod ios;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
@@ -103,6 +104,7 @@ ide_command::domains!(
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
ios: crate::ops::ios,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
lsp: crate::ops::lsp,
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod python_path;
|
||||
pub mod ruby_preload;
|
||||
pub mod ruby_reporter;
|
||||
pub mod scope;
|
||||
pub mod simulator;
|
||||
pub mod tomcat;
|
||||
mod utf8;
|
||||
pub mod wrap;
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on.
|
||||
//!
|
||||
//! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode
|
||||
//! projects use this.
|
||||
|
||||
use ide_core::process::prepare;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
/// One simulator `simctl list devices available` reports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IosSimulator {
|
||||
pub udid: String,
|
||||
pub name: String,
|
||||
/// The runtime, as Xcode shows it: `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`.
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
/// An Xcode project or workspace directly in `root`, outside a Flutter project (whose
|
||||
/// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter).
|
||||
pub fn is_xcode_project(root: &Path) -> bool {
|
||||
if root.join("pubspec.yaml").is_file() {
|
||||
return false;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(root) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
name.ends_with(".xcodeproj") || name.ends_with(".xcworkspace")
|
||||
})
|
||||
}
|
||||
|
||||
/// `com.apple.CoreSimulator.SimRuntime.iOS-27-0` → its version parts, for iOS runtimes only.
|
||||
fn ios_version(runtime: &str) -> Option<Vec<u32>> {
|
||||
let version = runtime.rsplit('.').next()?.strip_prefix("iOS-")?;
|
||||
version.split('-').map(|p| p.parse().ok()).collect()
|
||||
}
|
||||
|
||||
/// The iOS simulators in `simctl list devices available --json` output: booted first, then
|
||||
/// newest runtime, then by name.
|
||||
pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("simctl list: {e}")))?;
|
||||
let mut devices: Vec<(Vec<u32>, IosSimulator)> = Vec::new();
|
||||
for (runtime, list) in value.get("devices").and_then(Value::as_object).into_iter().flatten() {
|
||||
let Some(version) = ios_version(runtime) else { continue };
|
||||
let label = format!("iOS {}", version.iter().map(u32::to_string).collect::<Vec<_>>().join("."));
|
||||
for d in list.as_array().into_iter().flatten() {
|
||||
let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned);
|
||||
let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue };
|
||||
devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state }));
|
||||
}
|
||||
}
|
||||
devices.sort_by(|(va, a), (vb, b)| {
|
||||
(a.state != "Booted")
|
||||
.cmp(&(b.state != "Booted"))
|
||||
.then_with(|| vb.cmp(va))
|
||||
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
||||
.then_with(|| a.udid.cmp(&b.udid))
|
||||
});
|
||||
Ok(devices.into_iter().map(|(_, d)| d).collect())
|
||||
}
|
||||
|
||||
fn run(program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
prepare(&mut cmd).args(args);
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("could not run {program}: {e}")))?;
|
||||
if out.status.success() {
|
||||
return Ok(String::from_utf8_lossy(&out.stdout).into_owned());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim())))
|
||||
}
|
||||
|
||||
/// The available iOS simulators, sorted as [`parse_list`] does.
|
||||
pub fn list() -> IdeResult<Vec<IosSimulator>> {
|
||||
parse_list(&run("xcrun", &["simctl", "list", "devices", "available", "--json"])?)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once `simctl` has it booted.
|
||||
pub fn boot(udid: &str) -> IdeResult<()> {
|
||||
run("xcrun", &["simctl", "boot", udid]).map(drop)
|
||||
}
|
||||
|
||||
pub fn shutdown(udid: &str) -> IdeResult<()> {
|
||||
run("xcrun", &["simctl", "shutdown", udid]).map(drop)
|
||||
}
|
||||
|
||||
/// Brings Simulator.app to the front, which shows the booted simulators.
|
||||
pub fn open_app() -> IdeResult<()> {
|
||||
run("open", &["-a", "Simulator"]).map(drop)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const LIST: &str = r#"{"devices": {
|
||||
"com.apple.CoreSimulator.SimRuntime.iOS-26-4": [
|
||||
{"udid": "A1", "name": "iPhone 17", "state": "Shutdown", "isAvailable": true}
|
||||
],
|
||||
"com.apple.CoreSimulator.SimRuntime.watchOS-12-0": [
|
||||
{"udid": "W1", "name": "Apple Watch", "state": "Booted", "isAvailable": true}
|
||||
],
|
||||
"com.apple.CoreSimulator.SimRuntime.iOS-27-0": [
|
||||
{"udid": "B2", "name": "iPhone Air", "state": "Shutdown"},
|
||||
{"udid": "B1", "name": "iPad Pro", "state": "Shutdown"},
|
||||
{"udid": "B3", "name": "iPhone 18", "state": "Booted"},
|
||||
{"name": "no udid", "state": "Shutdown"}
|
||||
],
|
||||
"com.apple.CoreSimulator.SimRuntime.iOS-26-10": [
|
||||
{"udid": "C1", "name": "iPhone 17", "state": "Booted"}
|
||||
]
|
||||
}}"#;
|
||||
|
||||
#[test]
|
||||
fn lists_ios_simulators_booted_then_newest_then_by_name() {
|
||||
let devices = parse_list(LIST).unwrap();
|
||||
let order: Vec<_> = devices.iter().map(|d| (d.udid.as_str(), d.runtime.as_str())).collect();
|
||||
assert_eq!(
|
||||
order,
|
||||
[("B3", "iOS 27.0"), ("C1", "iOS 26.10"), ("B1", "iOS 27.0"), ("B2", "iOS 27.0"), ("A1", "iOS 26.4")]
|
||||
);
|
||||
assert_eq!(devices[0].name, "iPhone 18");
|
||||
assert_eq!(devices[0].state, "Booted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_output_that_is_not_json() {
|
||||
assert!(parse_list("xcrun: error").is_err());
|
||||
assert_eq!(parse_list("{}").unwrap(), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_xcode_projects_at_the_root_only() {
|
||||
let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("App.xcodeproj")).unwrap();
|
||||
assert!(is_xcode_project(&dir));
|
||||
std::fs::write(dir.join("pubspec.yaml"), "name: app\n").unwrap();
|
||||
assert!(!is_xcode_project(&dir), "Flutter projects list their devices through Flutter");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -372,6 +372,10 @@ http_variable_definitions trusted project_host bin
|
||||
index_file_extensions always project_host bindings sync
|
||||
index_status always project_host bindings sync
|
||||
inspect_code trusted project_host bindings async
|
||||
ios_simulator_boot trusted project_host bindings async
|
||||
ios_simulator_open_app trusted project_host bindings async
|
||||
ios_simulator_shutdown trusted project_host bindings async
|
||||
ios_simulators trusted project_host bindings async
|
||||
java_build_workspace trusted project_host bindings async
|
||||
java_debug_adapter trusted project_host bindings sync
|
||||
java_debug_server trusted project_host bindings async
|
||||
|
||||
@@ -935,6 +935,17 @@ export const commands = {
|
||||
* serves. Files stream through `on_event` as they finish; ends with `Done`.
|
||||
*/
|
||||
inspectCode: (request: RequestId, scope: SearchScope, onEvent: Channel<InspectEvent>) => typedError<null, IdeError>(__TAURI_INVOKE("inspect_code", { request, scope, onEvent })),
|
||||
/** Boots a simulator; returns once it is booted. */
|
||||
iosSimulatorBoot: (udid: string) => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_boot", { udid })),
|
||||
/** Opens Simulator.app. */
|
||||
iosSimulatorOpenApp: () => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_open_app")),
|
||||
iosSimulatorShutdown: (udid: string) => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_shutdown", { udid })),
|
||||
/**
|
||||
* The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
* Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
* no change feed, and one listing takes a fraction of a second.
|
||||
*/
|
||||
iosSimulators: () => typedError<IosSimulator[] | null, IdeError>(__TAURI_INVOKE("ios_simulators")),
|
||||
/** Incremental build of the jdtls workspace serving `module` (e.g. before HotSwap). */
|
||||
javaBuildWorkspace: (module: string, request: number | null) => typedError<JavaBuildStatus, IdeError>(__TAURI_INVOKE("java_build_workspace", { module, request })),
|
||||
/**
|
||||
@@ -9622,6 +9633,16 @@ export type InvalidateCachesOptions = {
|
||||
buildCaches?: boolean,
|
||||
};
|
||||
|
||||
/** One simulator `simctl list devices available` reports. */
|
||||
export type IosSimulator = {
|
||||
udid: string,
|
||||
name: string,
|
||||
/** The runtime, as Xcode shows it: `iOS 27.0`. */
|
||||
runtime: string,
|
||||
/** `Booted`, `Shutdown`, `Booting`, `Shutting Down`. */
|
||||
state: string,
|
||||
};
|
||||
|
||||
/** A binary argument or result of an IPC command. */
|
||||
export type IpcBytes = string;
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { BarButton, Icon, Menu, type MenuItem } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import type { IosSimulator } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
bootIosSimulator,
|
||||
currentIosSimulator,
|
||||
openSimulatorApp,
|
||||
refreshIosSimulators,
|
||||
selectIosSimulator,
|
||||
shutDownIosSimulator,
|
||||
useIosSimulators,
|
||||
watchIosSimulators,
|
||||
} from "@/workbench/iosSimulators";
|
||||
import styles from "./Run.module.css";
|
||||
|
||||
/** Title bar: the simulator Xcode launches use, in projects with an Xcode project on macOS. */
|
||||
export function IosSimulatorChooser() {
|
||||
const root = useProject((s) => s.project?.root);
|
||||
useEffect(() => (root ? watchIosSimulators(root) : undefined), [root]);
|
||||
const shown = useIosSimulators((s) => s.list !== null || s.error !== null);
|
||||
return shown ? <Chooser /> : null;
|
||||
}
|
||||
|
||||
const booted = (s: IosSimulator) => s.state === "Booted";
|
||||
|
||||
function Chooser() {
|
||||
const tx = useTx();
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const state = useIosSimulators();
|
||||
const { list, error, busy } = state;
|
||||
const current = currentIosSimulator(state);
|
||||
const label = current?.name ?? (error ? tx("Simulators unavailable") : tx("No simulators"));
|
||||
|
||||
const row = (s: IosSimulator): MenuItem => ({
|
||||
id: s.udid,
|
||||
label: `${s.name} · ${s.runtime}`,
|
||||
verbatim: true,
|
||||
checked: s.udid === current?.udid,
|
||||
hint: s.udid,
|
||||
performOnSelect: true,
|
||||
run: () => selectIosSimulator(s.udid),
|
||||
submenu: [
|
||||
booted(s)
|
||||
? { label: tx("Shut Down"), disabled: !!busy, run: () => void shutDownIosSimulator(s) }
|
||||
: { label: tx("Boot"), disabled: !!busy || s.state !== "Shutdown", run: () => void bootIosSimulator(s) },
|
||||
],
|
||||
});
|
||||
const running = (list ?? []).filter(booted);
|
||||
const idle = (list ?? []).filter((s) => !booted(s));
|
||||
const items: MenuItem[] = [
|
||||
...(running.length ? [{ kind: "header", label: tx("Booted") } as const, ...running.map(row)] : []),
|
||||
...(idle.length ? [{ kind: "header", label: tx("Available") } as const, ...idle.map(row)] : []),
|
||||
...(error ? [{ label: error, verbatim: true, disabled: true }] : []),
|
||||
...(list && !list.length ? [{ label: tx("No simulators available"), disabled: true }] : []),
|
||||
{ kind: "separator" },
|
||||
{ label: tx("Open Simulator"), run: () => void openSimulatorApp() },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<BarButton
|
||||
ref={anchor}
|
||||
variant="title"
|
||||
className={styles.widgetDevice}
|
||||
data-toolbar-icon-dropdown=""
|
||||
tooltip={tx("iOS Simulator")}
|
||||
aria-label={tx`iOS Simulator: ${label}`}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => {
|
||||
if (!open) void refreshIosSimulators();
|
||||
setOpen(!open);
|
||||
}}
|
||||
>
|
||||
<Icon name={error ? "warning" : "project-swift"} size={16} />
|
||||
<span className={styles.widgetName} data-toolbar-label="">
|
||||
{busy && busy === current?.udid ? `${label}…` : label}
|
||||
</span>
|
||||
<Icon name="chevron-down" size={14} className={styles.widgetChevron} />
|
||||
</BarButton>
|
||||
<Menu open={open} anchor={anchor} items={items} placement="bottom-end" onClose={() => setOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { shortcutLabel } from "@/platform/keymap";
|
||||
import { runExecutors, useRunExecutors, useDebugRunSessions } from "@/workbench/contributions";
|
||||
import { configIcon } from "./configs";
|
||||
import { FlutterDeviceChooser } from "./FlutterDeviceChooser";
|
||||
import { IosSimulatorChooser } from "./IosSimulatorChooser";
|
||||
import { useRemoteLabel } from "./remote";
|
||||
import { CURRENT_FILE, useRun, isLive } from "./store";
|
||||
import { compoundTargets, selectedTarget } from "./sessionTargets";
|
||||
@@ -63,6 +64,7 @@ export function RunWidget() {
|
||||
return (
|
||||
<div className={styles.widget}>
|
||||
<FlutterDeviceChooser />
|
||||
<IosSimulatorChooser />
|
||||
<BarButton
|
||||
variant="title"
|
||||
className={styles.widgetChooser}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useIosSimulators } from "@/workbench/iosSimulators";
|
||||
import { xcodeType } from "./xcodeType";
|
||||
|
||||
describe("Xcode run configurations", () => {
|
||||
@@ -15,4 +17,28 @@ describe("Xcode run configurations", () => {
|
||||
]);
|
||||
expect(xcodeType.commandLine({ container: "App.xcodeproj" })).toBeNull();
|
||||
});
|
||||
|
||||
describe("launch", () => {
|
||||
afterEach(() => useIosSimulators.setState({ list: null, preferred: null }));
|
||||
const config = (simulator?: string) =>
|
||||
({
|
||||
kind: "xcode",
|
||||
params: { container: "App.xcodeproj", scheme: "App", ...(simulator ? { simulator } : {}) },
|
||||
}) as unknown as RunConfig;
|
||||
const sim = (udid: string) => ({ udid, name: udid, runtime: "iOS 27.0", state: "Shutdown" });
|
||||
|
||||
it("runs an unpinned configuration on the toolbar's simulator", async () => {
|
||||
useIosSimulators.setState({ list: [sim("A"), sim("B")], preferred: "B" });
|
||||
expect((await xcodeType.prepareLaunch!(config())).params?.simulator).toBe("B");
|
||||
});
|
||||
|
||||
it("keeps a pinned simulator", async () => {
|
||||
useIosSimulators.setState({ list: [sim("A")], preferred: "A" });
|
||||
expect((await xcodeType.prepareLaunch!(config("U1"))).params?.simulator).toBe("U1");
|
||||
});
|
||||
|
||||
it("leaves the choice to the host when no simulator is listed", async () => {
|
||||
expect((await xcodeType.prepareLaunch!(config())).params?.simulator).toBe("");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
* launch (`ide_run::xcode::prepare`); the command line here names what is built.
|
||||
*/
|
||||
import type { RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { iosSimulatorFor } from "@/workbench/iosSimulators";
|
||||
|
||||
export const xcodeType: RunConfigTypeContribution = {
|
||||
id: "xcode",
|
||||
@@ -29,6 +30,11 @@ export const xcodeType: RunConfigTypeContribution = {
|
||||
},
|
||||
{ key: "arguments", label: "Launch arguments", mono: true },
|
||||
],
|
||||
// A configuration without a pinned simulator runs on the toolbar's choice.
|
||||
prepareLaunch: async (config) =>
|
||||
config.params?.simulator?.trim()
|
||||
? config
|
||||
: { ...config, params: { ...config.params, simulator: iosSimulatorFor(config) ?? "" } },
|
||||
commandLine: (p) => {
|
||||
const container = p.container?.trim() ?? "";
|
||||
if (!container || !p.scheme?.trim()) return null;
|
||||
|
||||
@@ -2363,6 +2363,18 @@
|
||||
"Packaged application": "Packaged application",
|
||||
"Creating the virtual environment": "Creating the virtual environment",
|
||||
"A Quarkus application from code.quarkus.io.": "A Quarkus application from code.quarkus.io.",
|
||||
"Simulators unavailable": "Simulators unavailable",
|
||||
"No simulators": "No simulators",
|
||||
"Shut Down": "Shut Down",
|
||||
"Boot": "Boot",
|
||||
"Booted": "Booted",
|
||||
"No simulators available": "No simulators available",
|
||||
"Open Simulator": "Open Simulator",
|
||||
"iOS Simulator": "iOS Simulator",
|
||||
"iOS Simulator: {label}": "iOS Simulator: {label}",
|
||||
"Could not boot {name}": "Could not boot {name}",
|
||||
"Could not shut down {name}": "Could not shut down {name}",
|
||||
"Could not open Simulator": "Could not open Simulator",
|
||||
"Version:": "Version:",
|
||||
"A Rails application from rails new.": "A Rails application from rails new.",
|
||||
"API only": "API only",
|
||||
|
||||
@@ -5683,6 +5683,18 @@
|
||||
"not resolved": "未解析",
|
||||
"Shows a Gradle project's resolved dependencies per configuration, version conflicts and where each library comes from": "按配置显示 Gradle 项目解析后的依赖、版本冲突以及每个库的来源",
|
||||
"Cannot find the declaration": "找不到声明",
|
||||
"Simulators unavailable": "模拟器不可用",
|
||||
"No simulators": "无模拟器",
|
||||
"Shut Down": "关闭",
|
||||
"Boot": "启动",
|
||||
"Booted": "已启动",
|
||||
"No simulators available": "没有可用的模拟器",
|
||||
"Open Simulator": "打开 Simulator",
|
||||
"iOS Simulator": "iOS 模拟器",
|
||||
"iOS Simulator: {label}": "iOS 模拟器:{label}",
|
||||
"Could not boot {name}": "无法启动 {name}",
|
||||
"Could not shut down {name}": "无法关闭 {name}",
|
||||
"Could not open Simulator": "无法打开 Simulator",
|
||||
"Cannot exclude {name}": "无法排除 {name}",
|
||||
"Solarized Light": "Solarized 浅色",
|
||||
"Solarized Dark": "Solarized 深色",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { IosSimulator, RunConfig } from "@/platform/ipc";
|
||||
import { iosSimulatorFor, useIosSimulators } from "./iosSimulators";
|
||||
|
||||
vi.mock("./contributions", () => ({ notifications: () => ({ notify: vi.fn() }) }));
|
||||
|
||||
const sim = (udid: string, state = "Shutdown"): IosSimulator => ({ udid, name: udid, runtime: "iOS 27.0", state });
|
||||
const config = (params?: Record<string, string>) =>
|
||||
({ id: "xcode:App", kind: "xcode", params }) as unknown as RunConfig;
|
||||
|
||||
describe("iosSimulatorFor", () => {
|
||||
it("prefers the configuration's pinned simulator, then the toolbar's choice, then the first listed", () => {
|
||||
useIosSimulators.setState({ list: [sim("BOOTED", "Booted"), sim("OTHER")], preferred: null });
|
||||
expect(iosSimulatorFor(config())).toBe("BOOTED");
|
||||
useIosSimulators.setState({ preferred: "OTHER" });
|
||||
expect(iosSimulatorFor(config())).toBe("OTHER");
|
||||
expect(iosSimulatorFor(config({ simulator: "PINNED" }))).toBe("PINNED");
|
||||
useIosSimulators.setState({ preferred: "GONE" });
|
||||
expect(iosSimulatorFor(config())).toBe("BOOTED");
|
||||
useIosSimulators.setState({ list: null });
|
||||
expect(iosSimulatorFor(config())).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* The iOS Simulators of an Xcode project's window and which one launches use. The Run feature
|
||||
* shows and changes the selection; Xcode run configurations read it through `iosSimulatorFor`.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, type IosSimulator, type RunConfig } from "@/platform/ipc";
|
||||
import { notifications } from "./contributions";
|
||||
|
||||
const SELECTED_KEY = "openidea.ios.simulator:";
|
||||
|
||||
interface IosSimulatorsState {
|
||||
/** null: not an Xcode project, not macOS, or not loaded yet. */
|
||||
list: IosSimulator[] | null;
|
||||
error: string | null;
|
||||
/** The UDID chosen in the toolbar; kept while that simulator is missing. */
|
||||
preferred: string | null;
|
||||
root: string | null;
|
||||
/** A boot or shutdown under way, by UDID. */
|
||||
busy: string | null;
|
||||
}
|
||||
|
||||
export const useIosSimulators = create<IosSimulatorsState>(() => ({
|
||||
list: null,
|
||||
error: null,
|
||||
preferred: null,
|
||||
root: null,
|
||||
busy: null,
|
||||
}));
|
||||
|
||||
function storedSimulator(root: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(SELECTED_KEY + root);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The toolbar's simulator: the chosen one while listed, else the first (booted ones come first). */
|
||||
export function currentIosSimulator(state = useIosSimulators.getState()): IosSimulator | null {
|
||||
const list = state.list ?? [];
|
||||
return list.find((s) => s.udid === state.preferred) ?? list[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The simulator UDID to launch `rc` on: `params.simulator` when the configuration pins one,
|
||||
* else the toolbar's choice; null when there is none.
|
||||
*/
|
||||
export function iosSimulatorFor(rc: RunConfig): string | null {
|
||||
return rc.params?.simulator?.trim() || currentIosSimulator()?.udid || null;
|
||||
}
|
||||
|
||||
/** Lists the simulators again; `simctl` has no change feed, so the chooser asks on every opening. */
|
||||
export async function refreshIosSimulators() {
|
||||
const root = useIosSimulators.getState().root;
|
||||
try {
|
||||
const list = await call(commands.iosSimulators());
|
||||
if (useIosSimulators.getState().root === root) useIosSimulators.setState({ list, error: null });
|
||||
} catch (err) {
|
||||
if (useIosSimulators.getState().root === root)
|
||||
useIosSimulators.setState({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the project's simulators until the returned function is called. */
|
||||
export function watchIosSimulators(root: string): () => void {
|
||||
useIosSimulators.setState({ root, preferred: storedSimulator(root), list: null, error: null, busy: null });
|
||||
void refreshIosSimulators();
|
||||
return () => useIosSimulators.setState({ list: null, error: null, root: null, busy: null });
|
||||
}
|
||||
|
||||
export function selectIosSimulator(udid: string) {
|
||||
const { root } = useIosSimulators.getState();
|
||||
useIosSimulators.setState({ preferred: udid });
|
||||
try {
|
||||
if (root) localStorage.setItem(SELECTED_KEY + root, udid);
|
||||
} catch {
|
||||
/* the choice lasts for this session */
|
||||
}
|
||||
}
|
||||
|
||||
async function act(s: IosSimulator, boot: boolean) {
|
||||
useIosSimulators.setState({ busy: s.udid });
|
||||
try {
|
||||
await call(boot ? commands.iosSimulatorBoot(s.udid) : commands.iosSimulatorShutdown(s.udid));
|
||||
} catch (err) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
key: "ios.simulator",
|
||||
title: boot ? tx`Could not boot ${s.name}` : tx`Could not shut down ${s.name}`,
|
||||
body: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
} finally {
|
||||
useIosSimulators.setState({ busy: null });
|
||||
await refreshIosSimulators();
|
||||
}
|
||||
}
|
||||
|
||||
export const bootIosSimulator = (s: IosSimulator) => act(s, true);
|
||||
export const shutDownIosSimulator = (s: IosSimulator) => act(s, false);
|
||||
|
||||
export async function openSimulatorApp() {
|
||||
try {
|
||||
await call(commands.iosSimulatorOpenApp());
|
||||
} catch (err) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
key: "ios.simulator",
|
||||
title: tx("Could not open Simulator"),
|
||||
body: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача