import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:ui'; import 'detached_platform.dart'; import 'detached_route.dart'; /// Widget tests run on a desktop host but are not a desktop app: there the /// action stays hidden unless a test supplies a platform. DetachedPlatform createDetachedPlatform() => IoDetachedPlatform( supported: (Platform.isLinux || Platform.isMacOS) && !Platform.environment.containsKey('FLUTTER_TEST'), ); DetachedRoute? launchedDetachedRoute(List args) => DetachedRoute.fromLaunch(args, Platform.environment); /// Detached windows as second processes of the desktop app (Linux, macOS). /// /// Flutter 3.44's multi-window API is still experimental (behind a flag and /// without macOS parity), so each detached window is the same executable /// started with `--detached `; `PIPELINES_DETACHED` carries the path /// too, since the macOS runner does not hand its arguments to Dart. It /// shares the saved servers, session and preferences on disk, and has its /// own connection. It writes messages for the main window as lines on its /// standard output, which the main process reads. class IoDetachedPlatform extends DetachedPlatform { IoDetachedPlatform({bool? supported}) : _supported = supported ?? (Platform.isLinux || Platform.isMacOS); final bool _supported; final Map _children = {}; final _messages = StreamController.broadcast(); static const _linePrefix = '@@pipelines-window '; static const titleVariable = 'PIPELINES_WINDOW_TITLE'; static const sizeVariable = 'PIPELINES_WINDOW_SIZE'; static const parentVariable = 'PIPELINES_PARENT_PID'; @override bool get supported => _supported; @override Future launch( DetachedRoute route, { required String title, required Size size, bool tab = false, }) async { if (!_supported) return DetachedLaunch.failed; // A window already open for the item is left as it is: another process // cannot be raised from here. if (_children.containsKey(route)) return DetachedLaunch.opened; final Process process; try { process = await Process.start( Platform.resolvedExecutable, [DetachedRoute.argument, route.path], environment: { DetachedRoute.environment: route.path, titleVariable: title, sizeVariable: '${size.width.round()}x${size.height.round()}', parentVariable: '$pid', }, ); } catch (_) { return DetachedLaunch.failed; } _children[route] = process; // Both streams are drained, so a chatty child never blocks on a full // pipe; only marked lines are messages. process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_line, onError: (_) {}); process.stderr.listen((_) {}, onError: (_) {}); unawaited(process.exitCode.then((_) => _children.remove(route))); return DetachedLaunch.opened; } void _line(String line) { if (!line.startsWith(_linePrefix)) return; final message = decodeDetachedMessage(line.substring(_linePrefix.length)); if (message != null) _messages.add(message); } @override Stream get messages => _messages.stream; File _file(String token) => File('${Directory.systemTemp.path}/pipelines-detached-$token.json'); @override Future put(String token, String json) async { try { await _file(token).writeAsString(json, flush: true); } catch (_) { // The window says the diff is gone. } } @override Future take(String token) async { final file = _file(token); try { final text = await file.readAsString(); await file.delete(); return text; } catch (_) { return null; } } int? get _parent => int.tryParse(Platform.environment[parentVariable] ?? ''); Future _parentAlive() async { final parent = _parent; if (parent == null) return false; try { return (await Process.run('kill', ['-0', '$parent'])).exitCode == 0; } catch (_) { return false; } } @override Future sendToMain(DetachedMessage message) async { if (!await _parentAlive()) return false; try { stdout.writeln('$_linePrefix${encodeDetachedMessage(message)}'); await stdout.flush(); return true; } catch (_) { return false; } } @override Future closeSelf() async => exit(0); /// Starts the app as an ordinary main window (it opens where it last was) /// for this one to close. @override Future becomeMain(String appPath) async { try { await Process.start( Platform.resolvedExecutable, const [], environment: {DetachedRoute.environment: '', parentVariable: ''}, mode: ProcessStartMode.detached, ); } catch (_) { return false; } exit(0); } }