From ab69a2033385801ee8cc26d5e2c53c209622bada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hakan=20G=C3=9CL?= Date: Wed, 18 Nov 2026 02:04:15 +0300 Subject: [PATCH] feat: add `screenshot` command and a live device grid to the app Add `simslim screenshot [path]`, which captures a booted simulator's screen as a PNG via `simctl io screenshot` and, under --json, reports the written path. Like boot and shutdown it resolves the exact UDID first, so an alias such as "all" never reaches the capture path. A device with more than one display (for example an iPad presenting an external display) makes simctl refuse to choose and list the displays. CaptureScreenshot parses that listing and retries against the display marked "(primary)". The macOS app gains a Table/Grid toggle in the toolbar. The grid shows each simulator as a card with its live screen, refreshed every few seconds while the grid is visible (at most four captures at a time), plus boot and slim state, tap-to-select, and a context menu for boot, shutdown, slim, unslim, and rename. Shut-down simulators show a placeholder. --- README.md | 1 + cmd/simslim/app.go | 1 + cmd/simslim/main.go | 48 +++++++++ gui/AppModel.swift | 55 +++++++++++ gui/Backend.swift | 4 + gui/ContentView.swift | 221 +++++++++++++++++++++++++++++++++++++++++- gui/Models.swift | 24 +++++ output.go | 8 ++ simctl.go | 59 +++++++++++ 9 files changed, 418 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6666f14..1eaf8ed 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ simslim clone simslim repair-clone simslim rename simslim boot # boot a simulator and wait for its services +simslim screenshot [path] # PNG of a booted simulator's screen simslim shutdown # shut down a booted simulator simslim erase # erase apps, data, settings, and slimming overrides simslim delete # permanently delete a simulator diff --git a/cmd/simslim/app.go b/cmd/simslim/app.go index 1ec4f5d..a85ecd3 100644 --- a/cmd/simslim/app.go +++ b/cmd/simslim/app.go @@ -53,6 +53,7 @@ func newApp() *cli.Command { {Name: "repair-clone", Flags: []cli.Flag{jsonFlag()}, Action: cmdRepairClone}, {Name: "rename", Flags: []cli.Flag{jsonFlag()}, Action: cmdRename}, {Name: "boot", Flags: []cli.Flag{jsonFlag()}, Action: cmdBoot}, + {Name: "screenshot", Flags: []cli.Flag{jsonFlag()}, Action: cmdScreenshot}, {Name: "shutdown", Flags: []cli.Flag{jsonFlag()}, Action: cmdShutdown}, {Name: "erase", Flags: []cli.Flag{jsonFlag()}, Action: cmdErase}, {Name: "delete", Flags: []cli.Flag{jsonFlag()}, Action: cmdDelete}, diff --git a/cmd/simslim/main.go b/cmd/simslim/main.go index 12641f4..53d2d2b 100644 --- a/cmd/simslim/main.go +++ b/cmd/simslim/main.go @@ -744,6 +744,51 @@ func cmdShutdown(ctx context.Context, cmd *cli.Command) error { return nil } +// cmdScreenshot captures a booted simulator's screen as a PNG and, under +// --json, reports the path so the GUI can render it in the live device grid. +// Without a path argument it writes to a temp file the caller then reads. +func cmdScreenshot(ctx context.Context, cmd *cli.Command) error { + jsonOutput := cmd.Bool("json") + args := cmd.Args().Slice() + if len(args) < 1 || len(args) > 2 { + return fmt.Errorf("screenshot expects a simulator UDID and an optional output path") + } + udid := args[0] + + // Resolve the exact device first so a simctl alias such as "all" can never + // enter the capture path, consistent with boot/shutdown. + device, err := simslim.FindDevice(ctx, udid, "") + if err != nil { + return err + } + if device.State != "Booted" { + return fmt.Errorf("simulator must be booted to capture a screenshot (it is %s)", device.State) + } + + dest := "" + if len(args) == 2 { + dest = args[1] + } else { + f, err := os.CreateTemp("", "simslim-screenshot-*.png") + if err != nil { + return fmt.Errorf("create screenshot file: %w", err) + } + dest = f.Name() + f.Close() + } + + tctx, cancel := context.WithTimeout(ctx, simslim.ShutdownTimeout) + defer cancel() + if err := simslim.CaptureScreenshot(tctx, device.Set, udid, dest); err != nil { + return err + } + if jsonOutput { + return writeJSON(simslim.ScreenshotOutput{UDID: udid, Name: device.Name, Path: dest}) + } + fmt.Printf("Captured %s screenshot to %s\n", udid, dest) + return nil +} + func cmdOn(ctx context.Context, cmd *cli.Command) error { preserveBootState := cmd.Bool("preserve-boot-state") noReboot := cmd.Bool("no-reboot") @@ -1157,6 +1202,9 @@ COMMANDS Repair source-bound state in an existing clone rename Rename a simulator boot Boot a simulator and wait for its services + screenshot [path] + Capture a booted simulator's screen as a PNG (to path, + or a temp file); --json reports the written path shutdown Shut down a booted simulator erase Erase a simulator's apps, data, and settings delete Permanently delete a simulator diff --git a/gui/AppModel.swift b/gui/AppModel.swift index a5c9545..9803655 100644 --- a/gui/AppModel.swift +++ b/gui/AppModel.swift @@ -1,5 +1,9 @@ import Foundation +#if canImport(AppKit) + import AppKit +#endif + @MainActor final class AppModel: ObservableObject { @Published private(set) var devices: [SimulatorDevice] = [] @@ -7,6 +11,7 @@ final class AppModel: ObservableObject { @Published private(set) var diskCleanupCategories: [DiskCleanupCategory] = [] @Published private(set) var diskCleanupPlans: [String: SimulatorDiskCleanupPlan] = [:] @Published private(set) var measurements: [String: SimulatorMeasurement] = [:] + @Published private(set) var screenshots: [String: NSImage] = [:] @Published private(set) var diskSizes: [String: SimulatorDiskMeasurement] = [:] @Published private(set) var diskSizeLoadingUDIDs: Set = [] @Published private(set) var activeOperations: [String: String] = [:] @@ -387,6 +392,56 @@ final class AppModel: ObservableObject { } } + /// Returns the latest captured screen for a simulator, or nil when none has + /// been captured (shutdown, or a capture that has not completed yet). + func screenshot(for udid: String) -> NSImage? { screenshots[udid] } + + /// Captures a fresh screen for every booted simulator so the grid shows live + /// previews, and drops images for simulators that are no longer booted. + /// Failures are silent: a card with no image shows a placeholder rather than + /// raising an error dialog, since the grid refreshes on a timer. + func refreshScreenshots(for snapshot: [SimulatorDevice]) async { + guard let backend else { return } + let booted = snapshot.filter(\.isBooted) + let directory = Self.screenshotDirectory + let captured = await withTaskGroup(of: (String, NSImage?).self) { group -> [String: NSImage] in + let limit = 4 + var iterator = booted.makeIterator() + func startNext() { + guard let device = iterator.next() else { return } + let path = directory.appendingPathComponent("\(device.udid).png").path + group.addTask { + do { + let result = try await backend.screenshot(udid: device.udid, to: path) + return (device.udid, NSImage(contentsOfFile: result.path)) + } catch { + return (device.udid, nil) + } + } + } + for _ in 0.. SimulatorScreenshot { + try await decode(SimulatorScreenshot.self, arguments: ["screenshot", "--json", udid, path]) + } + private func decode(_ type: T.Type, arguments: [String]) async throws -> T { let output = try await execute(arguments) do { diff --git a/gui/ContentView.swift b/gui/ContentView.swift index 89d86e8..0fd7d19 100644 --- a/gui/ContentView.swift +++ b/gui/ContentView.swift @@ -7,6 +7,7 @@ struct ContentView: View { @State private var searchIsExpanded = false @State private var managementSheet: SimulatorManagementSheet? @State private var slimmingMode: SlimmingMode = .memory + @State private var deviceLayout: DeviceLayout = .table private var filteredDevices: [SimulatorDevice] { guard !searchText.isEmpty else { return model.devices } @@ -37,6 +38,13 @@ struct ContentView: View { return "disk:" + model.selectedUDIDs.sorted().joined(separator: ",") } + // Restarts the grid's capture loop when the layout changes or the set of + // booted simulators does, so a freshly booted device gets a preview promptly. + private var screenshotRefreshID: String { + guard deviceLayout == .grid else { return "table" } + return "grid:" + model.devices.filter(\.isBooted).map(\.udid).sorted().joined(separator: ",") + } + var body: some View { NavigationSplitView { ProfileSidebar(mode: $slimmingMode) @@ -47,9 +55,15 @@ struct ContentView: View { Divider() selectionBar Divider() - simulatorTable - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - .layoutPriority(1) + Group { + if deviceLayout == .grid { + simulatorGrid + } else { + simulatorTable + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .layoutPriority(1) Divider() ActivityPanel() } @@ -186,6 +200,19 @@ struct ContentView: View { ToolbarSpacer(.flexible) } + ToolbarItem(placement: .automatic) { + Picker("Layout", selection: $deviceLayout) { + ForEach(DeviceLayout.allCases) { layout in + Image(systemName: layout.systemImage) + .help("\(layout.rawValue) view") + .tag(layout) + } + } + .pickerStyle(.segmented) + .labelsHidden() + .help("Switch between the table and the live device grid") + } + ToolbarItem(placement: .automatic) { CollapsibleToolbarSearch( text: $searchText, @@ -194,6 +221,16 @@ struct ContentView: View { ) } } + .task(id: screenshotRefreshID) { + guard deviceLayout == .grid else { return } + // Keep the grid's previews live: capture now, then every few seconds for + // as long as the grid stays on screen. The task is cancelled when the + // view id changes (layout switch, device-set change) or the view goes away. + while !Task.isCancelled { + await model.refreshScreenshots(for: model.devices) + try? await Task.sleep(nanoseconds: 4_000_000_000) + } + } .sheet(item: $managementSheet) { sheet in managementSheetContent(for: sheet) } @@ -347,6 +384,47 @@ struct ContentView: View { .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) } + private var simulatorGrid: some View { + GeometryReader { geometry in + Group { + if model.isRefreshing && model.devices.isEmpty { + VStack(spacing: 12) { + ProgressView() + Text("Loading simulators…") + .foregroundStyle(.secondary) + } + .frame(width: geometry.size.width, height: geometry.size.height) + } else if filteredDevices.isEmpty { + ContentUnavailableView( + searchText.isEmpty ? "No Simulators" : "No Matches", + systemImage: "rectangle.slash", + description: Text( + searchText.isEmpty + ? "Install an iOS, tvOS, watchOS, or visionOS Simulator runtime in Xcode." + : "Try a different name, UDID, or OS version.") + ) + .frame(width: geometry.size.width, height: geometry.size.height) + } else { + ScrollView { + LazyVGrid( + columns: [GridItem(.adaptive(minimum: 190, maximum: 240), spacing: 16)], + alignment: .leading, + spacing: 16 + ) { + ForEach(filteredDevices) { device in + SimulatorGridCard(device: device, managementSheet: $managementSheet) + } + } + .padding(18) + .frame(width: geometry.size.width, alignment: .topLeading) + } + } + } + .frame(width: geometry.size.width, height: geometry.size.height, alignment: .top) + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + } + private var tableHeader: some View { HStack(spacing: 12) { Color.clear.frame(width: 30, height: 1) @@ -1496,6 +1574,143 @@ private struct SimulatorRow: View { } } +private struct SimulatorGridCard: View { + @EnvironmentObject private var model: AppModel + let device: SimulatorDevice + @Binding var managementSheet: SimulatorManagementSheet? + + private var isSelected: Bool { model.selectedUDIDs.contains(device.udid) } + private var operation: String? { model.activeOperations[device.udid] } + + var body: some View { + VStack(alignment: .leading, spacing: 9) { + screen + .aspectRatio(0.56, contentMode: .fit) + .frame(maxWidth: .infinity) + .background(Color.black.opacity(0.35), in: RoundedRectangle(cornerRadius: 12)) + .clipShape(RoundedRectangle(cornerRadius: 12)) + .overlay(alignment: .topTrailing) { badge } + .overlay( + RoundedRectangle(cornerRadius: 12) + .strokeBorder(isSelected ? Color.accentColor : Color.black.opacity(0.1), lineWidth: 2) + ) + + VStack(alignment: .leading, spacing: 4) { + Text(device.name) + .font(.subheadline.weight(.semibold)) + .lineLimit(1) + HStack(spacing: 5) { + Image(systemName: device.deviceSymbol) + Text(device.runtimeName) + } + .font(.caption) + .foregroundStyle(.secondary) + HStack(spacing: 8) { + BootStateView(isBooted: device.isBooted) + Spacer(minLength: 0) + Image(systemName: model.slimState(for: device).systemImage) + .foregroundStyle(.secondary) + .help("Service slimming: \(model.slimState(for: device).title)") + } + .font(.caption) + } + } + .padding(11) + .background(Color(nsColor: .controlBackgroundColor), in: RoundedRectangle(cornerRadius: 15)) + .overlay( + RoundedRectangle(cornerRadius: 15) + .strokeBorder( + isSelected ? Color.accentColor.opacity(0.6) : Color.black.opacity(0.08), lineWidth: 1) + ) + .contentShape(RoundedRectangle(cornerRadius: 15)) + .onTapGesture { + guard !model.isBusy(device) else { return } + model.toggleSelection(device.udid) + } + .contextMenu { cardMenu } + .help(device.name) + } + + @ViewBuilder private var screen: some View { + if device.isBooted { + if let image = model.screenshot(for: device.udid) { + Image(nsImage: image) + .resizable() + .interpolation(.medium) + .scaledToFit() + } else { + VStack(spacing: 8) { + ProgressView().controlSize(.small) + Text("Capturing…") + .font(.caption2) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } else { + VStack(spacing: 8) { + Image(systemName: device.deviceSymbol) + .font(.system(size: 34, weight: .light)) + .foregroundStyle(.tertiary) + Text("Shut Down") + .font(.caption2) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + + @ViewBuilder private var badge: some View { + if operation != nil { + ProgressView() + .controlSize(.small) + .padding(7) + .background(.ultraThinMaterial, in: Circle()) + .padding(7) + } else if isSelected { + Image(systemName: "checkmark.circle.fill") + .symbolRenderingMode(.palette) + .foregroundStyle(.white, Color.accentColor) + .font(.title3) + .padding(7) + } + } + + @ViewBuilder private var cardMenu: some View { + if device.isBooted { + Button { + Task { await model.shutdownSimulator(device) } + } label: { + Label("Shut Down Simulator", systemImage: "stop.fill") + } + } else { + Button { + Task { await model.bootSimulator(device) } + } label: { + Label("Boot Simulator", systemImage: "play.fill") + } + } + Button { + managementSheet = .slimmingRecommendation([device]) + } label: { + Label("Slim Simulator", systemImage: "minus.circle") + } + .disabled(model.isBatchRunning) + Button { + Task { await model.restoreOriginalServices(for: device) } + } label: { + Label("Unslim Simulator", systemImage: "plus.circle") + } + .disabled(model.isBatchRunning) + Divider() + Button { + managementSheet = .rename(device) + } label: { + Label("Rename…", systemImage: "pencil") + } + } +} + private struct BootStateView: View { let isBooted: Bool diff --git a/gui/Models.swift b/gui/Models.swift index 2bf3aff..d6087b4 100644 --- a/gui/Models.swift +++ b/gui/Models.swift @@ -7,6 +7,22 @@ enum SlimmingMode: String, CaseIterable, Identifiable { var id: String { rawValue } } +/// How the detail pane lists simulators: the dense table, or a grid of cards +/// showing each booted simulator's live screen. +enum DeviceLayout: String, CaseIterable, Identifiable { + case table = "Table" + case grid = "Grid" + + var id: String { rawValue } + + var systemImage: String { + switch self { + case .table: return "list.bullet" + case .grid: return "square.grid.2x2" + } + } +} + struct SimulatorDevice: Decodable, Identifiable, Equatable { let udid: String let name: String @@ -158,6 +174,14 @@ struct SimulatorMutationResult: Decodable, Equatable { let sourceUdid: String? } +/// The PNG path `simslim screenshot --json` wrote for a booted simulator, used +/// to render its live screen in the device grid. +struct SimulatorScreenshot: Decodable, Equatable { + let udid: String + let name: String? + let path: String +} + enum ServiceSlimState: Equatable { case stock case partial(disabled: Int, total: Int) diff --git a/output.go b/output.go index 2ca2b1b..05fea28 100644 --- a/output.go +++ b/output.go @@ -48,6 +48,14 @@ type SimulatorMutationOutput struct { SourceUDID string `json:"sourceUdid,omitempty"` } +// ScreenshotOutput is returned by `screenshot`: the PNG path written for a +// booted simulator, so the GUI can render its live screen in the device grid. +type ScreenshotOutput struct { + UDID string `json:"udid"` + Name string `json:"name,omitempty"` + Path string `json:"path"` +} + // DoctorOutput reports whether each required feature survives the device's // current slimming. OK is false when any required feature has a disabled daemon. type DoctorOutput struct { diff --git a/simctl.go b/simctl.go index e70f269..6b99d51 100644 --- a/simctl.go +++ b/simctl.go @@ -349,6 +349,65 @@ func Shutdown(ctx context.Context, set, udid string) error { return nil } +// CaptureScreenshot writes a PNG of a booted simulator's screen to destPath via +// `simctl io screenshot`. The caller resolves the exact device first (so an +// alias like "all" can never enter this path) and guarantees it is booted: a +// shutdown simulator has no screen to capture. +// +// A device with more than one display (for example an iPad presenting an +// external display) makes simctl refuse to choose and list the displays, +// marking the device's own screen "(primary)". That listing is the only place +// simctl exposes the display ids, so on that error we parse out the primary id +// and retry against it. +func CaptureScreenshot(ctx context.Context, set, udid, destPath string) error { + out, err := runScreenshot(ctx, set, udid, destPath, "") + if err == nil { + return nil + } + if display := primaryDisplayID(out); display != "" { + if out2, err2 := runScreenshot(ctx, set, udid, destPath, display); err2 == nil { + return nil + } else { + out, err = out2, err2 + } + } + return fmt.Errorf("simctl io screenshot: %w: %s", err, strings.TrimSpace(out)) +} + +func runScreenshot(ctx context.Context, set, udid, destPath, display string) (string, error) { + sub := []string{"io", udid, "screenshot", "--type=png"} + if display != "" { + sub = append(sub, "--display="+display) + } + sub = append(sub, destPath) + out, err := exec.CommandContext(ctx, "xcrun", simctlArgs(set, sub...)...).CombinedOutput() + return string(out), err +} + +// primaryDisplayID returns the numeric id of the display simctl's multi-display +// error marks "(primary)", or "" when the output is not that error. The lines +// look like ` --display=1 LCD (primary) 1398x2034`; the exact "(primary)" +// match skips the "(primary-1)" external-display line. +func primaryDisplayID(simctlOutput string) string { + for _, line := range strings.Split(simctlOutput, "\n") { + if !strings.Contains(line, "(primary)") { + continue + } + _, after, found := strings.Cut(line, "--display=") + if !found { + continue + } + id := after + if i := strings.IndexFunc(id, func(r rune) bool { return r < '0' || r > '9' }); i >= 0 { + id = id[:i] + } + if id != "" { + return id + } + } + return "" +} + // readDisabled returns the labels currently disabled in the device's system // domain. A label absent from the output is enabled. func readDisabled(ctx context.Context, set, udid string) (map[string]bool, error) {