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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ simslim clone <udid> <name>
simslim repair-clone <source-udid> <clone-udid>
simslim rename <udid> <name>
simslim boot <udid> # boot a simulator and wait for its services
simslim screenshot <udid> [path] # PNG of a booted simulator's screen
simslim shutdown <udid> # shut down a booted simulator
simslim erase <udid> # erase apps, data, settings, and slimming overrides
simslim delete <udid> # permanently delete a simulator
Expand Down
1 change: 1 addition & 0 deletions cmd/simslim/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
48 changes: 48 additions & 0 deletions cmd/simslim/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -1157,6 +1202,9 @@ COMMANDS
Repair source-bound state in an existing clone
rename <udid> <name> Rename a simulator
boot <udid> Boot a simulator and wait for its services
screenshot <udid> [path]
Capture a booted simulator's screen as a PNG (to path,
or a temp file); --json reports the written path
shutdown <udid> Shut down a booted simulator
erase <udid> Erase a simulator's apps, data, and settings
delete <udid> Permanently delete a simulator
Expand Down
55 changes: 55 additions & 0 deletions gui/AppModel.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import Foundation

#if canImport(AppKit)
import AppKit
#endif

@MainActor
final class AppModel: ObservableObject {
@Published private(set) var devices: [SimulatorDevice] = []
@Published private(set) var categories: [SlimCategory] = []
@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<String> = []
@Published private(set) var activeOperations: [String: String] = [:]
Expand Down Expand Up @@ -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..<min(limit, booted.count) { startNext() }
var images: [String: NSImage] = [:]
for await (udid, image) in group {
if let image { images[udid] = image }
startNext()
}
return images
}
// Keep a previous frame for a device still capturing this pass, but discard
// anything no longer booted so the grid never shows a stale, dead screen.
let bootedUDIDs = Set(booted.map(\.udid))
var next = screenshots.filter { bootedUDIDs.contains($0.key) }
for (udid, image) in captured { next[udid] = image }
screenshots = next
}

private static let screenshotDirectory: URL = {
let dir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("simslim-screenshots", isDirectory: true)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir
}()

func applyProfileToSelection() async {
await applyProfile(to: selectedDevices)
}
Expand Down
4 changes: 4 additions & 0 deletions gui/Backend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ struct SimSlimBackend {
try await decode(SimulatorMutationResult.self, arguments: ["shutdown", "--json", udid])
}

func screenshot(udid: String, to path: String) async throws -> SimulatorScreenshot {
try await decode(SimulatorScreenshot.self, arguments: ["screenshot", "--json", udid, path])
}

private func decode<T: Decodable>(_ type: T.Type, arguments: [String]) async throws -> T {
let output = try await execute(arguments)
do {
Expand Down
Loading