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
8 changes: 8 additions & 0 deletions app/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Quitting SimUtil on macOS with Cmd+Q, the menu or the Dock now stops
its streams, recordings and helper processes, like closing the window
does; before, adb kept running in the background.
- Quitting SimUtil or closing an iOS simulator's stream while its
recording is still starting no longer leaves the recording running.

## [0.6.1] - 2026-11-21

### Fixed
Expand Down
9 changes: 9 additions & 0 deletions app/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:bloc_signals/bloc_signals.dart';
import 'package:flutter/foundation.dart';
import 'package:desktop_multi_window/desktop_multi_window.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:simutil_adb/simutil_adb.dart';
import 'package:simutil_core/simutil_core.dart';
import 'package:window_manager/window_manager.dart';
Expand Down Expand Up @@ -68,6 +69,11 @@ Future<void> main(List<String> args) async {
windowManager.addListener(quitOnClose);
onWindowsChanged.listen((_) => quitOnClose.onWindowsChanged());
await windowManager.setPreventClose(true);
// Cmd+Q, the app menu or the Dock quit without closing the window: the
// macOS app delegate asks for the release before it terminates.
_quitChannel.setMethodCallHandler((call) async {
if (call.method == 'release') await releaseApp();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

// Shared by the MCP tools and the scenario editor.
final tools = getIt.registerSingleton(
Expand Down Expand Up @@ -123,6 +129,9 @@ Future<void> main(List<String> args) async {
runApp(const SimutilApp());
}

/// Matches `quitChannel` in `macos/Runner/AppDelegate.swift`.
const _quitChannel = MethodChannel('simutil/quit');

/// Runs [quit] when the main window is closed, or hides it while device
/// [windows] are open and quits once the last of them closes. The Dock icon
/// or a device window's "Back to the main window" shows it again.
Expand Down
15 changes: 12 additions & 3 deletions app/lib/src/di.dart
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,23 @@ class _SimulatorSlimControl implements SlimControl {
/// Closes cubits and stops the shell-command isolate.
Future<void> disposeDependencies() => getIt.reset();

/// Releases streams (device windows' too) and recordings, then closes the
/// window and quits.
Future<void> quitApp() async {
Future<void>? _released;

/// Releases streams (device windows' too), recordings and the processes
/// behind them (adb, scrcpy, ffmpeg…), once; they would outlive the app.
Future<void> releaseApp() => _released ??= () async {
Comment thread
KrohnMi marked this conversation as resolved.
Resolved
try {
await getIt<DeviceWindows>().closeAll();
await disposeDependencies();
} catch (e, s) {
debugPrint('Dispose on quit failed: $e\n$s');
}
}();

/// [releaseApp], then closes the window and quits.
Future<void> quitApp() async {
try {
await releaseApp();
} finally {
await windowManager.destroy();
}
Expand Down
15 changes: 12 additions & 3 deletions app/lib/src/stream/streams_cubit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ class StreamsCubit extends CubitSignal<StreamsState> {
this.onSaved,
this.openElsewhere,
RecordingLock? recordingLock,
this.stopLimit = const Duration(seconds: 5),
}) : _recordingLock = recordingLock ?? RecordingLock(),
super(initialState: const StreamsState());

/// How long [close] waits for each session to stop: on quit, a session
/// that hangs must not keep the rest of the app from being released.
final Duration stopLimit;

/// One recording at a time, shared with the grid recorder.
final RecordingLock _recordingLock;

Expand Down Expand Up @@ -269,9 +274,13 @@ class StreamsCubit extends CubitSignal<StreamsState> {
for (final subscription in _subscriptions.values) {
await subscription.cancel();
}
for (final session in _sessions.values) {
await session.stop();
}
await Future.wait([
for (final session in _sessions.values)
session
.stop()
.timeout(stopLimit, onTimeout: () {})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.catchError((Object _) {}),
]);
_sessions.clear();
await super.close();
}
Expand Down
2 changes: 2 additions & 0 deletions app/lib/src/windows/device_window_app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Future<void> runDeviceWindow(WindowController window, Device device) async {
windowManager.addListener(_OnClose(close));
await windowManager.setPreventClose(true);

// Quitting asked while the window was still starting: open nothing.
if (stopped != null) return;
getIt<DeviceWindows>().backToMain = () => close(back: true);
final streams = getIt<StreamsCubit>();
unawaited(streams.open(device)); // adds the tile synchronously
Expand Down
40 changes: 31 additions & 9 deletions app/lib/src/windows/device_windows.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ class DeviceWindows {

final _moves = StreamController<DeviceMove>.broadcast();

/// Set by [closeAll]: SimUtil is quitting, so no new window opens.
var _closing = false;

/// Devices moved into their own window or back to the grid, for toasts.
Stream<DeviceMove> get moves => _moves.stream;

Expand Down Expand Up @@ -58,9 +61,10 @@ class DeviceWindows {
}

/// Opens [device] in its own window, or shows the one it has. The window
/// shows itself once it is sized.
/// shows itself once it is sized. Does nothing while quitting: a window
/// opened after [closeAll] looked would keep its stream running.
Future<void> open(Device device) async {
if (await focus(device)) return;
if (_closing || await focus(device) || _closing) return;
await WindowController.create(
WindowConfiguration(arguments: argumentsFor(device)),
);
Expand Down Expand Up @@ -90,22 +94,40 @@ class DeviceWindows {
}
}

/// Has every device window stop its stream; for quitting.
/// Has every device window stop its stream, all at once; for quitting.
/// Each gets 5 s, so a hung one leaves time to release the main window.
Future<void> closeAll() async {
_closing = true;
final List<WindowController> windows;
try {
windows = await WindowController.getAll();
} catch (_) {
return; // quitting still releases the main window's services
}
for (final window in windows) {
if (deviceOf(window.arguments) == null) continue;
await Future.wait([
for (final window in windows)
if (deviceOf(window.arguments) != null) _close(window),
]);
}

/// Asks [window] to stop its stream. A window still starting has no
/// handler yet (it adds it before it opens the stream), so ask again
/// until it answers. A window that never does must not block quitting.
static Future<void> _close(WindowController window) async {
final deadline = DateTime.now().add(const Duration(seconds: 5));
while (true) {
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) return;
try {
await window
.invokeMethod<void>(closeMethod)
.timeout(const Duration(seconds: 5));
await window.invokeMethod<void>(closeMethod).timeout(left);
return;
} on WindowChannelException catch (e) {
if (e.code != 'CHANNEL_UNREGISTERED' && e.code != 'CHANNEL_NOT_FOUND') {
return;
}
await Future<void>.delayed(const Duration(milliseconds: 100));
} catch (_) {
// A window that does not answer must not block quitting.
return;
}
}
}
Expand Down
63 changes: 63 additions & 0 deletions app/macos/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,73 @@ import FlutterMacOS

@main
class AppDelegate: FlutterAppDelegate {
/// Asks the main window's engine to release streams, recordings and
/// child processes (`releaseApp` in Dart); it closes the device windows.
private var quitChannel: FlutterMethodChannel? {
guard let controller = mainFlutterWindow?.contentViewController as? FlutterViewController
else { return nil }
return FlutterMethodChannel(
name: "simutil/quit", binaryMessenger: controller.engine.binaryMessenger)
}

/// The release ran (or gave up); the next terminate goes through.
private var released = false
private var releasing = false

/// A hung release must not keep the app from quitting.
private static let releaseTimeout: TimeInterval = 10

override init() {
super.init()
NotificationCenter.default.addObserver(
forName: NSApplication.willTerminateNotification, object: nil, queue: nil
) { _ in Self.terminateChildren() }
}

/// Last resort as SimUtil exits: a child process the release did not end
/// (it timed out, or a stop came while a start was still launching one)
/// would keep running under launchd. Emulators, plugins and the updater
/// are started detached, so they are no children and keep running.
private static func terminateChildren() {
for child in childProcesses() { kill(child, SIGTERM) }
}

private static func childProcesses() -> [pid_t] {
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0]
var size = 0
guard sysctl(&mib, UInt32(mib.count), nil, &size, nil, 0) == 0 else { return [] }
let stride = MemoryLayout<kinfo_proc>.stride
var procs = [kinfo_proc](repeating: kinfo_proc(), count: size / stride + 32)
size = procs.count * stride
guard sysctl(&mib, UInt32(mib.count), &procs, &size, nil, 0) == 0 else { return [] }
let me = getpid()
return procs.prefix(size / stride)
.filter { $0.kp_eproc.e_ppid == me }
.map { $0.kp_proc.p_pid }
}

override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}

/// Cmd+Q, the app menu, the Dock and logging out terminate without
/// closing the window, so the Dart side never hears of it: adb, scrcpy
/// and ffmpeg would keep running. Delay the quit until the release ran
/// (or timed out): a logout, restart or shutdown then carries on.
override func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
guard !released, let channel = quitChannel else { return .terminateNow }
if releasing { return .terminateCancel }
releasing = true
let finish = { [weak self] in
guard let self, !self.released else { return }
self.released = true
sender.reply(toApplicationShouldTerminate: true)
}
channel.invokeMethod("release", arguments: nil) { _ in finish() }
DispatchQueue.main.asyncAfter(deadline: .now() + Self.releaseTimeout, execute: finish)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return .terminateLater
}

/// The Dock icon shows the main window again after it was hidden while
/// device windows stayed open.
override func applicationShouldHandleReopen(
Expand Down
38 changes: 37 additions & 1 deletion app/test/streams_cubit_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,14 @@ class _FakeSession implements DeviceSession {
/// Completes the pending [start].
final gate = Completer<void>();

/// What [stop] waits for; set to make it hang.
Future<void>? stopGate;

@override
Future<void> stop() async => stopped = true;
Future<void> stop() async {
await stopGate;
stopped = true;
}

@override
Future<void> start() {
Expand Down Expand Up @@ -47,6 +53,36 @@ void main() {
type: DeviceType.simulator,
);

test('close() stops every session and does not wait on one that '
'hangs', () async {
final sessions = <String, _FakeSession>{
'A': _FakeSession('A')
..gate.complete()
..stopGate = Completer<void>().future,
'B': _FakeSession('B')..gate.complete(),
};
final cubit = StreamsCubit(
(device) async => sessions[device.id]!,
stopLimit: const Duration(milliseconds: 200),
);
for (final id in sessions.keys) {
await cubit.open(
Device.android(
id: id,
name: id,
state: DeviceState.booted,
type: DeviceType.simulator,
),
);
}
await pumpEventQueue();
expect(sessions.values.every((s) => s.started), isTrue);

await cubit.close().timeout(const Duration(seconds: 2));
expect(sessions['A']!.stopped, isFalse);
expect(sessions['B']!.stopped, isTrue);
});

test('a device streaming in its own window opens no tile', () async {
var created = 0;
var elsewhere = true;
Expand Down
7 changes: 7 additions & 0 deletions packages/simutil_apple/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 1.5.1

- `SimulatorRecorder.stop()` during `start()` stops the pending
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
`simctl io recordVideo` right away instead of waiting up to 15 s for it
to report `Recording started`; that `start()` then throws a
`StateError` and no recording is kept.

## 1.5.0

- `IOSDeviceService.launchDevice` throws a `SimulatorLaunchException`
Expand Down
42 changes: 38 additions & 4 deletions packages/simutil_apple/lib/src/simulator_recorder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ class _SimulatorRecorder implements SimulatorRecorder {
/// another `simctl`, and [stop] waits for it.
Future<void>? _starting;

/// The `simctl` a running start launched, before it reported recording,
/// and whether it did; [stop] ends that wait.
Process? _launching;
Completer<bool>? _started;

/// [stop] was called while a start was running: it must not record.
var _cancelled = false;

/// How long `simctl` may take to report `Recording started`.
static const _startTimeout = Duration(seconds: 15);

Expand All @@ -55,9 +63,13 @@ class _SimulatorRecorder implements SimulatorRecorder {
'--force',
path,
]);
_launching = process;
if (_cancelled) process.kill(ProcessSignal.sigint);
unawaited(process.stdout.drain<void>());
final stderr = StringBuffer();
final started = Completer<bool>();
final started = _started = Completer<bool>();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// stop() came before simctl launched: no need to wait for it to record.
if (_cancelled) started.complete(false);
process.stderr.transform(utf8.decoder).listen((text) {
stderr.write(text);
if (stderr.toString().contains('Recording started') &&
Expand All @@ -80,6 +92,19 @@ class _SimulatorRecorder implements SimulatorRecorder {
_startTimeout,
onTimeout: () => false,
);
_launching = null;
_started = null;
if (_cancelled) {
// Already sent SIGINT by stop(): let simctl finish on its own.
await process.exitCode.timeout(
const Duration(seconds: 2),
onTimeout: () {
process.kill();
return -1;
},
);
throw StateError('Recording stopped while it was starting');
}
if (!ok) {
process.kill();
// So a retry does not overlap the failed simctl.
Expand All @@ -96,12 +121,21 @@ class _SimulatorRecorder implements SimulatorRecorder {
/// simctl finalizes the movie on SIGINT, not on SIGTERM.
@override
Future<String?> stop() async {
// A stream closed while its recording starts: let the start finish,
// then stop what it started rather than leave it running.
// A stream closed (or the app quitting) while its recording starts:
// end the start now instead of waiting up to [_startTimeout] for
// simctl, and stop what it may already have started.
if (_starting case final starting?) {
_cancelled = true;
_launching?.kill(ProcessSignal.sigint);
if (_started case final started? when !started.isCompleted) {
started.complete(false);
}
try {
await starting;
} catch (_) {}
} catch (_) {
} finally {
_cancelled = false;
}
}
final process = _process;
final path = _path;
Expand Down
Loading
Loading