Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
391 changes: 260 additions & 131 deletions Xcodes/Backend/AppState+Runtimes.swift

Large diffs are not rendered by default.

26 changes: 24 additions & 2 deletions Xcodes/Backend/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ class AppState: ObservableObject {
// MARK: - Runtimes

@Published var downloadableRuntimes: [DownloadableRuntime] = []
@Published var waitingForXcodeRuntimes: Set<String> = []
@Published var removingRuntimeImages: Set<String> = []
@Published var installedRuntimes: [CoreSimulatorImage] = []

// MARK: - Operation State
Expand Down Expand Up @@ -780,8 +782,10 @@ class AppState: ObservableObject {
}

// MARK: - Uninstall
func uninstall(xcode: Xcode) {
guard let installedXcodePath = xcode.installedPath else { return }
@discardableResult
func uninstall(xcode: Xcode, removingRuntimes runtimes: [DownloadableRuntime] = []) -> Task<Void, Never>? {
guard let installedXcodePath = xcode.installedPath, xcode.installState.installed else { return nil }
let survivingXcode = newestInstalledXcode(excluding: xcode.id)

if let index = allXcodes.firstIndex(where: { $0.id == xcode.id }) {
allXcodes[index].installState = .uninstalling(installedXcodePath)
Expand All @@ -798,11 +802,28 @@ class AppState: ObservableObject {
}
}
do {
try Task.checkCancellation()
if survivingXcode == nil, !runtimes.isEmpty {
// The last full Xcode supplies simctl. Preserve it if runtime removal fails.
guard Current.files.fileExists(atPath: installedXcodePath.string) else {
throw FileError.fileNotFound(installedXcodePath.string)
}
guard await removeRuntimesForUninstall(runtimes, using: installedXcodePath) else {
try Task.checkCancellation()
if let index = allXcodes.firstIndex(where: { $0.id == xcode.id }) {
allXcodes[index].installState = .installed(installedXcodePath)
}
return
}
}
try Task.checkCancellation()
try await uninstallXcodeAsync(path: installedXcodePath)
try Task.checkCancellation()
await updateInstalledXcodesAsync()
await updateSelectedXcodePathAsync()
if let survivingPath = survivingXcode?.installedPath, !runtimes.isEmpty {
_ = await removeRuntimesForUninstall(runtimes, using: survivingPath)
}
} catch is CancellationError {
} catch {
if let index = allXcodes.firstIndex(where: { $0.id == xcode.id }) {
Expand All @@ -816,6 +837,7 @@ class AppState: ObservableObject {
}
}
}
return uninstallTask
}

func reveal(_ path: Path?) {
Expand Down
10 changes: 8 additions & 2 deletions Xcodes/Backend/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,14 @@ public struct Shell: Sendable {
return try await Process.runAsync(unxipPath.url, workingDirectory: url.deletingLastPathComponent(), ["\(url.path)"])
}

public var downloadRuntime: @Sendable (String, String, String?) -> AsyncThrowingStream<Progress, Error> = { platform, version, architecture in
XcodebuildRuntimeDownloadService().download(platform: platform, buildVersion: version, architecture: architecture)
public var deleteRuntimeWithDeveloperDirectory: @Sendable (String, String) async throws -> Void = { identifier, directory in
_ = try await CleanupOperations.runSimctl(["runtime", "delete", identifier], developerDirectory: directory)
}

public var downloadRuntime: @Sendable (String, String, String?, String?) -> AsyncThrowingStream<Progress, Error> = { platform, version, architecture, developerDirectory in
XcodebuildRuntimeDownloadService.download(
platform: platform, buildVersion: version, architecture: architecture, developerDirectory: developerDirectory
)
}
}

Expand Down
134 changes: 134 additions & 0 deletions Xcodes/Backend/Process.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import os
import Path
import XcodesKit

Expand All @@ -16,3 +17,136 @@ extension Process {
try await XcodesProcess.run(executable, workingDirectory: workingDirectory, input: input, arguments)
}
}

extension XcodebuildRuntimeDownloadService {
/// Runs with a per-process Xcode selection so a runtime can use an inactive Xcode.
static func download(
platform: String,
buildVersion: String,
architecture: String?,
developerDirectory: String?
) -> AsyncThrowingStream<Progress, Error> {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/xcodebuild")
if let developerDirectory {
process.environment = ProcessInfo.processInfo.environment.merging(["DEVELOPER_DIR": developerDirectory]) { _, scoped in scoped }
}
process.arguments = ["-downloadPlatform", platform, "-buildVersion", buildVersion]
if let architecture {
process.arguments?.append(contentsOf: ["-architectureVariant", architecture])
}
return runtimeProgressStream(for: process)
}

static func runtimeProgressStream(for process: Process) -> AsyncThrowingStream<Progress, Error> {
AsyncThrowingStream { continuation in
let stdout = Pipe()
let stderr = Pipe()
process.standardOutput = stdout
process.standardError = stderr
let output = OSAllocatedUnfairLock(initialState: RuntimeCommandOutput())
let progress = Progress(totalUnitCount: 100)
progress.kind = .file
progress.fileOperationKind = .downloading
continuation.yield(progress)

// Wait for exit and both pipes to drain so the final diagnostic is available.
let finish: @Sendable () -> Void = {
let result = output.withLock { $0.completedOutput() }
guard let result else { return }
if process.terminationReason == .exit, process.terminationStatus == 0 {
continuation.finish()
} else {
continuation.finish(throwing: ProcessExecutionError(
process: process, terminationStatus: process.terminationStatus,
standardOutput: result.stdout, standardError: result.stderr
))
}
}

for (pipe, isError) in [(stdout, false), (stderr, true)] {
pipe.fileHandleForReading.readabilityHandler = { handle in
let data = handle.availableData
if data.isEmpty { handle.readabilityHandler = nil }
output.withLock {
if data.isEmpty {
$0.closedPipes += 1
} else if isError {
$0.stderr.append(data)
} else {
$0.stdout.append(data)
$0.progressBuffer.append(data)
if let lastDelimiter = $0.progressBuffer.lastIndex(where: { $0 == 10 || $0 == 13 }) {
let records = String(decoding: $0.progressBuffer[...lastDelimiter], as: UTF8.self)
$0.progressBuffer.removeSubrange(...lastDelimiter)
for record in records.split(whereSeparator: \.isNewline) {
let line = record.trimmingCharacters(in: .whitespaces)
if line.hasPrefix("Installing") {
if !$0.installing {
$0.installing = true
continuation.yield(Progress(totalUnitCount: -1))
}
} else if !$0.installing, line.contains("%") {
progress.updateFromXcodebuild(text: line)
continuation.yield(progress)
}
}
}
}
}
if data.isEmpty { finish() }
}
}

process.terminationHandler = { process in
process.terminationHandler = nil
output.withLock { $0.exited = true }
finish()
}
continuation.onTermination = { reason in
if case .cancelled = reason, process.isRunning { process.terminate() }
}
do {
try process.run()
} catch {
stdout.fileHandleForReading.readabilityHandler = nil
stderr.fileHandleForReading.readabilityHandler = nil
process.terminationHandler = nil
continuation.finish(throwing: error)
}
}
}
}

private struct RuntimeCommandOutput {
var stdout = Data()
var stderr = Data()
var progressBuffer = Data()
var installing = false
var closedPipes = 0
var exited = false
var finished = false

mutating func completedOutput() -> (stdout: String, stderr: String)? {
guard exited, closedPipes == 2, !finished else { return nil }
finished = true
return (String(decoding: stdout, as: UTF8.self), String(decoding: stderr, as: UTF8.self))
}
}

extension ProcessExecutionError {
var runtimeFailureMessage: String {
let diagnostics = standardError.trimmingCharacters(in: .whitespacesAndNewlines)
let summary = String(format: localizeString("Xcode’s simulator runtime command failed (exit code %d)."), terminationStatus)
if !diagnostics.isEmpty {
return summary + "\n\n" + diagnostics
}

// Some Xcode versions report errors on stdout alongside carriage-return progress.
let failure = standardOutput.split(whereSeparator: \.isNewline).last { line in
line.localizedCaseInsensitiveContains("error") || line.localizedCaseInsensitiveContains("failed")
|| line.localizedCaseInsensitiveContains("cancelled")
}
return failure.map { summary + "\n\n" + $0 } ?? summary
}
}
27 changes: 17 additions & 10 deletions Xcodes/Backend/XcodeCommands.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,7 @@ struct CancelInstallButton: View {
let xcode: Xcode?

var body: some View {
Button(action: cancelInstall) {
Label("Cancel", systemImage: "xmark")
}
.help(localizeString("StopInstallation"))
.buttonStyle(.plain)
DownloadCancelButton(action: cancelInstall)
}

private func cancelInstall() {
Expand All @@ -76,10 +72,7 @@ struct CancelRuntimeInstallButton: View {
let runtime: DownloadableRuntime?

var body: some View {
Button(action: cancelInstall) {
Image(systemName: "xmark.circle.fill")
}.help(localizeString("StopInstallation"))
.buttonStyle(.plain)
DownloadCancelButton(action: cancelInstall)
}

private func cancelInstall() {
Expand All @@ -88,6 +81,19 @@ struct CancelRuntimeInstallButton: View {
}
}

struct DownloadCancelButton: View {
let action: () -> Void

var body: some View {
Button(action: action) {
Image(systemName: "xmark.circle.fill")
}
.accessibilityLabel(Text("StopInstallation"))
.help(localizeString("StopInstallation"))
.buttonStyle(.plain)
}
}

struct SelectButton: View {
@EnvironmentObject var appState: AppState
let xcode: Xcode?
Expand Down Expand Up @@ -233,6 +239,7 @@ struct CreateSymbolicLinkButton: View {
struct DownloadRuntimeButton: View {
@EnvironmentObject var appState: AppState
let runtime: DownloadableRuntime?
let xcodeID: XcodeID

var body: some View {
Button(action: install) {
Expand All @@ -243,7 +250,7 @@ struct DownloadRuntimeButton: View {

private func install() {
guard let runtime = runtime else { return }
appState.downloadRuntime(runtime: runtime)
appState.downloadRuntime(runtime: runtime, for: xcodeID)
}
}

Expand Down
3 changes: 3 additions & 0 deletions Xcodes/Frontend/Cleanup/CleanupModel+Simulators.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ extension CleanupModel {
}

func runtimeSelectionUnavailableReason(_ runtime: CleanupOperations.SimulatorRuntime) -> String? {
if appState?.removingRuntimeImages.contains(runtime.id) == true {
return "This simulator runtime is being removed."
}
if isScanning || isShowingCachedResults { return "Wait for the scan to finish." }
if runtimeInventoryUnavailable || runtimeAssociationCheckFailed { return "Could not check runtime associations. Rescan before removing runtimes." }
guard runtime.deletable == true, ["Ready", "Unusable"].contains(runtime.state) else { return "CoreSimulator does not currently allow removal of this runtime." }
Expand Down
22 changes: 21 additions & 1 deletion Xcodes/Frontend/Common/XcodesAlert.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import AppKit
import Foundation
import SwiftUI
import XcodesKit
Expand Down Expand Up @@ -48,7 +49,7 @@ extension Alert {
/// Removing a platform runs `simctl`, which only comes with Xcode. Offers to make the newest installed release active and retry.
@MainActor
static func noActiveXcode(appState: AppState, runtime: DownloadableRuntime, xcode: Xcode?, inSettings: Bool) -> Alert {
let explanation = String(format: localizeString("Alert.NoActiveXcode.Message"), runtime.name, appState.selectedXcodePath ?? "–")
let explanation = String(format: localizeString("Alert.NoActiveXcode.Message"), runtime.name, appState.selectedXcodePath?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "–")
guard let xcode else {
return Alert(
title: Text("Alert.NoActiveXcode.Title"),
Expand Down Expand Up @@ -161,3 +162,22 @@ private struct HelperSettingsButton: View {
}
}
}

/// Native alerts size to their message. Keep the buttons visible even for command output.
@MainActor
func boundedErrorAlert(title: String, message: String) -> Alert {
let lines = message.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline)
let preview = String(lines.prefix(6).joined(separator: "\n").prefix(480))
guard preview != message else {
return Alert(title: Text(title), message: Text(message), dismissButton: .default(Text("OK")))
}
return Alert(
title: Text(title),
message: Text(preview + "…"),
primaryButton: .default(Text("OK")),
secondaryButton: .default(Text("Copy Details"), action: {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(message, forType: .string)
})
)
}
38 changes: 25 additions & 13 deletions Xcodes/Frontend/InfoPane/PlatformsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ struct PlatformsView: View {

@ViewBuilder
func runtimeView(runtime: DownloadableRuntime) -> some View {
let waitingForXcode = appState.waitingForXcodeRuntimes.contains(runtime.identifier)
let isInstalled = appState.coreSimulatorInfo(runtime: runtime) != nil
VStack(spacing: 10) {
HStack {
runtime.icon()
Expand All @@ -96,28 +98,38 @@ struct PlatformsView: View {
Spacer()

// TODO: Update the downloadableRuntimes with the appropriate installState so we don't have to check path awkwardly
if appState.runtimeInstallPath(xcode: xcode, runtime: runtime) != nil {
if appState.isRemovingRuntime(runtime) {
ProgressView().controlSize(.small)
Text("Removing…").foregroundStyle(.secondary)
} else if isInstalled {
Button("Uninstall", role: .destructive) {
appState.presentedAlert = .deletePlatform(runtime: runtime)
}
.help("Alert.DeletePlatform.PrimaryButton")
} else if runtime.installState == .notInstalled {
DownloadRuntimeButton(runtime: runtime)
} else if appState.runtimeTasks[runtime.identifier] == nil && !waitingForXcode {
DownloadRuntimeButton(runtime: runtime, xcodeID: xcode.id)
}

Text(runtime.downloadFileSizeString)
.font(.subheadline)
.frame(width: 70, alignment: .trailing)
.frame(width: 70, alignment: .trailing)
}

if !isInstalled, waitingForXcode {
HStack {
Text("Waiting for Xcode to finish installing…")
Spacer()
CancelRuntimeInstallButton(runtime: runtime)
}
} else if !isInstalled, appState.runtimeTasks[runtime.identifier] != nil,
case let .installing(installationStep) = runtime.installState {
HStack(alignment: .top, spacing: 5) {
RuntimeInstallationStepDetailView(installationStep: installationStep)
.fixedSize(horizontal: false, vertical: true)
Spacer()
CancelRuntimeInstallButton(runtime: runtime)
}
}

if case let .installing(installationStep) = runtime.installState {
HStack(alignment: .top, spacing: 5){
RuntimeInstallationStepDetailView(installationStep: installationStep)
.fixedSize(horizontal: false, vertical: true)
Spacer()
CancelRuntimeInstallButton(runtime: runtime)
}
}
}
}

Expand Down
Loading
Loading