diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 0000000..dc90e5a --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,17 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - pinned + - security +# Label to use when marking an issue as stale +staleLabel: wontfix +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/.github/workflows/deploy-web.yaml b/.github/workflows/deploy-web.yaml new file mode 100644 index 0000000..622814c --- /dev/null +++ b/.github/workflows/deploy-web.yaml @@ -0,0 +1,31 @@ +name: deploy web on github-page +on: + push: + branches: + - master +jobs: + build: + name: Build Web + env: + my_secret: ${{secrets.commit_secret}} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: subosito/flutter-action@v1 + with: + channel: "stable" + - run: flutter config --enable-web + - run: flutter clean + - run: flutter pub get + - run: flutter build web --release --web-renderer html --base-href /flutter-webrtc-demo/ + - run: | + cd build/web + git init + git config --global user.email duanweiwei1982@gmail.com + git config --global user.name cloudwebrtc + git status + git remote add origin https://${{secrets.commit_secret}}@github.com/flutter-webrtc/flutter-webrtc-demo.git + git checkout -b gh-pages + git add --all + git commit -m "update" + git push origin gh-pages -f diff --git a/.github/workflows/flutter.yml b/.github/workflows/flutter.yml index 166d257..3b9b3ae 100644 --- a/.github/workflows/flutter.yml +++ b/.github/workflows/flutter.yml @@ -16,13 +16,13 @@ jobs: os: [ubuntu-latest] # os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: java-version: '12.x' - uses: subosito/flutter-action@v1 with: - flutter-version: '1.7.8+hotfix.4' + flutter-version: '3.3.2' channel: 'stable' - run: flutter packages get - run: flutter test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbe6700 --- /dev/null +++ b/.gitignore @@ -0,0 +1,74 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# Visual Studio Code related +.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.packages +.pub-cache/ +.pub/ +/build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +.flutter-plugins-dependencies + +ios/Flutter/flutter_export_environment.sh +lib/generated_plugin_registrant.dart \ No newline at end of file diff --git a/README.md b/README.md index c701b00..49790fe 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # flutter-webrtc-demo + [![slack](https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen)](https://join.slack.com/t/flutterwebrtc/shared_invite/zt-q83o7y1s-FExGLWEvtkPKM8ku_F8cEQ) + Flutter WebRTC plugin Demo + +Online Demo: https://flutter-webrtc.github.io/flutter-webrtc-demo/ + ## Usage - `git clone https://github.com/cloudwebrtc/flutter-webrtc-demo` - `cd flutter-webrtc-demo` diff --git a/android/app/build.gradle b/android/app/build.gradle index 4543909..f30d743 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,3 +1,9 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { @@ -6,11 +12,6 @@ if (localPropertiesFile.exists()) { } } -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' @@ -21,11 +22,11 @@ if (flutterVersionName == null) { flutterVersionName = '1.0' } -apply plugin: 'com.android.application' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - android { - compileSdkVersion 28 + namespace "com.cloudwebrtc.flutterwebrtcdemo" + compileSdkVersion flutter.compileSdkVersion + ndkVersion flutter.ndkVersion + lintOptions { disable 'InvalidPackage' @@ -34,8 +35,8 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.cloudwebrtc.flutterwebrtcdemo" - minSdkVersion 18 - targetSdkVersion 28 + minSdkVersion 23 + targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" @@ -51,8 +52,6 @@ android { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug - useProguard true - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { @@ -64,8 +63,4 @@ flutter { source '../..' } -dependencies { - testImplementation 'junit:junit:4.12' - androidTestImplementation 'com.android.support.test:runner:1.0.2' - androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' -} +dependencies {} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index a29bb70..97c9635 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -22,11 +22,14 @@ additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> + plugins.load(reader) } + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } } -plugins.each { name, path -> - def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() - include ":$name" - project(":$name").projectDir = pluginDirectory +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version '8.1.1' apply false + id "org.jetbrains.kotlin.android" version "2.0.0" apply false } + +include ":app" + diff --git a/ios/Podfile b/ios/Podfile index 2a3a960..41d619a 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -10,78 +10,29 @@ project 'Runner', { 'Release' => :release, } -def parse_KV_file(file, separator='=') - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return []; +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end - generated_key_values = {} - skip_line_start_symbols = ["#", "/"] - File.foreach(file_abs_path) do |line| - next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } - plugin = line.split(pattern=separator) - if plugin.length == 2 - podname = plugin[0].strip() - path = plugin[1].strip() - podpath = File.expand_path("#{path}", file_abs_path) - generated_key_values[podname] = podpath - else - puts "Invalid plugin specification: #{line}" - end - end - generated_key_values -end - -target 'Runner' do - # Flutter Pod - - copied_flutter_dir = File.join(__dir__, 'Flutter') - copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework') - copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec') - unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path) - # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet. - # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration. - # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist. - generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig') - unless File.exist?(generated_xcode_build_settings_path) - raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path) - cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR']; - - unless File.exist?(copied_framework_path) - FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir) - end - unless File.exist?(copied_podspec_path) - FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir) - end + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end - # Keep pod path relative so it can be checked into Podfile.lock. - pod 'Flutter', :path => 'Flutter' +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - # Plugin Pods +flutter_ios_podfile_setup - # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock - # referring to absolute paths on developers' machines. - system('rm -rf .symlinks') - system('mkdir -p .symlinks/plugins') - plugin_pods = parse_KV_file('../.flutter-plugins') - plugin_pods.each do |name, path| - symlink = File.join('.symlinks', 'plugins', name) - File.symlink(path, symlink) - pod name, :path => File.join(symlink, 'ios') - end +target 'Runner' do + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end -# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. -install! 'cocoapods', :disable_input_output_paths => true - post_install do |installer| installer.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['ENABLE_BITCODE'] = 'NO' - end + flutter_additional_ios_build_settings(target) end end diff --git a/ios/Runner/GeneratedPluginRegistrant.h b/ios/Runner/GeneratedPluginRegistrant.h deleted file mode 100644 index 3b700eb..0000000 --- a/ios/Runner/GeneratedPluginRegistrant.h +++ /dev/null @@ -1,14 +0,0 @@ -// -// Generated file. Do not edit. -// - -#ifndef GeneratedPluginRegistrant_h -#define GeneratedPluginRegistrant_h - -#import - -@interface GeneratedPluginRegistrant : NSObject -+ (void)registerWithRegistry:(NSObject*)registry; -@end - -#endif /* GeneratedPluginRegistrant_h */ diff --git a/ios/Runner/GeneratedPluginRegistrant.m b/ios/Runner/GeneratedPluginRegistrant.m deleted file mode 100644 index c200173..0000000 --- a/ios/Runner/GeneratedPluginRegistrant.m +++ /dev/null @@ -1,16 +0,0 @@ -// -// Generated file. Do not edit. -// - -#import "GeneratedPluginRegistrant.h" -#import -#import - -@implementation GeneratedPluginRegistrant - -+ (void)registerWithRegistry:(NSObject*)registry { - [FlutterWebRTCPlugin registerWithRegistrar:[registry registrarForPlugin:@"FlutterWebRTCPlugin"]]; - [FLTSharedPreferencesPlugin registerWithRegistrar:[registry registrarForPlugin:@"FLTSharedPreferencesPlugin"]]; -} - -@end diff --git a/lib/main.dart b/lib/main.dart index d51bb5e..ed3df9f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,8 +1,8 @@ -import 'package:flutter/material.dart'; -import 'src/utils/key_value_store.dart' - if (dart.library.js) 'src/utils/key_value_store_web.dart'; import 'dart:core'; -import 'src/basic_sample/basic_sample.dart'; + +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + import 'src/call_sample/call_sample.dart'; import 'src/call_sample/data_channel_sample.dart'; import 'src/route_item.dart'; @@ -20,9 +20,10 @@ enum DialogDemoAction { } class _MyAppState extends State { - List items; - String _serverAddress = ''; - KeyValueStore keyValueStore = KeyValueStore(); + List items = []; + String _server = ''; + late SharedPreferences _prefs; + bool _datachannel = false; @override initState() { @@ -44,12 +45,12 @@ class _MyAppState extends State { @override Widget build(BuildContext context) { - return new MaterialApp( - home: new Scaffold( - appBar: new AppBar( - title: new Text('Flutter-WebRTC example'), + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: Text('Flutter-WebRTC example'), ), - body: new ListView.builder( + body: ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: items.length, @@ -60,27 +61,28 @@ class _MyAppState extends State { } _initData() async { - await keyValueStore.init(); + _prefs = await SharedPreferences.getInstance(); setState(() { - _serverAddress = keyValueStore.getString('server') ?? 'demo.cloudwebrtc.com'; + _server = _prefs.getString('server') ?? 'demo.cloudwebrtc.com'; }); } - void showDemoDialog({BuildContext context, Widget child}) { + void showDemoDialog( + {required BuildContext context, required Widget child}) { showDialog( context: context, builder: (BuildContext context) => child, - ).then((T value) { + ).then((T? value) { // The value passed to Navigator.pop() or null. if (value != null) { if (value == DialogDemoAction.connect) { - keyValueStore.setString('server', _serverAddress); + _prefs.setString('server', _server); Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => _datachannel - ? DataChannelSample(ip: _serverAddress) - : CallSample(ip: _serverAddress))); + ? DataChannelSample(host: _server) + : CallSample(host: _server))); } } }); @@ -89,26 +91,26 @@ class _MyAppState extends State { _showAddressDialog(context) { showDemoDialog( context: context, - child: new AlertDialog( + child: AlertDialog( title: const Text('Enter server address:'), content: TextField( onChanged: (String text) { setState(() { - _serverAddress = text; + _server = text; }); }, decoration: InputDecoration( - hintText: _serverAddress, + hintText: _server, ), textAlign: TextAlign.center, ), actions: [ - new FlatButton( + TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.pop(context, DialogDemoAction.cancel); }), - new FlatButton( + TextButton( child: const Text('CONNECT'), onPressed: () { Navigator.pop(context, DialogDemoAction.connect); @@ -118,15 +120,6 @@ class _MyAppState extends State { _initItems() { items = [ - RouteItem( - title: 'Basic API Tests', - subtitle: 'Basic API Tests.', - push: (BuildContext context) { - Navigator.push( - context, - new MaterialPageRoute( - builder: (BuildContext context) => new BasicSample())); - }), RouteItem( title: 'P2P Call Sample', subtitle: 'P2P Call Sample.', diff --git a/lib/src/basic_sample/basic_sample.dart b/lib/src/basic_sample/basic_sample.dart deleted file mode 100644 index 4a3fe1d..0000000 --- a/lib/src/basic_sample/basic_sample.dart +++ /dev/null @@ -1,80 +0,0 @@ -import 'package:flutter/material.dart'; -import 'dart:core'; -import 'loopback_sample.dart'; -import 'get_user_media_sample.dart'; -import 'data_channel_sample.dart'; -import '../route_item.dart'; - -typedef void RouteCallback(BuildContext context); - -final List items = [ - RouteItem( - title: 'GetUserMedia Test', - push: (BuildContext context) { - Navigator.push( - context, - new MaterialPageRoute( - builder: (BuildContext context) => new GetUserMediaSample())); - }), - RouteItem( - title: 'LoopBack Sample', - push: (BuildContext context) { - Navigator.push( - context, - new MaterialPageRoute( - builder: (BuildContext context) => new LoopBackSample())); - }), - RouteItem( - title: 'DataChannel Test', - push: (BuildContext context) { - Navigator.push( - context, - new MaterialPageRoute( - builder: (BuildContext context) => new DataChannelSample())); - }), -]; - -class BasicSample extends StatefulWidget { - static String tag = 'basic_sample'; - @override - _BasicSampleState createState() => new _BasicSampleState(); -} - -class _BasicSampleState extends State { - GlobalKey _formKey = new GlobalKey(); - @override - initState() { - super.initState(); - } - - @override - deactivate() { - super.deactivate(); - } - - _buildRow(context, item) { - return ListBody(children: [ - ListTile( - title: Text(item.title), - onTap: () => item.push(context), - trailing: Icon(Icons.arrow_right), - ), - Divider() - ]); - } - - @override - Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('Basic API Tests'), - ), - body: new ListView.builder( - shrinkWrap: true, - padding: const EdgeInsets.all(0.0), - itemCount: items.length, - itemBuilder: (context, i) { - return _buildRow(context, items[i]); - })); - } -} diff --git a/lib/src/basic_sample/data_channel_sample.dart b/lib/src/basic_sample/data_channel_sample.dart deleted file mode 100644 index 69eaddf..0000000 --- a/lib/src/basic_sample/data_channel_sample.dart +++ /dev/null @@ -1,159 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_webrtc/webrtc.dart'; -import 'dart:core'; - -class DataChannelSample extends StatefulWidget { - - static String tag = 'data_channel_sample'; - - @override - _DataChannelSampleState createState() => new _DataChannelSampleState(); -} - -class _DataChannelSampleState extends State { - RTCPeerConnection _peerConnection; - bool _inCalling = false; - - RTCDataChannelInit _dataChannelDict = null; - RTCDataChannel _dataChannel; - - String _sdp; - - @override - initState() { - super.initState(); - } - - _onSignalingState(RTCSignalingState state) { - print(state); - } - - _onIceGatheringState(RTCIceGatheringState state) { - print(state); - } - - _onIceConnectionState(RTCIceConnectionState state) { - print(state); - } - - _onCandidate(RTCIceCandidate candidate) { - print('onCandidate: ' + candidate.candidate); - _peerConnection.addCandidate(candidate); - setState(() { - _sdp += '\n'; - _sdp += candidate.candidate; - }); - } - - _onRenegotiationNeeded() { - print('RenegotiationNeeded'); - } - - _onDataChannel(RTCDataChannel dataChannel) { - } - - // Platform messages are asynchronous, so we initialize in an async method. - _makeCall() async { - - Map configuration = { - "iceServers": [ - {"url": "stun:stun.l.google.com:19302"}, - ] - }; - - final Map offer_sdp_constraints = { - "mandatory": { - "OfferToReceiveAudio": false, - "OfferToReceiveVideo": false, - }, - "optional": [], - }; - - final Map loopback_constraints = { - "mandatory": {}, - "optional": [ - {"DtlsSrtpKeyAgreement": true }, - ], - }; - - if (_peerConnection != null) return; - - try { - - _peerConnection = - await createPeerConnection(configuration, loopback_constraints); - - _peerConnection.onSignalingState = _onSignalingState; - _peerConnection.onIceGatheringState = _onIceGatheringState; - _peerConnection.onIceConnectionState = _onIceConnectionState; - _peerConnection.onIceCandidate = _onCandidate; - _peerConnection.onRenegotiationNeeded = _onRenegotiationNeeded; - - _dataChannelDict = new RTCDataChannelInit(); - _dataChannelDict.id = 1; - _dataChannelDict.ordered = true; - _dataChannelDict.maxRetransmitTime = -1; - _dataChannelDict.maxRetransmits = -1; - _dataChannelDict.protocol = "sctp"; - _dataChannelDict.negotiated = false; - - _dataChannel = await _peerConnection.createDataChannel('dataChannel', _dataChannelDict); - _peerConnection.onDataChannel = _onDataChannel; - - RTCSessionDescription description = - await _peerConnection.createOffer(offer_sdp_constraints); - print(description.sdp); - _peerConnection.setLocalDescription(description); - - _sdp = description.sdp; - //change for loopback. - //description.type = 'answer'; - //_peerConnection.setRemoteDescription(description); - } catch (e) { - print(e.toString()); - } - if (!mounted) return; - - setState(() { - _inCalling = true; - }); - } - - _hangUp() async { - try { - await _dataChannel.close(); - await _peerConnection.close(); - _peerConnection = null; - } catch (e) { - print(e.toString()); - } - setState(() { - _inCalling = false; - }); - } - - @override - Widget build(BuildContext context) { - return - new Scaffold( - appBar: new AppBar( - title: new Text('Data Channel Test'), - ), - body: new OrientationBuilder( - builder: (context, orientation) { - return new Center( - child: new Container( - child: _inCalling? Text(_sdp) : Text('data channel test'), - ), - ); - }, - ), - floatingActionButton: new FloatingActionButton( - onPressed: _inCalling ? _hangUp : _makeCall, - tooltip: _inCalling ? 'Hangup' : 'Call', - child: new Icon(_inCalling ? Icons.call_end : Icons.phone), - ), - ); - - } -} diff --git a/lib/src/basic_sample/get_user_media_sample.dart b/lib/src/basic_sample/get_user_media_sample.dart deleted file mode 100644 index 156c9b9..0000000 --- a/lib/src/basic_sample/get_user_media_sample.dart +++ /dev/null @@ -1,107 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_webrtc/webrtc.dart'; -import 'dart:core'; - -/** - * getUserMedia sample - */ -class GetUserMediaSample extends StatefulWidget { - static String tag = 'get_usermedia_sample'; - - @override - _GetUserMediaSampleState createState() => new _GetUserMediaSampleState(); -} - -class _GetUserMediaSampleState extends State { - MediaStream _localStream; - final _localRenderer = new RTCVideoRenderer(); - bool _inCalling = false; - - @override - initState() { - super.initState(); - initRenderers(); - } - - @override - deactivate() { - super.deactivate(); - if (_inCalling) { - _hangUp(); - } - _localRenderer.dispose(); - } - - initRenderers() async { - await _localRenderer.initialize(); - } - - // Platform messages are asynchronous, so we initialize in an async method. - _makeCall() async { - final Map mediaConstraints = { - "audio": true, - "video": { - "mandatory": { - "minWidth":'640', // Provide your own width, height and frame rate here - "minHeight": '480', - "minFrameRate": '30', - }, - "facingMode": "user", - "optional": [], - } - }; - - try { - navigator.getUserMedia(mediaConstraints).then((stream){ - _localStream = stream; - _localRenderer.srcObject = _localStream; - }); - } catch (e) { - print(e.toString()); - } - if (!mounted) return; - - setState(() { - _inCalling = true; - }); - } - - _hangUp() async { - try { - await _localStream.dispose(); - _localRenderer.srcObject = null; - } catch (e) { - print(e.toString()); - } - setState(() { - _inCalling = false; - }); - } - - @override - Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('GetUserMedia API Test'), - ), - body: new OrientationBuilder( - builder: (context, orientation) { - return new Center( - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - width: MediaQuery.of(context).size.width, - height: MediaQuery.of(context).size.height, - child: RTCVideoView(_localRenderer), - decoration: new BoxDecoration(color: Colors.black54), - ), - ); - }, - ), - floatingActionButton: new FloatingActionButton( - onPressed: _inCalling ? _hangUp : _makeCall, - tooltip: _inCalling ? 'Hangup' : 'Call', - child: new Icon(_inCalling ? Icons.call_end : Icons.phone), - ), - ); - } -} diff --git a/lib/src/basic_sample/loopback_sample.dart b/lib/src/basic_sample/loopback_sample.dart deleted file mode 100644 index 32702bd..0000000 --- a/lib/src/basic_sample/loopback_sample.dart +++ /dev/null @@ -1,233 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_webrtc/webrtc.dart'; -import 'dart:core'; -import 'dart:async'; - - -class LoopBackSample extends StatefulWidget { - - static String tag = 'loopback_sample'; - - @override - _MyAppState createState() => new _MyAppState(); -} - -class _MyAppState extends State { - MediaStream _localStream; - RTCPeerConnection _peerConnection; - final _localRenderer = new RTCVideoRenderer(); - final _remoteRenderer = new RTCVideoRenderer(); - bool _inCalling = false; - Timer _timer; - - @override - initState() { - super.initState(); - initRenderers(); - } - - @override - deactivate() { - super.deactivate(); - if (_inCalling) { - _hangUp(); - } - _localRenderer.dispose(); - _remoteRenderer.dispose(); - } - - initRenderers() async { - await _localRenderer.initialize(); - await _remoteRenderer.initialize(); - } - - void handleStatsReport(Timer timer) async { - if (_peerConnection != null) { - List reports = await _peerConnection.getStats(); - reports.forEach((report) { - print("report => { "); - print(" id: " + report.id + ","); - print(" type: " + report.type + ","); - print(" timestamp: ${report.timestamp},"); - print(" values => {"); - report.values.forEach((key, value) { - print(" " + key + " : " + value + ", "); - }); - print(" }"); - print("}"); - }); - } - } - - _onSignalingState(RTCSignalingState state) { - print(state); - } - - _onIceGatheringState(RTCIceGatheringState state) { - print(state); - } - - _onIceConnectionState(RTCIceConnectionState state) { - print(state); - } - - _onAddStream(MediaStream stream) { - print('addStream: ' + stream.id); - _remoteRenderer.srcObject = stream; - } - - _onRemoveStream(MediaStream stream) { - _remoteRenderer.srcObject = null; - } - - _onCandidate(RTCIceCandidate candidate) { - print('onCandidate: ' + candidate.candidate); - _peerConnection.addCandidate(candidate); - } - - _onRenegotiationNeeded() { - print('RenegotiationNeeded'); - } - - // Platform messages are asynchronous, so we initialize in an async method. - _makeCall() async { - final Map mediaConstraints = { - "audio": true, - "video": { - "mandatory": { - "minWidth": - '640', // Provide your own width, height and frame rate here - "minHeight": '480', - "minFrameRate": '30', - }, - "facingMode": "user", - "optional": [], - } - }; - - Map configuration = { - "iceServers": [ - {"url": "stun:stun.l.google.com:19302"}, - ] - }; - - final Map offer_sdp_constraints = { - "mandatory": { - "OfferToReceiveAudio": true, - "OfferToReceiveVideo": true, - }, - "optional": [], - }; - - final Map loopback_constraints = { - "mandatory": {}, - "optional": [ - {"DtlsSrtpKeyAgreement": false}, - ], - }; - - if (_peerConnection != null) return; - - try { - _localStream = await navigator.getUserMedia(mediaConstraints); - _localRenderer.srcObject = _localStream; - - _peerConnection = - await createPeerConnection(configuration, loopback_constraints); - - _peerConnection.onSignalingState = _onSignalingState; - _peerConnection.onIceGatheringState = _onIceGatheringState; - _peerConnection.onIceConnectionState = _onIceConnectionState; - _peerConnection.onAddStream = _onAddStream; - _peerConnection.onRemoveStream = _onRemoveStream; - _peerConnection.onIceCandidate = _onCandidate; - _peerConnection.onRenegotiationNeeded = _onRenegotiationNeeded; - - _peerConnection.addStream(_localStream); - RTCSessionDescription description = - await _peerConnection.createOffer(offer_sdp_constraints); - print(description.sdp); - _peerConnection.setLocalDescription(description); - //change for loopback. - description.type = 'answer'; - _peerConnection.setRemoteDescription(description); - } catch (e) { - print(e.toString()); - } - if (!mounted) return; - - _timer = new Timer.periodic(Duration(seconds: 1), handleStatsReport); - - setState(() { - _inCalling = true; - }); - } - - _hangUp() async { - try { - await _localStream.dispose(); - await _peerConnection.close(); - _peerConnection = null; - _localRenderer.srcObject = null; - _remoteRenderer.srcObject = null; - } catch (e) { - print(e.toString()); - } - setState(() { - _inCalling = false; - }); - } - - @override - Widget build(BuildContext context) { - return - new Scaffold( - appBar: new AppBar( - title: new Text('LoopBack example'), - ), - body: new OrientationBuilder( - builder: (context, orientation) { - return new Center( - child: new Container( - decoration: new BoxDecoration(color: Colors.white), - child: new Stack( - children: [ - new Align( - alignment: orientation == Orientation.portrait - ? const FractionalOffset(0.5, 0.1) - : const FractionalOffset(0.0, 0.5), - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - width: 320.0, - height: 240.0, - child: new RTCVideoView(_localRenderer), - decoration: new BoxDecoration(color: Colors.black54), - ), - ), - new Align( - alignment: orientation == Orientation.portrait - ? const FractionalOffset(0.5, 0.9) - : const FractionalOffset(1.0, 0.5), - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - width: 320.0, - height: 240.0, - child: new RTCVideoView(_remoteRenderer), - decoration: new BoxDecoration(color: Colors.black54), - ), - ), - ], - ), - ), - ); - }, - ), - floatingActionButton: new FloatingActionButton( - onPressed: _inCalling ? _hangUp : _makeCall, - tooltip: _inCalling ? 'Hangup' : 'Call', - child: new Icon(_inCalling ? Icons.call_end : Icons.phone), - ), - ); - - } -} diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 273807b..fac35f2 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -1,35 +1,37 @@ import 'package:flutter/material.dart'; import 'dart:core'; +import '../widgets/screen_select_dialog.dart'; import 'signaling.dart'; -import 'package:flutter_webrtc/webrtc.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; class CallSample extends StatefulWidget { static String tag = 'call_sample'; - - final String ip; - - CallSample({Key key, @required this.ip}) : super(key: key); + final String host; + CallSample({required this.host}); @override - _CallSampleState createState() => new _CallSampleState(serverIP: ip); + _CallSampleState createState() => _CallSampleState(); } class _CallSampleState extends State { - Signaling _signaling; - List _peers; - var _selfId; - RTCVideoRenderer _localRenderer = new RTCVideoRenderer(); - RTCVideoRenderer _remoteRenderer = new RTCVideoRenderer(); + Signaling? _signaling; + List _peers = []; + String? _selfId; + RTCVideoRenderer _localRenderer = RTCVideoRenderer(); + RTCVideoRenderer _remoteRenderer = RTCVideoRenderer(); bool _inCalling = false; - final String serverIP; + Session? _session; + DesktopCapturerSource? selected_source_; + bool _waitAccept = false; - _CallSampleState({Key key, @required this.serverIP}); + // ignore: unused_element + _CallSampleState(); @override initState() { super.initState(); initRenderers(); - _connect(); + _connect(context); } initRenderers() async { @@ -40,103 +42,236 @@ class _CallSampleState extends State { @override deactivate() { super.deactivate(); - if (_signaling != null) _signaling.close(); + _signaling?.close(); _localRenderer.dispose(); _remoteRenderer.dispose(); } - void _connect() async { - if (_signaling == null) { - _signaling = new Signaling(serverIP)..connect(); + void _connect(BuildContext context) async { + _signaling ??= Signaling(widget.host, context)..connect(); + _signaling?.onSignalingStateChange = (SignalingState state) { + switch (state) { + case SignalingState.ConnectionClosed: + case SignalingState.ConnectionError: + case SignalingState.ConnectionOpen: + break; + } + }; - _signaling.onStateChange = (SignalingState state) { - switch (state) { - case SignalingState.CallStateNew: - this.setState(() { + _signaling?.onCallStateChange = (Session session, CallState state) async { + switch (state) { + case CallState.CallStateNew: + setState(() { + _session = session; + }); + break; + case CallState.CallStateRinging: + bool? accept = await _showAcceptDialog(); + if (accept!) { + _accept(); + setState(() { _inCalling = true; }); - break; - case SignalingState.CallStateBye: - this.setState(() { - _localRenderer.srcObject = null; - _remoteRenderer.srcObject = null; - _inCalling = false; - }); - break; - case SignalingState.CallStateInvite: - case SignalingState.CallStateConnected: - case SignalingState.CallStateRinging: - case SignalingState.ConnectionClosed: - case SignalingState.ConnectionError: - case SignalingState.ConnectionOpen: - break; - } - }; + } else { + _reject(); + } + break; + case CallState.CallStateBye: + if (_waitAccept) { + print('peer reject'); + _waitAccept = false; + Navigator.of(context).pop(false); + } + setState(() { + _localRenderer.srcObject = null; + _remoteRenderer.srcObject = null; + _inCalling = false; + _session = null; + }); + break; + case CallState.CallStateInvite: + _waitAccept = true; + _showInvateDialog(); + break; + case CallState.CallStateConnected: + if (_waitAccept) { + _waitAccept = false; + Navigator.of(context).pop(false); + } + setState(() { + _inCalling = true; + }); - _signaling.onPeersUpdate = ((event) { - this.setState(() { - _selfId = event['self']; - _peers = event['peers']; - }); - }); + break; + case CallState.CallStateRinging: + } + }; - _signaling.onLocalStream = ((stream) { - _localRenderer.srcObject = stream; + _signaling?.onPeersUpdate = ((event) { + setState(() { + _selfId = event['self']; + _peers = event['peers']; }); + }); - _signaling.onAddRemoteStream = ((stream) { - _remoteRenderer.srcObject = stream; - }); + _signaling?.onLocalStream = ((stream) { + _localRenderer.srcObject = stream; + setState(() {}); + }); - _signaling.onRemoveRemoteStream = ((stream) { - _remoteRenderer.srcObject = null; - }); - } + _signaling?.onAddRemoteStream = ((_, stream) { + _remoteRenderer.srcObject = stream; + setState(() {}); + }); + + _signaling?.onRemoveRemoteStream = ((_, stream) { + _remoteRenderer.srcObject = null; + }); + } + + Future _showAcceptDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("accept?"), + actions: [ + MaterialButton( + child: Text( + 'Reject', + style: TextStyle(color: Colors.red), + ), + onPressed: () => Navigator.of(context).pop(false), + ), + MaterialButton( + child: Text( + 'Accept', + style: TextStyle(color: Colors.green), + ), + onPressed: () => Navigator.of(context).pop(true), + ), + ], + ); + }, + ); + } + + Future _showInvateDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("waiting"), + actions: [ + TextButton( + child: Text("cancel"), + onPressed: () { + Navigator.of(context).pop(false); + _hangUp(); + }, + ), + ], + ); + }, + ); } - _invitePeer(context, peerId, use_screen) async { + _invitePeer(BuildContext context, String peerId, bool useScreen) async { if (_signaling != null && peerId != _selfId) { - _signaling.invite(peerId, 'video', use_screen); + _signaling?.invite(peerId, 'video', useScreen); + } + } + + _accept() { + if (_session != null) { + _signaling?.accept(_session!.sid, 'video'); + } + } + + _reject() { + if (_session != null) { + _signaling?.reject(_session!.sid); } } _hangUp() { - if (_signaling != null) { - _signaling.bye(); + if (_session != null) { + _signaling?.bye(_session!.sid); } } _switchCamera() { - _signaling.switchCamera(); + _signaling?.switchCamera(); + } + + Future selectScreenSourceDialog(BuildContext context) async { + MediaStream? screenStream; + if (WebRTC.platformIsDesktop) { + final source = await showDialog( + context: context, + builder: (context) => ScreenSelectDialog(), + ); + if (source != null) { + try { + var stream = + await navigator.mediaDevices.getDisplayMedia({ + 'video': { + 'deviceId': {'exact': source.id}, + 'mandatory': {'frameRate': 30.0} + } + }); + stream.getVideoTracks()[0].onEnded = () { + print( + 'By adding a listener on onEnded you can: 1) catch stop video sharing on Web'); + }; + screenStream = stream; + } catch (e) { + print(e); + } + } + } else if (WebRTC.platformIsWeb) { + screenStream = + await navigator.mediaDevices.getDisplayMedia({ + 'audio': false, + 'video': true, + }); + } + if (screenStream != null) _signaling?.switchToScreenSharing(screenStream); } - _muteMic() {} + _muteMic() { + _signaling?.muteMic(); + } _buildRow(context, peer) { var self = (peer['id'] == _selfId); return ListBody(children: [ ListTile( title: Text(self - ? peer['name'] + '[Your self]' - : peer['name'] + '[' + peer['user_agent'] + ']'), + ? peer['name'] + ', ID: ${peer['id']} ' + ' [Your self]' + : peer['name'] + ', ID: ${peer['id']} '), onTap: null, - trailing: new SizedBox( + trailing: SizedBox( width: 100.0, - child: new Row( + child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - icon: const Icon(Icons.videocam), + icon: Icon(self ? Icons.close : Icons.videocam, + color: self ? Colors.grey : Colors.black), onPressed: () => _invitePeer(context, peer['id'], false), tooltip: 'Video calling', ), IconButton( - icon: const Icon(Icons.screen_share), + icon: Icon(self ? Icons.close : Icons.screen_share, + color: self ? Colors.grey : Colors.black), onPressed: () => _invitePeer(context, peer['id'], true), tooltip: 'Screen sharing', ) ])), - subtitle: Text('id: ' + peer['id']), + subtitle: Text('[' + peer['user_agent'] + ']'), ), Divider() ]); @@ -144,9 +279,10 @@ class _CallSampleState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('P2P Call Sample'), + return Scaffold( + appBar: AppBar( + title: Text('P2P Call Sample' + + (_selfId != null ? ' [Your ID ($_selfId)] ' : '')), actions: [ IconButton( icon: const Icon(Icons.settings), @@ -157,58 +293,65 @@ class _CallSampleState extends State { ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: _inCalling - ? new SizedBox( - width: 200.0, - child: new Row( + ? SizedBox( + width: 240.0, + child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FloatingActionButton( child: const Icon(Icons.switch_camera), + tooltip: 'Camera', onPressed: _switchCamera, ), + FloatingActionButton( + child: const Icon(Icons.desktop_mac), + tooltip: 'Screen Sharing', + onPressed: () => selectScreenSourceDialog(context), + ), FloatingActionButton( onPressed: _hangUp, tooltip: 'Hangup', - child: new Icon(Icons.call_end), + child: Icon(Icons.call_end), backgroundColor: Colors.pink, ), FloatingActionButton( child: const Icon(Icons.mic_off), + tooltip: 'Mute Mic', onPressed: _muteMic, ) ])) : null, body: _inCalling ? OrientationBuilder(builder: (context, orientation) { - return new Container( - child: new Stack(children: [ - new Positioned( + return Container( + child: Stack(children: [ + Positioned( left: 0.0, right: 0.0, top: 0.0, bottom: 0.0, - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), + child: Container( + margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, - child: new RTCVideoView(_remoteRenderer), - decoration: new BoxDecoration(color: Colors.black54), + child: RTCVideoView(_remoteRenderer), + decoration: BoxDecoration(color: Colors.black54), )), - new Positioned( + Positioned( left: 20.0, top: 20.0, - child: new Container( + child: Container( width: orientation == Orientation.portrait ? 90.0 : 120.0, height: orientation == Orientation.portrait ? 120.0 : 90.0, - child: new RTCVideoView(_localRenderer), - decoration: new BoxDecoration(color: Colors.black54), + child: RTCVideoView(_localRenderer, mirror: true), + decoration: BoxDecoration(color: Colors.black54), ), ), ]), ); }) - : new ListView.builder( + : ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: (_peers != null ? _peers.length : 0), diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index 0a354c2..e9bb883 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -1,140 +1,219 @@ import 'package:flutter/material.dart'; -import 'dart:io'; import 'dart:core'; import 'dart:async'; import 'dart:typed_data'; import 'signaling.dart'; -import 'package:flutter_webrtc/webrtc.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; class DataChannelSample extends StatefulWidget { static String tag = 'call_sample'; - - final String ip; - - DataChannelSample({Key key, @required this.ip}) : super(key: key); + final String host; + DataChannelSample({required this.host}); @override - _DataChannelSampleState createState() => new _DataChannelSampleState(serverIP: ip); + _DataChannelSampleState createState() => _DataChannelSampleState(); } class _DataChannelSampleState extends State { - Signaling _signaling; - List _peers; - var _selfId; + Signaling? _signaling; + List _peers = []; + String? _selfId; bool _inCalling = false; - final String serverIP; - RTCDataChannel _dataChannel; - Timer _timer; + RTCDataChannel? _dataChannel; + Session? _session; + Timer? _timer; var _text = ''; - _DataChannelSampleState({Key key, @required this.serverIP}); + // ignore: unused_element + _DataChannelSampleState(); + bool _waitAccept = false; @override initState() { super.initState(); - _connect(); + _connect(context); } @override deactivate() { super.deactivate(); - if (_signaling != null) _signaling.close(); - if(_timer != null){ - _timer.cancel(); - } + _signaling?.close(); + _timer?.cancel(); + } + + Future _showAcceptDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("accept?"), + actions: [ + MaterialButton( + child: Text( + 'Reject', + style: TextStyle(color: Colors.red), + ), + onPressed: () => Navigator.of(context).pop(false), + ), + MaterialButton( + child: Text( + 'Accept', + style: TextStyle(color: Colors.green), + ), + onPressed: () => Navigator.of(context).pop(true), + ), + ], + ); + }, + ); } - void _connect() async { - if (_signaling == null) { - _signaling = new Signaling(serverIP) - ..connect(); + Future _showInvateDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("waiting"), + actions: [ + TextButton( + child: Text("cancel"), + onPressed: () { + Navigator.of(context).pop(false); + _hangUp(); + }, + ), + ], + ); + }, + ); + } + + void _connect(BuildContext context) async { + _signaling ??= Signaling(widget.host, context)..connect(); + + _signaling?.onDataChannelMessage = (_, dc, RTCDataChannelMessage data) { + setState(() { + if (data.isBinary) { + print('Got binary [' + data.binary.toString() + ']'); + } else { + _text = data.text; + } + }); + }; + + _signaling?.onDataChannel = (_, channel) { + _dataChannel = channel; + }; - _signaling.onDataChannelMessage = (dc, RTCDataChannelMessage data){ - setState(() { - if(data.isBinary) { - print('Got binary [' + data.binary.toString() + ']'); + _signaling?.onSignalingStateChange = (SignalingState state) { + switch (state) { + case SignalingState.ConnectionClosed: + case SignalingState.ConnectionError: + case SignalingState.ConnectionOpen: + break; + } + }; + + _signaling?.onCallStateChange = (Session session, CallState state) async { + switch (state) { + case CallState.CallStateNew: + setState(() { + _session = session; + }); + _timer = Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); + break; + case CallState.CallStateBye: + if (_waitAccept) { + print('peer reject'); + _waitAccept = false; + Navigator.of(context).pop(false); } - else{ - _text = data.text; + setState(() { + _inCalling = false; + }); + _timer?.cancel(); + _dataChannel = null; + _inCalling = false; + _session = null; + _text = ''; + break; + case CallState.CallStateInvite: + _waitAccept = true; + _showInvateDialog(); + break; + case CallState.CallStateConnected: + if (_waitAccept) { + _waitAccept = false; + Navigator.of(context).pop(false); } - }); - }; - - _signaling.onDataChannel = (channel){ - _dataChannel = channel; - }; - - _signaling.onStateChange = (SignalingState state) { - switch (state) { - case SignalingState.CallStateNew: - { - this.setState(() { - _inCalling = true; - }); - _timer = new Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); - break; - } - case SignalingState.CallStateBye: - { - this.setState(() { - _inCalling = false; - }); - if(_timer != null){ - _timer.cancel(); - _timer = null; - } - _dataChannel = null; - _text = ''; - break; - } - case SignalingState.CallStateInvite: - case SignalingState.CallStateConnected: - case SignalingState.CallStateRinging: - case SignalingState.ConnectionClosed: - case SignalingState.ConnectionError: - case SignalingState.ConnectionOpen: - break; - } - }; + setState(() { + _inCalling = true; + }); + break; + case CallState.CallStateRinging: + bool? accept = await _showAcceptDialog(); + if (accept!) { + _accept(); + setState(() { + _inCalling = true; + }); + } else { + _reject(); + } + + break; + } + }; - _signaling.onPeersUpdate = ((event) { - this.setState(() { - _selfId = event['self']; - _peers = event['peers']; - }); + _signaling?.onPeersUpdate = ((event) { + setState(() { + _selfId = event['self']; + _peers = event['peers']; }); - } + }); } _handleDataChannelTest(Timer timer) async { - if(_dataChannel != null){ - String text = 'Say hello ' + timer.tick.toString() + ' times, from [' + _selfId + ']'; - _dataChannel.send(RTCDataChannelMessage.fromBinary(Uint8List(timer.tick + 1))); - _dataChannel.send(RTCDataChannelMessage(text)); - } + String text = + 'Say hello ' + timer.tick.toString() + ' times, from [$_selfId]'; + _dataChannel + ?.send(RTCDataChannelMessage.fromBinary(Uint8List(timer.tick + 1))); + _dataChannel?.send(RTCDataChannelMessage(text)); } _invitePeer(context, peerId) async { - if (_signaling != null && peerId != _selfId) { - _signaling.invite(peerId, 'data', false); + if (peerId != _selfId) { + _signaling?.invite(peerId, 'data', false); } } - _hangUp() { - if (_signaling != null) { - _signaling.bye(); + _accept() { + if (_session != null) { + _signaling?.accept(_session!.sid, 'data'); } } + _reject() { + if (_session != null) { + _signaling?.reject(_session!.sid); + } + } + + _hangUp() { + _signaling?.bye(_session!.sid); + } + _buildRow(context, peer) { var self = (peer['id'] == _selfId); return ListBody(children: [ ListTile( title: Text(self - ? peer['name'] + '[Your self]' - : peer['name'] + '[' + peer['user_agent'] + ']'), + ? peer['name'] + ', ID: ${peer['id']} ' + ' [Your self]' + : peer['name'] + ', ID: ${peer['id']} '), onTap: () => _invitePeer(context, peer['id']), trailing: Icon(Icons.sms), - subtitle: Text('id: ' + peer['id']), + subtitle: Text('[' + peer['user_agent'] + ']'), ), Divider() ]); @@ -142,9 +221,10 @@ class _DataChannelSampleState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('Data Channel Sample'), + return Scaffold( + appBar: AppBar( + title: Text('Data Channel Sample' + + (_selfId != null ? ' [Your ID ($_selfId)] ' : '')), actions: [ IconButton( icon: const Icon(Icons.settings), @@ -157,14 +237,16 @@ class _DataChannelSampleState extends State { ? FloatingActionButton( onPressed: _hangUp, tooltip: 'Hangup', - child: new Icon(Icons.call_end), + child: Icon(Icons.call_end), ) : null, - body: _inCalling? new Center( - child: new Container( - child: Text('Recevied => ' + _text), + body: _inCalling + ? Center( + child: Container( + child: Text('Recevied => ' + _text), ), - ) : new ListView.builder( + ) + : ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: (_peers != null ? _peers.length : 0), diff --git a/lib/src/call_sample/random_string.dart b/lib/src/call_sample/random_string.dart index 2e45184..73c2f08 100644 --- a/lib/src/call_sample/random_string.dart +++ b/lib/src/call_sample/random_string.dart @@ -32,8 +32,8 @@ const UPPER_ALPHA_END = 90; /// Generates a random integer where [from] <= [to]. int randomBetween(int from, int to) { - if (from > to) throw new Exception('$from cannot be > $to'); - var rand = new Random(); + if (from > to) throw Exception('$from cannot be > $to'); + var rand = Random(); return ((to - from) * rand.nextDouble()).toInt() + from; } @@ -41,8 +41,8 @@ int randomBetween(int from, int to) { /// between ascii [from] to [to]. /// Defaults to characters of ascii '!' to '~'. String randomString(int length, {int from: ASCII_START, int to: ASCII_END}) { - return new String.fromCharCodes( - new List.generate(length, (index) => randomBetween(from, to))); + return String.fromCharCodes( + List.generate(length, (index) => randomBetween(from, to))); } /// Generates a random string of [length] with only numeric characters. @@ -71,7 +71,7 @@ String randomAlphaNumeric(int length) { /// Merge [a] with [b] and scramble characters. String randomMerge(String a, String b) { - var mergedCodeUnits = new List.from("$a$b".codeUnits); + var mergedCodeUnits = List.from("$a$b".codeUnits); mergedCodeUnits.shuffle(); - return new String.fromCharCodes(mergedCodeUnits); + return String.fromCharCodes(mergedCodeUnits); }*/ diff --git a/lib/src/call_sample/settings.dart b/lib/src/call_sample/settings.dart index a964836..fe9c953 100644 --- a/lib/src/call_sample/settings.dart +++ b/lib/src/call_sample/settings.dart @@ -5,7 +5,7 @@ class CallSettings extends StatefulWidget { static String tag = 'call_settings'; @override - _CallSettingsState createState() => new _CallSettingsState(); + _CallSettingsState createState() => _CallSettingsState(); } class _CallSettingsState extends State { @@ -17,20 +17,17 @@ class _CallSettingsState extends State { @override deactivate() { super.deactivate(); - } @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('Settings'), + return Scaffold( + appBar: AppBar( + title: Text('Settings'), ), - body: new OrientationBuilder( + body: OrientationBuilder( builder: (context, orientation) { - return new Center( - child: Text("settings") - ); + return Center(child: Text("settings")); }, ), ); diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 11ef011..abbaf6b 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -1,53 +1,73 @@ import 'dart:convert'; import 'dart:async'; -import 'package:flutter_webrtc/webrtc.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; + +import '../utils/screen_select_dialog.dart'; import 'random_string.dart'; import '../utils/device_info.dart' if (dart.library.js) '../utils/device_info_web.dart'; import '../utils/websocket.dart' if (dart.library.js) '../utils/websocket_web.dart'; +import '../utils/turn.dart' if (dart.library.js) '../utils/turn_web.dart'; enum SignalingState { + ConnectionOpen, + ConnectionClosed, + ConnectionError, +} + +enum CallState { CallStateNew, CallStateRinging, CallStateInvite, CallStateConnected, CallStateBye, - ConnectionOpen, - ConnectionClosed, - ConnectionError, } -/* - * callbacks for Signaling API. - */ -typedef void SignalingStateCallback(SignalingState state); -typedef void StreamStateCallback(MediaStream stream); -typedef void OtherEventCallback(dynamic event); -typedef void DataChannelMessageCallback( - RTCDataChannel dc, RTCDataChannelMessage data); -typedef void DataChannelCallback(RTCDataChannel dc); +enum VideoSource { + Camera, + Screen, +} + +class Session { + Session({required this.sid, required this.pid}); + String pid; + String sid; + RTCPeerConnection? pc; + RTCDataChannel? dc; + List remoteCandidates = []; +} class Signaling { + Signaling(this._host, this._context); + + JsonEncoder _encoder = JsonEncoder(); + JsonDecoder _decoder = JsonDecoder(); String _selfId = randomNumeric(6); - SimpleWebSocket _socket; - var _sessionId; + SimpleWebSocket? _socket; + BuildContext? _context; var _host; - var _port = 4443; - var _peerConnections = new Map(); - var _dataChannels = new Map(); - var _remoteCandidates = []; - - MediaStream _localStream; - List _remoteStreams; - SignalingStateCallback onStateChange; - StreamStateCallback onLocalStream; - StreamStateCallback onAddRemoteStream; - StreamStateCallback onRemoveRemoteStream; - OtherEventCallback onPeersUpdate; - DataChannelMessageCallback onDataChannelMessage; - DataChannelCallback onDataChannel; + var _port = 8086; + var _turnCredential; + Map _sessions = {}; + MediaStream? _localStream; + List _remoteStreams = []; + List _senders = []; + VideoSource _videoSource = VideoSource.Camera; + + Function(SignalingState state)? onSignalingStateChange; + Function(Session session, CallState state)? onCallStateChange; + Function(MediaStream stream)? onLocalStream; + Function(Session session, MediaStream stream)? onAddRemoteStream; + Function(Session session, MediaStream stream)? onRemoveRemoteStream; + Function(dynamic event)? onPeersUpdate; + Function(Session session, RTCDataChannel dc, RTCDataChannelMessage data)? + onDataChannelMessage; + Function(Session session, RTCDataChannel dc)? onDataChannel; + + String get sdpSemantics => 'unified-plan'; Map _iceServers = { 'iceServers': [ @@ -59,7 +79,7 @@ class Signaling { 'username': 'change_to_real_user', 'credential': 'change_to_real_secret' }, - */ + */ ] }; @@ -67,18 +87,10 @@ class Signaling { 'mandatory': {}, 'optional': [ {'DtlsSrtpKeyAgreement': true}, - ], - }; - - final Map _constraints = { - 'mandatory': { - 'OfferToReceiveAudio': true, - 'OfferToReceiveVideo': true, - }, - 'optional': [], + ] }; - final Map _dc_constraints = { + final Map _dcConstraints = { 'mandatory': { 'OfferToReceiveAudio': false, 'OfferToReceiveVideo': false, @@ -86,47 +98,87 @@ class Signaling { 'optional': [], }; - Signaling(this._host); + close() async { + await _cleanSessions(); + _socket?.close(); + } - close() { + void switchCamera() { if (_localStream != null) { - _localStream.dispose(); - _localStream = null; + if (_videoSource != VideoSource.Camera) { + _senders.forEach((sender) { + if (sender.track!.kind == 'video') { + sender.replaceTrack(_localStream!.getVideoTracks()[0]); + } + }); + _videoSource = VideoSource.Camera; + onLocalStream?.call(_localStream!); + } else { + Helper.switchCamera(_localStream!.getVideoTracks()[0]); + } } + } - _peerConnections.forEach((key, pc) { - pc.close(); - }); - if (_socket != null) _socket.close(); + void switchToScreenSharing(MediaStream stream) { + if (_localStream != null && _videoSource != VideoSource.Screen) { + _senders.forEach((sender) { + if (sender.track!.kind == 'video') { + sender.replaceTrack(stream.getVideoTracks()[0]); + } + }); + onLocalStream?.call(stream); + _videoSource = VideoSource.Screen; + } } - void switchCamera() { + void muteMic() { if (_localStream != null) { - _localStream.getVideoTracks()[0].switchCamera(); + bool enabled = _localStream!.getAudioTracks()[0].enabled; + _localStream!.getAudioTracks()[0].enabled = !enabled; } } - void invite(String peer_id, String media, use_screen) { - this._sessionId = this._selfId + '-' + peer_id; - - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateNew); + void invite(String peerId, String media, bool useScreen) async { + var sessionId = _selfId + '-' + peerId; + Session session = await _createSession(null, + peerId: peerId, + sessionId: sessionId, + media: media, + screenSharing: useScreen); + _sessions[sessionId] = session; + if (media == 'data') { + _createDataChannel(session); } - - _createPeerConnection(peer_id, media, use_screen).then((pc) { - _peerConnections[peer_id] = pc; - if (media == 'data') { - _createDataChannel(peer_id, pc); - } - _createOffer(peer_id, pc, media); - }); + _createOffer(session, media); + onCallStateChange?.call(session, CallState.CallStateNew); + onCallStateChange?.call(session, CallState.CallStateInvite); } - void bye() { + void bye(String sessionId) { _send('bye', { - 'session_id': this._sessionId, - 'from': this._selfId, + 'session_id': sessionId, + 'from': _selfId, }); + var sess = _sessions[sessionId]; + if (sess != null) { + _closeSession(sess); + } + } + + void accept(String sessionId, String media) { + var session = _sessions[sessionId]; + if (session == null) { + return; + } + _createAnswer(session, media); + } + + void reject(String sessionId) { + var session = _sessions[sessionId]; + if (session == null) { + return; + } + bye(session.sid); } void onMessage(message) async { @@ -137,114 +189,86 @@ class Signaling { case 'peers': { List peers = data; - if (this.onPeersUpdate != null) { - Map event = new Map(); + if (onPeersUpdate != null) { + Map event = Map(); event['self'] = _selfId; event['peers'] = peers; - this.onPeersUpdate(event); + onPeersUpdate?.call(event); } } break; case 'offer': { - var id = data['from']; + var peerId = data['from']; var description = data['description']; var media = data['media']; var sessionId = data['session_id']; - this._sessionId = sessionId; - - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateNew); - } - - var pc = await _createPeerConnection(id, media, false); - _peerConnections[id] = pc; - await pc.setRemoteDescription(new RTCSessionDescription( - description['sdp'], description['type'])); - await _createAnswer(id, pc, media); - if (this._remoteCandidates.length > 0) { - _remoteCandidates.forEach((candidate) async { - await pc.addCandidate(candidate); + var session = _sessions[sessionId]; + var newSession = await _createSession(session, + peerId: peerId, + sessionId: sessionId, + media: media, + screenSharing: false); + _sessions[sessionId] = newSession; + await newSession.pc?.setRemoteDescription( + RTCSessionDescription(description['sdp'], description['type'])); + // await _createAnswer(newSession, media); + + if (newSession.remoteCandidates.length > 0) { + newSession.remoteCandidates.forEach((candidate) async { + await newSession.pc?.addCandidate(candidate); }); - _remoteCandidates.clear(); + newSession.remoteCandidates.clear(); } + onCallStateChange?.call(newSession, CallState.CallStateNew); + onCallStateChange?.call(newSession, CallState.CallStateRinging); } break; case 'answer': { - var id = data['from']; var description = data['description']; - - var pc = _peerConnections[id]; - if (pc != null) { - await pc.setRemoteDescription(new RTCSessionDescription( - description['sdp'], description['type'])); - } + var sessionId = data['session_id']; + var session = _sessions[sessionId]; + session?.pc?.setRemoteDescription( + RTCSessionDescription(description['sdp'], description['type'])); + onCallStateChange?.call(session!, CallState.CallStateConnected); } break; case 'candidate': { - var id = data['from']; + var peerId = data['from']; var candidateMap = data['candidate']; - var pc = _peerConnections[id]; - RTCIceCandidate candidate = new RTCIceCandidate( - candidateMap['candidate'], - candidateMap['sdpMid'], - candidateMap['sdpMLineIndex']); - if (pc != null) { - await pc.addCandidate(candidate); + var sessionId = data['session_id']; + var session = _sessions[sessionId]; + RTCIceCandidate candidate = RTCIceCandidate(candidateMap['candidate'], + candidateMap['sdpMid'], candidateMap['sdpMLineIndex']); + + if (session != null) { + if (session.pc != null) { + await session.pc?.addCandidate(candidate); + } else { + session.remoteCandidates.add(candidate); + } } else { - _remoteCandidates.add(candidate); + _sessions[sessionId] = Session(pid: peerId, sid: sessionId) + ..remoteCandidates.add(candidate); } } break; case 'leave': { - var id = data; - var pc = _peerConnections.remove(id); - _dataChannels.remove(id); - - if (_localStream != null) { - _localStream.dispose(); - _localStream = null; - } - - if (pc != null) { - pc.close(); - } - this._sessionId = null; - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateBye); - } + var peerId = data as String; + _closeSessionByPeerId(peerId); } break; case 'bye': { - var from = data['from']; - var to = data['to']; var sessionId = data['session_id']; print('bye: ' + sessionId); - - if (_localStream != null) { - _localStream.dispose(); - _localStream = null; - } - - var pc = _peerConnections[to]; - if (pc != null) { - pc.close(); - _peerConnections.remove(to); - } - - var dc = _dataChannels[to]; - if (dc != null) { - dc.close(); - _dataChannels.remove(to); - } - - this._sessionId = null; - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateBye); + var session = _sessions.remove(sessionId); + if (session != null) { + onCallStateChange?.call(session, CallState.CallStateBye); + _closeSession(session); } } break; @@ -258,15 +282,37 @@ class Signaling { } } - void connect() async { - var url = 'wss://$_host:$_port'; + Future connect() async { + var url = 'https://$_host:$_port/ws'; _socket = SimpleWebSocket(url); print('connect to $url'); - _socket.onOpen = () { + if (_turnCredential == null) { + try { + _turnCredential = await getTurnCredential(_host, _port); + /*{ + "username": "1584195784:mbzrxpgjys", + "password": "isyl6FF6nqMTB9/ig5MrMRUXqZg", + "ttl": 86400, + "uris": ["turn:127.0.0.1:19302?transport=udp"] + } + */ + _iceServers = { + 'iceServers': [ + { + 'urls': _turnCredential['uris'][0], + 'username': _turnCredential['username'], + 'credential': _turnCredential['password'] + }, + ] + }; + } catch (e) {} + } + + _socket?.onOpen = () { print('onOpen'); - this?.onStateChange(SignalingState.ConnectionOpen); + onSignalingStateChange?.call(SignalingState.ConnectionOpen); _send('new', { 'name': DeviceInfo.label, 'id': _selfId, @@ -274,109 +320,211 @@ class Signaling { }); }; - _socket.onMessage = (message) { - print('Recivied data: ' + message); - JsonDecoder decoder = new JsonDecoder(); - this.onMessage(decoder.convert(message)); + _socket?.onMessage = (message) { + print('Received data: ' + message); + onMessage(_decoder.convert(message)); }; - _socket.onClose = (int code, String reason) { + _socket?.onClose = (int? code, String? reason) { print('Closed by server [$code => $reason]!'); - if (this.onStateChange != null) { - this.onStateChange(SignalingState.ConnectionClosed); - } + onSignalingStateChange?.call(SignalingState.ConnectionClosed); }; - await _socket.connect(); + await _socket?.connect(); } - Future createStream(media, user_screen) async { + Future createStream(String media, bool userScreen, + {BuildContext? context}) async { final Map mediaConstraints = { - 'audio': true, - 'video': { - 'mandatory': { - 'minWidth': - '640', // Provide your own width, height and frame rate here - 'minHeight': '480', - 'minFrameRate': '30', - }, - 'facingMode': 'user', - 'optional': [], - } + 'audio': userScreen ? false : true, + 'video': userScreen + ? true + : { + 'mandatory': { + 'minWidth': + '640', // Provide your own width, height and frame rate here + 'minHeight': '480', + 'minFrameRate': '30', + }, + 'facingMode': 'user', + 'optional': [], + } }; - - MediaStream stream = user_screen - ? await navigator.getDisplayMedia(mediaConstraints) - : await navigator.getUserMedia(mediaConstraints); - if (this.onLocalStream != null) { - this.onLocalStream(stream); + late MediaStream stream; + if (userScreen) { + if (WebRTC.platformIsDesktop) { + final source = await showDialog( + context: context!, + builder: (context) => ScreenSelectDialog(), + ); + stream = await navigator.mediaDevices.getDisplayMedia({ + 'video': source == null + ? true + : { + 'deviceId': {'exact': source.id}, + 'mandatory': {'frameRate': 30.0} + } + }); + } else { + stream = await navigator.mediaDevices.getDisplayMedia(mediaConstraints); + } + } else { + stream = await navigator.mediaDevices.getUserMedia(mediaConstraints); } + + onLocalStream?.call(stream); return stream; } - _createPeerConnection(id, media, user_screen) async { - if (media != 'data') _localStream = await createStream(media, user_screen); - RTCPeerConnection pc = await createPeerConnection(_iceServers, _config); - if (media != 'data') pc.addStream(_localStream); - pc.onIceCandidate = (candidate) { - _send('candidate', { - 'to': id, - 'candidate': { - 'sdpMLineIndex': candidate.sdpMlineIndex, - 'sdpMid': candidate.sdpMid, - 'candidate': candidate.candidate, - }, - 'session_id': this._sessionId, - }); + Future _createSession( + Session? session, { + required String peerId, + required String sessionId, + required String media, + required bool screenSharing, + }) async { + var newSession = session ?? Session(sid: sessionId, pid: peerId); + if (media != 'data') + _localStream = + await createStream(media, screenSharing, context: _context); + print(_iceServers); + RTCPeerConnection pc = await createPeerConnection({ + ..._iceServers, + ...{'sdpSemantics': sdpSemantics} + }, _config); + if (media != 'data') { + switch (sdpSemantics) { + case 'plan-b': + pc.onAddStream = (MediaStream stream) { + onAddRemoteStream?.call(newSession, stream); + _remoteStreams.add(stream); + }; + await pc.addStream(_localStream!); + break; + case 'unified-plan': + // Unified-Plan + pc.onTrack = (event) { + if (event.track.kind == 'video') { + onAddRemoteStream?.call(newSession, event.streams[0]); + } + }; + _localStream!.getTracks().forEach((track) async { + _senders.add(await pc.addTrack(track, _localStream!)); + }); + break; + } + + // Unified-Plan: Simuclast + /* + await pc.addTransceiver( + track: _localStream.getAudioTracks()[0], + init: RTCRtpTransceiverInit( + direction: TransceiverDirection.SendOnly, streams: [_localStream]), + ); + + await pc.addTransceiver( + track: _localStream.getVideoTracks()[0], + init: RTCRtpTransceiverInit( + direction: TransceiverDirection.SendOnly, + streams: [ + _localStream + ], + sendEncodings: [ + RTCRtpEncoding(rid: 'f', active: true), + RTCRtpEncoding( + rid: 'h', + active: true, + scaleResolutionDownBy: 2.0, + maxBitrate: 150000, + ), + RTCRtpEncoding( + rid: 'q', + active: true, + scaleResolutionDownBy: 4.0, + maxBitrate: 100000, + ), + ]), + );*/ + /* + var sender = pc.getSenders().find(s => s.track.kind == "video"); + var parameters = sender.getParameters(); + if(!parameters) + parameters = {}; + parameters.encodings = [ + { rid: "h", active: true, maxBitrate: 900000 }, + { rid: "m", active: true, maxBitrate: 300000, scaleResolutionDownBy: 2 }, + { rid: "l", active: true, maxBitrate: 100000, scaleResolutionDownBy: 4 } + ]; + sender.setParameters(parameters); + */ + } + pc.onIceCandidate = (candidate) async { + if (candidate == null) { + print('onIceCandidate: complete!'); + return; + } + // This delay is needed to allow enough time to try an ICE candidate + // before skipping to the next one. 1 second is just an heuristic value + // and should be thoroughly tested in your own environment. + await Future.delayed( + const Duration(seconds: 1), + () => _send('candidate', { + 'to': peerId, + 'from': _selfId, + 'candidate': { + 'sdpMLineIndex': candidate.sdpMLineIndex, + 'sdpMid': candidate.sdpMid, + 'candidate': candidate.candidate, + }, + 'session_id': sessionId, + })); }; pc.onIceConnectionState = (state) {}; - pc.onAddStream = (stream) { - if (this.onAddRemoteStream != null) this.onAddRemoteStream(stream); - //_remoteStreams.add(stream); - }; - pc.onRemoveStream = (stream) { - if (this.onRemoveRemoteStream != null) this.onRemoveRemoteStream(stream); + onRemoveRemoteStream?.call(newSession, stream); _remoteStreams.removeWhere((it) { return (it.id == stream.id); }); }; pc.onDataChannel = (channel) { - _addDataChannel(id, channel); + _addDataChannel(newSession, channel); }; - return pc; + newSession.pc = pc; + return newSession; } - _addDataChannel(id, RTCDataChannel channel) { + void _addDataChannel(Session session, RTCDataChannel channel) { channel.onDataChannelState = (e) {}; channel.onMessage = (RTCDataChannelMessage data) { - if (this.onDataChannelMessage != null) - this.onDataChannelMessage(channel, data); + onDataChannelMessage?.call(session, channel, data); }; - _dataChannels[id] = channel; - - if (this.onDataChannel != null) this.onDataChannel(channel); + session.dc = channel; + onDataChannel?.call(session, channel); } - _createDataChannel(id, RTCPeerConnection pc, {label: 'fileTransfer'}) async { - RTCDataChannelInit dataChannelDict = new RTCDataChannelInit(); - RTCDataChannel channel = await pc.createDataChannel(label, dataChannelDict); - _addDataChannel(id, channel); + Future _createDataChannel(Session session, + {label: 'fileTransfer'}) async { + RTCDataChannelInit dataChannelDict = RTCDataChannelInit() + ..maxRetransmits = 30; + RTCDataChannel channel = + await session.pc!.createDataChannel(label, dataChannelDict); + _addDataChannel(session, channel); } - _createOffer(String id, RTCPeerConnection pc, String media) async { + Future _createOffer(Session session, String media) async { try { - RTCSessionDescription s = await pc - .createOffer(media == 'data' ? _dc_constraints : _constraints); - pc.setLocalDescription(s); + RTCSessionDescription s = + await session.pc!.createOffer(media == 'data' ? _dcConstraints : {}); + await session.pc!.setLocalDescription(_fixSdp(s)); _send('offer', { - 'to': id, + 'to': session.pid, + 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, - 'session_id': this._sessionId, + 'session_id': session.sid, 'media': media, }); } catch (e) { @@ -384,15 +532,23 @@ class Signaling { } } - _createAnswer(String id, RTCPeerConnection pc, media) async { + RTCSessionDescription _fixSdp(RTCSessionDescription s) { + var sdp = s.sdp; + s.sdp = + sdp!.replaceAll('profile-level-id=640c1f', 'profile-level-id=42e032'); + return s; + } + + Future _createAnswer(Session session, String media) async { try { - RTCSessionDescription s = await pc - .createAnswer(media == 'data' ? _dc_constraints : _constraints); - pc.setLocalDescription(s); + RTCSessionDescription s = + await session.pc!.createAnswer(media == 'data' ? _dcConstraints : {}); + await session.pc!.setLocalDescription(_fixSdp(s)); _send('answer', { - 'to': id, + 'to': session.pid, + 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, - 'session_id': this._sessionId, + 'session_id': session.sid, }); } catch (e) { print(e.toString()); @@ -400,8 +556,50 @@ class Signaling { } _send(event, data) { - data['type'] = event; - JsonEncoder encoder = new JsonEncoder(); - _socket.send(encoder.convert(data)); + var request = Map(); + request["type"] = event; + request["data"] = data; + _socket?.send(_encoder.convert(request)); + } + + Future _cleanSessions() async { + if (_localStream != null) { + _localStream!.getTracks().forEach((element) async { + await element.stop(); + }); + await _localStream!.dispose(); + _localStream = null; + } + _sessions.forEach((key, sess) async { + await sess.pc?.close(); + await sess.dc?.close(); + }); + _sessions.clear(); + } + + void _closeSessionByPeerId(String peerId) { + var session; + _sessions.removeWhere((String key, Session sess) { + var ids = key.split('-'); + session = sess; + return peerId == ids[0] || peerId == ids[1]; + }); + if (session != null) { + _closeSession(session); + onCallStateChange?.call(session, CallState.CallStateBye); + } + } + + Future _closeSession(Session session) async { + _localStream?.getTracks().forEach((element) async { + await element.stop(); + }); + await _localStream?.dispose(); + _localStream = null; + + await session.pc?.close(); + await session.dc?.close(); + _senders.clear(); + _videoSource = VideoSource.Camera; } } diff --git a/lib/src/route_item.dart b/lib/src/route_item.dart index 78427b1..a7a46d9 100644 --- a/lib/src/route_item.dart +++ b/lib/src/route_item.dart @@ -5,12 +5,12 @@ typedef void RouteCallback(BuildContext context); class RouteItem { RouteItem({ - @required this.title, - @required this.subtitle, - @required this.push, + required this.title, + required this.subtitle, + required this.push, }); final String title; final String subtitle; final RouteCallback push; -} \ No newline at end of file +} diff --git a/lib/src/utils/device_info.dart b/lib/src/utils/device_info.dart index 21617f4..e89ab5b 100644 --- a/lib/src/utils/device_info.dart +++ b/lib/src/utils/device_info.dart @@ -2,7 +2,11 @@ import 'dart:io'; class DeviceInfo { static String get label { - return Platform.localHostname + '(' + Platform.operatingSystem + ")"; + return 'Flutter ' + + Platform.operatingSystem + + '(' + + Platform.localHostname + + ")"; } static String get userAgent { diff --git a/lib/src/utils/device_info_web.dart b/lib/src/utils/device_info_web.dart index 0899668..ca0a396 100644 --- a/lib/src/utils/device_info_web.dart +++ b/lib/src/utils/device_info_web.dart @@ -1,11 +1,15 @@ +// ignore: avoid_web_libraries_in_flutter import 'dart:html' as HTML; class DeviceInfo { static String get label { - return 'Flutter Web ( ' + HTML.window.navigator.userAgent + ' )'; + return 'Flutter Web'; } static String get userAgent { - return 'flutter-webrtc/web-plugin 0.0.1'; + return 'flutter-webrtc/web-plugin 0.0.1 ' + + ' ( ' + + HTML.window.navigator.userAgent + + ' )'; } } diff --git a/lib/src/utils/key_value_store.dart b/lib/src/utils/key_value_store.dart deleted file mode 100644 index 56e5eb5..0000000 --- a/lib/src/utils/key_value_store.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'dart:async'; -import 'package:shared_preferences/shared_preferences.dart'; - -class KeyValueStore { - KeyValueStore(); - SharedPreferences _preferences; - - init() async { - _preferences = await SharedPreferences.getInstance(); - } - - String getString(String key) => _preferences.getString(key); - - Future setString(String key, String value) => - _preferences.setString(key, value); -} diff --git a/lib/src/utils/key_value_store_web.dart b/lib/src/utils/key_value_store_web.dart deleted file mode 100644 index 0fc445a..0000000 --- a/lib/src/utils/key_value_store_web.dart +++ /dev/null @@ -1,28 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:html'; - -class KeyValueStore { - KeyValueStore(); - Storage _storage; - - init() async { - _storage = window.localStorage; - } - - String getString(String key) => _storage[key]; - - Future setString(String key, String value) => _setValue(key, value); - - Future _setValue(String key, dynamic value) { - if (value is String) { - _storage[key] = value; - } else if (value is bool || value is double || value is int) { - _storage[key] = value.toString(); - } else if (value is List) { - _storage[key] = json.encode(value); - } - - return Future.value(true); - } -} diff --git a/lib/src/utils/screen_select_dialog.dart b/lib/src/utils/screen_select_dialog.dart new file mode 100644 index 0000000..45a4f2a --- /dev/null +++ b/lib/src/utils/screen_select_dialog.dart @@ -0,0 +1,307 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; + +class ThumbnailWidget extends StatefulWidget { + const ThumbnailWidget( + {Key? key, + required this.source, + required this.selected, + required this.onTap}) + : super(key: key); + final DesktopCapturerSource source; + final bool selected; + final Function(DesktopCapturerSource) onTap; + + @override + _ThumbnailWidgetState createState() => _ThumbnailWidgetState(); +} + +class _ThumbnailWidgetState extends State { + final List _subscriptions = []; + + @override + void initState() { + super.initState(); + _subscriptions.add(widget.source.onThumbnailChanged.stream.listen((event) { + setState(() {}); + })); + _subscriptions.add(widget.source.onNameChanged.stream.listen((event) { + setState(() {}); + })); + } + + @override + void deactivate() { + _subscriptions.forEach((element) { + element.cancel(); + }); + super.deactivate(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Expanded( + child: Container( + decoration: widget.selected + ? BoxDecoration( + border: Border.all(width: 2, color: Colors.blueAccent)) + : null, + child: InkWell( + onTap: () { + print('Selected source id => ${widget.source.id}'); + widget.onTap(widget.source); + }, + child: widget.source.thumbnail != null + ? Image.memory( + widget.source.thumbnail!, + gaplessPlayback: true, + alignment: Alignment.center, + ) + : Container(), + ), + )), + Text( + widget.source.name, + style: TextStyle( + fontSize: 12, + color: Colors.black87, + fontWeight: + widget.selected ? FontWeight.bold : FontWeight.normal), + ), + ], + ); + } +} + +// ignore: must_be_immutable +class ScreenSelectDialog extends Dialog { + ScreenSelectDialog() { + Future.delayed(Duration(milliseconds: 100), () { + _getSources(); + }); + _subscriptions.add(desktopCapturer.onAdded.stream.listen((source) { + _sources[source.id] = source; + _stateSetter?.call(() {}); + })); + + _subscriptions.add(desktopCapturer.onRemoved.stream.listen((source) { + _sources.remove(source.id); + _stateSetter?.call(() {}); + })); + + _subscriptions + .add(desktopCapturer.onThumbnailChanged.stream.listen((source) { + _stateSetter?.call(() {}); + })); + } + final Map _sources = {}; + SourceType _sourceType = SourceType.Screen; + DesktopCapturerSource? _selected_source; + final List> _subscriptions = []; + StateSetter? _stateSetter; + Timer? _timer; + + void _ok(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, _selected_source); + } + + void _cancel(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, null); + } + + Future _getSources() async { + try { + var sources = await desktopCapturer.getSources(types: [_sourceType]); + sources.forEach((element) { + print( + 'name: ${element.name}, id: ${element.id}, type: ${element.type}'); + }); + _timer?.cancel(); + _timer = Timer.periodic(Duration(seconds: 3), (timer) { + desktopCapturer.updateSources(types: [_sourceType]); + }); + _sources.clear(); + sources.forEach((element) { + _sources[element.id] = element; + }); + _stateSetter?.call(() {}); + return; + } catch (e) { + print(e.toString()); + } + } + + @override + Widget build(BuildContext context) { + return Material( + type: MaterialType.transparency, + child: Center( + child: Container( + width: 640, + height: 560, + color: Colors.white, + child: Column( + children: [ + Padding( + padding: EdgeInsets.all(10), + child: Stack( + children: [ + Align( + alignment: Alignment.topLeft, + child: Text( + 'Choose what to share', + style: TextStyle(fontSize: 16, color: Colors.black87), + ), + ), + Align( + alignment: Alignment.topRight, + child: InkWell( + child: Icon(Icons.close), + onTap: () => _cancel(context), + ), + ), + ], + ), + ), + Expanded( + flex: 1, + child: Container( + width: double.infinity, + padding: EdgeInsets.all(10), + child: StatefulBuilder( + builder: (context, setState) { + _stateSetter = setState; + return DefaultTabController( + length: 2, + child: Column( + children: [ + Container( + constraints: BoxConstraints.expand(height: 24), + child: TabBar( + onTap: (value) => Future.delayed( + Duration(milliseconds: 300), () { + _sourceType = value == 0 + ? SourceType.Screen + : SourceType.Window; + _getSources(); + }), + tabs: [ + Tab( + child: Text( + 'Entire Screen', + style: TextStyle(color: Colors.black54), + )), + Tab( + child: Text( + 'Window', + style: TextStyle(color: Colors.black54), + )), + ]), + ), + SizedBox( + height: 2, + ), + Expanded( + child: Container( + child: TabBarView(children: [ + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 2, + children: _sources.entries + .where((element) => + element.value.type == + SourceType.Screen) + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, + )) + .toList(), + ), + )), + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 3, + children: _sources.entries + .where((element) => + element.value.type == + SourceType.Window) + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, + )) + .toList(), + ), + )), + ]), + ), + ) + ], + ), + ); + }, + ), + ), + ), + Container( + width: double.infinity, + child: ButtonBar( + children: [ + MaterialButton( + child: Text( + 'Cancel', + style: TextStyle(color: Colors.black54), + ), + onPressed: () { + _cancel(context); + }, + ), + MaterialButton( + color: Theme.of(context).primaryColor, + child: Text( + 'Share', + ), + onPressed: () { + _ok(context); + }, + ), + ], + ), + ), + ], + ), + )), + ); + } +} diff --git a/lib/src/utils/turn.dart b/lib/src/utils/turn.dart new file mode 100644 index 0000000..0d4a00f --- /dev/null +++ b/lib/src/utils/turn.dart @@ -0,0 +1,19 @@ +import 'dart:convert'; +import 'dart:async'; +import 'dart:io'; + +Future getTurnCredential(String host, int port) async { + HttpClient client = HttpClient(context: SecurityContext()); + client.badCertificateCallback = + (X509Certificate cert, String host, int port) { + print('getTurnCredential: Allow self-signed certificate => $host:$port. '); + return true; + }; + var url = 'https://$host:$port/api/turn?service=turn&username=flutter-webrtc'; + var request = await client.getUrl(Uri.parse(url)); + var response = await request.close(); + var responseBody = await response.transform(Utf8Decoder()).join(); + print('getTurnCredential:response => $responseBody.'); + Map data = JsonDecoder().convert(responseBody); + return data; + } diff --git a/lib/src/utils/turn_web.dart b/lib/src/utils/turn_web.dart new file mode 100644 index 0000000..bf2ea7a --- /dev/null +++ b/lib/src/utils/turn_web.dart @@ -0,0 +1,13 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +Future getTurnCredential(String host, int port) async { + var url = 'https://$host:$port/api/turn?service=turn&username=flutter-webrtc'; + final res = await http.get(Uri.parse(url)); + if (res.statusCode == 200) { + var data = json.decode(res.body); + print('getTurnCredential:response => $data.'); + return data; + } + return {}; +} diff --git a/lib/src/utils/websocket.dart b/lib/src/utils/websocket.dart index cd49115..c6ebffc 100644 --- a/lib/src/utils/websocket.dart +++ b/lib/src/utils/websocket.dart @@ -3,30 +3,26 @@ import 'dart:math'; import 'dart:convert'; import 'dart:async'; -typedef void OnMessageCallback(dynamic msg); -typedef void OnCloseCallback(int code, String reason); -typedef void OnOpenCallback(); - class SimpleWebSocket { String _url; var _socket; - OnOpenCallback onOpen; - OnMessageCallback onMessage; - OnCloseCallback onClose; + Function()? onOpen; + Function(dynamic msg)? onMessage; + Function(int? code, String? reaso)? onClose; SimpleWebSocket(this._url); connect() async { try { - _socket = await WebSocket.connect(_url); - //socket = await _connectForSelfSignedCert(_host, _port); - this?.onOpen(); + //_socket = await WebSocket.connect(_url); + _socket = await _connectForSelfSignedCert(_url); + onOpen?.call(); _socket.listen((data) { - this?.onMessage(data); + onMessage?.call(data); }, onDone: () { - this?.onClose(_socket.closeCode, _socket.closeReason); + onClose?.call(_socket.closeCode, _socket.closeReason); }); } catch (e) { - this.onClose(500, e.toString()); + onClose?.call(500, e.toString()); } } @@ -38,23 +34,23 @@ class SimpleWebSocket { } close() { - _socket.close(); + if (_socket != null) _socket.close(); } - Future _connectForSelfSignedCert(String host, int port) async { + Future _connectForSelfSignedCert(url) async { try { Random r = new Random(); String key = base64.encode(List.generate(8, (_) => r.nextInt(255))); - SecurityContext securityContext = new SecurityContext(); - HttpClient client = HttpClient(context: securityContext); + HttpClient client = HttpClient(context: SecurityContext()); client.badCertificateCallback = (X509Certificate cert, String host, int port) { - print('Allow self-signed certificate => $host:$port. '); + print( + 'SimpleWebSocket: Allow self-signed certificate => $host:$port. '); return true; }; - HttpClientRequest request = await client.getUrl( - Uri.parse('https://$host:$port/ws')); // form the correct url here + HttpClientRequest request = + await client.getUrl(Uri.parse(url)); // form the correct url here request.headers.add('Connection', 'Upgrade'); request.headers.add('Upgrade', 'websocket'); request.headers.add( @@ -62,6 +58,7 @@ class SimpleWebSocket { request.headers.add('Sec-WebSocket-Key', key.toLowerCase()); HttpClientResponse response = await request.close(); + // ignore: close_sinks Socket socket = await response.detachSocket(); var webSocket = WebSocket.fromUpgradedSocket( socket, diff --git a/lib/src/utils/websocket_web.dart b/lib/src/utils/websocket_web.dart index f7ecdc5..94c9546 100644 --- a/lib/src/utils/websocket_web.dart +++ b/lib/src/utils/websocket_web.dart @@ -1,34 +1,33 @@ +// ignore: avoid_web_libraries_in_flutter import 'dart:html'; -typedef void OnMessageCallback(dynamic msg); -typedef void OnCloseCallback(int code, String reason); -typedef void OnOpenCallback(); - class SimpleWebSocket { String _url; var _socket; - OnOpenCallback onOpen; - OnMessageCallback onMessage; - OnCloseCallback onClose; + Function()? onOpen; + Function(dynamic msg)? onMessage; + Function(int code, String reason)? onClose; - SimpleWebSocket(this._url); + SimpleWebSocket(this._url) { + _url = _url.replaceAll('https:', 'wss:'); + } connect() async { try { _socket = WebSocket(_url); _socket.onOpen.listen((e) { - this?.onOpen(); + onOpen?.call(); }); _socket.onMessage.listen((e) { - this?.onMessage(e.data); + onMessage?.call(e.data); }); _socket.onClose.listen((e) { - this?.onClose(e.code, e.reason); + onClose?.call(e.code, e.reason); }); } catch (e) { - this?.onClose(e.code, e.reason); + onClose?.call(500, e.toString()); } } @@ -42,6 +41,8 @@ class SimpleWebSocket { } close() { - _socket.close(); + if (_socket != null) { + _socket.close(); + } } } diff --git a/lib/src/widgets/screen_select_dialog.dart b/lib/src/widgets/screen_select_dialog.dart new file mode 100644 index 0000000..45a4f2a --- /dev/null +++ b/lib/src/widgets/screen_select_dialog.dart @@ -0,0 +1,307 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; + +class ThumbnailWidget extends StatefulWidget { + const ThumbnailWidget( + {Key? key, + required this.source, + required this.selected, + required this.onTap}) + : super(key: key); + final DesktopCapturerSource source; + final bool selected; + final Function(DesktopCapturerSource) onTap; + + @override + _ThumbnailWidgetState createState() => _ThumbnailWidgetState(); +} + +class _ThumbnailWidgetState extends State { + final List _subscriptions = []; + + @override + void initState() { + super.initState(); + _subscriptions.add(widget.source.onThumbnailChanged.stream.listen((event) { + setState(() {}); + })); + _subscriptions.add(widget.source.onNameChanged.stream.listen((event) { + setState(() {}); + })); + } + + @override + void deactivate() { + _subscriptions.forEach((element) { + element.cancel(); + }); + super.deactivate(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Expanded( + child: Container( + decoration: widget.selected + ? BoxDecoration( + border: Border.all(width: 2, color: Colors.blueAccent)) + : null, + child: InkWell( + onTap: () { + print('Selected source id => ${widget.source.id}'); + widget.onTap(widget.source); + }, + child: widget.source.thumbnail != null + ? Image.memory( + widget.source.thumbnail!, + gaplessPlayback: true, + alignment: Alignment.center, + ) + : Container(), + ), + )), + Text( + widget.source.name, + style: TextStyle( + fontSize: 12, + color: Colors.black87, + fontWeight: + widget.selected ? FontWeight.bold : FontWeight.normal), + ), + ], + ); + } +} + +// ignore: must_be_immutable +class ScreenSelectDialog extends Dialog { + ScreenSelectDialog() { + Future.delayed(Duration(milliseconds: 100), () { + _getSources(); + }); + _subscriptions.add(desktopCapturer.onAdded.stream.listen((source) { + _sources[source.id] = source; + _stateSetter?.call(() {}); + })); + + _subscriptions.add(desktopCapturer.onRemoved.stream.listen((source) { + _sources.remove(source.id); + _stateSetter?.call(() {}); + })); + + _subscriptions + .add(desktopCapturer.onThumbnailChanged.stream.listen((source) { + _stateSetter?.call(() {}); + })); + } + final Map _sources = {}; + SourceType _sourceType = SourceType.Screen; + DesktopCapturerSource? _selected_source; + final List> _subscriptions = []; + StateSetter? _stateSetter; + Timer? _timer; + + void _ok(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, _selected_source); + } + + void _cancel(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, null); + } + + Future _getSources() async { + try { + var sources = await desktopCapturer.getSources(types: [_sourceType]); + sources.forEach((element) { + print( + 'name: ${element.name}, id: ${element.id}, type: ${element.type}'); + }); + _timer?.cancel(); + _timer = Timer.periodic(Duration(seconds: 3), (timer) { + desktopCapturer.updateSources(types: [_sourceType]); + }); + _sources.clear(); + sources.forEach((element) { + _sources[element.id] = element; + }); + _stateSetter?.call(() {}); + return; + } catch (e) { + print(e.toString()); + } + } + + @override + Widget build(BuildContext context) { + return Material( + type: MaterialType.transparency, + child: Center( + child: Container( + width: 640, + height: 560, + color: Colors.white, + child: Column( + children: [ + Padding( + padding: EdgeInsets.all(10), + child: Stack( + children: [ + Align( + alignment: Alignment.topLeft, + child: Text( + 'Choose what to share', + style: TextStyle(fontSize: 16, color: Colors.black87), + ), + ), + Align( + alignment: Alignment.topRight, + child: InkWell( + child: Icon(Icons.close), + onTap: () => _cancel(context), + ), + ), + ], + ), + ), + Expanded( + flex: 1, + child: Container( + width: double.infinity, + padding: EdgeInsets.all(10), + child: StatefulBuilder( + builder: (context, setState) { + _stateSetter = setState; + return DefaultTabController( + length: 2, + child: Column( + children: [ + Container( + constraints: BoxConstraints.expand(height: 24), + child: TabBar( + onTap: (value) => Future.delayed( + Duration(milliseconds: 300), () { + _sourceType = value == 0 + ? SourceType.Screen + : SourceType.Window; + _getSources(); + }), + tabs: [ + Tab( + child: Text( + 'Entire Screen', + style: TextStyle(color: Colors.black54), + )), + Tab( + child: Text( + 'Window', + style: TextStyle(color: Colors.black54), + )), + ]), + ), + SizedBox( + height: 2, + ), + Expanded( + child: Container( + child: TabBarView(children: [ + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 2, + children: _sources.entries + .where((element) => + element.value.type == + SourceType.Screen) + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, + )) + .toList(), + ), + )), + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 3, + children: _sources.entries + .where((element) => + element.value.type == + SourceType.Window) + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, + )) + .toList(), + ), + )), + ]), + ), + ) + ], + ), + ); + }, + ), + ), + ), + Container( + width: double.infinity, + child: ButtonBar( + children: [ + MaterialButton( + child: Text( + 'Cancel', + style: TextStyle(color: Colors.black54), + ), + onPressed: () { + _cancel(context); + }, + ), + MaterialButton( + color: Theme.of(context).primaryColor, + child: Text( + 'Share', + ), + onPressed: () { + _ok(context); + }, + ), + ], + ), + ), + ], + ), + )), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..494646b --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,442 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + collection: + dependency: transitive + description: + name: collection + sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf + url: "https://pub.dev" + source: hosted + version: "1.19.0" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_webrtc: + dependency: transitive + description: + name: dart_webrtc + sha256: e65506edb452148220efab53d8d2f8bb9d827bd8bcd53cf3a3e6df70b27f3d86 + url: "https://pub.dev" + source: hosted + version: "1.4.10" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + ffi: + dependency: transitive + description: + name: ffi + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_webrtc: + dependency: "direct main" + description: + name: flutter_webrtc + sha256: e917067abeef2400e6a7a03db53a6e1418551e54809f18ab80447ac323eb77e4 + url: "https://pub.dev" + source: hosted + version: "0.12.8" + http: + dependency: "direct main" + description: + name: http + sha256: "5895291c13fa8a3bd82e76d5627f69e0d85ca6a30dcac95c4ea19a5d555879c2" + url: "https://pub.dev" + source: hosted + version: "0.13.6" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + js: + dependency: transitive + description: + name: js + sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf + url: "https://pub.dev" + source: hosted + version: "0.7.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06" + url: "https://pub.dev" + source: hosted + version: "10.0.7" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379" + url: "https://pub.dev" + source: hosted + version: "3.0.8" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + url: "https://pub.dev" + source: hosted + version: "0.12.16+1" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 + url: "https://pub.dev" + source: hosted + version: "1.15.0" + path: + dependency: transitive + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "4adf4fd5423ec60a29506c76581bc05854c55e3a0b72d35bb28d661c9686edf2" + url: "https://pub.dev" + source: hosted + version: "2.2.15" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + platform_detect: + dependency: transitive + description: + name: platform_detect + sha256: a62f99417fc4fa2d099ce0ccdbb1bd3977920f2a64292c326271f049d4bc3a4f + url: "https://pub.dev" + source: hosted + version: "2.1.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "7b3cfbf654f3edd0c6298ecd5be782ce997ddf0e00531b9464b55245185bbbbd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "688ee90fbfb6989c980254a56cb26ebe9bb30a3a2dff439a78894211f73de67a" + url: "https://pub.dev" + source: hosted + version: "2.5.1" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "650584dcc0a39856f369782874e562efd002a9c94aec032412c9eb81419cce1f" + url: "https://pub.dev" + source: hosted + version: "2.4.4" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: d2ca4132d3946fec2184261726b355836a82c33d7d5b67af32692aff18a4684e + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377" + url: "https://pub.dev" + source: hosted + version: "1.12.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "69fe30f3a8b04a0be0c15ae6490fc859a78ef4c43ae2dd5e8a623d45bfcf9225" + url: "https://pub.dev" + source: hosted + version: "3.3.0+3" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c" + url: "https://pub.dev" + source: hosted + version: "0.7.3" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b + url: "https://pub.dev" + source: hosted + version: "14.3.0" + web: + dependency: transitive + description: + name: web + sha256: cd3543bd5798f6ad290ea73d210f423502e71900302dde696f8bff84bf89a1cb + url: "https://pub.dev" + source: hosted + version: "1.1.0" + webrtc_interface: + dependency: transitive + description: + name: webrtc_interface + sha256: "10fc6dc0ac16f909f5e434c18902415211d759313c87261f1e4ec5b4f6a04c26" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" +sdks: + dart: ">=3.5.0 <4.0.0" + flutter: ">=3.24.0" diff --git a/pubspec.yaml b/pubspec.yaml index d82dbab..d27c17b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,75 +1,24 @@ name: flutter_webrtc_demo description: A new Flutter application. - -# The following defines the version and build number for your application. -# A version number is three numbers separated by dots, like 1.2.43 -# followed by an optional build number separated by a +. -# Both the version and the builder number may be overridden in flutter -# build by specifying --build-name and --build-number, respectively. -# Read more about versioning at semver.org. -version: 1.0.0+1 +version: 1.2.0 environment: - sdk: ">=2.2.0 <3.0.0" + sdk: '>=2.15.0 <3.0.0' + flutter: '>=1.22.0' dependencies: flutter: sdk: flutter - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^0.1.2 - flutter_webrtc: ^0.2.2 - shared_preferences: - shared_preferences_macos: - - # Required for MediaRecorder example - path_provider: - path_provider_macos: + cupertino_icons: ^1.0.3 + flutter_webrtc: ^0.12.8 + shared_preferences: ^2.0.7 + http: ^0.13.3 + path_provider: ^2.0.2 dev_dependencies: flutter_test: sdk: flutter - -# For information on the generic Dart part of this file, see the -# following page: https://www.dartlang.org/tools/pub/pubspec - -# The following section is specific to Flutter. flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.io/assets-and-images/#resolution-aware. - - # For details regarding adding assets from package dependencies, see - # https://flutter.io/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.io/custom-fonts/#from-packages + uses-material-design: true \ No newline at end of file diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..f45d8f1 --- /dev/null +++ b/renovate.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "config:base" + ] +} diff --git a/test/widget_test.dart b/test/widget_test.dart index 93e3022..1fcb865 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -4,7 +4,6 @@ // find child widgets in the widget tree, read text, and verify that the values of widget properties // are correct. -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_webrtc_demo/main.dart'; diff --git a/web/index.html b/web/index.html index 3940fd7..550e257 100644 --- a/web/index.html +++ b/web/index.html @@ -3,6 +3,7 @@ Codestin Search App + diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..69533fb --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.15) +project(flutter_webrtc_demo LANGUAGES CXX) + +set(BINARY_NAME "flutter_webrtc_demo") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() + +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..744f08a --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,102 @@ +cmake_minimum_required(VERSION 3.15) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..60a2e52 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,12 @@ +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterWebRTCPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterWebRTCPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..9846246 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,13 @@ +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..345025b --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,16 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_webrtc +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..977e38b --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) +project(runner LANGUAGES CXX) + +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "run_loop.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) +apply_standard_settings(${BINARY_NAME}) +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..b24b959 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.cloudwebrtc" "\0" + VALUE "FileDescription", "A new Flutter project." "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "flutter_webrtc_demo" "\0" + VALUE "LegalCopyright", "Copyright (C) 2021 com.cloudwebrtc. All rights reserved." "\0" + VALUE "OriginalFilename", "flutter_webrtc_demo.exe" "\0" + VALUE "ProductName", "flutter_webrtc_demo" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..c422723 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,64 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project) + : run_loop_(run_loop), project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + run_loop_->RegisterFlutterInstance(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + run_loop_->UnregisterFlutterInstance(flutter_controller_->engine()); + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opporutunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..b663ddd --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,39 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "run_loop.h" +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow driven by the |run_loop|, hosting a + // Flutter view running |project|. + explicit FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The run loop driving events for this window. + RunLoop* run_loop_; + + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..ec13ebc --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "run_loop.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + RunLoop run_loop; + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(&run_loop, project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.CreateAndShow(L"flutter_webrtc_demo", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + run_loop.Run(); + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/run_loop.cpp b/windows/runner/run_loop.cpp new file mode 100644 index 0000000..2d6636a --- /dev/null +++ b/windows/runner/run_loop.cpp @@ -0,0 +1,66 @@ +#include "run_loop.h" + +#include + +#include + +RunLoop::RunLoop() {} + +RunLoop::~RunLoop() {} + +void RunLoop::Run() { + bool keep_running = true; + TimePoint next_flutter_event_time = TimePoint::clock::now(); + while (keep_running) { + std::chrono::nanoseconds wait_duration = + std::max(std::chrono::nanoseconds(0), + next_flutter_event_time - TimePoint::clock::now()); + ::MsgWaitForMultipleObjects( + 0, nullptr, FALSE, static_cast(wait_duration.count() / 1000), + QS_ALLINPUT); + bool processed_events = false; + MSG message; + // All pending Windows messages must be processed; MsgWaitForMultipleObjects + // won't return again for items left in the queue after PeekMessage. + while (::PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { + processed_events = true; + if (message.message == WM_QUIT) { + keep_running = false; + break; + } + ::TranslateMessage(&message); + ::DispatchMessage(&message); + // Allow Flutter to process messages each time a Windows message is + // processed, to prevent starvation. + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + // If the PeekMessage loop didn't run, process Flutter messages. + if (!processed_events) { + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + } +} + +void RunLoop::RegisterFlutterInstance( + flutter::FlutterEngine* flutter_instance) { + flutter_instances_.insert(flutter_instance); +} + +void RunLoop::UnregisterFlutterInstance( + flutter::FlutterEngine* flutter_instance) { + flutter_instances_.erase(flutter_instance); +} + +RunLoop::TimePoint RunLoop::ProcessFlutterMessages() { + TimePoint next_event_time = TimePoint::max(); + for (auto instance : flutter_instances_) { + std::chrono::nanoseconds wait_duration = instance->ProcessMessages(); + if (wait_duration != std::chrono::nanoseconds::max()) { + next_event_time = + std::min(next_event_time, TimePoint::clock::now() + wait_duration); + } + } + return next_event_time; +} diff --git a/windows/runner/run_loop.h b/windows/runner/run_loop.h new file mode 100644 index 0000000..000d362 --- /dev/null +++ b/windows/runner/run_loop.h @@ -0,0 +1,40 @@ +#ifndef RUNNER_RUN_LOOP_H_ +#define RUNNER_RUN_LOOP_H_ + +#include + +#include +#include + +// A runloop that will service events for Flutter instances as well +// as native messages. +class RunLoop { + public: + RunLoop(); + ~RunLoop(); + + // Prevent copying + RunLoop(RunLoop const&) = delete; + RunLoop& operator=(RunLoop const&) = delete; + + // Runs the run loop until the application quits. + void Run(); + + // Registers the given Flutter instance for event servicing. + void RegisterFlutterInstance( + flutter::FlutterEngine* flutter_instance); + + // Unregisters the given Flutter instance from event servicing. + void UnregisterFlutterInstance( + flutter::FlutterEngine* flutter_instance); + + private: + using TimePoint = std::chrono::steady_clock::time_point; + + // Processes all currently pending messages for registered Flutter instances. + TimePoint ProcessFlutterMessages(); + + std::set flutter_instances_; +}; + +#endif // RUNNER_RUN_LOOP_H_ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..d19bdbb --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..c10f08d --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + FreeLibrary(user32_module); + } +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + return OnCreate(); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..17ba431 --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates and shows a win32 window with |title| and position and size using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_