Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Split BuilderView into one view per card, delete ContentView.swift (#387, step 8)

v0lumehic80e20d4da25
diff --git a/frontend/Sources/NX2Apple/BuildNotifications.swift b/frontend/Sources/NX2Apple/BuildNotifications.swift
index abddf1f9..af960574 100644
--- a/frontend/Sources/NX2Apple/BuildNotifications.swift
+++ b/frontend/Sources/NX2Apple/BuildNotifications.swift
@@ -63,9 +63,9 @@ final class BuildNotifier: NSObject, ObservableObject, UNUserNotificationCenterD
var game: UUID?
}
- /// Where a clicked notification asks the window to go (ContentView takes it and clears it).
+ /// Where a clicked notification asks the window to go (LauncherView takes it and clears it).
@Published var route: Route?
- /// The Builds page opens its log when this is set (BuilderView clears it).
+ /// The Builds page opens its log when this is set (BuildPage clears it through LogCard).
@Published var showLog = false
private var watching: AnyCancellable?
diff --git a/frontend/Sources/NX2Apple/BuildPage.swift b/frontend/Sources/NX2Apple/BuildPage.swift
new file mode 100644
index 00000000..19a7cef8
--- /dev/null
+++ b/frontend/Sources/NX2Apple/BuildPage.swift
@@ -0,0 +1,38 @@
+import SwiftUI
+import NXCore
+import NXLauncher
+import NXModel
+
+// The Builds page: the cards in the order a build goes, from the files to the progress. It only arranges them (CardPages.swift
+// scrolls them). Each card observes the stores it shows (NXLauncher, and `FilesCard` here), so a change in one store redraws that
+// card and no other.
+
+struct BuildPage: View {
+ let build: BuildStore
+ let repo: RepoStore
+ let dependencies: DependencyStore
+ let devices: DeviceStore
+ @Binding var extrasOpen: Bool // the optional input rows of the files card
+ @Binding var logOpen: Bool // the log card's disclosure
+ var onViewGame: () -> Void = {}
+ var onOpenSettings: () -> Void = {}
+ @EnvironmentObject var loc: Localizer
+
+ var body: some View {
+ CardPageHeading(loc.t("build.heading"), note: loc.t("build.intro"))
+ SetupHintCard(repo: repo, dependencies: dependencies, onOpenSettings: onOpenSettings)
+ FilesCard(build: build, extrasOpen: $extrasOpen)
+ TargetCard(build: build)
+ InstallCard(devices: devices, build: build)
+ LogCard(log: build.log, devices: devices, isOpen: $logOpen,
+ showRequests: BuildNotifier.shared.$showLog.eraseToAnyPublisher(), // a clicked notification of a failed build
+ didShow: { BuildNotifier.shared.showLog = false })
+ ActionCard(build: build, dependencies: dependencies, repo: repo)
+ Group { // a ViewBuilder holds ten views at most
+ ShellCopyCard(devices: devices)
+ BuildFailureCard(m: build)
+ OutcomeCard(build: build, devices: devices, onViewGame: onViewGame)
+ ProgressCard(build: build)
+ }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/CardPages.swift b/frontend/Sources/NX2Apple/CardPages.swift
new file mode 100644
index 00000000..54f12590
--- /dev/null
+++ b/frontend/Sources/NX2Apple/CardPages.swift
@@ -0,0 +1,46 @@
+import SwiftUI
+import NXCore
+import NXLauncher
+import NXModel
+
+// The Builds and Settings pages share one scrolling column, so the scroll position, the open log and the open extra rows stay when
+// someone goes from one to the other. This is that column and nothing else: it holds those three things and puts the cards of one
+// page or the other in it. The cards observe the stores they show (NXLauncher, and `FilesCard`, `LibraryCard` in this target).
+// A game file dropped on the Builds page goes to the build store (DropFiles.swift).
+
+struct CardPages: View {
+ let settings: Bool
+ @ObservedObject var build: BuildStore // for the drop target (off while a build runs) and the two cards that need to know
+ let updates: AppUpdateStore
+ let repo: RepoStore
+ let engine: EngineSyncStore
+ let dependencies: DependencyStore
+ let devices: DeviceStore
+ @ObservedObject var library: GameLibrary
+ var diagnostics: (LibraryGame?, @escaping (String) -> Void) -> Void = { _, _ in } // the report of Copy diagnostics (LauncherStores)
+ var onViewGame: () -> Void = {}
+ var onOpenSettings: () -> Void = {}
+ var onChooseLibraryFolder: () -> Void = {}
+ var onOpenControls: () -> Void = {}
+ var onOpenControllers: () -> Void = {} // the Controllers sheet (the console mode's list, with the player-mode setting)
+ var onRunSetup: (() -> Void)? // the guided first-run setup, again (nil where there is none)
+ var controlChanges = 0
+ var padMerge: Binding<Bool> = .constant(false) // "All controllers are player 1" (ControlLayout.padMerge)
+ @State private var extrasOpen = false
+ @State private var logOpen = false
+ @EnvironmentObject var loc: Localizer
+
+ var body: some View {
+ LauncherPageScroll {
+ if settings {
+ SettingsPage(build: build, updates: updates, repo: repo, engine: engine, dependencies: dependencies, library: library,
+ diagnostics: diagnostics, onChooseLibraryFolder: onChooseLibraryFolder, onOpenControls: onOpenControls,
+ onOpenControllers: onOpenControllers, onRunSetup: onRunSetup, controlChanges: controlChanges, padMerge: padMerge)
+ } else {
+ BuildPage(build: build, repo: repo, dependencies: dependencies, devices: devices, extrasOpen: $extrasOpen, logOpen: $logOpen,
+ onViewGame: onViewGame, onOpenSettings: onOpenSettings)
+ }
+ }
+ .modifier(GameFilesDrop(enabled: !settings && !build.running, label: loc.t("drop.hint")) { build.take(dropped: $0) }) // DropFiles.swift
+ }
+}
diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swift
deleted file mode 100644
index 17c7cf71..00000000
--- a/frontend/Sources/NX2Apple/ContentView.swift
+++ /dev/null
@@ -1,720 +0,0 @@
-import Combine
-import SwiftUI
-import NXCore
-import NXLauncher
-import NXModel
-
-// NS Port Builder: a macOS front end that walks a user through building a playable
-// IPA from their own Switch game files. Not part of the host runtime; drives the
-// repository's scripts (build_ipa_from_nsp.py, romfs_image.py) as subprocesses.
-//
-// The four inputs are picked separately — base game, update, add-on content (DLC),
-// prod.keys — because they are not always in one folder. When they are (the common
-// case) the folder is passed straight to the script; otherwise a staging folder of
-// symlinks is built and the script's --work-dir keeps the real build folder next to
-// the base game.
-
-// MARK: - Pieces
-
-extension StepState {
- var color: Color {
- switch self {
- case .pending: return .gray
- case .running: return .yellow
- case .done: return .green
- case .failed: return .red
- }
- }
-}
-
-// MARK: - View
-
-struct BuilderView: View {
- @ObservedObject var m: BuildStore
- @ObservedObject var updates: AppUpdateStore // the app's self-update (Settings, "NX2Apple" section)
- @ObservedObject var repo: RepoStore // the repository (Settings, "Tools" section, and the setup hint)
- @ObservedObject var engine: EngineSyncStore // the engine (Settings, "Tools" section)
- @ObservedObject var dependencies: DependencyStore // the tools (Settings, "Tools" section, and the setup hint and status)
- @ObservedObject var devices: DeviceStore // the install target (the Builds page) and the copy card
- var diagnostics: (LibraryGame?, @escaping (String) -> Void) -> Void = { _, _ in } // the report of Copy diagnostics (LauncherStores)
- @EnvironmentObject var loc: Localizer
- @ObservedObject var library: GameLibrary
- var settings = false
- var onViewGame: () -> Void = {}
- var onOpenSettings: () -> Void = {}
- var onChooseLibraryFolder: () -> Void = {}
- var onOpenControls: () -> Void = {}
- var onOpenControllers: () -> Void = {} // the Controllers sheet (the console mode's list, with the player-mode setting)
- var onRunSetup: (() -> Void)? // the guided first-run setup, again (nil where there is none)
- var controlChanges = 0
- var padMerge: Binding<Bool> = .constant(false) // "All controllers are player 1" (ControlLayout.padMerge)
- @AppStorage(ConsolePrompt.defaultsKey) private var consolePromptOn = true // ConsoleCoordinator.swift
- @AppStorage(BuildNotice.defaultsKey) private var notifyBuilds = true // BuildNotifications.swift
- @AppStorage(ReturnAfterPlay.defaultsKey) private var returnAfterPlay = true // ReturnAfterPlay.swift
- @State private var extrasOpen = false
- @State private var logOpen = false
- @State private var keyCheck: KeyCheck.Outcome? // prod.keys against the chosen files (KeyCheck.swift)
- @EnvironmentObject private var padFocus: PadFocus
-
- var body: some View {
- ScrollViewReader { proxy in
- ScrollView(.vertical) {
- VStack(alignment: .leading, spacing: 34) {
- if settings { settingsPage } else { buildPage }
- }
- .padding(.horizontal, 40).padding(.top, 40).padding(.bottom, 48)
- .frame(maxWidth: 900)
- .frame(maxWidth: .infinity)
- }
- .onChange(of: padFocus.focused) { id in // a controller's focus on this page scrolls into view
- if let id, id.hasPrefix("set.") { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } }
- }
- .modifier(GameFilesDrop(enabled: !settings && !m.running, label: loc.t("drop.hint")) { m.take(dropped: $0) }) // DropFiles.swift
- }
- .buttonStyle(LauncherSecondaryButtonStyle())
- }
-
- // ---- shared pieces: the library's and the launch options' look ----
-
- private func pageHeading(_ title: String, note: String) -> some View {
- VStack(alignment: .leading, spacing: 10) {
- Text(title).font(.manrope(44, .heavy)).tracking(-1.3)
- Text(note).font(.manrope(15)).foregroundStyle(.secondary)
- }
- }
-
- /// A titled group: a small tracked label over one card of rows.
- private func group<Content: View>(_ label: String, footnote: String = "", @ViewBuilder _ content: () -> Content) -> some View {
- VStack(alignment: .leading, spacing: 10) {
- Text(label).font(.manrope(15, .semibold)).foregroundStyle(.secondary)
- .padding(.leading, 2)
- VStack(spacing: 0, content: content)
- .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
- .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
- if !footnote.isEmpty {
- Text(footnote).font(.manrope(12)).foregroundStyle(.secondary).padding(.leading, 2)
- .fixedSize(horizontal: false, vertical: true)
- }
- }
- }
-
- /// One line of a card: a status dot (its place kept when there is none, so every title starts on one line),
- /// the title (with a disclosure chevron beside it when `open` is given), a secondary detail, and its controls.
- /// Its buttons and dropdowns are all LauncherControl.width wide, so they line up in one column across the cards.
- private func row<Trailing: View>(_ title: String, detail: String = "", detail2: String = "", dot: Color? = nil, help: String = "", open: Bool? = nil,
- @ViewBuilder trailing: () -> Trailing) -> some View {
- HStack(spacing: 12) {
- Circle().fill(dot ?? .clear).frame(width: 7, height: 7)
- VStack(alignment: .leading, spacing: 3) {
- HStack(spacing: 6) {
- Text(title).font(.manrope(14)).fixedSize(horizontal: false, vertical: true)
- if let open {
- Image(systemName: "chevron.right").font(.system(size: 10, weight: .bold)).foregroundStyle(.secondary)
- .rotationEffect(.degrees(open ? 90 : 0))
- }
- }
- if !detail.isEmpty {
- // A path is technical text: the system's monospaced face, on one line, cut in the middle when
- // too long. Everything else is prose in Manrope and wraps, so no word is ever cut.
- if detail.hasPrefix("/") || detail.hasPrefix("~") {
- Text(detail).font(.mono(12)).foregroundStyle(.secondary)
- .lineLimit(1).truncationMode(.middle).help(help.isEmpty ? detail : help)
- } else {
- Text(detail).font(.manrope(12.5)).foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true).help(help.isEmpty ? detail : help)
- }
- }
- if !detail2.isEmpty {
- Text(detail2).font(.mono(12)).foregroundStyle(.secondary)
- .lineLimit(1).truncationMode(.middle).help(detail2)
- }
- }
- Spacer(minLength: 12)
- trailing().launcherRowControls()
- }
- .padding(.horizontal, 18).padding(.vertical, 13)
- .frame(minHeight: 52)
- }
-
- private var divider: some View { Divider().opacity(0.25).padding(.leading, 18) }
-
- /// A row that opens the rows under it.
- private func disclosure(_ title: String, detail: String = "", isOpen: Bool, toggle: @escaping () -> Void) -> some View {
- Button(action: { withAnimation(.easeInOut(duration: 0.18)) { toggle() } }) {
- row(title, detail: detail, open: isOpen) { EmptyView() }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
-
- private func reveal(_ path: String) {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
- }
-
- // ---- Build game ----
-
- @ViewBuilder private var buildPage: some View {
- pageHeading(loc.t("build.heading"), note: loc.t("build.intro"))
- if !repo.isRepo || !dependencies.allPresent {
- group(loc.t("section.setup")) {
- row(loc.t("library.setupHint"), dot: LauncherPalette.building) {
- Button(loc.t("build.setup"), action: onOpenSettings)
- }
- }
- }
- files.disabled(m.running)
- target
- if m.target != BuildTarget.mac { install.disabled(m.running) }
- logPanel
- action
- ShellCopyCard(devices: devices)
- BuildFailureCard(m: m)
- outcome
- progress
- }
-
- /// Where an iPhone build goes: exported as an IPA (as before), or signed and installed on a paired device.
- private var install: some View {
- let devices = devices
- let options = [(value: "", label: loc.t("dev.none"))] + devices.devices.map { d in
- (value: d.id, label: d.name + (d.reachable ? "" : " (" + loc.t("dev.notConnected") + ")"))
- }
- let teams = devices.teams.map { (value: $0.id, label: $0.label(personalTeam: loc.t("dev.personalTeam"))) }
- let needsCertificate = devices.teams.first { $0.id == devices.signingTeam }.map { !$0.hasCertificate } ?? false
- return group(loc.t("dev.section"), footnote: devices.installDevice.isEmpty ? "" : (needsCertificate ? loc.t("dev.teamNoCert") + " " : "") + loc.t("dev.note")) {
- row(loc.t("dev.target"), detail: devices.checked && devices.devices.isEmpty ? loc.t("dev.noDevices") : "") {
- if !devices.checked { ProgressView().controlSize(.small) }
- Button(loc.t("dev.refresh")) { _ = devices.refresh() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)
- LauncherDropdown(options: options, selection: devices.installDevice, label: loc.t("dev.target")) { devices.installDevice = $0 }
- }
- if !devices.installDevice.isEmpty {
- divider
- if teams.isEmpty {
- row(loc.t("dev.team"), detail: loc.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() }
- } else {
- row(loc.t("dev.team")) {
- LauncherDropdown(options: teams, selection: devices.signingTeam, label: loc.t("dev.team")) { devices.signingTeam = $0 }
- }
- }
- }
- }
- .onAppear { if !devices.checked { _ = devices.refresh() } }
- }
-
- private var files: some View {
- // The report's own mistake, and a reasonable one: the output folder silently decides where
- // the build cache lives, so changing it threw away a finished build. Say it under Save to, all the time.
- group(loc.t("section.files"), footnote: loc.t("msg.workdirHint")) {
- Button(action: pickFolder) {
- row(loc.t(m.gameDir.isEmpty ? "build.folderCTA" : "build.folderSelected"),
- detail: m.gameDir.isEmpty ? loc.t("build.folderNote") : m.shortPath(m.gameDir), help: m.gameDir) {
- Text(loc.t(m.gameDir.isEmpty ? "data.choose" : "data.change"))
- .font(.manrope(13, .semibold)).foregroundStyle(.black)
- .launcherRowControlFrame()
- .background(LauncherPalette.cream, in: Capsule())
- }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- ForEach(m.slots.filter { !$0.optional }, id: \.id) { s in
- divider; slotRow(s)
- if s.id == "keys", let keyCheck { KeyCheckLine(outcome: keyCheck, t: loc.t) }
- }
- divider
- disclosure(loc.t("build.options"), isOpen: extrasOpen) { extrasOpen.toggle() }
- if extrasOpen {
- ForEach(m.slots.filter(\.optional), id: \.id) { s in divider; slotRow(s) }
- }
- divider
- row(loc.t("build.saveTo"), detail: m.outDir.isEmpty ? loc.t("build.saveDefault") : m.shortPath(m.outDir), help: m.outDir) {
- Button(loc.t("data.change")) { m.chooseBuildFolder() }
- }
- }
- .task(id: KeyCheck.Inputs(keys: m.keysPath, files: [m.basePath, m.updatePath] + m.dlcPaths)) {
- keyCheck = await KeyCheck.runDetached(KeyCheck.Inputs(keys: m.keysPath, files: [m.basePath, m.updatePath] + m.dlcPaths))
- }
- }
-
- private func slotRow(_ s: Slot) -> some View {
- // An empty prod.keys row says where the file comes from.
- row(loc.t(s.title), detail: s.id == "keys" && s.paths.isEmpty ? loc.t("build.keyHint") : s.summary(loc.t), dot: s.ok ? LauncherPalette.ready : LauncherPalette.unbuilt,
- help: s.paths.joined(separator: "\n")) {
- if !s.paths.isEmpty {
- Button(loc.t("data.clear")) { m.clear(s.id) }.buttonStyle(.plain)
- .font(.manrope(13)).foregroundStyle(.secondary)
- }
- Button(s.paths.isEmpty ? loc.t("data.choose") : loc.t("data.change")) { m.pickFiles(kind: s.kind) }
- }
- }
-
- private func pickFolder() {
- let d = NSOpenPanel()
- d.canChooseDirectories = true; d.canChooseFiles = false
- if d.runModal() == .OK, let u = d.url { m.scan(folder: u.path) }
- }
-
- private var target: some View {
- VStack(alignment: .leading, spacing: 10) {
- Text(loc.t("section.target")).font(.manrope(15, .semibold)).foregroundStyle(.secondary)
- .padding(.leading, 2)
- HStack(spacing: 14) {
- targetCard(BuildTarget.mac, symbol: "desktopcomputer", title: "build.mac", note: "build.macNote")
- targetCard(BuildTarget.ios, symbol: "iphone", title: "build.ios", note: "build.iosNote")
- }
- // A Mac app runs on this Mac's GPU, which always decodes BC textures: the switch is the iPhone's only.
- if m.target != BuildTarget.mac {
- VStack(spacing: 0) {
- HStack(alignment: .center, spacing: 12) {
- VStack(alignment: .leading, spacing: 3) {
- Text(loc.t("opt.bc")).font(.manrope(14))
- Text(loc.t("opt.bc.note")).font(.manrope(12.5)).foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true)
- }
- Spacer(minLength: 12)
- Toggle("", isOn: $m.bcOnCPU).toggleStyle(LauncherSwitchStyle()).labelsHidden().disabled(m.running)
- }
- .padding(.horizontal, 18).padding(.vertical, 14)
- }
- .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
- .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
- .padding(.top, 4)
- }
- }
- }
-
- private func targetCard(_ value: String, symbol: String, title: String, note: String) -> some View {
- let selected = m.target == value
- return Button { m.target = value } label: {
- VStack(alignment: .leading, spacing: 14) {
- HStack(alignment: .top) {
- Image(systemName: symbol).font(.system(size: 26, weight: .light))
- .foregroundStyle(selected ? LauncherPalette.cream : .secondary)
- Spacer()
- Circle().strokeBorder(selected ? LauncherPalette.cream : Color.white.opacity(0.25), lineWidth: selected ? 5 : 1.5)
- .frame(width: 18, height: 18)
- }
- VStack(alignment: .leading, spacing: 4) {
- Text(loc.t(title)).font(.manrope(16, .semibold))
- Text(loc.t(note)).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
- }
- }
- .padding(20).frame(maxWidth: .infinity, alignment: .leading)
- .background(selected ? LauncherPalette.cream.opacity(0.05) : LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
- .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(selected ? LauncherPalette.cream.opacity(0.7) : Color.white.opacity(0.06), lineWidth: selected ? 1.5 : 1))
- .contentShape(RoundedRectangle(cornerRadius: 14))
- }
- .buttonStyle(.plain).disabled(m.running)
- .accessibilityAddTraits(selected ? .isSelected : [])
- }
-
- @ViewBuilder private var outcome: some View {
- if m.done && m.target == BuildTarget.mac {
- group(loc.t("section.done")) {
- row(loc.t("library.ready"), detail: m.shortPath(m.macAppPath), dot: LauncherPalette.ready, help: m.macAppPath) {
- Button(loc.t("install.reveal")) { reveal(m.macAppPath) }
- Button(loc.t("build.showLibrary"), action: onViewGame)
- }
- }
- }
- if m.done && !m.installedOn.isEmpty {
- group(String(format: loc.t("dev.installed"), devices.deviceName(m.installedOn))) {
- row(loc.t("dev.installedNote"), dot: LauncherPalette.ready) {
- Button(String(format: loc.t("dev.open"), devices.deviceName(m.installedOn))) {
- m.openOnDevice(udid: m.installedOn, app: m.installedAppPath) { error in if let error { m.doneNote = error } }
- }
- }
- // The game files were copied (or, after a skipped transfer, await a manual copy — a
- // fast external drive handed to the device is quicker than USB): show where they are.
- if !m.archivePath.isEmpty {
- divider
- row(loc.t("dev.gameData"), detail: m.shortPath(m.archivePath), dot: LauncherPalette.ready, help: m.archivePath) {
- Button(loc.t("install.reveal")) { reveal(m.archivePath) }
- }
- }
- }
- }
- }
-
- /// The script's own stages once a build has run, and its log behind a disclosure.
- @ViewBuilder private var progress: some View {
- if m.running || !m.stages.isEmpty {
- group(loc.t("section.progress")) {
- ForEach(Array(m.stages.enumerated()), id: \.element.id) { index, s in
- if index > 0 { divider }
- HStack(spacing: 12) {
- if s.state == .running { ProgressView().controlSize(.small).frame(width: 14) }
- else { Circle().fill(s.state.color).frame(width: 7, height: 7).frame(width: 14) }
- Text(s.name).font(.manrope(14)).lineLimit(1)
- Spacer(minLength: 12)
- if s.state == .running {
- TimelineView(.periodic(from: Date(), by: 1)) { context in
- Text([s.detail, s.clock(at: context.date, left: loc.t("prog.eta"))].filter { !$0.isEmpty }.joined(separator: " · "))
- .font(.manrope(12)).monospacedDigit().foregroundStyle(.secondary).lineLimit(1)
- }
- } else if !s.detail.isEmpty { Text(s.detail).font(.manrope(12)).foregroundStyle(.secondary).lineLimit(1) }
- if s.state == .running {
- LauncherProgressBar(value: s.percent.map { $0 / 100 }, height: 6).frame(width: 180)
- Text(s.percent.map { "\(Int($0))%" } ?? "").font(.manrope(13, .semibold)).monospacedDigit()
- .foregroundStyle(.secondary).frame(width: 40, alignment: .trailing)
- }
- }
- .padding(.horizontal, 18).padding(.vertical, 12)
- }
- if m.stages.isEmpty && m.running {
- row(loc.t("library.preparing")) { ProgressView().controlSize(.small) }
- }
- }
- }
- }
-
- /// The build log, right under the Mac / iPhone choice and folded away until it is asked for.
- /// It used to sit at the bottom of the progress card, which is where a failed build's message
- /// pointed ("see the log below") while the log itself was out of view on a short window (#52).
- @ViewBuilder private var logPanel: some View {
- group(loc.t("section.log")) {
- if devices.shellCopy != nil || devices.shellWaiting {
- // The log below is the build's own output; the data transfer is driven by the app, so
- // its questions and errors (a locked device, a failed listing) answer here, not in it.
- Text(loc.t("log.transferNote")).font(.manrope(12.5)).foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true).padding(.horizontal, 14).padding(.top, 2)
- }
- disclosure(loc.t("build.log"), isOpen: logOpen) { logOpen.toggle() }
- if logOpen { logView.padding(.horizontal, 14).padding(.bottom, 14) }
- }
- .onReceive(BuildNotifier.shared.$showLog) { show in // a clicked notification of a failed build
- if show { logOpen = true; DispatchQueue.main.async { BuildNotifier.shared.showLog = false } }
- }
- }
-
- private var logView: some View {
- BuildLogView(log: m.log,placeholder: loc.t("log.placeholder"))
- }
-
- /// The page's conclusion, at the end of its column: what is still missing, and the button.
- private var action: some View {
- HStack(spacing: 18) {
- statusText
- Spacer(minLength: 12)
- Button {
- m.running ? m.stop() : m.startBuild()
- } label: {
- Label(m.running ? loc.t(m.stopping ? "library.stopping" : "btn.stop") : (m.done ? loc.t("btn.rebuild") : loc.t("build.startGame")),
- systemImage: m.running ? "stop.fill" : "hammer.fill")
- .font(.manrope(15, .semibold)).padding(.horizontal, 24).padding(.vertical, 13)
- .foregroundStyle(.black).background(m.running ? LauncherPalette.building : LauncherPalette.cream, in: Capsule())
- }
- .buttonStyle(.plain)
- .disabled(m.stopping || (!m.running && !m.canBuild))
- .opacity(m.stopping || (!m.running && !m.canBuild) ? 0.4 : 1)
- .keyboardShortcut(.return, modifiers: .command)
- }
- .padding(.top, 2)
- .staleFrameworksPrompt(m)
- }
-
- @ViewBuilder private var statusText: some View {
- if !m.doneNote.isEmpty {
- Text(m.doneNote).font(.manrope(13))
- .foregroundStyle(m.done ? LauncherPalette.ready : LauncherPalette.building).lineLimit(2)
- } else if !dependencies.checked {
- Text(loc.t("status.checkingDeps")).font(.manrope(13)).foregroundStyle(.secondary)
- } else if !dependencies.allPresent {
- Text(loc.t("status.installFirst")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)
- } else if !repo.isRepo {
- Text(loc.t("status.chooseRepo")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)
- } else if !m.slot("base").ok || !m.slot("keys").ok {
- Text(loc.t("status.needInputs")).font(.manrope(13)).foregroundStyle(.secondary)
- } else {
- Text(String(format: loc.t("status.output"), m.shortPath(m.outDir.isEmpty ? (m.basePath as NSString).deletingLastPathComponent : m.outDir)))
- .font(.manrope(13)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.head)
- }
- }
-
- // ---- Settings ----
-
- @ViewBuilder private var settingsPage: some View {
- pageHeading(loc.t("settings.heading"), note: loc.t("settings.note"))
- settingsCards
- }
-
- @ViewBuilder private var settingsCards: some View {
- group(loc.t("section.library"), footnote: loc.t("library.folderHint")) {
- row(loc.t("library.folderTitle"), detail: library.folder.isEmpty ? loc.t("library.folderUnset") : m.shortPath(library.folder),
- dot: library.folder.isEmpty ? LauncherPalette.unbuilt : LauncherPalette.ready, help: library.folder) {
- if library.scanning { ProgressView().controlSize(.small) }
- if !library.folder.isEmpty {
- Button(loc.t("library.rescan")) { library.discover() }.disabled(library.scanning)
- .padTarget("set.rescan", scope: "main") { if !library.scanning { library.discover() } }
- }
- Button(loc.t("library.chooseFolder"), action: onChooseLibraryFolder)
- .padTarget("set.folder", scope: "main") { onChooseLibraryFolder() }
- }
- }
- group(loc.t("section.controls"), footnote: loc.t("controls.settingsHint")) {
- row(loc.t("controls.row"), detail: controlChanges == 0 ? loc.t("controls.defaultLayout") : String(format: loc.t("controls.changes"), controlChanges)) {
- Button(loc.t("controls.customize"), action: onOpenControls)
- .padTarget("set.controls", scope: "main") { onOpenControls() }
- }
- divider
- row(loc.t("console.mergeAll"), detail: loc.t("console.mergeNote")) {
- Toggle("", isOn: padMerge).labelsHidden().toggleStyle(LauncherSwitchStyle())
- .padTarget("set.padMerge", scope: "main") { padMerge.wrappedValue.toggle() }
- }
- divider
- row(loc.t("console.controllers"), detail: loc.t("console.controllersRowNote")) {
- Button(loc.t("console.controllersOpen"), action: onOpenControllers)
- .padTarget("set.controllers", scope: "main") { onOpenControllers() }
- }
- divider
- row(loc.t("console.promptSetting"), detail: loc.t("console.promptSettingNote")) {
- Toggle("", isOn: $consolePromptOn).labelsHidden().toggleStyle(LauncherSwitchStyle())
- .padTarget("set.consolePrompt", scope: "main") { consolePromptOn.toggle() }
- }
- }
- tools
- group(loc.t("section.app"), footnote: updates.status) {
- // The interface language: the device default unless someone picks one here. Stored as
- // "" (follow), "zh", "en", "sv", "de" or "fr" so a later system-language change still applies.
- row(loc.t("settings.language"),
- detail: Lang.saved.map { loc.t("settings.language.\($0.rawValue)") }
- ?? loc.t("settings.language.system"), dot: LauncherPalette.ready, help: "") {
- // The launcher's own list, drawn like the buttons beside it and as wide as they are.
- // The language names are in their own language (see "settings.language.*"), only "system" follows the UI.
- LauncherDropdown(options: Self.languageCodes.map { (value: $0, label: loc.t("settings.language." + ($0.isEmpty ? "system" : $0))) },
- selection: Lang.saved.map { $0.rawValue } ?? "", label: loc.t("settings.language"),
- style: .button) { v in
- loc.choose(v)
- }
- .padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) })
- }
- divider
- // Build notifications (BuildNotifications.swift): none without an app bundle, e.g. under swift run
- row(loc.t("settings.notify"), detail: loc.t(BuildNotice.hasBundleID ? "settings.notifyNote" : "settings.notifyUnbundled")) {
- Toggle("", isOn: $notifyBuilds).toggleStyle(LauncherSwitchStyle()).labelsHidden().disabled(!BuildNotice.hasBundleID)
- .padTarget("set.notify", scope: "main") { notifyBuilds.toggle() }
- }
- divider
- if let onRunSetup {
- row(loc.t("settings.setup"), detail: loc.t("settings.setupNote")) {
- Button(loc.t("settings.setupBtn"), action: onRunSetup)
- .padTarget("set.setup", scope: "main") { onRunSetup() }
- }
- divider
- }
- // The launcher back in front when a game it started quits (ReturnAfterPlay.swift)
- row(loc.t("settings.returnAfterPlay"), detail: loc.t("settings.returnAfterPlayNote")) {
- Toggle("", isOn: $returnAfterPlay).toggleStyle(LauncherSwitchStyle()).labelsHidden()
- .padTarget("set.returnAfterPlay", scope: "main") { returnAfterPlay.toggle() }
- }
- divider
- row("NX2Apple", detail: String(format: loc.t("app.version"), updates.version),
- dot: updates.staged != nil ? LauncherPalette.ready : nil) {
- if updates.busy { ProgressView().controlSize(.small) }
- if updates.staged != nil {
- // Downloaded and verified: it goes in when the app quits; this restarts into it now (not during a build)
- Button(loc.t("app.restartNow")) { updates.restartNow() }.disabled(m.running)
- .padTarget("set.appRestart", scope: "main") { if !m.running { updates.restartNow() } }
- } else if let u = updates.update, updates.installability == .ok {
- Button(String(format: loc.t("app.updateBtn"), u.tag)) { updates.performUpdate() }.disabled(updates.busy || m.running)
- .padTarget("set.appUpdate", scope: "main") { if !(updates.busy || m.running) { updates.performUpdate() } }
- } else {
- Button(loc.t("repo.check")) { updates.checkForUpdate() }.disabled(updates.busy)
- .padTarget("set.appCheck", scope: "main") { if !updates.busy { updates.checkForUpdate() } }
- }
- }
- divider
- if updates.installability == .ok {
- // The uninstaller (Uninstall.swift): state folders and the launcher's own checkout go; the
- // games folder and prod.keys stay; the app itself goes to the Trash.
- row(loc.t("uninstall.title"), detail: loc.t("uninstall.note")) {
- Button(loc.t("uninstall.button")) { updates.uninstallPlan = uninstallPlan() }
- .disabled(m.running)
- .padTarget("set.uninstall", scope: "main") { if !m.running { updates.uninstallPlan = uninstallPlan() } }
- }
- divider
- }
- // A launcher built from the repository never replaces itself (AppUpdate.installability): the switch says so and stays off
- row(loc.t("app.auto"), detail: loc.t(updates.installability == .ok ? "app.autoNote" : updates.installability == .developer ? "app.autoDev" : "app.autoReadOnly")) {
- Toggle("", isOn: Binding(get: { updates.automatic && updates.installability == .ok }, set: { updates.automatic = $0 }))
- .labelsHidden().toggleStyle(LauncherSwitchStyle()).disabled(updates.installability != .ok)
- .padTarget("set.appAuto", scope: "main") { if updates.installability == .ok { updates.automatic.toggle() } }
- }
- }
- }
-
- /// The interface language one step on (a controller's left / right on the language list).
- /// The language picker's choices in order, "" being the system's. A new language is one more code here and its
- /// "settings.language.<code>" entry, which is its own name (Svenska, Deutsch) in every language.
- static let languageCodes = ["", "zh", "en", "sv", "de", "fr"]
-
- private func cycleLanguage(_ by: Int) {
- let values = Self.languageCodes
- let at = values.firstIndex(of: Lang.saved.map { $0.rawValue } ?? "") ?? 0
- let v = values[(at + by + values.count) % values.count]
- loc.choose(v)
- }
-
- private func uninstallPlan() -> Uninstall.Plan {
- Uninstall.plan(home: NSHomeDirectory(), gamesFolder: library.folder, outputFolder: m.outDir,
- checkouts: [repo.path], defaultsDomain: Bundle.main.bundleIdentifier)
- }
-
- private var tools: some View {
- group(loc.t("section.tools"), footnote: engine.usesEngineStore ? engine.status
- : (repo.status.isEmpty ? (repo.isRepo ? "" : loc.t("repo.firstHint")) : repo.status)) {
- if engine.usesEngineStore {
- engineRows
- } else {
- row(loc.t("repo.title"),
- detail: repo.isRepo ? m.shortPath(repo.path)
- : (repo.path.isEmpty ? loc.t("repo.notFound") : String(format: loc.t("repo.notRepo"), m.shortPath(repo.path))),
- dot: repo.isRepo ? LauncherPalette.ready : LauncherPalette.building, help: repo.path) {
- if repo.busy { ProgressView().controlSize(.small) }
- if repo.isRepo {
- if repo.isGit {
- if let n = repo.behind, n > 0 {
- Button(loc.t("repo.pull")) { repo.pull() }.disabled(repo.busy || m.running)
- .padTarget("set.repoPull", scope: "main") { if !(repo.busy || m.running) { repo.pull() } }
- }
- Button(loc.t("repo.check")) { repo.checkForUpdates() }.disabled(repo.busy || m.running)
- .padTarget("set.repoCheck", scope: "main") { if !(repo.busy || m.running) { repo.checkForUpdates() } }
- } else {
- Button(loc.t("repo.adopt")) { repo.adoptAsGit() }.disabled(repo.busy || m.running)
- .padTarget("set.repoAdopt", scope: "main") { if !(repo.busy || m.running) { repo.adoptAsGit() } }
- }
- }
- // Always offered, including when a repository is already configured: a saved path from
- // an earlier session (an upstream clone, a moved folder) is exactly the state a user
- // cannot fix without this button — the report had no way to leave the wrong repository.
- Button(loc.t("repo.choose")) { pickRepo() }
- if !repo.isRepo {
- Button(loc.t("repo.download")) { repo.clone() }.disabled(repo.busy || m.running)
- }
- }
- if !repo.isRepo {
- // GitHub does not load everywhere: the manual route (Code → Download ZIP → unzip →
- // Choose repository) needs no git at all, and the note says which folder to pick.
- HStack(spacing: 4) {
- Text(loc.t("repo.manualHint")).foregroundStyle(.secondary)
- Link("github.com/LNPANDY/NX2Apple", destination: URL(string: RepoStore.url.replacingOccurrences(of: ".git", with: ""))!)
- Text(loc.t("repo.manualHint2")).foregroundStyle(.secondary)
- }
- .font(.manrope(12)).padding(.horizontal, 18).padding(.bottom, 12)
- }
- if repo.isRepo, !repo.isGit {
- Text(loc.t(repo.autoUpdate ? "repo.noGit" : "repo.zipNoAuto")).font(.manrope(12)).foregroundStyle(.secondary)
- .padding(.horizontal, 18).padding(.bottom, 12)
- }
- if repo.isRepo, !RepoLayout.missingTools(in: repo.path).isEmpty {
- Text(String(format: loc.t("repo.toolsOld"), RepoLayout.missingTools(in: repo.path).joined(separator: ", ")))
- .font(.manrope(12)).foregroundStyle(LauncherPalette.building)
- .padding(.horizontal, 18).padding(.bottom, 12)
- }
- if repo.isRepo { // a ZIP copy too: its adoption at launch follows this switch
- divider
- row(loc.t("repo.auto"), detail: loc.t("repo.autoNote")) {
- Toggle("", isOn: $repo.autoUpdate).labelsHidden().toggleStyle(LauncherSwitchStyle())
- }
- }
- }
- divider
- Button(action: { withAnimation(.easeInOut(duration: 0.18)) { dependencies.toggle() } }) {
- row(loc.t("dep.title"),
- detail: !dependencies.checked ? loc.t("dep.checking")
- : (dependencies.allPresent ? loc.t("dep.allReady") : String(format: loc.t("dep.missing"), dependencies.deps.filter { !$0.present }.count)),
- dot: !dependencies.checked ? LauncherPalette.unbuilt : (dependencies.allPresent ? LauncherPalette.ready : LauncherPalette.building),
- open: dependencies.open) {
- if !dependencies.checked { ProgressView().controlSize(.small) }
- Button(loc.t("dep.recheck")) { _ = dependencies.check() }
- .padTarget("set.deps", scope: "main") { _ = dependencies.check() }
- }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- if dependencies.open {
- ForEach(dependencies.deps, id: \.id) { d in
- divider
- VStack(alignment: .leading, spacing: 0) {
- row(loc.t(d.name), detail: m.shortPath(dependencies.detail(of: d)), dot: d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building,
- help: loc.t(d.hint)) {
- if d.installing {
- ProgressView().controlSize(.small)
- Text(loc.t("dep.installing")).font(.manrope(12)).foregroundStyle(LauncherPalette.building)
- } else if !d.present {
- Button(d.actionLabel.isEmpty ? (d.installCmd.isEmpty ? loc.t("dep.openAppStore") : loc.t("dep.install")) : loc.t(d.actionLabel)) { _ = dependencies.install(d) }
- }
- }
- // Why the last install failed, and what to do about it: the tool's own
- // error line under the row, the fix (a command or a place to look) below it.
- if !d.lastError.isEmpty {
- VStack(alignment: .leading, spacing: 3) {
- Text(d.lastError).font(.mono(11)).foregroundStyle(LauncherPalette.building)
- .lineLimit(3).help(d.lastError)
- if !d.fixHint.isEmpty {
- Text(loc.t(d.fixHint)).font(.manrope(11.5)).foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true)
- }
- }
- .padding(.leading, 37).padding(.trailing, 18).padding(.bottom, 11)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- }
- }
- }
- divider
- row(loc.t("diag.title"), detail: loc.t("diag.note")) { DiagnosticsButton(report: diagnostics, game: library.selected) }
- }
- }
-
- /// The release app's engine (EngineSyncStore): which one the build uses, its channel, and the automatic update.
- @ViewBuilder private var engineRows: some View {
- let idle = !(engine.busy || m.running)
- row(loc.t("engine.title"), detail: engine.detail,
- dot: engine.selection.engineID.isEmpty ? LauncherPalette.building : LauncherPalette.ready, help: repo.path) {
- if engine.busy { ProgressView().controlSize(.small) }
- if let next = engine.available {
- Button(String(format: loc.t("engine.install"), next.version)) { engine.installAvailable() }.disabled(!idle)
- .padTarget("set.engineInstall", scope: "main") { if idle { engine.installAvailable() } }
- }
- Button(loc.t("repo.check")) { engine.checkForUpdate() }.disabled(!idle)
- .padTarget("set.engineCheck", scope: "main") { if idle { engine.checkForUpdate() } }
- }
- divider
- // A different channel is asked about first (the alert below): the switch can recompile every game's shaders
- row(loc.t("engine.update"), detail: loc.t("engine.channelNote"), dot: LauncherPalette.ready) {
- LauncherDropdown(options: EngineChannel.allCases.map { (value: $0.rawValue, label: loc.t($0.labelKey)) },
- selection: engine.selection.channel.rawValue) { v in
- if let channel = EngineChannel(rawValue: v) { engine.requestChannel(channel) }
- }
- .disabled(!idle)
- .padTarget("set.engineChannel", scope: "main") {
- if idle { engine.requestChannel(engine.selection.channel == .stable ? .experimental : .stable) }
- }
- }
- .alert(loc.t("engine.switch.title"), isPresented: Binding(get: { engine.confirmingChannel != nil },
- set: { if !$0 { engine.cancelChannel() } })) {
- if let channel = engine.confirmingChannel {
- Button(String(format: loc.t("engine.switch.go"), loc.t(channel.labelKey))) { engine.confirmChannel(channel) }
- }
- Button(loc.t("engine.switch.cancel"), role: .cancel) { engine.cancelChannel() }
- } message: {
- Text(engine.confirmingChannel.flatMap { engine.selection.channel.switchWarningKey(to: $0) }.map { loc.t($0) } ?? "")
- }
- divider
- row(loc.t("shellCache.row"), detail: loc.t("shellCache.note"), detail2: m.shellCachePath) {
- Button(loc.t("shellCache.open")) { m.revealFolder(URL(fileURLWithPath: m.shellCachePath)) }
- .buttonStyle(LauncherSecondaryButtonStyle())
- }
- divider
- row(loc.t("repo.auto"), detail: loc.t("engine.autoNote")) {
- Toggle("", isOn: $repo.autoUpdate).labelsHidden().toggleStyle(LauncherSwitchStyle())
- }
- }
-
- private func pickRepo() {
- let d = NSOpenPanel()
- d.canChooseDirectories = true; d.canChooseFiles = false
- d.message = loc.t("repo.pickMessage")
- if d.runModal() == .OK, let u = d.url { repo.path = u.path }
- }
-}
diff --git a/frontend/Sources/NX2Apple/FilesCard.swift b/frontend/Sources/NX2Apple/FilesCard.swift
new file mode 100644
index 00000000..9eb6305e
--- /dev/null
+++ b/frontend/Sources/NX2Apple/FilesCard.swift
@@ -0,0 +1,68 @@
+import SwiftUI
+import AppKit
+import NXCore
+import NXLauncher
+import NXModel
+
+/// The Builds page's first card: the game folder, the four input rows (base game, update, add-on content, prod.keys) and where the
+/// build goes. Observes the build store. It stays in the app target because it runs `KeyCheck` (KeyCheck.swift, which needs
+/// CommonCrypto) on the chosen files.
+struct FilesCard: View {
+ @ObservedObject var build: BuildStore
+ @EnvironmentObject var loc: Localizer
+ @Binding var extrasOpen: Bool // the optional input rows, kept by the page so they stay as they were when it is left and back
+ @State private var keyCheck: KeyCheck.Outcome? // prod.keys against the chosen files (KeyCheck.swift)
+
+ var body: some View {
+ // The report's own mistake, and a reasonable one: the output folder silently decides where
+ // the build cache lives, so changing it threw away a finished build. Say it under Save to, all the time.
+ CardGroup(loc.t("section.files"), footnote: loc.t("msg.workdirHint")) {
+ Button(action: pickFolder) {
+ CardRow(loc.t(build.gameDir.isEmpty ? "build.folderCTA" : "build.folderSelected"),
+ detail: build.gameDir.isEmpty ? loc.t("build.folderNote") : build.shortPath(build.gameDir), help: build.gameDir) {
+ Text(loc.t(build.gameDir.isEmpty ? "data.choose" : "data.change"))
+ .font(.manrope(13, .semibold)).foregroundStyle(.black)
+ .launcherRowControlFrame()
+ .background(LauncherPalette.cream, in: Capsule())
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ ForEach(build.slots.filter { !$0.optional }, id: \.id) { s in
+ CardDivider(); slotRow(s)
+ if s.id == "keys", let keyCheck { KeyCheckLine(outcome: keyCheck, t: loc.t) }
+ }
+ CardDivider()
+ CardDisclosure(loc.t("build.options"), isOpen: extrasOpen) { extrasOpen.toggle() }
+ if extrasOpen {
+ ForEach(build.slots.filter(\.optional), id: \.id) { s in CardDivider(); slotRow(s) }
+ }
+ CardDivider()
+ CardRow(loc.t("build.saveTo"), detail: build.outDir.isEmpty ? loc.t("build.saveDefault") : build.shortPath(build.outDir), help: build.outDir) {
+ Button(loc.t("data.change")) { build.chooseBuildFolder() }
+ }
+ }
+ .task(id: KeyCheck.Inputs(keys: build.keysPath, files: [build.basePath, build.updatePath] + build.dlcPaths)) {
+ keyCheck = await KeyCheck.runDetached(KeyCheck.Inputs(keys: build.keysPath, files: [build.basePath, build.updatePath] + build.dlcPaths))
+ }
+ .disabled(build.running)
+ }
+
+ private func slotRow(_ s: Slot) -> some View {
+ // An empty prod.keys row says where the file comes from.
+ CardRow(loc.t(s.title), detail: s.id == "keys" && s.paths.isEmpty ? loc.t("build.keyHint") : s.summary(loc.t), dot: s.ok ? LauncherPalette.ready : LauncherPalette.unbuilt,
+ help: s.paths.joined(separator: "\n")) {
+ if !s.paths.isEmpty {
+ Button(loc.t("data.clear")) { build.clear(s.id) }.buttonStyle(.plain)
+ .font(.manrope(13)).foregroundStyle(.secondary)
+ }
+ Button(s.paths.isEmpty ? loc.t("data.choose") : loc.t("data.change")) { build.pickFiles(kind: s.kind) }
+ }
+ }
+
+ private func pickFolder() {
+ let d = NSOpenPanel()
+ d.canChooseDirectories = true; d.canChooseFiles = false
+ if d.runModal() == .OK, let u = d.url { build.scan(folder: u.path) }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/LauncherView.swift b/frontend/Sources/NX2Apple/LauncherView.swift
index d65f1e55..65856f49 100644
--- a/frontend/Sources/NX2Apple/LauncherView.swift
+++ b/frontend/Sources/NX2Apple/LauncherView.swift
@@ -177,10 +177,10 @@ struct ContentView: View {
if page == .library {
libraryPage
} else {
- BuilderView(m: m, updates: updates, repo: repo, engine: engine, dependencies: stores.dependencies, devices: devices, diagnostics: stores.diagnostics, library: library, settings: page == .settings, onViewGame: { page = .library },
- onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,
- onOpenControls: { controlsOpen = true }, onOpenControllers: { controllerSheet = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,
- padMerge: Binding(get: { controls.padMerge }, set: { setPadMerge($0) }))
+ CardPages(settings: page == .settings, build: m, updates: updates, repo: repo, engine: engine, dependencies: stores.dependencies, devices: devices,
+ library: library, diagnostics: stores.diagnostics, onViewGame: { page = .library }, onOpenSettings: { page = .settings },
+ onChooseLibraryFolder: chooseLibraryFolder, onOpenControls: { controlsOpen = true }, onOpenControllers: { controllerSheet = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,
+ padMerge: Binding(get: { controls.padMerge }, set: { setPadMerge($0) }))
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
if m.running || page == .library { activityBar }
diff --git a/frontend/Sources/NX2Apple/SettingsPage.swift b/frontend/Sources/NX2Apple/SettingsPage.swift
new file mode 100644
index 00000000..ac43bf9d
--- /dev/null
+++ b/frontend/Sources/NX2Apple/SettingsPage.swift
@@ -0,0 +1,67 @@
+import SwiftUI
+import NXCore
+import NXLauncher
+import NXModel
+
+// The Settings page: one card per area, in order. The page owns what only the app can give the cards: the switches kept in the app's
+// defaults (the console prompt, build notifications, return after play), the library and the Copy diagnostics report.
+
+struct SettingsPage: View {
+ let build: BuildStore // whether a build runs turns off the update and pull buttons
+ let updates: AppUpdateStore
+ let repo: RepoStore
+ let engine: EngineSyncStore
+ let dependencies: DependencyStore
+ @ObservedObject var library: GameLibrary
+ var diagnostics: (LibraryGame?, @escaping (String) -> Void) -> Void = { _, _ in } // the report of Copy diagnostics (LauncherStores)
+ var onChooseLibraryFolder: () -> Void = {}
+ var onOpenControls: () -> Void = {}
+ var onOpenControllers: () -> Void = {} // the Controllers sheet (the console mode's list, with the player-mode setting)
+ var onRunSetup: (() -> Void)? // the guided first-run setup, again (nil where there is none)
+ var controlChanges = 0
+ var padMerge: Binding<Bool> = .constant(false) // "All controllers are player 1" (ControlLayout.padMerge)
+ @AppStorage(ConsolePrompt.defaultsKey) private var consolePromptOn = true // ConsoleCoordinator.swift
+ @AppStorage(BuildNotice.defaultsKey) private var notifyBuilds = true // BuildNotifications.swift
+ @AppStorage(ReturnAfterPlay.defaultsKey) private var returnAfterPlay = true // ReturnAfterPlay.swift
+ @EnvironmentObject var loc: Localizer
+
+ var body: some View {
+ CardPageHeading(loc.t("settings.heading"), note: loc.t("settings.note"))
+ LibraryCard(library: library, onChooseFolder: onChooseLibraryFolder)
+ ControlsCard(controlChanges: controlChanges, padMerge: padMerge, consolePrompt: $consolePromptOn,
+ onOpenControls: onOpenControls, onOpenControllers: onOpenControllers)
+ ToolsCard(repo: repo, engine: engine, dependencies: dependencies, buildRunning: build.running,
+ shellCachePath: build.shellCachePath, revealFolder: { build.revealFolder($0) }) {
+ DiagnosticsButton(report: diagnostics, game: library.selected)
+ }
+ AppCard(updates: updates, buildRunning: build.running, notify: $notifyBuilds, notifyAvailable: BuildNotice.hasBundleID,
+ returnAfterPlay: $returnAfterPlay, onRunSetup: onRunSetup, uninstallPlan: uninstallPlan)
+ }
+
+ private func uninstallPlan() -> Uninstall.Plan {
+ Uninstall.plan(home: NSHomeDirectory(), gamesFolder: library.folder, outputFolder: build.outDir,
+ checkouts: [repo.path], defaultsDomain: Bundle.main.bundleIdentifier)
+ }
+}
+
+/// Settings, "Library": the folder the launcher looks for games in. It stays in the app target because it observes `GameLibrary`.
+struct LibraryCard: View {
+ @ObservedObject var library: GameLibrary
+ let onChooseFolder: () -> Void
+ @EnvironmentObject var loc: Localizer
+
+ var body: some View {
+ CardGroup(loc.t("section.library"), footnote: loc.t("library.folderHint")) {
+ CardRow(loc.t("library.folderTitle"), detail: library.folder.isEmpty ? loc.t("library.folderUnset") : RepoLayout.shortPath(library.folder),
+ dot: library.folder.isEmpty ? LauncherPalette.unbuilt : LauncherPalette.ready, help: library.folder) {
+ if library.scanning { ProgressView().controlSize(.small) }
+ if !library.folder.isEmpty {
+ Button(loc.t("library.rescan")) { library.discover() }.disabled(library.scanning)
+ .padTarget("set.rescan", scope: "main") { if !library.scanning { library.discover() } }
+ }
+ Button(loc.t("library.chooseFolder"), action: onChooseFolder)
+ .padTarget("set.folder", scope: "main") { onChooseFolder() }
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NXLauncher/ActionCard.swift b/frontend/Sources/NXLauncher/ActionCard.swift
new file mode 100644
index 00000000..32ff6116
--- /dev/null
+++ b/frontend/Sources/NXLauncher/ActionCard.swift
@@ -0,0 +1,57 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// The page's conclusion, at the end of its column: what is still missing, and the build button.
+/// Observes the build store, and the dependency and repository stores for the status text.
+package struct ActionCard: View {
+ @ObservedObject var build: BuildStore
+ @ObservedObject var dependencies: DependencyStore
+ @ObservedObject var repo: RepoStore
+ @EnvironmentObject var loc: Localizer
+
+ package init(build: BuildStore, dependencies: DependencyStore, repo: RepoStore) {
+ self.build = build
+ self.dependencies = dependencies
+ self.repo = repo
+ }
+
+ package var body: some View {
+ HStack(spacing: 18) {
+ statusText
+ Spacer(minLength: 12)
+ Button {
+ build.running ? build.stop() : build.startBuild()
+ } label: {
+ Label(build.running ? loc.t(build.stopping ? "library.stopping" : "btn.stop") : (build.done ? loc.t("btn.rebuild") : loc.t("build.startGame")),
+ systemImage: build.running ? "stop.fill" : "hammer.fill")
+ .font(.manrope(15, .semibold)).padding(.horizontal, 24).padding(.vertical, 13)
+ .foregroundStyle(.black).background(build.running ? LauncherPalette.building : LauncherPalette.cream, in: Capsule())
+ }
+ .buttonStyle(.plain)
+ .disabled(build.stopping || (!build.running && !build.canBuild))
+ .opacity(build.stopping || (!build.running && !build.canBuild) ? 0.4 : 1)
+ .keyboardShortcut(.return, modifiers: .command)
+ }
+ .padding(.top, 2)
+ .staleFrameworksPrompt(build)
+ }
+
+ @ViewBuilder private var statusText: some View {
+ if !build.doneNote.isEmpty {
+ Text(build.doneNote).font(.manrope(13))
+ .foregroundStyle(build.done ? LauncherPalette.ready : LauncherPalette.building).lineLimit(2)
+ } else if !dependencies.checked {
+ Text(loc.t("status.checkingDeps")).font(.manrope(13)).foregroundStyle(.secondary)
+ } else if !dependencies.allPresent {
+ Text(loc.t("status.installFirst")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)
+ } else if !repo.isRepo {
+ Text(loc.t("status.chooseRepo")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)
+ } else if !build.slot("base").ok || !build.slot("keys").ok {
+ Text(loc.t("status.needInputs")).font(.manrope(13)).foregroundStyle(.secondary)
+ } else {
+ Text(String(format: loc.t("status.output"), build.shortPath(build.outDir.isEmpty ? (build.basePath as NSString).deletingLastPathComponent : build.outDir)))
+ .font(.manrope(13)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.head)
+ }
+ }
+}
diff --git a/frontend/Sources/NXLauncher/AppCard.swift b/frontend/Sources/NXLauncher/AppCard.swift
new file mode 100644
index 00000000..d61c3c1f
--- /dev/null
+++ b/frontend/Sources/NXLauncher/AppCard.swift
@@ -0,0 +1,111 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// Settings, "NX2Apple": the language, notifications, the guided setup, the self-update and the uninstaller. Observes the update
+/// store. The two switches that live in the app's defaults come as bindings, and what the uninstaller needs from the library
+/// and the build store as a closure.
+package struct AppCard: View {
+ @ObservedObject var updates: AppUpdateStore
+ let buildRunning: Bool
+ let notify: Binding<Bool>
+ let notifyAvailable: Bool // false without an app bundle, e.g. under swift run
+ let returnAfterPlay: Binding<Bool>
+ let onRunSetup: (() -> Void)? // the guided first-run setup, again (nil where there is none)
+ let uninstallPlan: () -> Uninstall.Plan
+ @EnvironmentObject var loc: Localizer
+
+ package init(updates: AppUpdateStore, buildRunning: Bool, notify: Binding<Bool>, notifyAvailable: Bool, returnAfterPlay: Binding<Bool>,
+ onRunSetup: (() -> Void)?, uninstallPlan: @escaping () -> Uninstall.Plan) {
+ self.updates = updates
+ self.buildRunning = buildRunning
+ self.notify = notify
+ self.notifyAvailable = notifyAvailable
+ self.returnAfterPlay = returnAfterPlay
+ self.onRunSetup = onRunSetup
+ self.uninstallPlan = uninstallPlan
+ }
+
+ /// The language picker's choices in order, "" being the system's. A new language is one more code here and its
+ /// "settings.language.<code>" entry, which is its own name (Svenska, Deutsch) in every language.
+ package static let languageCodes = ["", "zh", "en", "sv", "de", "fr"]
+
+ package var body: some View {
+ CardGroup(loc.t("section.app"), footnote: updates.status) {
+ // The interface language: the device default unless someone picks one here. Stored as
+ // "" (follow), "zh", "en", "sv", "de" or "fr" so a later system-language change still applies.
+ CardRow(loc.t("settings.language"),
+ detail: Lang.saved.map { loc.t("settings.language.\($0.rawValue)") }
+ ?? loc.t("settings.language.system"), dot: LauncherPalette.ready, help: "") {
+ // The launcher's own list, drawn like the buttons beside it and as wide as they are.
+ // The language names are in their own language (see "settings.language.*"), only "system" follows the UI.
+ LauncherDropdown(options: Self.languageCodes.map { (value: $0, label: loc.t("settings.language." + ($0.isEmpty ? "system" : $0))) },
+ selection: Lang.saved.map { $0.rawValue } ?? "", label: loc.t("settings.language"),
+ style: .button) { v in
+ loc.choose(v)
+ }
+ .padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) })
+ }
+ CardDivider()
+ // Build notifications (BuildNotifications.swift): none without an app bundle, e.g. under swift run
+ CardRow(loc.t("settings.notify"), detail: loc.t(notifyAvailable ? "settings.notifyNote" : "settings.notifyUnbundled")) {
+ Toggle("", isOn: notify).toggleStyle(LauncherSwitchStyle()).labelsHidden().disabled(!notifyAvailable)
+ .padTarget("set.notify", scope: "main") { notify.wrappedValue.toggle() }
+ }
+ CardDivider()
+ if let onRunSetup {
+ CardRow(loc.t("settings.setup"), detail: loc.t("settings.setupNote")) {
+ Button(loc.t("settings.setupBtn"), action: onRunSetup)
+ .padTarget("set.setup", scope: "main") { onRunSetup() }
+ }
+ CardDivider()
+ }
+ // The launcher back in front when a game it started quits (ReturnAfterPlay.swift)
+ CardRow(loc.t("settings.returnAfterPlay"), detail: loc.t("settings.returnAfterPlayNote")) {
+ Toggle("", isOn: returnAfterPlay).toggleStyle(LauncherSwitchStyle()).labelsHidden()
+ .padTarget("set.returnAfterPlay", scope: "main") { returnAfterPlay.wrappedValue.toggle() }
+ }
+ CardDivider()
+ CardRow("NX2Apple", detail: String(format: loc.t("app.version"), updates.version),
+ dot: updates.staged != nil ? LauncherPalette.ready : nil) {
+ if updates.busy { ProgressView().controlSize(.small) }
+ if updates.staged != nil {
+ // Downloaded and verified: it goes in when the app quits; this restarts into it now (not during a build)
+ Button(loc.t("app.restartNow")) { updates.restartNow() }.disabled(buildRunning)
+ .padTarget("set.appRestart", scope: "main") { if !buildRunning { updates.restartNow() } }
+ } else if let u = updates.update, updates.installability == .ok {
+ Button(String(format: loc.t("app.updateBtn"), u.tag)) { updates.performUpdate() }.disabled(updates.busy || buildRunning)
+ .padTarget("set.appUpdate", scope: "main") { if !(updates.busy || buildRunning) { updates.performUpdate() } }
+ } else {
+ Button(loc.t("repo.check")) { updates.checkForUpdate() }.disabled(updates.busy)
+ .padTarget("set.appCheck", scope: "main") { if !updates.busy { updates.checkForUpdate() } }
+ }
+ }
+ CardDivider()
+ if updates.installability == .ok {
+ // The uninstaller (Uninstall.swift): state folders and the launcher's own checkout go; the
+ // games folder and prod.keys stay; the app itself goes to the Trash.
+ CardRow(loc.t("uninstall.title"), detail: loc.t("uninstall.note")) {
+ Button(loc.t("uninstall.button")) { updates.uninstallPlan = uninstallPlan() }
+ .disabled(buildRunning)
+ .padTarget("set.uninstall", scope: "main") { if !buildRunning { updates.uninstallPlan = uninstallPlan() } }
+ }
+ CardDivider()
+ }
+ // A launcher built from the repository never replaces itself (AppUpdate.installability): the switch says so and stays off
+ CardRow(loc.t("app.auto"), detail: loc.t(updates.installability == .ok ? "app.autoNote" : updates.installability == .developer ? "app.autoDev" : "app.autoReadOnly")) {
+ Toggle("", isOn: Binding(get: { updates.automatic && updates.installability == .ok }, set: { updates.automatic = $0 }))
+ .labelsHidden().toggleStyle(LauncherSwitchStyle()).disabled(updates.installability != .ok)
+ .padTarget("set.appAuto", scope: "main") { if updates.installability == .ok { updates.automatic.toggle() } }
+ }
+ }
+ }
+
+ /// The interface language one step on (a controller's left / right on the language list).
+ private func cycleLanguage(_ by: Int) {
+ let values = Self.languageCodes
+ let at = values.firstIndex(of: Lang.saved.map { $0.rawValue } ?? "") ?? 0
+ let v = values[(at + by + values.count) % values.count]
+ loc.choose(v)
+ }
+}
diff --git a/frontend/Sources/NX2Apple/BuildFailureView.swift b/frontend/Sources/NXLauncher/BuildFailureCard.swift
similarity index 93%
rename from frontend/Sources/NX2Apple/BuildFailureView.swift
rename to frontend/Sources/NXLauncher/BuildFailureCard.swift
index ccc5ab3f..ba2c1d30 100644
--- a/frontend/Sources/NX2Apple/BuildFailureView.swift
+++ b/frontend/Sources/NXLauncher/BuildFailureCard.swift
@@ -5,7 +5,7 @@ import NXLauncher
/// Under the build button after a stop the script's early checks explain: what happened in plain words, the next step, and the
/// button that does it (a dependency's own install command, or "Build anyway" for the three stops that have an override).
-struct BuildFailureCard: View {
+package struct BuildFailureCard: View {
@ObservedObject var m: BuildStore
/// Where the engine's failure row retries. nil for a failure of a build.
var engine: EngineSyncStore?
@@ -13,13 +13,13 @@ struct BuildFailureCard: View {
/// The failure to show: the build's (`m.failure`) unless the caller passes another one, such as the engine sync's.
var failure: BuildFailure?
- init(m: BuildStore, engine: EngineSyncStore? = nil, failure: BuildFailure? = nil) {
+ package init(m: BuildStore, engine: EngineSyncStore? = nil, failure: BuildFailure? = nil) {
self.m = m
self.engine = engine
self.failure = failure
}
- var body: some View {
+ package var body: some View {
if let f = failure ?? m.failure {
VStack(alignment: .leading, spacing: 10) {
Text(loc.t("fail.section")).font(.manrope(15, .semibold)).foregroundStyle(.secondary).padding(.leading, 2)
@@ -93,12 +93,17 @@ struct BuildFailureCard: View {
/// Above every page of the launcher while the engine is fetched and patched (tools/engine.py sync, run for a checkout at launch and after
/// updates), and its failure row when that stops: what happened, what to do, and Try again.
-struct EngineSyncBanner: View {
+package struct EngineSyncBanner: View {
@ObservedObject var engine: EngineSyncStore
let m: BuildStore
@EnvironmentObject var loc: Localizer
- var body: some View {
+ package init(engine: EngineSyncStore, m: BuildStore) {
+ self.engine = engine
+ self.m = m
+ }
+
+ package var body: some View {
if engine.syncing {
HStack(spacing: 10) {
ProgressView().controlSize(.small)
diff --git a/frontend/Sources/NXLauncher/ControlsCard.swift b/frontend/Sources/NXLauncher/ControlsCard.swift
new file mode 100644
index 00000000..75207eba
--- /dev/null
+++ b/frontend/Sources/NXLauncher/ControlsCard.swift
@@ -0,0 +1,47 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// Settings, "Controls": the key layout, the merge of all controllers into player 1, the controllers list and the console prompt.
+/// It observes no store: the layout's numbers and switches come from the app as values and bindings.
+package struct ControlsCard: View {
+ let controlChanges: Int
+ let padMerge: Binding<Bool> // "All controllers are player 1" (ControlLayout.padMerge)
+ let consolePrompt: Binding<Bool>
+ let onOpenControls: () -> Void
+ let onOpenControllers: () -> Void // the Controllers sheet (the console mode's list, with the player-mode setting)
+ @EnvironmentObject var loc: Localizer
+
+ package init(controlChanges: Int, padMerge: Binding<Bool>, consolePrompt: Binding<Bool>,
+ onOpenControls: @escaping () -> Void, onOpenControllers: @escaping () -> Void) {
+ self.controlChanges = controlChanges
+ self.padMerge = padMerge
+ self.consolePrompt = consolePrompt
+ self.onOpenControls = onOpenControls
+ self.onOpenControllers = onOpenControllers
+ }
+
+ package var body: some View {
+ CardGroup(loc.t("section.controls"), footnote: loc.t("controls.settingsHint")) {
+ CardRow(loc.t("controls.row"), detail: controlChanges == 0 ? loc.t("controls.defaultLayout") : String(format: loc.t("controls.changes"), controlChanges)) {
+ Button(loc.t("controls.customize"), action: onOpenControls)
+ .padTarget("set.controls", scope: "main") { onOpenControls() }
+ }
+ CardDivider()
+ CardRow(loc.t("console.mergeAll"), detail: loc.t("console.mergeNote")) {
+ Toggle("", isOn: padMerge).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ .padTarget("set.padMerge", scope: "main") { padMerge.wrappedValue.toggle() }
+ }
+ CardDivider()
+ CardRow(loc.t("console.controllers"), detail: loc.t("console.controllersRowNote")) {
+ Button(loc.t("console.controllersOpen"), action: onOpenControllers)
+ .padTarget("set.controllers", scope: "main") { onOpenControllers() }
+ }
+ CardDivider()
+ CardRow(loc.t("console.promptSetting"), detail: loc.t("console.promptSettingNote")) {
+ Toggle("", isOn: consolePrompt).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ .padTarget("set.consolePrompt", scope: "main") { consolePrompt.wrappedValue.toggle() }
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/DockProgress.swift b/frontend/Sources/NXLauncher/DockProgress.swift
similarity index 90%
rename from frontend/Sources/NX2Apple/DockProgress.swift
rename to frontend/Sources/NXLauncher/DockProgress.swift
index 405549c2..44e8c570 100644
--- a/frontend/Sources/NX2Apple/DockProgress.swift
+++ b/frontend/Sources/NXLauncher/DockProgress.swift
@@ -4,15 +4,15 @@ import AppKit
/// native gray progress bar along its bottom, so a build's progress is visible from wherever the
/// launcher was left. macOS has no public API for the App Store bar, so this is a plain
/// NSProgressIndicator on the Dock tile.
-enum DockProgress {
+package enum DockProgress {
/// The text for a progress fraction (accessibility label); nil clears the tile. Pure, so tests run it.
- static func percentText(_ fraction: Double?) -> String? {
+ package static func percentText(_ fraction: Double?) -> String? {
guard let fraction, fraction.isFinite, fraction >= 0, fraction <= 1 else { return nil }
return "\(Int((fraction * 100).rounded()))%"
}
/// The tile's view: the app icon with a bar style progress indicator near its bottom edge.
- static func makeTileView(fraction: Double, icon: NSImage, size: CGFloat = 128) -> NSView {
+ package static func makeTileView(fraction: Double, icon: NSImage, size: CGFloat = 128) -> NSView {
let tile = NSView(frame: NSRect(x: 0, y: 0, width: size, height: size))
let iconView = NSImageView(frame: tile.bounds)
iconView.image = icon
@@ -40,7 +40,7 @@ enum DockProgress {
}
/// The view drawn to an image with its colors turned to gray.
- static func grayImage(of view: NSView) -> NSImage {
+ package static func grayImage(of view: NSView) -> NSImage {
guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return NSImage() }
view.cacheDisplay(in: view.bounds, to: rep)
let color = NSImage(size: view.bounds.size)
@@ -54,7 +54,7 @@ enum DockProgress {
}
/// Reflects the running build on the Dock tile; nil restores the plain icon.
- static func update(_ fraction: Double?) {
+ package static func update(_ fraction: Double?) {
let dock = NSApplication.shared.dockTile
guard let fraction, percentText(fraction) != nil else {
dock.contentView = nil
diff --git a/frontend/Sources/NX2Apple/DropFiles.swift b/frontend/Sources/NXLauncher/DropFiles.swift
similarity index 89%
rename from frontend/Sources/NX2Apple/DropFiles.swift
rename to frontend/Sources/NXLauncher/DropFiles.swift
index 5abcfbc6..13d26030 100644
--- a/frontend/Sources/NX2Apple/DropFiles.swift
+++ b/frontend/Sources/NXLauncher/DropFiles.swift
@@ -8,19 +8,19 @@ import NXLauncher
// (GameInputs.classify), so a drop and a picked folder never disagree about what is the update.
/// The Builds page as a drop target: a highlight while files are dragged over it, the files to the model when dropped.
-struct GameFilesDrop: ViewModifier {
+package struct GameFilesDrop: ViewModifier {
let enabled: Bool
let label: String
let onDrop: ([String]) -> Void
@State private var targeted: Bool
/// `targeted` starts the highlight on (visual QA renders it without a drag).
- init(enabled: Bool, label: String, targeted: Bool = false, onDrop: @escaping ([String]) -> Void) {
+ package init(enabled: Bool, label: String, targeted: Bool = false, onDrop: @escaping ([String]) -> Void) {
self.enabled = enabled; self.label = label; self.onDrop = onDrop
_targeted = State(initialValue: targeted)
}
- func body(content: Content) -> some View {
+ package func body(content: Content) -> some View {
content
.overlay {
if targeted && enabled {
@@ -47,7 +47,7 @@ struct GameFilesDrop: ViewModifier {
}
/// The file URLs of a drop, delivered on the main queue once all have loaded.
- static func paths(from providers: [NSItemProvider], then done: @escaping ([String]) -> Void) {
+ package static func paths(from providers: [NSItemProvider], then done: @escaping ([String]) -> Void) {
let group = DispatchGroup()
let lock = NSLock()
var paths: [String] = []
diff --git a/frontend/Sources/NXLauncher/InstallCard.swift b/frontend/Sources/NXLauncher/InstallCard.swift
new file mode 100644
index 00000000..5db3ca53
--- /dev/null
+++ b/frontend/Sources/NXLauncher/InstallCard.swift
@@ -0,0 +1,46 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// Where an iPhone build goes: exported as an IPA (as before), or signed and installed on a paired device. Shown for the iPhone
+/// target only. Observes the device store, and the build store for the target and whether a build runs.
+package struct InstallCard: View {
+ @ObservedObject var devices: DeviceStore
+ @ObservedObject var build: BuildStore
+ @EnvironmentObject var loc: Localizer
+
+ package init(devices: DeviceStore, build: BuildStore) {
+ self.devices = devices
+ self.build = build
+ }
+
+ package var body: some View {
+ if build.target != BuildTarget.mac { card.disabled(build.running) }
+ }
+
+ private var card: some View {
+ let options = [(value: "", label: loc.t("dev.none"))] + devices.devices.map { d in
+ (value: d.id, label: d.name + (d.reachable ? "" : " (" + loc.t("dev.notConnected") + ")"))
+ }
+ let teams = devices.teams.map { (value: $0.id, label: $0.label(personalTeam: loc.t("dev.personalTeam"))) }
+ let needsCertificate = devices.teams.first { $0.id == devices.signingTeam }.map { !$0.hasCertificate } ?? false
+ return CardGroup(loc.t("dev.section"), footnote: devices.installDevice.isEmpty ? "" : (needsCertificate ? loc.t("dev.teamNoCert") + " " : "") + loc.t("dev.note")) {
+ CardRow(loc.t("dev.target"), detail: devices.checked && devices.devices.isEmpty ? loc.t("dev.noDevices") : "") {
+ if !devices.checked { ProgressView().controlSize(.small) }
+ Button(loc.t("dev.refresh")) { _ = devices.refresh() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)
+ LauncherDropdown(options: options, selection: devices.installDevice, label: loc.t("dev.target")) { devices.installDevice = $0 }
+ }
+ if !devices.installDevice.isEmpty {
+ CardDivider()
+ if teams.isEmpty {
+ CardRow(loc.t("dev.team"), detail: loc.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() }
+ } else {
+ CardRow(loc.t("dev.team")) {
+ LauncherDropdown(options: teams, selection: devices.signingTeam, label: loc.t("dev.team")) { devices.signingTeam = $0 }
+ }
+ }
+ }
+ }
+ .onAppear { if !devices.checked { _ = devices.refresh() } }
+ }
+}
diff --git a/frontend/Sources/NXLauncher/LauncherCard.swift b/frontend/Sources/NXLauncher/LauncherCard.swift
new file mode 100644
index 00000000..2317eb91
--- /dev/null
+++ b/frontend/Sources/NXLauncher/LauncherCard.swift
@@ -0,0 +1,176 @@
+import SwiftUI
+import AppKit
+import NXCore
+import NXModel
+
+// The pieces every card of the Builds and Settings pages is made of: a titled group, a row, a divider, a disclosure row.
+// They are the library's and the launch options' look (LNPANDY/NX2Apple#387, step 8).
+
+extension StepState {
+ package var color: Color {
+ switch self {
+ case .pending: return .gray
+ case .running: return .yellow
+ case .done: return .green
+ case .failed: return .red
+ }
+ }
+}
+
+/// The big title of a page with a note under it.
+package struct CardPageHeading: View {
+ let title: String
+ let note: String
+
+ package init(_ title: String, note: String) {
+ self.title = title
+ self.note = note
+ }
+
+ package var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(title).font(.manrope(44, .heavy)).tracking(-1.3)
+ Text(note).font(.manrope(15)).foregroundStyle(.secondary)
+ }
+ }
+}
+
+/// A titled group: a small tracked label over one card of rows.
+package struct CardGroup<Content: View>: View {
+ let label: String
+ let footnote: String
+ let content: Content
+
+ package init(_ label: String, footnote: String = "", @ViewBuilder _ content: () -> Content) {
+ self.label = label
+ self.footnote = footnote
+ self.content = content()
+ }
+
+ package var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(label).font(.manrope(15, .semibold)).foregroundStyle(.secondary)
+ .padding(.leading, 2)
+ VStack(spacing: 0) { content }
+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
+ if !footnote.isEmpty {
+ Text(footnote).font(.manrope(12)).foregroundStyle(.secondary).padding(.leading, 2)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+}
+
+/// One line of a card: a status dot (its place kept when there is none, so every title starts on one line),
+/// the title (with a disclosure chevron beside it when `open` is given), a secondary detail, and its controls.
+/// Its buttons and dropdowns are all LauncherControl.width wide, so they line up in one column across the cards.
+package struct CardRow<Trailing: View>: View {
+ let title: String
+ let detail: String
+ let detail2: String
+ let dot: Color?
+ let help: String
+ let open: Bool?
+ let trailing: Trailing
+
+ package init(_ title: String, detail: String = "", detail2: String = "", dot: Color? = nil, help: String = "", open: Bool? = nil,
+ @ViewBuilder trailing: () -> Trailing) {
+ self.title = title
+ self.detail = detail
+ self.detail2 = detail2
+ self.dot = dot
+ self.help = help
+ self.open = open
+ self.trailing = trailing()
+ }
+
+ package var body: some View {
+ HStack(spacing: 12) {
+ Circle().fill(dot ?? .clear).frame(width: 7, height: 7)
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 6) {
+ Text(title).font(.manrope(14)).fixedSize(horizontal: false, vertical: true)
+ if let open {
+ Image(systemName: "chevron.right").font(.system(size: 10, weight: .bold)).foregroundStyle(.secondary)
+ .rotationEffect(.degrees(open ? 90 : 0))
+ }
+ }
+ if !detail.isEmpty {
+ // A path is technical text: the system's monospaced face, on one line, cut in the middle when
+ // too long. Everything else is prose in Manrope and wraps, so no word is ever cut.
+ if detail.hasPrefix("/") || detail.hasPrefix("~") {
+ Text(detail).font(.mono(12)).foregroundStyle(.secondary)
+ .lineLimit(1).truncationMode(.middle).help(help.isEmpty ? detail : help)
+ } else {
+ Text(detail).font(.manrope(12.5)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true).help(help.isEmpty ? detail : help)
+ }
+ }
+ if !detail2.isEmpty {
+ Text(detail2).font(.mono(12)).foregroundStyle(.secondary)
+ .lineLimit(1).truncationMode(.middle).help(detail2)
+ }
+ }
+ Spacer(minLength: 12)
+ trailing.launcherRowControls()
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13)
+ .frame(minHeight: 52)
+ }
+}
+
+package struct CardDivider: View {
+ package init() {}
+ package var body: some View { Divider().opacity(0.25).padding(.leading, 18) }
+}
+
+/// A row that opens the rows under it.
+package struct CardDisclosure: View {
+ let title: String
+ let detail: String
+ let isOpen: Bool
+ let toggle: () -> Void
+
+ package init(_ title: String, detail: String = "", isOpen: Bool, toggle: @escaping () -> Void) {
+ self.title = title
+ self.detail = detail
+ self.isOpen = isOpen
+ self.toggle = toggle
+ }
+
+ package var body: some View {
+ Button(action: { withAnimation(.easeInOut(duration: 0.18)) { toggle() } }) {
+ CardRow(title, detail: detail, open: isOpen) { EmptyView() }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+/// The scrolling column of a page of cards. A controller's focus on one of its `set.` targets scrolls into view.
+package struct LauncherPageScroll<Content: View>: View {
+ let content: Content
+ @EnvironmentObject private var padFocus: PadFocus
+
+ package init(@ViewBuilder _ content: () -> Content) { self.content = content() }
+
+ package var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView(.vertical) {
+ VStack(alignment: .leading, spacing: 34) { content }
+ .padding(.horizontal, 40).padding(.top, 40).padding(.bottom, 48)
+ .frame(maxWidth: 900)
+ .frame(maxWidth: .infinity)
+ }
+ .onChange(of: padFocus.focused) { id in // a controller's focus on this page scrolls into view
+ if let id, id.hasPrefix("set.") { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } }
+ }
+ }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ }
+}
+
+package func revealInFinder(_ path: String) {
+ NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
+}
diff --git a/frontend/Sources/NXLauncher/LogCard.swift b/frontend/Sources/NXLauncher/LogCard.swift
new file mode 100644
index 00000000..deb1160b
--- /dev/null
+++ b/frontend/Sources/NXLauncher/LogCard.swift
@@ -0,0 +1,42 @@
+import Combine
+import SwiftUI
+import NXCore
+import NXModel
+
+/// The build log, right under the Mac / iPhone choice and folded away until it is asked for.
+/// It used to sit at the bottom of the progress card, which is where a failed build's message
+/// pointed ("see the log below") while the log itself was out of view on a short window (#52).
+/// Observes the device store (for the note about the data transfer) and, through `BuildLogView`, the log.
+package struct LogCard: View {
+ let log: BuildLog
+ @ObservedObject var devices: DeviceStore
+ /// A request to open the log (a clicked notification of a failed build). `didShow` tells the sender it was taken.
+ let showRequests: AnyPublisher<Bool, Never>
+ let didShow: () -> Void
+ @EnvironmentObject var loc: Localizer
+ @Binding var logOpen: Bool // kept by the page, so the log stays open when the page is left and back
+
+ package init(log: BuildLog, devices: DeviceStore, isOpen: Binding<Bool>, showRequests: AnyPublisher<Bool, Never>, didShow: @escaping () -> Void) {
+ self.log = log
+ self.devices = devices
+ _logOpen = isOpen
+ self.showRequests = showRequests
+ self.didShow = didShow
+ }
+
+ package var body: some View {
+ CardGroup(loc.t("section.log")) {
+ if devices.shellCopy != nil || devices.shellWaiting {
+ // The log below is the build's own output; the data transfer is driven by the app, so
+ // its questions and errors (a locked device, a failed listing) answer here, not in it.
+ Text(loc.t("log.transferNote")).font(.manrope(12.5)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true).padding(.horizontal, 14).padding(.top, 2)
+ }
+ CardDisclosure(loc.t("build.log"), isOpen: logOpen) { logOpen.toggle() }
+ if logOpen { BuildLogView(log: log, placeholder: loc.t("log.placeholder")).padding(.horizontal, 14).padding(.bottom, 14) }
+ }
+ .onReceive(showRequests) { show in
+ if show { logOpen = true; DispatchQueue.main.async { didShow() } }
+ }
+ }
+}
diff --git a/frontend/Sources/NXLauncher/OutcomeCard.swift b/frontend/Sources/NXLauncher/OutcomeCard.swift
new file mode 100644
index 00000000..859a42c2
--- /dev/null
+++ b/frontend/Sources/NXLauncher/OutcomeCard.swift
@@ -0,0 +1,46 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// What a finished build leaves: the Mac app in Finder, or the app on the device and where its game data is.
+/// Observes the build store, and the device store for the device's name.
+package struct OutcomeCard: View {
+ @ObservedObject var build: BuildStore
+ @ObservedObject var devices: DeviceStore
+ let onViewGame: () -> Void
+ @EnvironmentObject var loc: Localizer
+
+ package init(build: BuildStore, devices: DeviceStore, onViewGame: @escaping () -> Void) {
+ self.build = build
+ self.devices = devices
+ self.onViewGame = onViewGame
+ }
+
+ package var body: some View {
+ if build.done && build.target == BuildTarget.mac {
+ CardGroup(loc.t("section.done")) {
+ CardRow(loc.t("library.ready"), detail: build.shortPath(build.macAppPath), dot: LauncherPalette.ready, help: build.macAppPath) {
+ Button(loc.t("install.reveal")) { revealInFinder(build.macAppPath) }
+ Button(loc.t("build.showLibrary"), action: onViewGame)
+ }
+ }
+ }
+ if build.done && !build.installedOn.isEmpty {
+ CardGroup(String(format: loc.t("dev.installed"), devices.deviceName(build.installedOn))) {
+ CardRow(loc.t("dev.installedNote"), dot: LauncherPalette.ready) {
+ Button(String(format: loc.t("dev.open"), devices.deviceName(build.installedOn))) {
+ build.openOnDevice(udid: build.installedOn, app: build.installedAppPath) { error in if let error { build.doneNote = error } }
+ }
+ }
+ // The game files were copied (or, after a skipped transfer, await a manual copy — a
+ // fast external drive handed to the device is quicker than USB): show where they are.
+ if !build.archivePath.isEmpty {
+ CardDivider()
+ CardRow(loc.t("dev.gameData"), detail: build.shortPath(build.archivePath), dot: LauncherPalette.ready, help: build.archivePath) {
+ Button(loc.t("install.reveal")) { revealInFinder(build.archivePath) }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NXLauncher/ProgressCard.swift b/frontend/Sources/NXLauncher/ProgressCard.swift
new file mode 100644
index 00000000..62cdfd5d
--- /dev/null
+++ b/frontend/Sources/NXLauncher/ProgressCard.swift
@@ -0,0 +1,42 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// The script's own stages once a build has run. Observes the build store.
+package struct ProgressCard: View {
+ @ObservedObject var build: BuildStore
+ @EnvironmentObject var loc: Localizer
+
+ package init(build: BuildStore) { self.build = build }
+
+ package var body: some View {
+ if build.running || !build.stages.isEmpty {
+ CardGroup(loc.t("section.progress")) {
+ ForEach(Array(build.stages.enumerated()), id: \.element.id) { index, s in
+ if index > 0 { CardDivider() }
+ HStack(spacing: 12) {
+ if s.state == .running { ProgressView().controlSize(.small).frame(width: 14) }
+ else { Circle().fill(s.state.color).frame(width: 7, height: 7).frame(width: 14) }
+ Text(s.name).font(.manrope(14)).lineLimit(1)
+ Spacer(minLength: 12)
+ if s.state == .running {
+ TimelineView(.periodic(from: Date(), by: 1)) { context in
+ Text([s.detail, s.clock(at: context.date, left: loc.t("prog.eta"))].filter { !$0.isEmpty }.joined(separator: " · "))
+ .font(.manrope(12)).monospacedDigit().foregroundStyle(.secondary).lineLimit(1)
+ }
+ } else if !s.detail.isEmpty { Text(s.detail).font(.manrope(12)).foregroundStyle(.secondary).lineLimit(1) }
+ if s.state == .running {
+ LauncherProgressBar(value: s.percent.map { $0 / 100 }, height: 6).frame(width: 180)
+ Text(s.percent.map { "\(Int($0))%" } ?? "").font(.manrope(13, .semibold)).monospacedDigit()
+ .foregroundStyle(.secondary).frame(width: 40, alignment: .trailing)
+ }
+ }
+ .padding(.horizontal, 18).padding(.vertical, 12)
+ }
+ if build.stages.isEmpty && build.running {
+ CardRow(loc.t("library.preparing")) { ProgressView().controlSize(.small) }
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/RowScroller.swift b/frontend/Sources/NXLauncher/RowScroller.swift
similarity index 74%
rename from frontend/Sources/NX2Apple/RowScroller.swift
rename to frontend/Sources/NXLauncher/RowScroller.swift
index 446aed07..fab727bc 100644
--- a/frontend/Sources/NX2Apple/RowScroller.swift
+++ b/frontend/Sources/NXLauncher/RowScroller.swift
@@ -2,13 +2,14 @@ import SwiftUI
/// The collection row's scroll state, read from its NSScrollView: SwiftUI's horizontal ScrollView does not
/// report its offset on macOS 13, so the pager chevrons follow the clip view's bounds instead.
-final class RowScroller: ObservableObject {
- @Published private(set) var canBack = false
- @Published private(set) var canForward = false
+package final class RowScroller: ObservableObject {
+ package init() {}
+ @Published package private(set) var canBack = false
+ @Published package private(set) var canForward = false
private weak var scrollView: NSScrollView?
private var observers: [NSObjectProtocol] = []
- func attach(_ view: NSScrollView) {
+ package func attach(_ view: NSScrollView) {
guard view !== scrollView else { return update() }
observers.forEach(NotificationCenter.default.removeObserver)
scrollView = view
@@ -33,7 +34,7 @@ final class RowScroller: ObservableObject {
}
/// Scroll by the whole cards that fit in the row.
- func page(_ direction: CGFloat, step: CGFloat) {
+ package func page(_ direction: CGFloat, step: CGFloat) {
guard let view = scrollView, let document = view.documentView else { return }
let clip = view.contentView
let distance = max(step, (clip.bounds.width / step).rounded(.down) * step)
@@ -48,26 +49,27 @@ final class RowScroller: ObservableObject {
}
/// Hands the NSScrollView around this background view to the row's scroller once it is in a window.
-struct EnclosingScrollView: NSViewRepresentable {
+package struct EnclosingScrollView: NSViewRepresentable {
let row: RowScroller
- final class Probe: NSView {
- var row: RowScroller?
- override func viewDidMoveToWindow() {
+ package init(row: RowScroller) { self.row = row }
+ package final class Probe: NSView {
+ package var row: RowScroller?
+ package override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
DispatchQueue.main.async { [weak self] in
if let view = self?.enclosingScrollView { self?.row?.attach(view) }
}
}
}
- func makeNSView(context: Context) -> Probe { let probe = Probe(); probe.row = row; return probe }
- func updateNSView(_ probe: Probe, context: Context) {
+ package func makeNSView(context: Context) -> Probe { let probe = Probe(); probe.row = row; return probe }
+ package func updateNSView(_ probe: Probe, context: Context) {
probe.row = row
DispatchQueue.main.async { if let view = probe.enclosingScrollView { row.attach(view) } }
}
}
/// The library's collection row reports its height, so the hero above it fills exactly what is left.
-struct CollectionHeightKey: PreferenceKey {
- static var defaultValue: CGFloat = 0
- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) }
+package struct CollectionHeightKey: PreferenceKey {
+ package static var defaultValue: CGFloat = 0
+ package static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) }
}
diff --git a/frontend/Sources/NXLauncher/SetupHintCard.swift b/frontend/Sources/NXLauncher/SetupHintCard.swift
new file mode 100644
index 00000000..8c2cfa36
--- /dev/null
+++ b/frontend/Sources/NXLauncher/SetupHintCard.swift
@@ -0,0 +1,27 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// The hint at the top of the Builds page while the repository or a tool is missing. Observes the repository and dependency stores.
+package struct SetupHintCard: View {
+ @ObservedObject var repo: RepoStore
+ @ObservedObject var dependencies: DependencyStore
+ let onOpenSettings: () -> Void
+ @EnvironmentObject var loc: Localizer
+
+ package init(repo: RepoStore, dependencies: DependencyStore, onOpenSettings: @escaping () -> Void) {
+ self.repo = repo
+ self.dependencies = dependencies
+ self.onOpenSettings = onOpenSettings
+ }
+
+ package var body: some View {
+ if !repo.isRepo || !dependencies.allPresent {
+ CardGroup(loc.t("section.setup")) {
+ CardRow(loc.t("library.setupHint"), dot: LauncherPalette.building) {
+ Button(loc.t("build.setup"), action: onOpenSettings)
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/ShellCopyView.swift b/frontend/Sources/NXLauncher/ShellCopyCard.swift
similarity index 94%
rename from frontend/Sources/NX2Apple/ShellCopyView.swift
rename to frontend/Sources/NXLauncher/ShellCopyCard.swift
index e9d8cc8c..fa524bdd 100644
--- a/frontend/Sources/NX2Apple/ShellCopyView.swift
+++ b/frontend/Sources/NXLauncher/ShellCopyCard.swift
@@ -6,11 +6,13 @@ import NXLauncher
/// Before the shared app's game data goes over USB or Wi-Fi: how much, over which connection, and what to do about it. A cable
/// gets one short note. Wi-Fi gets an estimate with Continue and a way to wait for a cable (the copy then starts by itself when the
/// device shows up wired). While it waits, the card says so and offers to stop.
-struct ShellCopyCard: View {
+package struct ShellCopyCard: View {
@ObservedObject var devices: DeviceStore
@EnvironmentObject var loc: Localizer
- var body: some View {
+ package init(devices: DeviceStore) { self.devices = devices }
+
+ package var body: some View {
if let plan = devices.shellCopy {
card {
Text(loc.t("shell.copyTitle")).font(.manrope(14, .semibold))
diff --git a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift b/frontend/Sources/NXLauncher/StaleFrameworksPrompt.swift
similarity index 87%
rename from frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift
rename to frontend/Sources/NXLauncher/StaleFrameworksPrompt.swift
index 7392d7ab..a957f0a5 100644
--- a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift
+++ b/frontend/Sources/NXLauncher/StaleFrameworksPrompt.swift
@@ -18,5 +18,5 @@ private struct StaleFrameworksPrompt: ViewModifier {
}
extension View {
- func staleFrameworksPrompt(_ m: BuildStore) -> some View { modifier(StaleFrameworksPrompt(m: m)) }
+ package func staleFrameworksPrompt(_ m: BuildStore) -> some View { modifier(StaleFrameworksPrompt(m: m)) }
}
diff --git a/frontend/Sources/NXLauncher/TargetCard.swift b/frontend/Sources/NXLauncher/TargetCard.swift
new file mode 100644
index 00000000..dbb64785
--- /dev/null
+++ b/frontend/Sources/NXLauncher/TargetCard.swift
@@ -0,0 +1,65 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// Mac or iPhone, and for the iPhone the switch that decodes textures on the CPU. Observes the build store only.
+package struct TargetCard: View {
+ @ObservedObject var build: BuildStore
+ @EnvironmentObject var loc: Localizer
+
+ package init(build: BuildStore) { self.build = build }
+
+ package var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(loc.t("section.target")).font(.manrope(15, .semibold)).foregroundStyle(.secondary)
+ .padding(.leading, 2)
+ HStack(spacing: 14) {
+ targetCard(BuildTarget.mac, symbol: "desktopcomputer", title: "build.mac", note: "build.macNote")
+ targetCard(BuildTarget.ios, symbol: "iphone", title: "build.ios", note: "build.iosNote")
+ }
+ // A Mac app runs on this Mac's GPU, which always decodes BC textures: the switch is the iPhone's only.
+ if build.target != BuildTarget.mac {
+ VStack(spacing: 0) {
+ HStack(alignment: .center, spacing: 12) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(loc.t("opt.bc")).font(.manrope(14))
+ Text(loc.t("opt.bc.note")).font(.manrope(12.5)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 12)
+ Toggle("", isOn: $build.bcOnCPU).toggleStyle(LauncherSwitchStyle()).labelsHidden().disabled(build.running)
+ }
+ .padding(.horizontal, 18).padding(.vertical, 14)
+ }
+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
+ .padding(.top, 4)
+ }
+ }
+ }
+
+ private func targetCard(_ value: String, symbol: String, title: String, note: String) -> some View {
+ let selected = build.target == value
+ return Button { build.target = value } label: {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(alignment: .top) {
+ Image(systemName: symbol).font(.system(size: 26, weight: .light))
+ .foregroundStyle(selected ? LauncherPalette.cream : .secondary)
+ Spacer()
+ Circle().strokeBorder(selected ? LauncherPalette.cream : Color.white.opacity(0.25), lineWidth: selected ? 5 : 1.5)
+ .frame(width: 18, height: 18)
+ }
+ VStack(alignment: .leading, spacing: 4) {
+ Text(loc.t(title)).font(.manrope(16, .semibold))
+ Text(loc.t(note)).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .padding(20).frame(maxWidth: .infinity, alignment: .leading)
+ .background(selected ? LauncherPalette.cream.opacity(0.05) : LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(selected ? LauncherPalette.cream.opacity(0.7) : Color.white.opacity(0.06), lineWidth: selected ? 1.5 : 1))
+ .contentShape(RoundedRectangle(cornerRadius: 14))
+ }
+ .buttonStyle(.plain).disabled(build.running)
+ .accessibilityAddTraits(selected ? .isSelected : [])
+ }
+}
diff --git a/frontend/Sources/NXLauncher/ToolsCard.swift b/frontend/Sources/NXLauncher/ToolsCard.swift
new file mode 100644
index 00000000..6b9551fc
--- /dev/null
+++ b/frontend/Sources/NXLauncher/ToolsCard.swift
@@ -0,0 +1,188 @@
+import SwiftUI
+import AppKit
+import NXCore
+import NXModel
+
+/// Settings, "Tools": the repository or the release app's engine, the dependency rows and the diagnostics row.
+/// Observes the repository, engine sync and dependency stores. What it needs from the build store comes as values:
+/// whether a build runs, where the shell cache is and the closure that reveals it. The diagnostics button belongs to the app.
+package struct ToolsCard<Diagnostics: View>: View {
+ @ObservedObject var repo: RepoStore
+ @ObservedObject var engine: EngineSyncStore
+ @ObservedObject var dependencies: DependencyStore
+ let buildRunning: Bool
+ let shellCachePath: String
+ let revealFolder: (URL) -> Void
+ let diagnostics: Diagnostics
+ @EnvironmentObject var loc: Localizer
+
+ package init(repo: RepoStore, engine: EngineSyncStore, dependencies: DependencyStore, buildRunning: Bool, shellCachePath: String,
+ revealFolder: @escaping (URL) -> Void, @ViewBuilder diagnostics: () -> Diagnostics) {
+ self.repo = repo
+ self.engine = engine
+ self.dependencies = dependencies
+ self.buildRunning = buildRunning
+ self.shellCachePath = shellCachePath
+ self.revealFolder = revealFolder
+ self.diagnostics = diagnostics()
+ }
+
+ package var body: some View {
+ CardGroup(loc.t("section.tools"), footnote: engine.usesEngineStore ? engine.status
+ : (repo.status.isEmpty ? (repo.isRepo ? "" : loc.t("repo.firstHint")) : repo.status)) {
+ if engine.usesEngineStore {
+ engineRows
+ } else {
+ CardRow(loc.t("repo.title"),
+ detail: repo.isRepo ? repo.shortPath(repo.path)
+ : (repo.path.isEmpty ? loc.t("repo.notFound") : String(format: loc.t("repo.notRepo"), repo.shortPath(repo.path))),
+ dot: repo.isRepo ? LauncherPalette.ready : LauncherPalette.building, help: repo.path) {
+ if repo.busy { ProgressView().controlSize(.small) }
+ if repo.isRepo {
+ if repo.isGit {
+ if let n = repo.behind, n > 0 {
+ Button(loc.t("repo.pull")) { repo.pull() }.disabled(repo.busy || buildRunning)
+ .padTarget("set.repoPull", scope: "main") { if !(repo.busy || buildRunning) { repo.pull() } }
+ }
+ Button(loc.t("repo.check")) { repo.checkForUpdates() }.disabled(repo.busy || buildRunning)
+ .padTarget("set.repoCheck", scope: "main") { if !(repo.busy || buildRunning) { repo.checkForUpdates() } }
+ } else {
+ Button(loc.t("repo.adopt")) { repo.adoptAsGit() }.disabled(repo.busy || buildRunning)
+ .padTarget("set.repoAdopt", scope: "main") { if !(repo.busy || buildRunning) { repo.adoptAsGit() } }
+ }
+ }
+ // Always offered, including when a repository is already configured: a saved path from
+ // an earlier session (an upstream clone, a moved folder) is exactly the state a user
+ // cannot fix without this button — the report had no way to leave the wrong repository.
+ Button(loc.t("repo.choose")) { pickRepo() }
+ if !repo.isRepo {
+ Button(loc.t("repo.download")) { repo.clone() }.disabled(repo.busy || buildRunning)
+ }
+ }
+ if !repo.isRepo {
+ // GitHub does not load everywhere: the manual route (Code → Download ZIP → unzip →
+ // Choose repository) needs no git at all, and the note says which folder to pick.
+ HStack(spacing: 4) {
+ Text(loc.t("repo.manualHint")).foregroundStyle(.secondary)
+ Link("github.com/LNPANDY/NX2Apple", destination: URL(string: RepoStore.url.replacingOccurrences(of: ".git", with: ""))!)
+ Text(loc.t("repo.manualHint2")).foregroundStyle(.secondary)
+ }
+ .font(.manrope(12)).padding(.horizontal, 18).padding(.bottom, 12)
+ }
+ if repo.isRepo, !repo.isGit {
+ Text(loc.t(repo.autoUpdate ? "repo.noGit" : "repo.zipNoAuto")).font(.manrope(12)).foregroundStyle(.secondary)
+ .padding(.horizontal, 18).padding(.bottom, 12)
+ }
+ if repo.isRepo, !RepoLayout.missingTools(in: repo.path).isEmpty {
+ Text(String(format: loc.t("repo.toolsOld"), RepoLayout.missingTools(in: repo.path).joined(separator: ", ")))
+ .font(.manrope(12)).foregroundStyle(LauncherPalette.building)
+ .padding(.horizontal, 18).padding(.bottom, 12)
+ }
+ if repo.isRepo { // a ZIP copy too: its adoption at launch follows this switch
+ CardDivider()
+ CardRow(loc.t("repo.auto"), detail: loc.t("repo.autoNote")) {
+ Toggle("", isOn: $repo.autoUpdate).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ }
+ }
+ }
+ CardDivider()
+ Button(action: { withAnimation(.easeInOut(duration: 0.18)) { dependencies.toggle() } }) {
+ CardRow(loc.t("dep.title"),
+ detail: !dependencies.checked ? loc.t("dep.checking")
+ : (dependencies.allPresent ? loc.t("dep.allReady") : String(format: loc.t("dep.missing"), dependencies.deps.filter { !$0.present }.count)),
+ dot: !dependencies.checked ? LauncherPalette.unbuilt : (dependencies.allPresent ? LauncherPalette.ready : LauncherPalette.building),
+ open: dependencies.open) {
+ if !dependencies.checked { ProgressView().controlSize(.small) }
+ Button(loc.t("dep.recheck")) { _ = dependencies.check() }
+ .padTarget("set.deps", scope: "main") { _ = dependencies.check() }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ if dependencies.open {
+ ForEach(dependencies.deps, id: \.id) { d in
+ CardDivider()
+ VStack(alignment: .leading, spacing: 0) {
+ CardRow(loc.t(d.name), detail: repo.shortPath(dependencies.detail(of: d)), dot: d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building,
+ help: loc.t(d.hint)) {
+ if d.installing {
+ ProgressView().controlSize(.small)
+ Text(loc.t("dep.installing")).font(.manrope(12)).foregroundStyle(LauncherPalette.building)
+ } else if !d.present {
+ Button(d.actionLabel.isEmpty ? (d.installCmd.isEmpty ? loc.t("dep.openAppStore") : loc.t("dep.install")) : loc.t(d.actionLabel)) { _ = dependencies.install(d) }
+ }
+ }
+ // Why the last install failed, and what to do about it: the tool's own
+ // error line under the row, the fix (a command or a place to look) below it.
+ if !d.lastError.isEmpty {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(d.lastError).font(.mono(11)).foregroundStyle(LauncherPalette.building)
+ .lineLimit(3).help(d.lastError)
+ if !d.fixHint.isEmpty {
+ Text(loc.t(d.fixHint)).font(.manrope(11.5)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .padding(.leading, 37).padding(.trailing, 18).padding(.bottom, 11)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ }
+ }
+ CardDivider()
+ CardRow(loc.t("diag.title"), detail: loc.t("diag.note")) { diagnostics }
+ }
+ }
+
+ /// The release app's engine (EngineSyncStore): which one the build uses, its channel, and the automatic update.
+ @ViewBuilder private var engineRows: some View {
+ let idle = !(engine.busy || buildRunning)
+ CardRow(loc.t("engine.title"), detail: engine.detail,
+ dot: engine.selection.engineID.isEmpty ? LauncherPalette.building : LauncherPalette.ready, help: repo.path) {
+ if engine.busy { ProgressView().controlSize(.small) }
+ if let next = engine.available {
+ Button(String(format: loc.t("engine.install"), next.version)) { engine.installAvailable() }.disabled(!idle)
+ .padTarget("set.engineInstall", scope: "main") { if idle { engine.installAvailable() } }
+ }
+ Button(loc.t("repo.check")) { engine.checkForUpdate() }.disabled(!idle)
+ .padTarget("set.engineCheck", scope: "main") { if idle { engine.checkForUpdate() } }
+ }
+ CardDivider()
+ // A different channel is asked about first (the alert below): the switch can recompile every game's shaders
+ CardRow(loc.t("engine.update"), detail: loc.t("engine.channelNote"), dot: LauncherPalette.ready) {
+ LauncherDropdown(options: EngineChannel.allCases.map { (value: $0.rawValue, label: loc.t($0.labelKey)) },
+ selection: engine.selection.channel.rawValue) { v in
+ if let channel = EngineChannel(rawValue: v) { engine.requestChannel(channel) }
+ }
+ .disabled(!idle)
+ .padTarget("set.engineChannel", scope: "main") {
+ if idle { engine.requestChannel(engine.selection.channel == .stable ? .experimental : .stable) }
+ }
+ }
+ .alert(loc.t("engine.switch.title"), isPresented: Binding(get: { engine.confirmingChannel != nil },
+ set: { if !$0 { engine.cancelChannel() } })) {
+ if let channel = engine.confirmingChannel {
+ Button(String(format: loc.t("engine.switch.go"), loc.t(channel.labelKey))) { engine.confirmChannel(channel) }
+ }
+ Button(loc.t("engine.switch.cancel"), role: .cancel) { engine.cancelChannel() }
+ } message: {
+ Text(engine.confirmingChannel.flatMap { engine.selection.channel.switchWarningKey(to: $0) }.map { loc.t($0) } ?? "")
+ }
+ CardDivider()
+ CardRow(loc.t("shellCache.row"), detail: loc.t("shellCache.note"), detail2: shellCachePath) {
+ Button(loc.t("shellCache.open")) { revealFolder(URL(fileURLWithPath: shellCachePath)) }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ }
+ CardDivider()
+ CardRow(loc.t("repo.auto"), detail: loc.t("engine.autoNote")) {
+ Toggle("", isOn: $repo.autoUpdate).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ }
+ }
+
+ private func pickRepo() {
+ let d = NSOpenPanel()
+ d.canChooseDirectories = true; d.canChooseFiles = false
+ d.message = loc.t("repo.pickMessage")
+ if d.runModal() == .OK, let u = d.url { repo.path = u.path }
+ }
+}
diff --git a/frontend/Sources/NX2Apple/UpdateSheet.swift b/frontend/Sources/NXLauncher/UpdateSheet.swift
similarity index 97%
rename from frontend/Sources/NX2Apple/UpdateSheet.swift
rename to frontend/Sources/NXLauncher/UpdateSheet.swift
index 414b8132..15ac210c 100644
--- a/frontend/Sources/NX2Apple/UpdateSheet.swift
+++ b/frontend/Sources/NXLauncher/UpdateSheet.swift
@@ -12,14 +12,16 @@ import NXLauncher
/// docs/RELEASE-NOTES-GUIDE.md). The sheet does not try to translate them; it shows the lines that
/// match the interface language and falls back to the whole body when it cannot tell them apart.
/// ReleaseNotes turns them into blocks with links, and this file only styles those.
-struct UpdateSheet: View {
+package struct UpdateSheet: View {
@ObservedObject var updates: AppUpdateStore
@EnvironmentObject var loc: Localizer
@Environment(\.dismiss) private var dismiss
+ package init(updates: AppUpdateStore) { self.updates = updates }
+
private var update: AppUpdate.Release? { updates.update }
- var body: some View {
+ package var body: some View {
VStack(alignment: .leading, spacing: 0) {
VStack(alignment: .leading, spacing: 6) {
Text(loc.t("update.title"))
diff --git a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
index b50a00a8..ddca780a 100644
--- a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
@@ -305,7 +305,7 @@ import NXModel
}
}
-/// The dependency panel's rows as the Settings card draws them, for the screenshot (the card itself is private to BuilderView).
+/// The dependency panel's rows as the Settings card draws them, for the screenshot (the card itself is ToolsCard in NXLauncher).
private struct MetalRowPreview: View {
@ObservedObject var dependencies: DependencyStore
let t: (String) -> String
diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
index 3a2930d9..99eabe39 100644
--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
@@ -139,7 +139,7 @@ import NXModel
MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
// the page as a drag shows it: the highlight drawn over the Builds page
- let page = BuilderView(m: model, updates: modelStores.appUpdates, repo: modelStores.repo, engine: modelStores.engineSync, dependencies: modelStores.dependencies, devices: modelStores.deviceStore, library: library).environmentObject(PadFocus()).environmentObject(modelStores.localizer)
+ let page = CardPages(settings: false, build: model, updates: modelStores.appUpdates, repo: modelStores.repo, engine: modelStores.engineSync, dependencies: modelStores.dependencies, devices: modelStores.deviceStore, library: library).environmentObject(PadFocus()).environmentObject(modelStores.localizer)
.modifier(GameFilesDrop(enabled: true, label: model.t("drop.hint"), targeted: true) { _ in })
.frame(width: 1100, height: 760).background(LauncherPalette.background).environment(\.colorScheme, .dark)
let host = NSHostingView(rootView: page)
diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
index 2f6b0203..6fb4fa70 100644
--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
@@ -20,12 +20,12 @@ import NXModel
// MARK: Languages
func testThePickerOffersEveryLanguage() {
- let offered = Set(BuilderView.languageCodes.filter { !$0.isEmpty })
+ let offered = Set(AppCard.languageCodes.filter { !$0.isEmpty })
XCTAssertEqual(offered, Set(Lang.allCases.map(\.rawValue)), "Settings > Language lists the launcher's languages")
}
func testDropdownChoicesFitBesideTheChevron() throws {
- for code in BuilderView.languageCodes {
+ for code in AppCard.languageCodes {
let key = "settings.language." + (code.isEmpty ? "system" : code)
XCTAssertNotNil(L10n.table[key], key)
for lang in Lang.allCases {
diff --git a/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift b/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
index 2441b03a..4ff4dd34 100644
--- a/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
@@ -52,8 +52,8 @@ final class LauncherDropdownTests: XCTestCase {
}
func testEveryLanguageInThePickerHasAName() {
- XCTAssertEqual(BuilderView.languageCodes.first, "")
- for code in BuilderView.languageCodes.dropFirst() {
+ XCTAssertEqual(AppCard.languageCodes.first, "")
+ for code in AppCard.languageCodes.dropFirst() {
XCTAssertNotNil(Lang(rawValue: code), code)
for lang: Lang in [.zh, .en, .sv, .de] { XCTAssertNotEqual(L10n.string("settings.language." + code, lang), "settings.language." + code) }
}
diff --git a/frontend/Tests/NXModelTests/LayerImportsTests.swift b/frontend/Tests/NXModelTests/LayerImportsTests.swift
new file mode 100644
index 00000000..162235eb
--- /dev/null
+++ b/frontend/Tests/NXModelTests/LayerImportsTests.swift
@@ -0,0 +1,48 @@
+import XCTest
+
+/// LNPANDY/NX2Apple#387: the layers are kept apart by what each target imports. `NXCore` and `NXModel` never import SwiftUI or AppKit,
+/// and a target never imports one above it. `Package.swift` lets any target link a system framework, so the compiler alone does not
+/// stop a `Color` or an `NSImage` from slipping in. This reads the sources and fails the moment a wrong import is added, with the
+/// file and the line.
+final class LayerImportsTests: XCTestCase {
+ private func sources(_ target: String) -> URL {
+ var url = URL(fileURLWithPath: #filePath)
+ for _ in 0..<3 { url.deleteLastPathComponent() } // frontend/Tests/NXModelTests/<this file> -> frontend
+ return url.appendingPathComponent("Sources").appendingPathComponent(target)
+ }
+
+ /// Every `import X` line of the target's Swift files, as "File.swift:line: module".
+ private func imports(of target: String) throws -> [(where: String, module: String)] {
+ let root = sources(target)
+ let files = try XCTUnwrap(FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil))
+ var found: [(String, String)] = []
+ for case let file as URL in files where file.pathExtension == "swift" {
+ let text = try String(contentsOf: file, encoding: .utf8)
+ for (index, line) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
+ let words = line.trimmingCharacters(in: .whitespaces).split(separator: " ")
+ guard words.first == "import" || (words.count > 1 && words.first == "@testable" && words[1] == "import") else { continue }
+ found.append(("\(file.lastPathComponent):\(index + 1)", String(words.last ?? "")))
+ }
+ }
+ XCTAssertFalse(found.isEmpty, "found no imports under Sources/\(target)")
+ return found
+ }
+
+ private func assertNoImports(in target: String, of forbidden: Set<String>) throws {
+ for (place, module) in try imports(of: target) where forbidden.contains(module) {
+ XCTFail("\(place): \(target) imports \(module), which a \(target) file must not (frontend/ARCHITECTURE.md)")
+ }
+ }
+
+ func testNXCoreImportsNoUIFramework() throws {
+ try assertNoImports(in: "NXCore", of: ["SwiftUI", "AppKit", "Cocoa", "UIKit", "NXModel", "NXLauncher", "NX2Apple"])
+ }
+
+ func testNXModelImportsNoUIFramework() throws {
+ try assertNoImports(in: "NXModel", of: ["SwiftUI", "AppKit", "Cocoa", "UIKit", "NXLauncher", "NX2Apple"])
+ }
+
+ func testNXLauncherImportsNoAppTarget() throws {
+ try assertNoImports(in: "NXLauncher", of: ["NX2Apple"])
+ }
+}