feat(flutter): Build APK / App Bundle / iOS / Web and open the native modules (#5790)

Flutter projects get a Build › Flutter submenu first in the Build menu: Build APK, Build App Bundle, Build iOS, Build Web (flutter build <target> in the selected Flutter configuration's package, output in the Run tool window), and on macOS Open iOS/macOS Module in Xcode (running flutter build ios --config-only first when the module isn't configured) and Open Android Module in Android Studio. The submenu is a dynamic native-menu slot filled only while flutterProject holds; all six are also in Find Action. iOS builds and the Open actions are macOS only.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-25 14:13:23 +08:00
1 джерело e5a4a6940a
коміт aec80ced53
9 files changed
+421 -2

No files matched your search

+67 -1
Переглянути файл
@@ -180,6 +180,11 @@ pub const DYNAMIC_LAYOUTS: &str = "toolWindowLayouts";
pub const DYNAMIC_STATUS_BAR_WIDGETS: &str = "statusBarWidgets";
/// Tools › entries of plugins (`[[contributes.menus]] menu = "tools"`).
pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
/// Build › Flutter: the Flutter build actions, filled only in Flutter projects. Shown as a submenu
/// first in Build (the Flutter plugin's anchor) when it has items, nothing otherwise.
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
/// Id (and `menu.` label key) of the Build › Flutter submenu.
const FLUTTER_BUILD_MENU: &str = "build.flutter";
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
/// them with `menu.<id>` strings from the active locale catalog.
@@ -615,6 +620,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
"build",
"Build",
vec![
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
act("build.buildProject", "Build Project"),
act("build.buildModule", "Build Module"),
act("build.compileFile", "Recompile"),
@@ -1290,6 +1296,18 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
}
}));
}
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
if !items.is_empty() {
out.push(RenderedItem::Submenu {
id: FLUTTER_BUILD_MENU.into(),
title: config.label(FLUTTER_BUILD_MENU, "Flutter"),
current: false,
items: items.iter().map(|item| item.render(config)).collect(),
});
out.push(RenderedItem::Separator);
}
}
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|item| item.render(config))),
Entry::Native(kind) => {
out.push(RenderedItem::Native { kind: *kind, text: config.label(kind.key(), kind.default_label()) })
@@ -1632,6 +1650,18 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
}
}));
}
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
if !items.is_empty() {
out.push(MenuNode::Submenu {
id: FLUTTER_BUILD_MENU.into(),
label: "Flutter".into(),
current: None,
children: items.iter().map(DynamicItem::model).collect(),
});
out.push(MenuNode::Separator);
}
}
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(DynamicItem::model)),
Entry::Action { id, label, hint, .. } => out.push(MenuNode::Action {
id: (*id).into(),
@@ -2385,7 +2415,13 @@ mod tests {
slots(&spec, &mut found);
assert_eq!(
found,
[DYNAMIC_TOOL_WINDOWS, DYNAMIC_STATUS_BAR_WIDGETS, DYNAMIC_PLUGIN_TOOLS, DYNAMIC_LAYOUTS],
[
DYNAMIC_TOOL_WINDOWS,
DYNAMIC_STATUS_BAR_WIDGETS,
DYNAMIC_FLUTTER_BUILD,
DYNAMIC_PLUGIN_TOOLS,
DYNAMIC_LAYOUTS
],
"{os:?}"
);
assert!(!action_ids(&spec).iter().any(|id| {
@@ -2542,6 +2578,36 @@ mod tests {
}
}
#[test]
fn flutter_build_submenu_leads_build_only_when_filled() {
let build_items = |config: &MenuConfig| {
render_bar(&spec(Os::Mac), config, &[]).into_iter().find(|m| m.id == "build").expect("Build menu").items
};
let mut config = MenuConfig::default();
assert!(matches!(&build_items(&config)[0], RenderedItem::Action { id, .. } if id == "build.buildProject"));
config.labels.insert("menu.build.flutter".into(), "Flutter".into());
config.dynamic.insert(
DYNAMIC_FLUTTER_BUILD.into(),
vec![
dynamic_item("flutter.build.apk", None, "Build APK"),
dynamic_item("flutter.build.web", None, "Build Web"),
],
);
let items = build_items(&config);
let RenderedItem::Submenu { id, title, items: flutter, .. } = &items[0] else { panic!("no Flutter submenu") };
assert_eq!((id.as_str(), title.as_str(), flutter.len()), ("build.flutter", "Flutter", 2));
assert!(matches!(items[1], RenderedItem::Separator));
let model = model(&spec(Os::Mac), &[], &config);
let build = model.iter().find_map(|n| match n {
MenuNode::Submenu { id, children, .. } if id == "build" => Some(children),
_ => None,
});
assert!(
matches!(&build.unwrap()[0], MenuNode::Submenu { id, children, .. } if id == "build.flutter" && children.len() == 2)
);
}
#[test]
fn build_menu_lists_recompile_and_patches_its_label() {
for os in ALL_OS {
+147
Переглянути файл
@@ -0,0 +1,147 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
const ipc = vi.hoisted(() => ({ fsEntryKind: vi.fn(), runApplySettings: vi.fn() }));
const run = vi.hoisted(() => ({
startRun: vi.fn(),
state: { configs: [] as unknown[], selectedId: null as string | null },
}));
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
commands: ipc,
}));
vi.mock("./store", () => ({ startRun: run.startRun, useRun: { getState: () => run.state } }));
import { useActions, type ActionContext } from "@/platform/actions";
import type { RunConfig } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { setContext } from "@/platform/context";
import { provideNotificationService, useMenuSlotItems } from "@/workbench/contributions";
import { registerFlutterBuildActions } from "./flutterBuild";
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
const missing = () => Promise.resolve({ status: "error" as const, error: { kind: "notFound", message: "" } });
const flutterConfig = (id: string, cwd: string | null) =>
({ id, kind: "flutter", command: "flutter", args: ["run"], cwd, debugAdapter: "dart" }) as unknown as RunConfig;
const action = (id: string) => useActions.getState().actions.get(id)!;
const ctx = {} as ActionContext;
/** The command lines started so far: `[cwd, command, ...args]`. */
const started = () => run.startRun.mock.calls.map(([c]) => [c.cwd, c.command, ...c.args] as (string | null)[]);
let files: Set<string>;
let exitCode: number;
const notify = vi.fn();
let dispose: () => void;
beforeEach(() => {
files = new Set();
exitCode = 0;
useProject.setState({ project: { root: "/p", trusted: true } as never });
usePlatform.setState({ os: "macos" });
run.state = {
configs: [flutterConfig("flutter:run", null), flutterConfig("app/flutter:run", "app")],
selectedId: null,
};
ipc.fsEntryKind.mockImplementation((path: string) => (files.has(path) ? ok("dir") : missing()));
ipc.runApplySettings.mockImplementation((configs: RunConfig[]) => ok(configs));
run.startRun.mockImplementation(async (_c, _r, _b, options: { onExit: (code: number, stopped: boolean) => void }) => {
setTimeout(() => options.onExit(exitCode, false));
return {};
});
provideNotificationService({ notify } as never);
dispose = registerFlutterBuildActions();
});
afterEach(() => {
dispose();
vi.clearAllMocks();
useProject.setState({ project: null });
});
it("runs flutter build in the selected Flutter configuration's package", async () => {
expect(action("flutter.build.apk").when).toBe("flutterProject");
action("flutter.build.apk").run(ctx);
await vi.waitFor(() => expect(started()).toEqual([["/p", "flutter", "build", "apk"]]));
run.state.selectedId = "app/flutter:run";
action("flutter.build.aab").run(ctx);
action("flutter.build.web").run(ctx);
await vi.waitFor(() => expect(started()).toHaveLength(3));
expect(started().slice(1)).toEqual([
["/p/app", "flutter", "build", "appbundle"],
["/p/app", "flutter", "build", "web"],
]);
});
it("lists Build › Flutter in the native menu only in Flutter projects", () => {
const listed = () => (useMenuSlotItems.getState().slots.flutterBuild ?? []).map((i) => i.label);
expect(listed()).toEqual([]);
setContext("flutterProject", true);
expect(listed()).toEqual([
"Build APK",
"Build App Bundle",
"Build iOS",
"Build Web",
"Open iOS/macOS Module in Xcode",
"Open Android Module in Android Studio",
]);
setContext("flutterProject", false);
expect(listed()).toEqual([]);
// No Xcode or `open -a` elsewhere.
dispose();
usePlatform.setState({ os: "linux" });
dispose = registerFlutterBuildActions();
setContext("flutterProject", true);
expect(listed()).toEqual(["Build APK", "Build App Bundle", "Build iOS", "Build Web"]);
dispose();
expect(listed()).toEqual([]);
dispose = () => {};
setContext("flutterProject", false);
});
it("offers iOS builds and the Xcode / Android Studio actions only on macOS", () => {
const ids = ["flutter.build.ios", "flutter.xcode.open", "flutter.androidstudio.open"];
expect(ids.map((id) => action(id).enabled!(ctx))).toEqual([true, true, true]);
usePlatform.setState({ os: "linux" });
expect(ids.map((id) => action(id).enabled!(ctx))).toEqual([false, false, false]);
expect(action("flutter.build.apk").enabled!(ctx)).toBe(true);
});
it("opens the iOS workspace in Xcode, configuring the module first when Flutter has not", async () => {
files = new Set(["/p/ios/Runner.xcworkspace", "/p/ios/Runner.xcodeproj"]);
action("flutter.xcode.open").run(ctx);
await vi.waitFor(() => expect(started()).toHaveLength(2));
expect(started()).toEqual([
["/p", "flutter", "build", "ios", "--config-only"],
["/p", "open", "-a", "Xcode", "ios/Runner.xcworkspace"],
]);
// Configured already, no workspace yet (before `pod install`): the project itself.
run.startRun.mockClear();
files = new Set(["/p/ios/Runner.xcodeproj", "/p/ios/Flutter/Generated.xcconfig"]);
action("flutter.xcode.open").run(ctx);
await vi.waitFor(() => expect(started()).toEqual([["/p", "open", "-a", "Xcode", "ios/Runner.xcodeproj"]]));
});
it("does not open Xcode when configuring the module fails", async () => {
files = new Set(["/p/ios/Runner.xcworkspace"]);
exitCode = 1;
action("flutter.xcode.open").run(ctx);
await vi.waitFor(() => expect(started()).toHaveLength(1));
await new Promise((r) => setTimeout(r, 10));
expect(started()).toHaveLength(1);
});
it("reports a missing module or application instead of failing silently", async () => {
action("flutter.xcode.open").run(ctx);
action("flutter.androidstudio.open").run(ctx);
await vi.waitFor(() => expect(notify).toHaveBeenCalledTimes(2));
expect(notify.mock.calls.map(([n]) => n.title).sort()).toEqual(["No Android module found", "No Xcode project found"]);
expect(run.startRun).not.toHaveBeenCalled();
files = new Set(["/p/android"]);
exitCode = 1;
action("flutter.androidstudio.open").run(ctx);
await vi.waitFor(() => expect(notify).toHaveBeenCalledTimes(3));
expect(started()).toEqual([["/p", "open", "-a", "Android Studio", "android"]]);
expect(notify.mock.calls[2]![0].title).toBe("Could not open Android Studio");
});
+174
Переглянути файл
@@ -0,0 +1,174 @@
/**
* Build › Flutter (the Flutter plugin's Build menu group, shown in Flutter projects): `flutter build
* apk / appbundle / ios / web` in the Flutter package, in the Run tool window; and the plugin's Open
* iOS/macOS Module in Xcode and Open Android Module in Android Studio (macOS: `open -a`).
*/
import { registerActions, type Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, type RunConfig } from "@/platform/ipc";
import { useContextKeys } from "@/platform/context";
import { isMacHost } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { notifications, registerMenuSlotItem } from "@/workbench/contributions";
import { isFlutterConfig } from "@/workbench/flutterDevices";
import { withExpandedCwd } from "./cwdMacros";
import { dartTool } from "./flutterType";
import { joinPath } from "./links";
import { startRun, useRun } from "./store";
const FLUTTER = dartTool(true);
/** The Flutter plugin's build actions (`flutter build <target>`); iOS builds need a Mac. */
const FLUTTER_BUILDS = [
{ id: "flutter.build.apk", title: "Build APK", target: "apk", mac: false },
{ id: "flutter.build.aab", title: "Build App Bundle", target: "appbundle", mac: false },
{ id: "flutter.build.ios", title: "Build iOS", target: "ios", mac: true },
{ id: "flutter.build.web", title: "Build Web", target: "web", mac: false },
] as const;
/** The native Build menu's Flutter submenu (src-tauri/src/menu.rs `DYNAMIC_FLUTTER_BUILD`). */
const FLUTTER_BUILD_SLOT = "flutterBuild";
/** Xcode projects the plugin opens, first found wins. */
const XCODE_PROJECTS = [
"ios/Runner.xcworkspace",
"ios/Runner.xcodeproj",
"macos/Runner.xcworkspace",
"macos/Runner.xcodeproj",
];
/** The Flutter package: the working directory of the selected Flutter configuration, else the first one's. */
async function flutterPackage(): Promise<string | null> {
const root = useProject.getState().project?.root;
if (!root) return null;
const { configs, selectedId } = useRun.getState();
const flutter = configs.filter(isFlutterConfig);
const config = flutter.find((c) => c.id === selectedId) ?? flutter[0];
const cwd = config ? (await withExpandedCwd(config)).cwd : null;
return joinPath(root, cwd ?? "");
}
/** A transient configuration running `command args` in `dir` (the pubspec banner's kind). */
function commandConfig(dir: string, command: string, args: string[], name = `${command} ${args.join(" ")}`): RunConfig {
return {
id: `dart:${args.join(" ")}:${dir}`,
name,
kind: "dart-command",
command,
args,
cwd: dir,
env: {},
detected: true,
isTest: false,
debugAdapter: null,
};
}
/** Runs `config` in the Run tool window; resolves with its exit code (null when it did not start or was stopped). */
async function runConfig(config: RunConfig): Promise<number | null> {
const [applied] = await call(commands.runApplySettings([config]));
return new Promise((resolve) => {
void startRun(applied ?? config, undefined, undefined, {
onExit: (code, stopped) => resolve(stopped ? null : code),
})
.then((session) => {
if (!session) resolve(null);
})
.catch(() => resolve(null));
});
}
const exists = (path: string) =>
call(commands.fsEntryKind(path))
.then(() => true)
.catch(() => false);
function notifyError(title: string, body: string) {
notifications().notify({ group: "run", level: "error", key: "flutter.openModule", title, body });
}
async function build(target: string) {
const dir = await flutterPackage();
if (dir) await runConfig(commandConfig(dir, FLUTTER, ["build", target]));
}
async function openInXcode() {
const dir = await flutterPackage();
if (!dir) return;
const found = await Promise.all(XCODE_PROJECTS.map((p) => exists(`${dir}/${p}`)));
const project = XCODE_PROJECTS.find((_, i) => found[i]);
if (!project) {
notifyError(tx`No Xcode project found`, tx`${dir} has no ios/Runner.xcworkspace or ios/Runner.xcodeproj.`);
return;
}
// As the plugin does: an iOS module Flutter has not configured yet gets `flutter build ios --config-only` first.
if (project.startsWith("ios/") && !(await exists(`${dir}/ios/Flutter/Generated.xcconfig`))) {
if ((await runConfig(commandConfig(dir, FLUTTER, ["build", "ios", "--config-only"]))) !== 0) return;
}
const code = await runConfig(commandConfig(dir, "open", ["-a", "Xcode", project], "Open in Xcode"));
if (code !== null && code !== 0)
notifyError(tx`Could not open Xcode`, tx`Is Xcode installed? It could not open ${project}.`);
}
async function openInAndroidStudio() {
const dir = await flutterPackage();
if (!dir) return;
if (!(await exists(`${dir}/android`))) {
notifyError(tx`No Android module found`, tx`${dir} has no android folder.`);
return;
}
const config = commandConfig(dir, "open", ["-a", "Android Studio", "android"], "Open in Android Studio");
const code = await runConfig(config);
if (code !== null && code !== 0)
notifyError(tx`Could not open Android Studio`, tx`Is Android Studio installed? It could not open ${dir}/android.`);
}
export function registerFlutterBuildActions(): () => void {
const actions: Action[] = [
...FLUTTER_BUILDS.map((b): Action => ({
id: b.id,
title: b.title,
category: "Flutter",
keywords: [`flutter build ${b.target}`],
when: "flutterProject",
enabled: () => !b.mac || isMacHost(),
run: () => void build(b.target),
})),
{
id: "flutter.xcode.open",
title: "Open iOS/macOS Module in Xcode",
category: "Flutter",
when: "flutterProject",
// macOS only, as in the plugin.
enabled: () => isMacHost(),
run: () => void openInXcode(),
},
{
id: "flutter.androidstudio.open",
title: "Open Android Module in Android Studio",
category: "Flutter",
when: "flutterProject",
// ponytail: `open -a` is macOS; Linux/Windows need Android Studio's install folder (`flutter config --android-studio-dir`).
enabled: () => isMacHost(),
run: () => void openInAndroidStudio(),
},
];
// Build › Flutter lists them only in Flutter projects; the Open actions only on macOS.
const items = actions
.filter((a) => !a.id.endsWith(".open") || isMacHost())
.map((a) => ({ action: a.id, label: a.title }));
let inMenu: (() => void)[] = [];
const sync = (flutter: boolean) => {
if (flutter === inMenu.length > 0) return;
inMenu.forEach((d) => d());
inMenu = flutter ? items.map((item) => registerMenuSlotItem(FLUTTER_BUILD_SLOT, item)) : [];
};
sync(!!useContextKeys.getState().flutterProject);
const offContext = useContextKeys.subscribe((s) => sync(!!s.flutterProject));
const offActions = registerActions(actions);
return () => {
offContext();
sync(false);
offActions();
};
}
+2
Переглянути файл
@@ -78,6 +78,7 @@ import {
updatableSessions,
} from "./applicationUpdate";
import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { registerFlutterBuildActions } from "./flutterBuild";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
@@ -466,6 +467,7 @@ export function activate(): () => void {
registerBuiltinTypes(),
registerRunConfigType(junitType),
registerGoActions(),
registerFlutterBuildActions(),
registerRunTabActions(),
registerComposerInstall(),
registerPubspecCommands(),
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ async function inspect(pubspec: string): Promise<Package> {
mtimesIn(`${dir}/.dart_tool`),
]);
const flutter = /^\s+sdk:\s*flutter\b/m.test(text);
// A workspace member's package config sits at the workspace root; no prompt there.
// ponytail: a workspace member's package config sits at the workspace root; no prompt there.
if (/^resolution:\s*workspace\b/m.test(text)) return { flutter, pubGet: null };
const at = (m: Map<string, number | null>, name: string) => m.get(name) ?? null;
const config = at(tool, "package_config.json");
+1
Переглянути файл
@@ -416,6 +416,7 @@
"menu.build.compileFile": "{compileFile, select, yes {Recompile '{compileFileName}'} other {Recompile}}",
"menu.build.rebuildProject": "Rebuild Project",
"menu.build.buildArtifacts": "Build Artifacts",
"menu.build.flutter": "Flutter",
"menu.toolwindow.build": "Build",
"menu.find.structural": "Search Structurally…",
"menu.find.replaceStructural": "Replace Structurally…",
+14
Переглянути файл
@@ -3429,6 +3429,20 @@
"Select Flutter Device…": "Select Flutter Device…",
"Use Flutter Device": "Use Flutter Device",
"Restart Flutter Daemon": "Restart Flutter Daemon",
"Build APK": "Build APK",
"Build App Bundle": "Build App Bundle",
"Build iOS": "Build iOS",
"Build Web": "Build Web",
"Open iOS/macOS Module in Xcode": "Open iOS/macOS Module in Xcode",
"Open Android Module in Android Studio": "Open Android Module in Android Studio",
"No Xcode project found": "No Xcode project found",
"{dir} has no ios/Runner.xcworkspace or ios/Runner.xcodeproj.": "{dir} has no ios/Runner.xcworkspace or ios/Runner.xcodeproj.",
"Could not open Xcode": "Could not open Xcode",
"Is Xcode installed? It could not open {project}.": "Is Xcode installed? It could not open {project}.",
"No Android module found": "No Android module found",
"{dir} has no android folder.": "{dir} has no android folder.",
"Could not open Android Studio": "Could not open Android Studio",
"Is Android Studio installed? It could not open {dir}/android.": "Is Android Studio installed? It could not open {dir}/android.",
"Flutter SDK not found": "Flutter SDK not found",
"Flutter devices unavailable": "Flutter devices unavailable",
"No devices": "No devices",
+14
Переглянути файл
@@ -9769,6 +9769,20 @@
"Select Flutter Device…": "选择 Flutter 设备…",
"Use Flutter Device": "使用 Flutter 设备",
"Restart Flutter Daemon": "重启 Flutter 守护进程",
"Build APK": "构建 APK",
"Build App Bundle": "构建 App Bundle",
"Build iOS": "构建 iOS",
"Build Web": "构建 Web",
"Open iOS/macOS Module in Xcode": "在 Xcode 中打开 iOS/macOS 模块",
"Open Android Module in Android Studio": "在 Android Studio 中打开 Android 模块",
"No Xcode project found": "未找到 Xcode 项目",
"{dir} has no ios/Runner.xcworkspace or ios/Runner.xcodeproj.": "{dir} 中没有 ios/Runner.xcworkspace 或 ios/Runner.xcodeproj。",
"Could not open Xcode": "无法打开 Xcode",
"Is Xcode installed? It could not open {project}.": "Xcode 是否已安装?它无法打开 {project}。",
"No Android module found": "未找到 Android 模块",
"{dir} has no android folder.": "{dir} 中没有 android 文件夹。",
"Could not open Android Studio": "无法打开 Android Studio",
"Is Android Studio installed? It could not open {dir}/android.": "Android Studio 是否已安装?它无法打开 {dir}/android。",
"Flutter SDK not found": "未找到 Flutter SDK",
"Flutter devices unavailable": "Flutter 设备不可用",
"Finding devices…": "正在查找设备…",
+1
Переглянути файл
@@ -416,6 +416,7 @@
"menu.build.compileFile": "{compileFile, select, yes {重新编译 '{compileFileName}'} other {重新编译}}",
"menu.build.rebuildProject": "重新构建项目",
"menu.build.buildArtifacts": "构建工件",
"menu.build.flutter": "Flutter",
"menu.toolwindow.build": "构建",
"menu.find.structural": "结构化搜索…",
"menu.find.replaceStructural": "结构化替换…",