feat: add Flutter USB mirroring and single-instance desktop clients
This commit is contained in:
1 parent
3a7bb071f0
commit
a339465392
30 files changed
+1688
-104
No files matched your search
@@ -0,0 +1,145 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:ads_manager/data/manager_repository.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:ads_manager/ui/embedded_screen.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets(
|
||||
'screen page switches between embedded and standalone without disconnecting',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(1280, 820);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
EmbeddedScreen.channel,
|
||||
(call) async => call.method == 'attach' ? true : null,
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
EmbeddedScreen.channel,
|
||||
null,
|
||||
),
|
||||
);
|
||||
final process = ScreenProcess();
|
||||
final session =
|
||||
Session('phone', '127.0.0.1:15555', 'adb', 'status', process)
|
||||
..screen = process
|
||||
..screenEmbedded = true
|
||||
..ready = true;
|
||||
var switches = 0;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: StatefulBuilder(
|
||||
builder: (context, setState) => ScreenPage(
|
||||
session: session,
|
||||
onBack: () {},
|
||||
onStop: () async {},
|
||||
onToggle: () async {
|
||||
setState(() {
|
||||
session.screenEmbedded = !session.screenEmbedded;
|
||||
switches++;
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
await tester.tap(find.text('独立投屏'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(EmbeddedScreen), findsNothing);
|
||||
expect(find.textContaining('独立窗口运行'), findsOneWidget);
|
||||
expect(session.ready, true);
|
||||
expect(session.endpoint, '127.0.0.1:15555');
|
||||
await tester.tap(find.text('返回内嵌'));
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
expect(find.byType(EmbeddedScreen), findsOneWidget);
|
||||
expect(switches, 2);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
},
|
||||
);
|
||||
testWidgets('native screen scales its bounds and hides on removal', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(1600, 1200);
|
||||
tester.view.devicePixelRatio = 2;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final calls = <MethodCall>[];
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
EmbeddedScreen.channel,
|
||||
(call) async {
|
||||
calls.add(call);
|
||||
return call.method == 'attach' ? true : null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
EmbeddedScreen.channel,
|
||||
null,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
const MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Padding(
|
||||
padding: EdgeInsets.all(20),
|
||||
child: EmbeddedScreen(pid: 123),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
await tester.pump();
|
||||
final layout =
|
||||
calls.lastWhere((c) => c.method == 'layout').arguments
|
||||
as Map<dynamic, dynamic>;
|
||||
expect(layout['pid'], 123);
|
||||
expect(layout['x'], 40);
|
||||
expect(layout['width'], 1520);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
expect(calls.last.method, 'hide');
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
testWidgets('attach failure shows an error and hides the child', (
|
||||
tester,
|
||||
) async {
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
EmbeddedScreen.channel,
|
||||
(call) async {
|
||||
if (call.method == 'attach') {
|
||||
throw PlatformException(code: 'set_parent', message: 'test failure');
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
EmbeddedScreen.channel,
|
||||
null,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
const MaterialApp(home: Scaffold(body: EmbeddedScreen(pid: 234))),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
await tester.pump();
|
||||
expect(find.textContaining('投屏嵌入失败'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
});
|
||||
}
|
||||
|
||||
class ScreenProcess extends Fake implements Process {
|
||||
@override
|
||||
int get pid => 123;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ Future<void> main(List<String> args) async {
|
||||
final repo = ManagerRepository(stdout.writeln);
|
||||
try {
|
||||
await repo.init();
|
||||
repo.settings.usbMode = args.contains('--usb');
|
||||
final devices = await repo.devices();
|
||||
stdout.writeln(
|
||||
'API devices: ${devices.map((d) => "${d.id} busy=${d.busy}").join(", ")}',
|
||||
@@ -40,6 +41,33 @@ Future<void> main(List<String> args) async {
|
||||
}
|
||||
stdout.writeln('scrcpy process alive: ${s.screen!.pid}');
|
||||
}
|
||||
if (args.contains('--usb')) {
|
||||
final path = await repo.run(s.adb, ['-s', s.endpoint, 'get-devpath']);
|
||||
// Windows ADB may return "unknown" for get-devpath. USB-only selection
|
||||
// must either select this virtual serial or report multiple USB devices.
|
||||
try {
|
||||
final selected = await repo.run(s.adb, ['-d', 'get-serialno']);
|
||||
if (selected.trim() != s.endpoint) {
|
||||
throw StateError('USB-only selection did not include virtual device');
|
||||
}
|
||||
} on ProcessException catch (error) {
|
||||
if (!error.message.contains('more than one')) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
stdout.writeln('Native USB-only selection verified; get-devpath=$path');
|
||||
await repo.disconnect(s.id);
|
||||
await Future<void>.delayed(const Duration(seconds: 2));
|
||||
final listing = await repo.run(s.adb, ['devices']);
|
||||
if (listing
|
||||
.split('\n')
|
||||
.any((line) => line.startsWith('${s.endpoint}\t'))) {
|
||||
throw StateError('USB transport was not removed');
|
||||
}
|
||||
if (repo.reservedPorts.isNotEmpty) {
|
||||
throw StateError('Ports leaked after USB disconnect');
|
||||
}
|
||||
}
|
||||
stdout.writeln('LIVE PASS');
|
||||
} finally {
|
||||
await repo.shutdown();
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
import 'package:ads_manager/data/manager_repository.dart';
|
||||
import 'package:ads_manager/ui/embedded_screen.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await windowManager.ensureInitialized();
|
||||
final repo = ManagerRepository(stdout.writeln);
|
||||
Process? screen;
|
||||
Session? usbSession;
|
||||
final report = <String, dynamic>{};
|
||||
try {
|
||||
await repo.init();
|
||||
var serial = const String.fromEnvironment('ADS_EMBED_SERIAL');
|
||||
if (const bool.fromEnvironment('ADS_EMBED_USB')) {
|
||||
repo.settings.usbMode = true;
|
||||
final idle = (await repo.devices())
|
||||
.where((device) => !device.busy)
|
||||
.firstOrNull;
|
||||
if (idle == null) {
|
||||
throw StateError('No idle device for USB embedding smoke');
|
||||
}
|
||||
final session = await repo.connect(idle.id);
|
||||
usbSession = session;
|
||||
for (var i = 0; i < 20 && !session.ready; i++) {
|
||||
await Future<void>.delayed(const Duration(seconds: 3));
|
||||
await repo.monitor();
|
||||
}
|
||||
if (!session.ready) {
|
||||
throw StateError('Virtual USB ADB did not become ready');
|
||||
}
|
||||
serial = session.endpoint;
|
||||
}
|
||||
if (serial.isEmpty) {
|
||||
throw StateError('Specify --dart-define=ADS_EMBED_SERIAL=...');
|
||||
}
|
||||
screen = await repo.launchScreen(
|
||||
serial,
|
||||
repo.settings.adb,
|
||||
'native-smoke',
|
||||
embedded: true,
|
||||
);
|
||||
if (usbSession != null) {
|
||||
usbSession.screen = screen;
|
||||
usbSession.screenEmbedded = true;
|
||||
}
|
||||
repo.watch(screen, 'native-smoke');
|
||||
unawaited(
|
||||
screen.exitCode.then((code) => stdout.writeln("SCRCPY EXIT=$code")),
|
||||
);
|
||||
final pid = screen.pid;
|
||||
stdout.writeln("SCRCPY PID=$pid");
|
||||
final show = ValueNotifier(true);
|
||||
runApp(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(220, 80, 24, 24),
|
||||
child: ValueListenableBuilder<bool>(
|
||||
valueListenable: show,
|
||||
builder: (_, visible, child) => visible
|
||||
? EmbeddedScreen(key: ValueKey(pid), pid: pid)
|
||||
: const SizedBox(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await windowManager.waitUntilReadyToShow(
|
||||
const WindowOptions(size: Size(1280, 820), title: 'ADS Embedded Smoke'),
|
||||
() async {
|
||||
await windowManager.show();
|
||||
},
|
||||
);
|
||||
Future<Map<String, dynamic>> state() async => Map<String, dynamic>.from(
|
||||
await EmbeddedScreen.channel.invokeMethod<Map<Object?, Object?>>(
|
||||
'state',
|
||||
{'pid': pid},
|
||||
) ??
|
||||
{},
|
||||
);
|
||||
for (var i = 0; i < 60; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
if ((await state())['visible'] == true) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
report['initial'] = await state();
|
||||
if (report['initial']['embedded'] != true ||
|
||||
report['initial']['visible'] != true) {
|
||||
throw StateError('Embedding failed: $report');
|
||||
}
|
||||
await windowManager.setSize(const Size(1080, 720));
|
||||
await Future<void>.delayed(const Duration(seconds: 2));
|
||||
report['resized'] = await state();
|
||||
if (report['resized']['width'] == report['initial']['width']) {
|
||||
throw StateError('Resize did not reach child');
|
||||
}
|
||||
show.value = false;
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
report['pageHidden'] = await state();
|
||||
if (report['pageHidden']['visible'] != false) {
|
||||
throw StateError('Page hide failed');
|
||||
}
|
||||
show.value = true;
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
await windowManager.hide();
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
report['trayHidden'] = await state();
|
||||
if (report['trayHidden']['visible'] != false) {
|
||||
throw StateError('Host hide failed');
|
||||
}
|
||||
final duplicate = await Process.start(Platform.resolvedExecutable, []);
|
||||
final duplicateExit = await duplicate.exitCode.timeout(
|
||||
const Duration(seconds: 10),
|
||||
);
|
||||
if (duplicateExit != 0) {
|
||||
throw StateError('Duplicate instance failed to exit');
|
||||
}
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
report['duplicateExited'] = duplicateExit;
|
||||
if (!await windowManager.isVisible()) {
|
||||
throw StateError('Duplicate did not restore existing tray window');
|
||||
}
|
||||
report['restored'] = await state();
|
||||
if (report['restored']['visible'] != true) {
|
||||
throw StateError('Restore failed');
|
||||
}
|
||||
await EmbeddedScreen.channel.invokeMethod<void>('release', {'pid': pid});
|
||||
report['released'] = await state();
|
||||
if (report['released']['embedded'] != false) {
|
||||
throw StateError('Release failed');
|
||||
}
|
||||
if (usbSession != null) {
|
||||
final tunnelPid = usbSession.process.pid;
|
||||
final bridgePid = usbSession.usb!.bridge!.pid;
|
||||
await repo.screen(usbSession, embedded: false);
|
||||
var standaloneVisible = false;
|
||||
for (var i = 0; i < 30; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
final child = usbSession.screen;
|
||||
if (child == null) {
|
||||
throw StateError('Standalone scrcpy exited');
|
||||
}
|
||||
standaloneVisible =
|
||||
await EmbeddedScreen.channel.invokeMethod<bool>(
|
||||
'standaloneVisible',
|
||||
{'pid': child.pid},
|
||||
) ??
|
||||
false;
|
||||
if (standaloneVisible) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!standaloneVisible) {
|
||||
throw StateError('Standalone window did not appear');
|
||||
}
|
||||
report['standaloneVisible'] = true;
|
||||
if (usbSession.screenEmbedded || usbSession.screen?.pid == pid) {
|
||||
throw StateError('Standalone mode did not restart scrcpy');
|
||||
}
|
||||
if (usbSession.process.pid != tunnelPid ||
|
||||
usbSession.usb!.bridge!.pid != bridgePid) {
|
||||
throw StateError('Screen switch changed device connection');
|
||||
}
|
||||
final state = await repo.run(usbSession.adb, [
|
||||
'-s',
|
||||
usbSession.endpoint,
|
||||
'get-state',
|
||||
]);
|
||||
if (state.trim() != 'device') {
|
||||
throw StateError('USB connection lost during screen switch');
|
||||
}
|
||||
report['standalonePreservesUsb'] = true;
|
||||
}
|
||||
report['passed'] = true;
|
||||
} catch (e, stack) {
|
||||
report['passed'] = false;
|
||||
report['error'] = '$e';
|
||||
stderr.writeln('$e\n$stack');
|
||||
} finally {
|
||||
await repo.stop(screen);
|
||||
await repo.shutdown();
|
||||
final root = repo.root?.path ?? Directory.current.parent.path;
|
||||
await File('$root/work/flutter-embed-smoke.json')
|
||||
.writeAsString(const JsonEncoder.withIndent(' ').convert(report));
|
||||
stdout.writeln(jsonEncode(report));
|
||||
await windowManager.destroy();
|
||||
exit(report['passed'] == true ? 0 : 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:ads_manager/ui/manager_model.dart';
|
||||
import 'package:ads_manager/ui/manager_view.dart';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ads_manager/data/windows_usb.dart';
|
||||
import 'package:ads_manager/data/manager_repository.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('enabling USB without driver prompts before installation', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(1280, 1600);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final model = ManagerModel();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SettingsView(model: model, driverInstalled: () async => false),
|
||||
),
|
||||
),
|
||||
);
|
||||
final toggle = find.widgetWithText(SwitchListTile, '挂载为 USB 设备 · Windows');
|
||||
await tester.ensureVisible(toggle);
|
||||
await tester.tap(toggle);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('需要安装 USBip 驱动'), findsOneWidget);
|
||||
expect(find.text('安装驱动'), findsOneWidget);
|
||||
await tester.tap(find.text('暂不安装'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.widget<SwitchListTile>(toggle).value, false);
|
||||
expect(model.repository.settings.usbMode, false);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
model.dispose();
|
||||
});
|
||||
test(
|
||||
'USB defaults off, persists explicitly and maps stable ASCII serials',
|
||||
() {
|
||||
final settings = Settings();
|
||||
expect(settings.usbMode, false);
|
||||
settings.usbMode = true;
|
||||
settings.usbip = 'C:/USBip/usbip.exe';
|
||||
final restored = Settings()..load(settings.toJson());
|
||||
expect(restored.usbMode, true);
|
||||
expect(restored.usbip, settings.usbip);
|
||||
expect(WindowsUsbSession.serialFor('home-phone'), 'ADS-home-phone');
|
||||
final serial = WindowsUsbSession.serialFor('a' * 128);
|
||||
expect(serial.length, 28);
|
||||
expect(serial, WindowsUsbSession.serialFor('a' * 128));
|
||||
expect(RegExp(r'^ADS-[A-F0-9]{24}$').hasMatch(serial), true);
|
||||
},
|
||||
);
|
||||
test('missing driver is reported without installing anything', () async {
|
||||
final installed = await UsbDriver.installed((exe, args) async {
|
||||
expect(exe, 'sc.exe');
|
||||
expect(args, ['query', 'usbip2_ude']);
|
||||
throw const ProcessException('sc.exe', [], 'missing', 1060);
|
||||
});
|
||||
expect(installed, false);
|
||||
});
|
||||
test(
|
||||
'USB and tunnel ports avoid each other and external listeners',
|
||||
() async {
|
||||
final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final repo = ManagerRepository((_) {});
|
||||
try {
|
||||
final a = await repo.allocatePort(listener.port, listener.port + 4);
|
||||
final b = await repo.allocatePort(listener.port, listener.port + 4);
|
||||
expect(a, isNot(listener.port));
|
||||
expect(b, isNot(a));
|
||||
expect(b, isNot(listener.port));
|
||||
} finally {
|
||||
await listener.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
test('USB lease timeout does not start a bridge or attach', () async {
|
||||
final usb = WindowsUsbSession('test', 3240);
|
||||
final directory = await Directory.systemTemp.createTemp('ads-usb-test');
|
||||
try {
|
||||
await expectLater(
|
||||
usb.start(
|
||||
leaseFile: '${directory.path}/lease',
|
||||
upstream: '127.0.0.1:15555',
|
||||
executable: 'must-not-run.exe',
|
||||
usbip: 'must-not-run.exe',
|
||||
environment: {},
|
||||
run: (exe, args) async =>
|
||||
throw StateError('Must not attach before lease'),
|
||||
watch: (process, label) => fail('Must not start before lease'),
|
||||
cancelled: () => false,
|
||||
leaseTimeout: Duration.zero,
|
||||
),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(usb.bridge, isNull);
|
||||
} finally {
|
||||
await directory.delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user