├── example ├── linux │ ├── .gitignore │ ├── main.cc │ ├── flutter │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ ├── generated_plugins.cmake │ │ └── CMakeLists.txt │ ├── my_application.h │ ├── my_application.cc │ └── CMakeLists.txt ├── ios │ ├── Runner │ │ ├── Runner-Bridging-Header.h │ │ ├── Assets.xcassets │ │ │ ├── LaunchImage.imageset │ │ │ │ ├── LaunchImage.png │ │ │ │ ├── LaunchImage@2x.png │ │ │ │ ├── LaunchImage@3x.png │ │ │ │ ├── README.md │ │ │ │ └── Contents.json │ │ │ └── AppIcon.appiconset │ │ │ │ ├── Icon-App-20x20@1x.png │ │ │ │ ├── Icon-App-20x20@2x.png │ │ │ │ ├── Icon-App-20x20@3x.png │ │ │ │ ├── Icon-App-29x29@1x.png │ │ │ │ ├── Icon-App-29x29@2x.png │ │ │ │ ├── Icon-App-29x29@3x.png │ │ │ │ ├── Icon-App-40x40@1x.png │ │ │ │ ├── Icon-App-40x40@2x.png │ │ │ │ ├── Icon-App-40x40@3x.png │ │ │ │ ├── Icon-App-60x60@2x.png │ │ │ │ ├── Icon-App-60x60@3x.png │ │ │ │ ├── Icon-App-76x76@1x.png │ │ │ │ ├── Icon-App-76x76@2x.png │ │ │ │ ├── Icon-App-1024x1024@1x.png │ │ │ │ ├── Icon-App-83.5x83.5@2x.png │ │ │ │ └── Contents.json │ │ ├── AppDelegate.swift │ │ ├── Base.lproj │ │ │ ├── Main.storyboard │ │ │ └── LaunchScreen.storyboard │ │ └── Info.plist │ ├── Flutter │ │ ├── Debug.xcconfig │ │ ├── Release.xcconfig │ │ └── AppFrameworkInfo.plist │ ├── Runner.xcodeproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ ├── WorkspaceSettings.xcsettings │ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ ├── WorkspaceSettings.xcsettings │ │ │ └── IDEWorkspaceChecks.plist │ ├── RunnerTests │ │ └── RunnerTests.swift │ ├── .gitignore │ └── Podfile ├── web │ ├── favicon.png │ ├── icons │ │ ├── Icon-192.png │ │ ├── Icon-512.png │ │ ├── Icon-maskable-192.png │ │ └── Icon-maskable-512.png │ ├── manifest.json │ └── index.html ├── macos │ ├── Runner │ │ ├── Configs │ │ │ ├── Debug.xcconfig │ │ │ ├── Release.xcconfig │ │ │ ├── Warnings.xcconfig │ │ │ └── AppInfo.xcconfig │ │ ├── Assets.xcassets │ │ │ └── AppIcon.appiconset │ │ │ │ ├── app_icon_128.png │ │ │ │ ├── app_icon_16.png │ │ │ │ ├── app_icon_256.png │ │ │ │ ├── app_icon_32.png │ │ │ │ ├── app_icon_512.png │ │ │ │ ├── app_icon_64.png │ │ │ │ ├── app_icon_1024.png │ │ │ │ └── Contents.json │ │ ├── AppDelegate.swift │ │ ├── Release.entitlements │ │ ├── DebugProfile.entitlements │ │ ├── MainFlutterWindow.swift │ │ └── Info.plist │ ├── .gitignore │ ├── Flutter │ │ ├── Flutter-Debug.xcconfig │ │ ├── Flutter-Release.xcconfig │ │ └── GeneratedPluginRegistrant.swift │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ ├── Runner.xcodeproj │ │ ├── project.xcworkspace │ │ │ └── xcshareddata │ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ ├── RunnerTests │ │ └── RunnerTests.swift │ └── Podfile ├── windows │ ├── runner │ │ ├── resources │ │ │ └── app_icon.ico │ │ ├── resource.h │ │ ├── runner.exe.manifest │ │ ├── utils.h │ │ ├── flutter_window.h │ │ ├── main.cpp │ │ ├── CMakeLists.txt │ │ ├── utils.cpp │ │ ├── flutter_window.cpp │ │ ├── Runner.rc │ │ ├── win32_window.h │ │ └── win32_window.cpp │ ├── .gitignore │ ├── flutter │ │ ├── generated_plugin_registrant.h │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugins.cmake │ │ └── CMakeLists.txt │ └── CMakeLists.txt ├── android │ ├── gradle.properties │ ├── app │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── drawable │ │ │ │ │ │ └── launch_background.xml │ │ │ │ │ ├── drawable-v21 │ │ │ │ │ │ └── launch_background.xml │ │ │ │ │ ├── values │ │ │ │ │ │ └── styles.xml │ │ │ │ │ └── values-night │ │ │ │ │ │ └── styles.xml │ │ │ │ ├── kotlin │ │ │ │ │ └── com │ │ │ │ │ │ └── ugo │ │ │ │ │ │ └── studio │ │ │ │ │ │ └── plugins │ │ │ │ │ │ └── flutter_p2p_connection_example │ │ │ │ │ │ └── MainActivity.kt │ │ │ │ └── AndroidManifest.xml │ │ │ ├── debug │ │ │ │ └── AndroidManifest.xml │ │ │ └── profile │ │ │ │ └── AndroidManifest.xml │ │ └── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ ├── .gitignore │ ├── build.gradle │ └── settings.gradle ├── README.md ├── .gitignore ├── test │ └── widget_test.dart ├── integration_test │ └── plugin_integration_test.dart ├── lib │ ├── qr │ │ ├── qr_image_page.dart │ │ └── scanner_page.dart │ └── main.dart ├── analysis_options.yaml ├── .metadata └── pubspec.yaml ├── android ├── settings.gradle ├── .gitignore ├── src │ ├── main │ │ ├── AndroidManifest.xml │ │ └── kotlin │ │ │ └── com │ │ │ └── ugo │ │ │ └── studio │ │ │ └── plugins │ │ │ └── flutter_p2p_connection │ │ │ ├── Constants.kt │ │ │ ├── PermissionsManager.kt │ │ │ ├── ServiceManager.kt │ │ │ └── DataUtils.kt │ └── test │ │ └── kotlin │ │ └── com │ │ └── ugo │ │ └── studio │ │ └── plugins │ │ └── flutter_p2p_connection │ │ └── FlutterP2pConnectionPluginTest.kt └── build.gradle ├── analysis_options.yaml ├── lib ├── src │ ├── common │ │ ├── p2p_constants.dart │ │ ├── utils.dart │ │ └── p2p_connection_base.dart │ └── transport │ │ └── common │ │ ├── transport_enums.dart │ │ ├── transport_file_models.dart │ │ └── file_request_server_mixin.dart ├── flutter_p2p_connection.dart └── flutter_p2p_connection_platform_interface.dart ├── windows ├── .gitignore ├── flutter_p2p_connection_plugin_c_api.cpp ├── include │ └── flutter_p2p_connection │ │ └── flutter_p2p_connection_plugin_c_api.h ├── constants.h ├── utils.h ├── flutter_p2p_connection_plugin.h ├── pch.h ├── test │ └── flutter_p2p_connection_plugin_test.cpp ├── flutter_p2p_connection_plugin.cpp └── CMakeLists.txt ├── .gitignore ├── CHANGELOG.md ├── test ├── flutter_p2p_connection_method_channel_test.dart └── flutter_p2p_connection_test.dart ├── LICENSE ├── .metadata └── pubspec.yaml /example/linux/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral 2 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'flutter_p2p_connection' 2 | -------------------------------------------------------------------------------- /example/ios/Runner/Runner-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import "GeneratedPluginRegistrant.h" 2 | -------------------------------------------------------------------------------- /example/web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/web/favicon.png -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Debug.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Release.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /example/web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/web/icons/Icon-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/web/icons/Icon-512.png -------------------------------------------------------------------------------- /example/macos/.gitignore: -------------------------------------------------------------------------------- 1 | # Flutter-related 2 | **/Flutter/ephemeral/ 3 | **/Pods/ 4 | 5 | # Xcode-related 6 | **/dgph 7 | **/xcuserdata/ 8 | -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /example/ios/Flutter/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/ios/Flutter/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /android/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .cxx 10 | -------------------------------------------------------------------------------- /example/macos/Flutter/Flutter-Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "ephemeral/Flutter-Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError 2 | android.useAndroidX=true 3 | android.enableJetifier=true 4 | -------------------------------------------------------------------------------- /example/macos/Flutter/Flutter-Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "ephemeral/Flutter-Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:flutter_lints/flutter.yaml 2 | 3 | # Additional information about this file can be found at 4 | # https://dart.dev/guides/language/analysis-options 5 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugo-studio/flutter_p2p_connection/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png -------------------------------------------------------------------------------- /example/linux/main.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | int main(int argc, char** argv) { 4 | g_autoptr(MyApplication) app = my_application_new(); 5 | return g_application_run(G_APPLICATION(app), argc, argv); 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/macos/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/linux/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | 10 | void fl_register_plugins(FlPluginRegistry* registry) { 11 | } 12 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip 6 | -------------------------------------------------------------------------------- /example/android/app/src/main/kotlin/com/ugo/studio/plugins/flutter_p2p_connection_example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.ugo.studio.plugins.flutter_p2p_connection_example 2 | 3 | import io.flutter.embedding.android.FlutterActivity 4 | 5 | class MainActivity: FlutterActivity() 6 | -------------------------------------------------------------------------------- /example/macos/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | @main 5 | class AppDelegate: FlutterAppDelegate { 6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 7 | return true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /lib/src/common/p2p_constants.dart: -------------------------------------------------------------------------------- 1 | /// Default port for the P2P transport layer if not specified otherwise. 2 | const int defaultP2pTransportPort = 3456; 3 | 4 | /// Default port for the client's file server in the P2P transport layer. 5 | const int defaultP2pTransportClientFileServerPort = 4567; 6 | -------------------------------------------------------------------------------- /example/macos/Runner/Release.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/android/.gitignore: -------------------------------------------------------------------------------- 1 | gradle-wrapper.jar 2 | /.gradle 3 | /captures/ 4 | /gradlew 5 | /gradlew.bat 6 | /local.properties 7 | GeneratedPluginRegistrant.java 8 | 9 | # Remember to never publicly share your keystore. 10 | # See https://flutter.dev/to/reference-keystore 11 | key.properties 12 | **/*.keystore 13 | **/*.jks 14 | -------------------------------------------------------------------------------- /example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/macos/Flutter/GeneratedPluginRegistrant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | import FlutterMacOS 6 | import Foundation 7 | 8 | import mobile_scanner 9 | 10 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 11 | MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) 12 | } 13 | -------------------------------------------------------------------------------- /example/ios/RunnerTests/RunnerTests.swift: -------------------------------------------------------------------------------- 1 | import Flutter 2 | import UIKit 3 | import XCTest 4 | 5 | class RunnerTests: XCTestCase { 6 | 7 | func testExample() { 8 | // If you add code to the Runner application, consider adding tests here. 9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /example/macos/RunnerTests/RunnerTests.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | import XCTest 4 | 5 | class RunnerTests: XCTestCase { 6 | 7 | func testExample() { 8 | // If you add code to the Runner application, consider adding tests here. 9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /example/windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md: -------------------------------------------------------------------------------- 1 | # Launch Screen Assets 2 | 3 | You can customize the launch screen with your own desired assets by replacing the image files in this directory. 4 | 5 | You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. -------------------------------------------------------------------------------- /example/linux/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void fl_register_plugins(FlPluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | } 7 | 8 | rootProject.buildDir = "../build" 9 | subprojects { 10 | project.buildDir = "${rootProject.buildDir}/${project.name}" 11 | } 12 | subprojects { 13 | project.evaluationDependsOn(":app") 14 | } 15 | 16 | tasks.register("clean", Delete) { 17 | delete rootProject.buildDir 18 | } 19 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/macos/Runner/DebugProfile.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /example/ios/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Flutter 2 | import UIKit 3 | 4 | @main 5 | @objc class AppDelegate: FlutterAppDelegate { 6 | override func application( 7 | _ application: UIApplication, 8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? 9 | ) -> Bool { 10 | GeneratedPluginRegistrant.register(with: self) 11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | 11 | void RegisterPlugins(flutter::PluginRegistry* registry) { 12 | PermissionHandlerWindowsPluginRegisterWithRegistrar( 13 | registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); 14 | } 15 | -------------------------------------------------------------------------------- /example/macos/Runner/MainFlutterWindow.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | class MainFlutterWindow: NSWindow { 5 | override func awakeFromNib() { 6 | let flutterViewController = FlutterViewController() 7 | let windowFrame = self.frame 8 | self.contentViewController = flutterViewController 9 | self.setFrame(windowFrame, display: true) 10 | 11 | RegisterGeneratedPlugins(registry: flutterViewController) 12 | 13 | super.awakeFromNib() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/linux/my_application.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_MY_APPLICATION_H_ 2 | #define FLUTTER_MY_APPLICATION_H_ 3 | 4 | #include 5 | 6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, 7 | GtkApplication) 8 | 9 | /** 10 | * my_application_new: 11 | * 12 | * Creates a new Flutter-based application. 13 | * 14 | * Returns: a new #MyApplication. 15 | */ 16 | MyApplication* my_application_new(); 17 | 18 | #endif // FLUTTER_MY_APPLICATION_H_ 19 | -------------------------------------------------------------------------------- /example/windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable-v21/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchImage.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchImage@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchImage@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /windows/flutter_p2p_connection_plugin_c_api.cpp: -------------------------------------------------------------------------------- 1 | #include "include/flutter_p2p_connection/flutter_p2p_connection_plugin_c_api.h" 2 | 3 | #include 4 | 5 | #include "flutter_p2p_connection_plugin.h" 6 | 7 | void FlutterP2pConnectionPluginCApiRegisterWithRegistrar( 8 | FlutterDesktopPluginRegistrarRef registrar) { 9 | flutter_p2p_connection::FlutterP2pConnectionPlugin::RegisterWithRegistrar( 10 | flutter::PluginRegistrarManager::GetInstance() 11 | ->GetRegistrar(registrar)); 12 | } 13 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Warnings.xcconfig: -------------------------------------------------------------------------------- 1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings 2 | GCC_WARN_UNDECLARED_SELECTOR = YES 3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES 4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE 5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES 6 | CLANG_WARN_PRAGMA_PACK = YES 7 | CLANG_WARN_STRICT_PROTOTYPES = YES 8 | CLANG_WARN_COMMA = YES 9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES 10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES 11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES 12 | GCC_WARN_SHADOW = YES 13 | CLANG_WARN_UNREACHABLE_CODE = YES 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | # The .vscode folder contains launch configuration and tasks you configure in 20 | # VS Code which you may wish to be included in version control, so this line 21 | # is commented out by default. 22 | #.vscode/ 23 | 24 | # Flutter/Dart/Pub related 25 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. 26 | /pubspec.lock 27 | **/doc/api/ 28 | .dart_tool/ 29 | build/ 30 | /clean.sh -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # flutter_p2p_connection_example 2 | 3 | Demonstrates how to use the flutter_p2p_connection plugin. 4 | 5 | ## Getting Started 6 | 7 | This project is a starting point for a Flutter application. 8 | 9 | A few resources to get you started if this is your first Flutter project: 10 | 11 | - [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) 12 | - [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) 13 | 14 | For help getting started with Flutter development, view the 15 | [online documentation](https://docs.flutter.dev/), which offers tutorials, 16 | samples, guidance on mobile development, and a full API reference. 17 | -------------------------------------------------------------------------------- /example/windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/AppInfo.xcconfig: -------------------------------------------------------------------------------- 1 | // Application-level settings for the Runner target. 2 | // 3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the 4 | // future. If not, the values below would default to using the project name when this becomes a 5 | // 'flutter create' template. 6 | 7 | // The application's name. By default this is also the title of the Flutter window. 8 | PRODUCT_NAME = example 9 | 10 | // The application's bundle identifier 11 | PRODUCT_BUNDLE_IDENTIFIER = com.ugo.studio.plugins.example 12 | 13 | // The copyright displayed in application information 14 | PRODUCT_COPYRIGHT = Copyright © 2025 com.ugo.studio.plugins. All rights reserved. 15 | -------------------------------------------------------------------------------- /example/ios/.gitignore: -------------------------------------------------------------------------------- 1 | **/dgph 2 | *.mode1v3 3 | *.mode2v3 4 | *.moved-aside 5 | *.pbxuser 6 | *.perspectivev3 7 | **/*sync/ 8 | .sconsign.dblite 9 | .tags* 10 | **/.vagrant/ 11 | **/DerivedData/ 12 | Icon? 13 | **/Pods/ 14 | **/.symlinks/ 15 | profile 16 | xcuserdata 17 | **/.generated/ 18 | Flutter/App.framework 19 | Flutter/Flutter.framework 20 | Flutter/Flutter.podspec 21 | Flutter/Generated.xcconfig 22 | Flutter/ephemeral/ 23 | Flutter/app.flx 24 | Flutter/app.zip 25 | Flutter/flutter_assets/ 26 | Flutter/flutter_export_environment.sh 27 | ServiceDefinitions.json 28 | Runner/GeneratedPluginRegistrant.* 29 | 30 | # Exceptions to above rules. 31 | !default.mode1v3 32 | !default.mode2v3 33 | !default.pbxuser 34 | !default.perspectivev3 35 | -------------------------------------------------------------------------------- /windows/include/flutter_p2p_connection/flutter_p2p_connection_plugin_c_api.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_PLUGIN_FLUTTER_P2P_CONNECTION_PLUGIN_C_API_H_ 2 | #define FLUTTER_PLUGIN_FLUTTER_P2P_CONNECTION_PLUGIN_C_API_H_ 3 | 4 | #include 5 | 6 | #ifdef FLUTTER_PLUGIN_IMPL 7 | #define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) 8 | #else 9 | #define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) 10 | #endif 11 | 12 | #if defined(__cplusplus) 13 | extern "C" { 14 | #endif 15 | 16 | FLUTTER_PLUGIN_EXPORT void FlutterP2pConnectionPluginCApiRegisterWithRegistrar( 17 | FlutterDesktopPluginRegistrarRef registrar); 18 | 19 | #if defined(__cplusplus) 20 | } // extern "C" 21 | #endif 22 | 23 | #endif // FLUTTER_PLUGIN_FLUTTER_P2P_CONNECTION_PLUGIN_C_API_H_ 24 | -------------------------------------------------------------------------------- /example/windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 3.0.3 2 | 3 | use correct IP for file transfers 4 | 5 | ## 3.0.2 6 | 7 | improve connection stability and file sharing with port sharing 8 | 9 | ## 3.0.1 10 | 11 | feat: improve connection stability and file sharing 12 | 13 | - Set ping interval and disable idle timeout for servers. 14 | - Rewrote and expanded the project's documentation (`README.md`) to be more professional, detailed, and cover all functionalities. 15 | - Added a "Platform Support" section to clarify current (Android) and future platform targets. 16 | - Included a comprehensive "Troubleshooting" guide. 17 | - Added a "Migration Guide" for users upgrading from older versions. 18 | 19 | ## 3.0.0 20 | 21 | - Modernized API with Host/Client Roles, BLE Discovery, and Enhanced File Transfer!. 22 | 23 | ## 2.1.0 24 | 25 | - TODO: Fix create-group issue. 26 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | def flutterSdkPath = { 3 | def properties = new Properties() 4 | file("local.properties").withInputStream { properties.load(it) } 5 | def flutterSdkPath = properties.getProperty("flutter.sdk") 6 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties" 7 | return flutterSdkPath 8 | }() 9 | 10 | includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") 11 | 12 | repositories { 13 | google() 14 | mavenCentral() 15 | gradlePluginPortal() 16 | } 17 | } 18 | 19 | plugins { 20 | id "dev.flutter.flutter-plugin-loader" version "1.0.0" 21 | id "com.android.application" version "8.1.0" apply false 22 | id "org.jetbrains.kotlin.android" version "1.8.22" apply false 23 | } 24 | 25 | include ":app" 26 | -------------------------------------------------------------------------------- /example/linux/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | ) 7 | 8 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 9 | ) 10 | 11 | set(PLUGIN_BUNDLED_LIBRARIES) 12 | 13 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 14 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) 15 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 16 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 18 | endforeach(plugin) 19 | 20 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 21 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) 22 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 23 | endforeach(ffi_plugin) 24 | -------------------------------------------------------------------------------- /lib/src/transport/common/transport_enums.dart: -------------------------------------------------------------------------------- 1 | /// Enum representing the type of a P2P message. 2 | enum P2pMessageType { 3 | /// Message contains a data payload (text and/or files). 4 | payload, 5 | 6 | /// Message contains an updated list of connected clients. 7 | clientList, 8 | 9 | /// Message contains an update on file download progress. 10 | fileProgressUpdate, 11 | 12 | /// Message type is unknown or cannot be determined. 13 | unknown, 14 | } 15 | 16 | /// Enum representing the state of a file that can be received. 17 | enum ReceivableFileState { 18 | /// The file is available for download, but no download is in progress. 19 | idle, 20 | 21 | /// The file is currently being downloaded. 22 | downloading, 23 | 24 | /// The file download has completed successfully. 25 | completed, 26 | 27 | /// An error occurred during the file download. 28 | error, 29 | } 30 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | # The .vscode folder contains launch configuration and tasks you configure in 20 | # VS Code which you may wish to be included in version control, so this line 21 | # is commented out by default. 22 | #.vscode/ 23 | 24 | # Flutter/Dart/Pub related 25 | **/doc/api/ 26 | **/ios/Flutter/.last_build_id 27 | .dart_tool/ 28 | .flutter-plugins 29 | .flutter-plugins-dependencies 30 | .pub-cache/ 31 | .pub/ 32 | /build/ 33 | 34 | # Symbolication related 35 | app.*.symbols 36 | 37 | # Obfuscation related 38 | app.*.map.json 39 | 40 | # Android Studio will place build artifacts here 41 | /android/app/debug 42 | /android/app/profile 43 | /android/app/release 44 | 45 | /clean.sh -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | permission_handler_windows 7 | ) 8 | 9 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 10 | ) 11 | 12 | set(PLUGIN_BUNDLED_LIBRARIES) 13 | 14 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 15 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 16 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 19 | endforeach(plugin) 20 | 21 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 22 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) 23 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 24 | endforeach(ffi_plugin) 25 | -------------------------------------------------------------------------------- /example/ios/Flutter/AppFrameworkInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | App 9 | CFBundleIdentifier 10 | io.flutter.flutter.app 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | App 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1.0 23 | MinimumOSVersion 24 | 12.0 25 | 26 | 27 | -------------------------------------------------------------------------------- /lib/src/common/utils.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | Future getLocalIpAddress() async { 4 | try { 5 | // Get a list of all network interfaces 6 | // Setting includeLoopback to false filters out the loopback interface (127.0.0.1) 7 | // Setting internetAddressType to InternetAddressType.IPv4 ensures we only get IPv4 addresses 8 | final interfaces = await NetworkInterface.list( 9 | includeLoopback: false, type: InternetAddressType.IPv4); 10 | 11 | for (var interface in interfaces) { 12 | // The addresses property of a NetworkInterface object is a list of InternetAddress objects. 13 | for (var addr in interface.addresses) { 14 | // A non-loopback IPv4 address is a good candidate for the local network IP 15 | if (addr.address.startsWith('192.168.')) { 16 | return addr.address; 17 | } 18 | } 19 | } 20 | } catch (_) {} 21 | return null; 22 | } 23 | -------------------------------------------------------------------------------- /test/flutter_p2p_connection_method_channel_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/services.dart'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_p2p_connection/flutter_p2p_connection_method_channel.dart'; 4 | 5 | void main() { 6 | TestWidgetsFlutterBinding.ensureInitialized(); 7 | 8 | MethodChannelFlutterP2pConnection platform = MethodChannelFlutterP2pConnection(); 9 | const MethodChannel channel = MethodChannel('flutter_p2p_connection'); 10 | 11 | setUp(() { 12 | TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( 13 | channel, 14 | (MethodCall methodCall) async { 15 | return '42'; 16 | }, 17 | ); 18 | }); 19 | 20 | tearDown(() { 21 | TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, null); 22 | }); 23 | 24 | test('getPlatformVersion', () async { 25 | expect(await platform.getPlatformVersion(), '42'); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /example/test/widget_test.dart: -------------------------------------------------------------------------------- 1 | // This is a basic Flutter widget test. 2 | // 3 | // To perform an interaction with a widget in your test, use the WidgetTester 4 | // utility in the flutter_test package. For example, you can send tap and scroll 5 | // gestures. You can also use WidgetTester to find child widgets in the widget 6 | // tree, read text, and verify that the values of widget properties are correct. 7 | 8 | import 'package:flutter/material.dart'; 9 | import 'package:flutter_test/flutter_test.dart'; 10 | 11 | import 'package:flutter_p2p_connection_example/main.dart'; 12 | 13 | void main() { 14 | testWidgets('Verify Platform version', (WidgetTester tester) async { 15 | // Build our app and trigger a frame. 16 | await tester.pumpWidget(const MyApp()); 17 | 18 | // Verify that platform version is retrieved. 19 | expect( 20 | find.byWidgetPredicate( 21 | (Widget widget) => widget is Text && 22 | widget.data!.startsWith('Running on:'), 23 | ), 24 | findsOneWidget, 25 | ); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /example/integration_test/plugin_integration_test.dart: -------------------------------------------------------------------------------- 1 | // This is a basic Flutter integration test. 2 | // 3 | // Since integration tests run in a full Flutter application, they can interact 4 | // with the host side of a plugin implementation, unlike Dart unit tests. 5 | // 6 | // For more information about Flutter integration tests, please see 7 | // https://flutter.dev/to/integration-testing 8 | 9 | import 'package:flutter_test/flutter_test.dart'; 10 | import 'package:integration_test/integration_test.dart'; 11 | 12 | import 'package:flutter_p2p_connection/flutter_p2p_connection.dart'; 13 | 14 | void main() { 15 | IntegrationTestWidgetsFlutterBinding.ensureInitialized(); 16 | 17 | testWidgets('getDeviceModel test', (WidgetTester tester) async { 18 | final FlutterP2pClient plugin = FlutterP2pClient(); 19 | final String version = await plugin.getDeviceModel(); 20 | // The version string depends on the host platform running the test, so 21 | // just assert that some non-empty string is returned. 22 | expect(version.isNotEmpty, true); 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /example/web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "short_name": "example", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#0175C2", 7 | "theme_color": "#0175C2", 8 | "description": "A new Flutter project.", 9 | "orientation": "portrait-primary", 10 | "prefer_related_applications": false, 11 | "icons": [ 12 | { 13 | "src": "icons/Icon-192.png", 14 | "sizes": "192x192", 15 | "type": "image/png" 16 | }, 17 | { 18 | "src": "icons/Icon-512.png", 19 | "sizes": "512x512", 20 | "type": "image/png" 21 | }, 22 | { 23 | "src": "icons/Icon-maskable-192.png", 24 | "sizes": "192x192", 25 | "type": "image/png", 26 | "purpose": "maskable" 27 | }, 28 | { 29 | "src": "icons/Icon-maskable-512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "win32_window.h" 10 | 11 | // A window that does nothing but host a Flutter view. 12 | class FlutterWindow : public Win32Window { 13 | public: 14 | // Creates a new FlutterWindow hosting a Flutter view running |project|. 15 | explicit FlutterWindow(const flutter::DartProject& project); 16 | virtual ~FlutterWindow(); 17 | 18 | protected: 19 | // Win32Window: 20 | bool OnCreate() override; 21 | void OnDestroy() override; 22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 23 | LPARAM const lparam) noexcept override; 24 | 25 | private: 26 | // The project to run. 27 | flutter::DartProject project_; 28 | 29 | // The Flutter instance hosted by this window. 30 | std::unique_ptr flutter_controller_; 31 | }; 32 | 33 | #endif // RUNNER_FLUTTER_WINDOW_H_ 34 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values-night/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /windows/constants.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | namespace Constants { 5 | const std::string TAG = "FlutterP2pConnection"; 6 | 7 | // Method Channel 8 | const std::string METHOD_CHANNEL_NAME = "flutter_p2p_connection"; 9 | 10 | // Event Channels 11 | const std::string CLIENT_STATE_EVENT_CHANNEL_NAME = "flutter_p2p_connection_clientState"; 12 | const std::string HOTSPOT_STATE_EVENT_CHANNEL_NAME = "flutter_p2p_connection_hotspotState"; 13 | const std::string BLE_SCAN_RESULT_EVENT_CHANNEL_NAME = "flutter_p2p_connection_bleScanResult"; 14 | const std::string BLE_CONNECTION_STATE_EVENT_CHANNEL_NAME = "flutter_p2p_connection_bleConnectionState"; 15 | const std::string BLE_RECEIVED_DATA_EVENT_CHANNEL_NAME = "flutter_p2p_connection_bleReceivedData"; 16 | 17 | // BLE UUIDs 18 | const std::string BLE_CREDENTIAL_SERVICE_UUID = "0f0540bd-4a04-46d0-b90d-b0447453ec3a"; 19 | const std::string BLE_SSID_CHARACTERISTIC_UUID = "7a374008-fc31-4476-be4d-1b3347233f00"; 20 | const std::string BLE_PSK_CHARACTERISTIC_UUID = "81a5ec62-a8b1-48b0-b533-938636a57ba4"; 21 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 ugo-studio 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /windows/utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | namespace utils { 5 | // Converts a UTF-8 string to a UTF-16 wstring. 6 | inline std::wstring string_to_wstring(const std::string& str) { 7 | if (str.empty()) return std::wstring(); 8 | int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); 9 | std::wstring wstrTo(size_needed, 0); 10 | MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); 11 | return wstrTo; 12 | } 13 | 14 | // Converts a UTF-16 wstring to a UTF-8 string. 15 | inline std::string wstring_to_string(const std::wstring& wstr) { 16 | if (wstr.empty()) return std::string(); 17 | int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); 18 | std::string strTo(size_needed, 0); 19 | WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); 20 | return strTo; 21 | } 22 | 23 | inline winrt::guid guid_from_string(const std::string& guid_str) { 24 | return winrt::guid(string_to_wstring(guid_str)); 25 | } 26 | } -------------------------------------------------------------------------------- /windows/flutter_p2p_connection_plugin.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_PLUGIN_FLUTTER_P2P_CONNECTION_PLUGIN_H_ 2 | #define FLUTTER_PLUGIN_FLUTTER_P2P_CONNECTION_PLUGIN_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | namespace flutter_p2p_connection { 10 | 11 | class FlutterP2pConnectionPlugin : public flutter::Plugin { 12 | public: 13 | static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); 14 | 15 | FlutterP2pConnectionPlugin(); 16 | 17 | virtual ~FlutterP2pConnectionPlugin(); 18 | 19 | // Disallow copy and assign. 20 | FlutterP2pConnectionPlugin(const FlutterP2pConnectionPlugin&) = delete; 21 | FlutterP2pConnectionPlugin& operator=(const FlutterP2pConnectionPlugin&) = delete; 22 | 23 | // Called when a method is called on this plugin's channel from Dart. 24 | void HandleMethodCall( 25 | const flutter::MethodCall &method_call, 26 | std::unique_ptr> result); 27 | }; 28 | 29 | } // namespace flutter_p2p_connection 30 | 31 | #endif // FLUTTER_PLUGIN_FLUTTER_P2P_CONNECTION_PLUGIN_H_ 32 | -------------------------------------------------------------------------------- /android/src/test/kotlin/com/ugo/studio/plugins/flutter_p2p_connection/FlutterP2pConnectionPluginTest.kt: -------------------------------------------------------------------------------- 1 | package com.ugo.studio.plugins.flutter_p2p_connection 2 | 3 | import io.flutter.plugin.common.MethodCall 4 | import io.flutter.plugin.common.MethodChannel 5 | import kotlin.test.Test 6 | import org.mockito.Mockito 7 | 8 | /* 9 | * This demonstrates a simple unit test of the Kotlin portion of this plugin's implementation. 10 | * 11 | * Once you have built the plugin's example app, you can run these tests from the command 12 | * line by running `./gradlew testDebugUnitTest` in the `example/android/` directory, or 13 | * you can run them directly from IDEs that support JUnit such as Android Studio. 14 | */ 15 | 16 | internal class FlutterP2pConnectionPluginTest { 17 | @Test 18 | fun onMethodCall_getPlatformVersion_returnsExpectedValue() { 19 | val plugin = FlutterP2pConnectionPlugin() 20 | 21 | val call = MethodCall("getPlatformVersion", null) 22 | val mockResult: MethodChannel.Result = Mockito.mock(MethodChannel.Result::class.java) 23 | plugin.onMethodCall(call, mockResult) 24 | 25 | Mockito.verify(mockResult).success("Android " + android.os.Build.VERSION.RELEASE) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /example/macos/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | $(PRODUCT_COPYRIGHT) 27 | NSMainNibFile 28 | MainMenu 29 | NSPrincipalClass 30 | NSApplication 31 | 32 | 33 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: "2663184aa79047d0a33a14a3b607954f8fdd8730" 8 | channel: "stable" 9 | 10 | project_type: plugin 11 | 12 | # Tracks metadata for the flutter migrate command 13 | migration: 14 | platforms: 15 | - platform: root 16 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 17 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 18 | - platform: android 19 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 20 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 21 | - platform: windows 22 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 23 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 24 | 25 | # User provided section 26 | 27 | # List of Local paths (relative to this file) that should be 28 | # ignored by the migrate tool. 29 | # 30 | # Files that are not part of the templates will be ignored by default. 31 | unmanaged_files: 32 | - 'lib/main.dart' 33 | - 'ios/Runner.xcodeproj/project.pbxproj' 34 | -------------------------------------------------------------------------------- /windows/pch.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // Standard Library 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | // Windows & COM 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | // Flutter 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include -------------------------------------------------------------------------------- /example/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | example 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /windows/test/flutter_p2p_connection_plugin_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include "flutter_p2p_connection_plugin.h" 12 | 13 | namespace flutter_p2p_connection { 14 | namespace test { 15 | 16 | namespace { 17 | 18 | using flutter::EncodableMap; 19 | using flutter::EncodableValue; 20 | using flutter::MethodCall; 21 | using flutter::MethodResultFunctions; 22 | 23 | } // namespace 24 | 25 | TEST(FlutterP2pConnectionPlugin, GetPlatformVersion) { 26 | FlutterP2pConnectionPlugin plugin; 27 | // Save the reply value from the success callback. 28 | std::string result_string; 29 | plugin.HandleMethodCall( 30 | MethodCall("getPlatformVersion", std::make_unique()), 31 | std::make_unique>( 32 | [&result_string](const EncodableValue* result) { 33 | result_string = std::get(*result); 34 | }, 35 | nullptr, nullptr)); 36 | 37 | // Since the exact string varies by host, just ensure that it's a string 38 | // with the expected format. 39 | EXPECT_TRUE(result_string.rfind("Windows ", 0) == 0); 40 | } 41 | 42 | } // namespace test 43 | } // namespace flutter_p2p_connection 44 | -------------------------------------------------------------------------------- /test/flutter_p2p_connection_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter_test/flutter_test.dart'; 2 | import 'package:flutter_p2p_connection/flutter_p2p_connection.dart'; 3 | import 'package:flutter_p2p_connection/flutter_p2p_connection_platform_interface.dart'; 4 | import 'package:flutter_p2p_connection/flutter_p2p_connection_method_channel.dart'; 5 | import 'package:plugin_platform_interface/plugin_platform_interface.dart'; 6 | 7 | class MockFlutterP2pConnectionPlatform 8 | with MockPlatformInterfaceMixin 9 | implements FlutterP2pConnectionPlatform { 10 | @override 11 | Future getPlatformVersion() => Future.value('42'); 12 | 13 | @override 14 | dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); 15 | } 16 | 17 | void main() { 18 | final FlutterP2pConnectionPlatform initialPlatform = 19 | FlutterP2pConnectionPlatform.instance; 20 | 21 | test('$MethodChannelFlutterP2pConnection is the default instance', () { 22 | expect(initialPlatform, isInstanceOf()); 23 | }); 24 | 25 | test('getDeviceModel', () async { 26 | FlutterP2pClient flutterP2pConnectionPlugin = FlutterP2pClient(); 27 | MockFlutterP2pConnectionPlatform fakePlatform = 28 | MockFlutterP2pConnectionPlatform(); 29 | FlutterP2pConnectionPlatform.instance = fakePlatform; 30 | 31 | expect(await flutterP2pConnectionPlugin.getDeviceModel(), 'Test Model'); 32 | }); 33 | } 34 | -------------------------------------------------------------------------------- /example/windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "utils.h" 7 | 8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 9 | _In_ wchar_t *command_line, _In_ int show_command) { 10 | // Attach to console when present (e.g., 'flutter run') or create a 11 | // new console when running with a debugger. 12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 13 | CreateAndAttachConsole(); 14 | } 15 | 16 | // Initialize COM, so that it is available for use in the library and/or 17 | // plugins. 18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 19 | 20 | flutter::DartProject project(L"data"); 21 | 22 | std::vector command_line_arguments = 23 | GetCommandLineArguments(); 24 | 25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 26 | 27 | FlutterWindow window(project); 28 | Win32Window::Point origin(10, 10); 29 | Win32Window::Size size(1280, 720); 30 | if (!window.Create(L"example", origin, size)) { 31 | return EXIT_FAILURE; 32 | } 33 | window.SetQuitOnClose(true); 34 | 35 | ::MSG msg; 36 | while (::GetMessage(&msg, nullptr, 0, 0)) { 37 | ::TranslateMessage(&msg); 38 | ::DispatchMessage(&msg); 39 | } 40 | 41 | ::CoUninitialize(); 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /lib/flutter_p2p_connection.dart: -------------------------------------------------------------------------------- 1 | /// A Flutter plugin for establishing peer-to-peer connections 2 | /// using Wi-Fi Direct (Group Owner/Hotspot) and BLE for discovery and credential exchange. 3 | /// 4 | /// This library provides classes to act as a P2P host (`FlutterP2pHost`) 5 | /// or a P2P client (`FlutterP2pClient`), along with necessary data models 6 | /// for managing connection states, discovered devices, and data transfer. 7 | library flutter_p2p_connection; 8 | 9 | // Export common P2P functionalities (Host and Client) 10 | export 'src/host/p2p_host.dart' show FlutterP2pHost; 11 | export 'src/client/p2p_client.dart' show FlutterP2pClient; 12 | 13 | // Export data models related to P2P connection states and BLE 14 | export 'src/models/p2p_connection_models.dart' 15 | show 16 | HotspotHostState, 17 | HotspotClientState, 18 | BleConnectionState, 19 | BleDiscoveredDevice, 20 | BleReceivedData; 21 | 22 | // Export data models and enums related to the P2P transport layer 23 | export 'src/transport/common/transport_enums.dart' 24 | show P2pMessageType, ReceivableFileState; 25 | export 'src/transport/common/transport_data_models.dart' 26 | show 27 | P2pClientInfo, 28 | P2pFileInfo, 29 | P2pMessagePayload, 30 | P2pFileProgressUpdate, 31 | P2pMessage; 32 | export 'src/transport/common/transport_file_models.dart' 33 | show HostedFileInfo, ReceivableFileInfo, FileDownloadProgressUpdate; 34 | -------------------------------------------------------------------------------- /example/lib/qr/qr_image_page.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:flutter/material.dart'; 4 | import 'package:flutter_p2p_connection/flutter_p2p_connection.dart'; 5 | import 'package:pretty_qr_code/pretty_qr_code.dart'; 6 | 7 | class QrImagePage extends StatefulWidget { 8 | final HotspotHostState? hotspotState; 9 | const QrImagePage({ 10 | super.key, 11 | required this.hotspotState, 12 | }); 13 | 14 | @override 15 | State createState() => _QrImagePageState(); 16 | } 17 | 18 | class _QrImagePageState extends State { 19 | QrImage? qrImage; 20 | 21 | @override 22 | void initState() { 23 | super.initState(); 24 | 25 | String? ssid = widget.hotspotState?.ssid; 26 | String? preSharedKey = widget.hotspotState?.preSharedKey; 27 | 28 | // generate qrcode 29 | if (ssid != null && preSharedKey != null) { 30 | QrCode qrCode = QrCode(8, QrErrorCorrectLevel.H); 31 | qrCode.addData(jsonEncode({'ssid': ssid, 'preSharedKey': preSharedKey})); 32 | qrImage = QrImage(qrCode); 33 | } 34 | } 35 | 36 | @override 37 | Widget build(BuildContext context) { 38 | return Scaffold( 39 | appBar: AppBar( 40 | title: const Text('qr image'), 41 | ), 42 | body: Center( 43 | child: qrImage != null 44 | ? SizedBox( 45 | width: 300, 46 | child: PrettyQrView(qrImage: qrImage!), 47 | ) 48 | : const Text("no qr code"), 49 | ), 50 | ); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /example/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at https://dart.dev/lints. 17 | # 18 | # Instead of disabling a lint rule for the entire project in the 19 | # section below, it can also be suppressed for a single line of code 20 | # or a specific dart file by using the `// ignore: name_of_lint` and 21 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 22 | # producing the lint. 23 | rules: 24 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 25 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 26 | 27 | # Additional information about this file can be found at 28 | # https://dart.dev/guides/language/analysis-options 29 | -------------------------------------------------------------------------------- /example/macos/Podfile: -------------------------------------------------------------------------------- 1 | platform :osx, '10.14' 2 | 3 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency. 4 | ENV['COCOAPODS_DISABLE_STATS'] = 'true' 5 | 6 | project 'Runner', { 7 | 'Debug' => :debug, 8 | 'Profile' => :release, 9 | 'Release' => :release, 10 | } 11 | 12 | def flutter_root 13 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) 14 | unless File.exist?(generated_xcode_build_settings_path) 15 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" 16 | end 17 | 18 | File.foreach(generated_xcode_build_settings_path) do |line| 19 | matches = line.match(/FLUTTER_ROOT\=(.*)/) 20 | return matches[1].strip if matches 21 | end 22 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" 23 | end 24 | 25 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) 26 | 27 | flutter_macos_podfile_setup 28 | 29 | target 'Runner' do 30 | use_frameworks! 31 | 32 | flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) 33 | target 'RunnerTests' do 34 | inherit! :search_paths 35 | end 36 | end 37 | 38 | post_install do |installer| 39 | installer.pods_project.targets.each do |target| 40 | flutter_additional_macos_build_settings(target) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /android/src/main/kotlin/com/ugo/studio/plugins/flutter_p2p_connection/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.ugo.studio.plugins.flutter_p2p_connection 2 | 3 | import android.os.Build 4 | import java.util.UUID 5 | 6 | object Constants { 7 | const val TAG = "FlutterP2pConnection" 8 | 9 | // Method Channel 10 | const val METHOD_CHANNEL_NAME = "flutter_p2p_connection" 11 | 12 | // Event Channels 13 | const val CLIENT_STATE_EVENT_CHANNEL_NAME = "flutter_p2p_connection_clientState" 14 | const val HOTSPOT_STATE_EVENT_CHANNEL_NAME = "flutter_p2p_connection_hotspotState" 15 | const val BLE_SCAN_RESULT_EVENT_CHANNEL_NAME = "flutter_p2p_connection_bleScanResult" 16 | const val BLE_CONNECTION_STATE_EVENT_CHANNEL_NAME = "flutter_p2p_connection_bleConnectionState" 17 | const val BLE_RECEIVED_DATA_EVENT_CHANNEL_NAME = "flutter_p2p_connection_bleReceivedData" 18 | 19 | // Permission Request Codes 20 | const val LOCATION_PERMISSION_REQUEST_CODE = 2468 21 | // const val ENABLE_BLUETOOTH_REQUEST_CODE = 2469 // Keep if used internally by ServiceManager 22 | 23 | // API Level Checks 24 | const val MIN_HOTSPOT_API_LEVEL = Build.VERSION_CODES.O 25 | 26 | // BLE Specific 27 | // Generate a unique UUID for your application's service 28 | val BLE_CREDENTIAL_SERVICE_UUID: UUID = UUID.fromString("0f0540bd-4a04-46d0-b90d-b0447453ec3a") 29 | val BLE_SSID_CHARACTERISTIC_UUID: UUID = UUID.fromString("7a374008-fc31-4476-be4d-1b3347233f00") 30 | val BLE_PSK_CHARACTERISTIC_UUID: UUID = UUID.fromString("81a5ec62-a8b1-48b0-b533-938636a57ba4") 31 | 32 | } -------------------------------------------------------------------------------- /example/ios/Podfile: -------------------------------------------------------------------------------- 1 | # Uncomment this line to define a global platform for your project 2 | # platform :ios, '12.0' 3 | 4 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency. 5 | ENV['COCOAPODS_DISABLE_STATS'] = 'true' 6 | 7 | project 'Runner', { 8 | 'Debug' => :debug, 9 | 'Profile' => :release, 10 | 'Release' => :release, 11 | } 12 | 13 | def flutter_root 14 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) 15 | unless File.exist?(generated_xcode_build_settings_path) 16 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" 17 | end 18 | 19 | File.foreach(generated_xcode_build_settings_path) do |line| 20 | matches = line.match(/FLUTTER_ROOT\=(.*)/) 21 | return matches[1].strip if matches 22 | end 23 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" 24 | end 25 | 26 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) 27 | 28 | flutter_ios_podfile_setup 29 | 30 | target 'Runner' do 31 | use_frameworks! 32 | 33 | flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) 34 | target 'RunnerTests' do 35 | inherit! :search_paths 36 | end 37 | end 38 | 39 | post_install do |installer| 40 | installer.pods_project.targets.each do |target| 41 | flutter_additional_ios_build_settings(target) 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "app_icon_16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "app_icon_32.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "app_icon_32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "app_icon_64.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "app_icon_128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "app_icon_256.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "app_icon_256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "app_icon_512.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "app_icon_512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "app_icon_1024.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.android.application" 3 | id "kotlin-android" 4 | // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. 5 | id "dev.flutter.flutter-gradle-plugin" 6 | } 7 | 8 | android { 9 | namespace = "com.ugo.studio.plugins.flutter_p2p_connection_example" 10 | // compileSdk = flutter.compileSdkVersion 11 | compileSdk = 36 12 | ndkVersion = flutter.ndkVersion 13 | 14 | compileOptions { 15 | sourceCompatibility = JavaVersion.VERSION_1_8 16 | targetCompatibility = JavaVersion.VERSION_1_8 17 | } 18 | 19 | kotlinOptions { 20 | jvmTarget = JavaVersion.VERSION_1_8 21 | } 22 | 23 | defaultConfig { 24 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). 25 | applicationId = "com.ugo.studio.plugins.flutter_p2p_connection_example" 26 | // You can update the following values to match your application needs. 27 | // For more information, see: https://flutter.dev/to/review-gradle-config. 28 | // minSdk = flutter.minSdkVersion 29 | minSdk = 21 30 | // targetSdk = flutter.targetSdkVersion 31 | targetSdk = 31 32 | versionCode = flutter.versionCode 33 | versionName = flutter.versionName 34 | } 35 | 36 | buildTypes { 37 | release { 38 | // TODO: Add your own signing config for the release build. 39 | // Signing with the debug keys for now, so `flutter run --release` works. 40 | signingConfig = signingConfigs.debug 41 | } 42 | } 43 | } 44 | 45 | flutter { 46 | source = "../.." 47 | } 48 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/ios/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleDisplayName 8 | Example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | example 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(FLUTTER_BUILD_NUMBER) 25 | LSRequiresIPhoneOS 26 | 27 | UILaunchStoryboardName 28 | LaunchScreen 29 | UIMainStoryboardFile 30 | Main 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | CADisableMinimumFrameDurationOnPhone 45 | 46 | UIApplicationSupportsIndirectInputEvents 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /example/.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: "2663184aa79047d0a33a14a3b607954f8fdd8730" 8 | channel: "stable" 9 | 10 | project_type: app 11 | 12 | # Tracks metadata for the flutter migrate command 13 | migration: 14 | platforms: 15 | - platform: root 16 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 17 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 18 | - platform: android 19 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 20 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 21 | - platform: ios 22 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 23 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 24 | - platform: linux 25 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 26 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 27 | - platform: macos 28 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 29 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 30 | - platform: web 31 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 32 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 33 | - platform: windows 34 | create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 35 | base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 36 | 37 | # User provided section 38 | 39 | # List of Local paths (relative to this file) that should be 40 | # ignored by the migrate tool. 41 | # 42 | # Files that are not part of the templates will be ignored by default. 43 | unmanaged_files: 44 | - 'lib/main.dart' 45 | - 'ios/Runner.xcodeproj/project.pbxproj' 46 | -------------------------------------------------------------------------------- /example/windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | # Define the application target. To change its name, change BINARY_NAME in the 5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer 6 | # work. 7 | # 8 | # Any new source files that you add to the application should be added here. 9 | add_executable(${BINARY_NAME} WIN32 10 | "flutter_window.cpp" 11 | "main.cpp" 12 | "utils.cpp" 13 | "win32_window.cpp" 14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 15 | "Runner.rc" 16 | "runner.exe.manifest" 17 | ) 18 | 19 | # Apply the standard set of build settings. This can be removed for applications 20 | # that need different build settings. 21 | apply_standard_settings(${BINARY_NAME}) 22 | 23 | # Add preprocessor definitions for the build version. 24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") 25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") 26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") 27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") 28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") 29 | 30 | # Disable Windows macros that collide with C++ standard library functions. 31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 32 | 33 | # Add dependency libraries and include directories. Add any application-specific 34 | # dependencies here. 35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 36 | target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") 37 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 38 | 39 | # Run the Flutter tool portions of the build. This must not be removed. 40 | add_dependencies(${BINARY_NAME} flutter_assemble) 41 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | group = "com.ugo.studio.plugins.flutter_p2p_connection" 2 | version = "1.0-SNAPSHOT" 3 | 4 | buildscript { 5 | ext.kotlin_version = "1.8.22" 6 | repositories { 7 | google() 8 | mavenCentral() 9 | } 10 | 11 | dependencies { 12 | classpath("com.android.tools.build:gradle:8.1.0") 13 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | mavenCentral() 21 | } 22 | } 23 | 24 | apply plugin: "com.android.library" 25 | apply plugin: "kotlin-android" 26 | 27 | android { 28 | if (project.android.hasProperty("namespace")) { 29 | namespace = "com.ugo.studio.plugins.flutter_p2p_connection" 30 | } 31 | 32 | compileSdk = 34 33 | 34 | compileOptions { 35 | sourceCompatibility = JavaVersion.VERSION_1_8 36 | targetCompatibility = JavaVersion.VERSION_1_8 37 | } 38 | 39 | kotlinOptions { 40 | jvmTarget = JavaVersion.VERSION_1_8 41 | } 42 | 43 | sourceSets { 44 | main.java.srcDirs += "src/main/kotlin" 45 | test.java.srcDirs += "src/test/kotlin" 46 | } 47 | 48 | defaultConfig { 49 | minSdk = 21 50 | } 51 | 52 | dependencies { 53 | testImplementation("org.jetbrains.kotlin:kotlin-test") 54 | testImplementation("org.mockito:mockito-core:5.0.0") 55 | 56 | implementation "androidx.lifecycle:lifecycle-common-java8:2.7.0" 57 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" 58 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3" 59 | } 60 | 61 | testOptions { 62 | unitTests.all { 63 | useJUnitPlatform() 64 | 65 | testLogging { 66 | events "passed", "skipped", "failed", "standardOut", "standardError" 67 | outputs.upToDateWhen {false} 68 | showStandardStreams = true 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /example/windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | unsigned int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr) 51 | -1; // remove the trailing null character 52 | int input_length = (int)wcslen(utf16_string); 53 | std::string utf8_string; 54 | if (target_length == 0 || target_length > utf8_string.max_size()) { 55 | return utf8_string; 56 | } 57 | utf8_string.resize(target_length); 58 | int converted_length = ::WideCharToMultiByte( 59 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 60 | input_length, utf8_string.data(), target_length, nullptr, nullptr); 61 | if (converted_length == 0) { 62 | return std::string(); 63 | } 64 | return utf8_string; 65 | } 66 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project) 8 | : project_(project) {} 9 | 10 | FlutterWindow::~FlutterWindow() {} 11 | 12 | bool FlutterWindow::OnCreate() { 13 | if (!Win32Window::OnCreate()) { 14 | return false; 15 | } 16 | 17 | RECT frame = GetClientArea(); 18 | 19 | // The size here must match the window dimensions to avoid unnecessary surface 20 | // creation / destruction in the startup path. 21 | flutter_controller_ = std::make_unique( 22 | frame.right - frame.left, frame.bottom - frame.top, project_); 23 | // Ensure that basic setup of the controller was successful. 24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 25 | return false; 26 | } 27 | RegisterPlugins(flutter_controller_->engine()); 28 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 29 | 30 | flutter_controller_->engine()->SetNextFrameCallback([&]() { 31 | this->Show(); 32 | }); 33 | 34 | // Flutter can complete the first frame before the "show window" callback is 35 | // registered. The following call ensures a frame is pending to ensure the 36 | // window is shown. It is a no-op if the first frame hasn't completed yet. 37 | flutter_controller_->ForceRedraw(); 38 | 39 | return true; 40 | } 41 | 42 | void FlutterWindow::OnDestroy() { 43 | if (flutter_controller_) { 44 | flutter_controller_ = nullptr; 45 | } 46 | 47 | Win32Window::OnDestroy(); 48 | } 49 | 50 | LRESULT 51 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 52 | WPARAM const wparam, 53 | LPARAM const lparam) noexcept { 54 | // Give Flutter, including plugins, an opportunity to handle window messages. 55 | if (flutter_controller_) { 56 | std::optional result = 57 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 58 | lparam); 59 | if (result) { 60 | return *result; 61 | } 62 | } 63 | 64 | switch (message) { 65 | case WM_FONTCHANGE: 66 | flutter_controller_->engine()->ReloadSystemFonts(); 67 | break; 68 | } 69 | 70 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 71 | } 72 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /windows/flutter_p2p_connection_plugin.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "flutter_p2p_connection_plugin.h" 3 | #include "constants.h" 4 | #include "utils.h" 5 | 6 | namespace flutter_p2p_connection { 7 | 8 | void FlutterP2pConnectionPlugin::RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar) { 9 | auto plugin = std::make_unique(registrar); 10 | auto channel = std::make_unique>( 11 | registrar->messenger(), Constants::METHOD_CHANNEL_NAME, 12 | &flutter::StandardMethodCodec::GetInstance()); 13 | 14 | channel->SetMethodCallHandler( 15 | [plugin_pointer = plugin.get()](const auto& call, auto result) { 16 | plugin_pointer->HandleMethodCall(call, std::move(result)); 17 | }); 18 | 19 | registrar->AddPlugin(std::move(plugin)); 20 | } 21 | 22 | FlutterP2pConnectionPlugin::FlutterP2pConnectionPlugin(flutter::PluginRegistrarWindows* registrar) 23 | : registrar_(registrar) { 24 | // Initialize COM for WinRT and other COM-based APIs on this thread. 25 | winrt::init_apartment(); 26 | 27 | // TODO: Instantiate manager classes here, passing the registrar or messenger 28 | // service_manager_ = std::make_unique(registrar); 29 | // ble_manager_ = std::make_unique(registrar); 30 | } 31 | 32 | FlutterP2pConnectionPlugin::~FlutterP2pConnectionPlugin() { 33 | // TODO: Clean up resources if needed 34 | // ble_manager_->Dispose(); 35 | winrt::uninit_apartment(); 36 | } 37 | 38 | void FlutterP2pConnectionPlugin::HandleMethodCall( 39 | const flutter::MethodCall& method_call, 40 | std::unique_ptr> result) { 41 | 42 | const std::string& method = method_call.method_name(); 43 | 44 | if (method == "getPlatformVersion") { 45 | OSVERSIONINFOEXW os_info = { sizeof(os_info) }; 46 | if (RtlGetVersion(&os_info) == 0) { 47 | std::wstringstream ss; 48 | ss << L"Windows " << os_info.dwMajorVersion << L"." << os_info.dwMinorVersion << L" Build " << os_info.dwBuildNumber; 49 | result->Success(flutter::EncodableValue(utils::wstring_to_string(ss.str()))); 50 | } else { 51 | result->Error("VERSION_ERROR", "Failed to get Windows version."); 52 | } 53 | } 54 | // TODO: Route method calls to the appropriate manager class 55 | /* 56 | else if (method == "checkBluetoothEnabled") { 57 | service_manager_->CheckBluetoothEnabled(std::move(result)); 58 | } 59 | else if (method.rfind("ble#", 0) == 0) { 60 | ble_manager_->HandleMethodCall(method, method_call.arguments(), std::move(result)); 61 | } 62 | */ 63 | else { 64 | result->NotImplemented(); 65 | } 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: flutter_p2p_connection 2 | description: A WiFi Direct Plugin for Flutter. 3 | version: 3.0.3 4 | homepage: https://github.com/ugo-studio/flutter_p2p_connection.git 5 | repository: https://github.com/ugo-studio/flutter_p2p_connection 6 | issue_tracker: https://github.com/ugo-studio/flutter_p2p_connection/issues 7 | 8 | environment: 9 | sdk: ^3.5.0 10 | flutter: '>=3.3.0' 11 | 12 | dependencies: 13 | flutter: 14 | sdk: flutter 15 | plugin_platform_interface: ^2.0.2 16 | permission_handler: ^11.3.1 17 | uuid: ^4.5.1 18 | http: ^1.4.0 19 | path: ^1.9.0 20 | 21 | dev_dependencies: 22 | flutter_test: 23 | sdk: flutter 24 | flutter_lints: ^4.0.0 25 | 26 | # For information on the generic Dart part of this file, see the 27 | # following page: https://dart.dev/tools/pub/pubspec 28 | 29 | # The following section is specific to Flutter packages. 30 | flutter: 31 | # This section identifies this Flutter project as a plugin project. 32 | # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) 33 | # which should be registered in the plugin registry. This is required for 34 | # using method channels. 35 | # The Android 'package' specifies package in which the registered class is. 36 | # This is required for using method channels on Android. 37 | # The 'ffiPlugin' specifies that native code should be built and bundled. 38 | # This is required for using `dart:ffi`. 39 | # All these are used by the tooling to maintain consistency when 40 | # adding or updating assets for this project. 41 | plugin: 42 | platforms: 43 | android: 44 | package: com.ugo.studio.plugins.flutter_p2p_connection 45 | pluginClass: FlutterP2pConnectionPlugin 46 | # windows: 47 | # package: com.ugo.studio.plugins.flutter_p2p_connection 48 | # pluginClass: FlutterP2pConnectionPluginCApi 49 | 50 | # To add assets to your plugin package, add an assets section, like this: 51 | # assets: 52 | # - images/a_dot_burr.jpeg 53 | # - images/a_dot_ham.jpeg 54 | # 55 | # For details regarding assets in packages, see 56 | # https://flutter.dev/to/asset-from-package 57 | # 58 | # An image asset can refer to one or more resolution-specific "variants", see 59 | # https://flutter.dev/to/resolution-aware-images 60 | 61 | # To add custom fonts to your plugin package, add a fonts section here, 62 | # in this "flutter" section. Each entry in this list should have a 63 | # "family" key with the font family name, and a "fonts" key with a 64 | # list giving the asset and other descriptors for the font. For 65 | # example: 66 | # fonts: 67 | # - family: Schyler 68 | # fonts: 69 | # - asset: fonts/Schyler-Regular.ttf 70 | # - asset: fonts/Schyler-Italic.ttf 71 | # style: italic 72 | # - family: Trajan Pro 73 | # fonts: 74 | # - asset: fonts/TrajanPro.ttf 75 | # - asset: fonts/TrajanPro_Bold.ttf 76 | # weight: 700 77 | # 78 | # For details regarding fonts in packages, see 79 | # https://flutter.dev/to/font-from-package 80 | -------------------------------------------------------------------------------- /example/linux/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.10) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | 12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...), 13 | # which isn't available in 3.10. 14 | function(list_prepend LIST_NAME PREFIX) 15 | set(NEW_LIST "") 16 | foreach(element ${${LIST_NAME}}) 17 | list(APPEND NEW_LIST "${PREFIX}${element}") 18 | endforeach(element) 19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) 20 | endfunction() 21 | 22 | # === Flutter Library === 23 | # System-level dependencies. 24 | find_package(PkgConfig REQUIRED) 25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) 27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) 28 | 29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") 30 | 31 | # Published to parent scope for install step. 32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) 36 | 37 | list(APPEND FLUTTER_LIBRARY_HEADERS 38 | "fl_basic_message_channel.h" 39 | "fl_binary_codec.h" 40 | "fl_binary_messenger.h" 41 | "fl_dart_project.h" 42 | "fl_engine.h" 43 | "fl_json_message_codec.h" 44 | "fl_json_method_codec.h" 45 | "fl_message_codec.h" 46 | "fl_method_call.h" 47 | "fl_method_channel.h" 48 | "fl_method_codec.h" 49 | "fl_method_response.h" 50 | "fl_plugin_registrar.h" 51 | "fl_plugin_registry.h" 52 | "fl_standard_message_codec.h" 53 | "fl_standard_method_codec.h" 54 | "fl_string_codec.h" 55 | "fl_value.h" 56 | "fl_view.h" 57 | "flutter_linux.h" 58 | ) 59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") 60 | add_library(flutter INTERFACE) 61 | target_include_directories(flutter INTERFACE 62 | "${EPHEMERAL_DIR}" 63 | ) 64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") 65 | target_link_libraries(flutter INTERFACE 66 | PkgConfig::GTK 67 | PkgConfig::GLIB 68 | PkgConfig::GIO 69 | ) 70 | add_dependencies(flutter flutter_assemble) 71 | 72 | # === Flutter tool backend === 73 | # _phony_ is a non-existent file to force this command to run every time, 74 | # since currently there's no way to get a full input/output list from the 75 | # flutter tool. 76 | add_custom_command( 77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_ 79 | COMMAND ${CMAKE_COMMAND} -E env 80 | ${FLUTTER_TOOL_ENVIRONMENT} 81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" 82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} 83 | VERBATIM 84 | ) 85 | add_custom_target(flutter_assemble DEPENDS 86 | "${FLUTTER_LIBRARY}" 87 | ${FLUTTER_LIBRARY_HEADERS} 88 | ) 89 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "Icon-App-20x20@2x.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "Icon-App-20x20@3x.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "Icon-App-29x29@1x.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "Icon-App-29x29@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "29x29", 29 | "idiom" : "iphone", 30 | "filename" : "Icon-App-29x29@3x.png", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "Icon-App-40x40@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "40x40", 41 | "idiom" : "iphone", 42 | "filename" : "Icon-App-40x40@3x.png", 43 | "scale" : "3x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "Icon-App-60x60@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "60x60", 53 | "idiom" : "iphone", 54 | "filename" : "Icon-App-60x60@3x.png", 55 | "scale" : "3x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "Icon-App-20x20@1x.png", 61 | "scale" : "1x" 62 | }, 63 | { 64 | "size" : "20x20", 65 | "idiom" : "ipad", 66 | "filename" : "Icon-App-20x20@2x.png", 67 | "scale" : "2x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "Icon-App-29x29@1x.png", 73 | "scale" : "1x" 74 | }, 75 | { 76 | "size" : "29x29", 77 | "idiom" : "ipad", 78 | "filename" : "Icon-App-29x29@2x.png", 79 | "scale" : "2x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "Icon-App-40x40@1x.png", 85 | "scale" : "1x" 86 | }, 87 | { 88 | "size" : "40x40", 89 | "idiom" : "ipad", 90 | "filename" : "Icon-App-40x40@2x.png", 91 | "scale" : "2x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "Icon-App-76x76@1x.png", 97 | "scale" : "1x" 98 | }, 99 | { 100 | "size" : "76x76", 101 | "idiom" : "ipad", 102 | "filename" : "Icon-App-76x76@2x.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "83.5x83.5", 107 | "idiom" : "ipad", 108 | "filename" : "Icon-App-83.5x83.5@2x.png", 109 | "scale" : "2x" 110 | }, 111 | { 112 | "size" : "1024x1024", 113 | "idiom" : "ios-marketing", 114 | "filename" : "Icon-App-1024x1024@1x.png", 115 | "scale" : "1x" 116 | } 117 | ], 118 | "info" : { 119 | "version" : 1, 120 | "author" : "xcode" 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /example/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter_p2p_connection_example/client.dart'; 3 | import 'package:flutter_p2p_connection_example/host.dart'; 4 | 5 | void main() { 6 | runApp(const MyApp()); 7 | } 8 | 9 | class MyApp extends StatelessWidget { 10 | const MyApp({super.key}); 11 | 12 | @override 13 | Widget build(BuildContext context) { 14 | return const MaterialApp( 15 | home: MyHomePage(), 16 | ); 17 | } 18 | } 19 | 20 | class MyHomePage extends StatefulWidget { 21 | const MyHomePage({super.key}); 22 | 23 | @override 24 | State createState() => _MyHomePageState(); 25 | } 26 | 27 | class _MyHomePageState extends State { 28 | @override 29 | Widget build(BuildContext context) { 30 | return Scaffold( 31 | appBar: AppBar( 32 | title: const Text('Flutter p2p connection plugin'), 33 | ), 34 | body: SingleChildScrollView( 35 | physics: const BouncingScrollPhysics(), 36 | child: Column( 37 | mainAxisAlignment: MainAxisAlignment.center, 38 | crossAxisAlignment: CrossAxisAlignment.center, 39 | children: [ 40 | // host 41 | const SizedBox(height: 30), 42 | GestureDetector( 43 | onTap: () { 44 | Navigator.push( 45 | context, 46 | MaterialPageRoute( 47 | builder: (context) => const HostPage(), 48 | ), 49 | ); 50 | }, 51 | child: Container( 52 | height: 150, 53 | width: MediaQuery.of(context).size.width, 54 | decoration: BoxDecoration( 55 | borderRadius: BorderRadius.circular(10), 56 | color: Colors.blue, 57 | ), 58 | child: const Center( 59 | child: Text( 60 | 'HOST', 61 | style: TextStyle( 62 | fontWeight: FontWeight.w800, 63 | fontSize: 30, 64 | ), 65 | ), 66 | ), 67 | ), 68 | ), 69 | 70 | // client 71 | const SizedBox(height: 30), 72 | GestureDetector( 73 | onTap: () { 74 | Navigator.push( 75 | context, 76 | MaterialPageRoute( 77 | builder: (context) => const ClientPage(), 78 | ), 79 | ); 80 | }, 81 | child: Container( 82 | height: 150, 83 | width: MediaQuery.of(context).size.width, 84 | decoration: BoxDecoration( 85 | borderRadius: BorderRadius.circular(10), 86 | color: Colors.red, 87 | ), 88 | child: const Center( 89 | child: Text( 90 | 'CLIENT', 91 | style: TextStyle( 92 | fontWeight: FontWeight.w800, 93 | fontSize: 30, 94 | ), 95 | ), 96 | ), 97 | ), 98 | ), 99 | ], 100 | ), 101 | ), 102 | ); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /example/windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) 64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0,0 67 | #endif 68 | 69 | #if defined(FLUTTER_VERSION) 70 | #define VERSION_AS_STRING FLUTTER_VERSION 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.ugo.studio.plugins" "\0" 93 | VALUE "FileDescription", "example" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "example" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2025 com.ugo.studio.plugins. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "example.exe" "\0" 98 | VALUE "ProductName", "example" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: flutter_p2p_connection_example 2 | description: "Demonstrates how to use the flutter_p2p_connection plugin." 3 | # The following line prevents the package from being accidentally published to 4 | # pub.dev using `flutter pub publish`. This is preferred for private packages. 5 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev 6 | 7 | environment: 8 | sdk: ^3.5.3 9 | 10 | # Dependencies specify other packages that your package needs in order to work. 11 | # To automatically upgrade your package dependencies to the latest versions 12 | # consider running `flutter pub upgrade --major-versions`. Alternatively, 13 | # dependencies can be manually updated by changing the version numbers below to 14 | # the latest version available on pub.dev. To see which dependencies have newer 15 | # versions available, run `flutter pub outdated`. 16 | dependencies: 17 | flutter: 18 | sdk: flutter 19 | 20 | flutter_p2p_connection: 21 | # When depending on this package from a real application you should use: 22 | # flutter_p2p_connection: ^x.y.z 23 | # See https://dart.dev/tools/pub/dependencies#version-constraints 24 | # The example app is bundled with the plugin so we use a path dependency on 25 | # the parent directory to use the current plugin's version. 26 | path: ../ 27 | 28 | # The following adds the Cupertino Icons font to your application. 29 | # Use with the CupertinoIcons class for iOS style icons. 30 | cupertino_icons: ^1.0.8 31 | pretty_qr_code: ^3.4.0 32 | mobile_scanner: ^6.0.7 33 | filesystem_picker: ^4.1.0 34 | 35 | dev_dependencies: 36 | integration_test: 37 | sdk: flutter 38 | flutter_test: 39 | sdk: flutter 40 | 41 | # The "flutter_lints" package below contains a set of recommended lints to 42 | # encourage good coding practices. The lint set provided by the package is 43 | # activated in the `analysis_options.yaml` file located at the root of your 44 | # package. See that file for information about deactivating specific lint 45 | # rules and activating additional ones. 46 | flutter_lints: ^5.0.0 47 | 48 | # For information on the generic Dart part of this file, see the 49 | # following page: https://dart.dev/tools/pub/pubspec 50 | 51 | # The following section is specific to Flutter packages. 52 | flutter: 53 | 54 | # The following line ensures that the Material Icons font is 55 | # included with your application, so that you can use the icons in 56 | # the material Icons class. 57 | uses-material-design: true 58 | 59 | # To add assets to your application, add an assets section, like this: 60 | # assets: 61 | # - images/a_dot_burr.jpeg 62 | # - images/a_dot_ham.jpeg 63 | 64 | # An image asset can refer to one or more resolution-specific "variants", see 65 | # https://flutter.dev/to/resolution-aware-images 66 | 67 | # For details regarding adding assets from package dependencies, see 68 | # https://flutter.dev/to/asset-from-package 69 | 70 | # To add custom fonts to your application, add a fonts section here, 71 | # in this "flutter" section. Each entry in this list should have a 72 | # "family" key with the font family name, and a "fonts" key with a 73 | # list giving the asset and other descriptors for the font. For 74 | # example: 75 | # fonts: 76 | # - family: Schyler 77 | # fonts: 78 | # - asset: fonts/Schyler-Regular.ttf 79 | # - asset: fonts/Schyler-Italic.ttf 80 | # style: italic 81 | # - family: Trajan Pro 82 | # fonts: 83 | # - asset: fonts/TrajanPro.ttf 84 | # - asset: fonts/TrajanPro_Bold.ttf 85 | # weight: 700 86 | # 87 | # For details regarding fonts from package dependencies, 88 | # see https://flutter.dev/to/font-from-package 89 | -------------------------------------------------------------------------------- /example/lib/qr/scanner_page.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:convert'; 3 | 4 | import 'package:flutter/material.dart'; 5 | import 'package:mobile_scanner/mobile_scanner.dart'; 6 | 7 | class ScannerPage extends StatefulWidget { 8 | final void Function(String ssid, String preSharedKey) onScanned; 9 | const ScannerPage({super.key, required this.onScanned}); 10 | 11 | @override 12 | State createState() => _ScannerPageState(); 13 | } 14 | 15 | class _ScannerPageState extends State with WidgetsBindingObserver { 16 | final MobileScannerController controller = MobileScannerController(); 17 | StreamSubscription? _subscription; 18 | 19 | @override 20 | void initState() { 21 | super.initState(); 22 | // Start listening to lifecycle changes. 23 | WidgetsBinding.instance.addObserver(this); 24 | 25 | // Start listening to the barcode events. 26 | _subscription = controller.barcodes.listen(_handleBarcode); 27 | 28 | // Finally, start the scanner itself. 29 | unawaited(controller.start()); 30 | } 31 | 32 | @override 33 | void didChangeAppLifecycleState(AppLifecycleState state) { 34 | // If the controller is not ready, do not try to start or stop it. 35 | // Permission dialogs can trigger lifecycle changes before the controller is ready. 36 | if (!controller.value.hasCameraPermission) { 37 | return; 38 | } 39 | 40 | switch (state) { 41 | case AppLifecycleState.detached: 42 | case AppLifecycleState.hidden: 43 | case AppLifecycleState.paused: 44 | return; 45 | case AppLifecycleState.resumed: 46 | // Restart the scanner when the app is resumed. 47 | // Don't forget to resume listening to the barcode events. 48 | _subscription = controller.barcodes.listen(_handleBarcode); 49 | 50 | unawaited(controller.start()); 51 | case AppLifecycleState.inactive: 52 | // Stop the scanner when the app is paused. 53 | // Also stop the barcode events subscription. 54 | unawaited(_subscription?.cancel()); 55 | _subscription = null; 56 | unawaited(controller.stop()); 57 | } 58 | } 59 | 60 | @override 61 | Future dispose() async { 62 | // Stop listening to lifecycle changes. 63 | WidgetsBinding.instance.removeObserver(this); 64 | // Stop listening to the barcode events. 65 | unawaited(_subscription?.cancel()); 66 | _subscription = null; 67 | // Dispose the widget itself. 68 | super.dispose(); 69 | // Finally, dispose of the controller. 70 | await controller.dispose(); 71 | } 72 | 73 | bool handlingBarCode = false; 74 | Future _handleBarcode(BarcodeCapture barcode) async { 75 | if (handlingBarCode) { 76 | return; 77 | } else { 78 | handlingBarCode = true; 79 | } 80 | 81 | final data = barcode.barcodes.first.rawValue; 82 | if (data == null) { 83 | handlingBarCode = false; 84 | return; 85 | } 86 | 87 | var parsed = jsonDecode(data); 88 | 89 | String? ssid = parsed['ssid']; 90 | String? preSharedKey = parsed['preSharedKey']; 91 | if (ssid == null || preSharedKey == null) { 92 | handlingBarCode = false; 93 | return; 94 | } 95 | 96 | widget.onScanned(ssid, preSharedKey); 97 | Navigator.pop(context); 98 | } 99 | 100 | @override 101 | Widget build(BuildContext context) { 102 | return Scaffold( 103 | appBar: AppBar( 104 | title: const Text('scanner'), 105 | ), 106 | body: Center( 107 | child: MobileScanner( 108 | controller: controller, 109 | ), 110 | ), 111 | ); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /example/windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates a win32 window with |title| that is positioned and sized using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size this function will scale the inputted width and height as 35 | // as appropriate for the default monitor. The window is invisible until 36 | // |Show| is called. Returns true if the window was created successfully. 37 | bool Create(const std::wstring& title, const Point& origin, const Size& size); 38 | 39 | // Show the current window. Returns true if the window was successfully shown. 40 | bool Show(); 41 | 42 | // Release OS resources associated with window. 43 | void Destroy(); 44 | 45 | // Inserts |content| into the window tree. 46 | void SetChildContent(HWND content); 47 | 48 | // Returns the backing Window handle to enable clients to set icon and other 49 | // window properties. Returns nullptr if the window has been destroyed. 50 | HWND GetHandle(); 51 | 52 | // If true, closing this window will quit the application. 53 | void SetQuitOnClose(bool quit_on_close); 54 | 55 | // Return a RECT representing the bounds of the current client area. 56 | RECT GetClientArea(); 57 | 58 | protected: 59 | // Processes and route salient window messages for mouse handling, 60 | // size change and DPI. Delegates handling of these to member overloads that 61 | // inheriting classes can handle. 62 | virtual LRESULT MessageHandler(HWND window, 63 | UINT const message, 64 | WPARAM const wparam, 65 | LPARAM const lparam) noexcept; 66 | 67 | // Called when CreateAndShow is called, allowing subclass window-related 68 | // setup. Subclasses should return false if setup fails. 69 | virtual bool OnCreate(); 70 | 71 | // Called when Destroy is called. 72 | virtual void OnDestroy(); 73 | 74 | private: 75 | friend class WindowClassRegistrar; 76 | 77 | // OS callback called by message pump. Handles the WM_NCCREATE message which 78 | // is passed when the non-client area is being created and enables automatic 79 | // non-client DPI scaling so that the non-client area automatically 80 | // responds to changes in DPI. All other messages are handled by 81 | // MessageHandler. 82 | static LRESULT CALLBACK WndProc(HWND const window, 83 | UINT const message, 84 | WPARAM const wparam, 85 | LPARAM const lparam) noexcept; 86 | 87 | // Retrieves a class instance pointer for |window| 88 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 89 | 90 | // Update the window frame's theme to match the system theme. 91 | static void UpdateTheme(HWND const window); 92 | 93 | bool quit_on_close_ = false; 94 | 95 | // window handle for top level window. 96 | HWND window_handle_ = nullptr; 97 | 98 | // window handle for hosted content. 99 | HWND child_content_ = nullptr; 100 | }; 101 | 102 | #endif // RUNNER_WIN32_WINDOW_H_ 103 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 43 | 49 | 50 | 51 | 52 | 53 | 63 | 65 | 71 | 72 | 73 | 74 | 80 | 82 | 88 | 89 | 90 | 91 | 93 | 94 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 43 | 49 | 50 | 51 | 52 | 53 | 63 | 65 | 71 | 72 | 73 | 74 | 80 | 82 | 88 | 89 | 90 | 91 | 93 | 94 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /lib/src/transport/common/transport_file_models.dart: -------------------------------------------------------------------------------- 1 | import 'transport_data_models.dart'; // For P2pFileInfo 2 | import 'transport_enums.dart'; // For ReceivableFileState 3 | 4 | /// Manages information about a file being hosted (shared) by the local client. 5 | class HostedFileInfo { 6 | /// Information about the file being hosted. 7 | final P2pFileInfo info; 8 | 9 | /// The local path to the file on the host's system. 10 | final String localPath; 11 | 12 | ReceivableFileState _state = ReceivableFileState.idle; 13 | 14 | final Map _downloadProgressBytes; 15 | 16 | /// The current state of the file (e.g., idle, downloading, completed). 17 | ReceivableFileState get state => _state; 18 | 19 | /// A list of client IDs who are recipients of this file. 20 | List get receiverIds => _downloadProgressBytes.keys.toList(); 21 | 22 | /// Creates a [HostedFileInfo] instance. 23 | /// 24 | /// [info] is the general P2P file information. 25 | /// [localPath] is the path to the file on the local filesystem. 26 | /// [recipientIds] is a list of client IDs intended to receive this file. 27 | HostedFileInfo({ 28 | required this.info, 29 | required this.localPath, 30 | required List recipientIds, 31 | }) : _downloadProgressBytes = {for (var id in recipientIds) id: 0}; 32 | 33 | /// Gets the download progress percentage for a specific receiver. 34 | /// 35 | /// Returns 0.0 if the file size is 0, or if the receiver ID is not found. 36 | double getProgressPercent(String receiverId) { 37 | final bytes = _downloadProgressBytes[receiverId]; 38 | if (info.size == 0 || bytes == null) return 0.0; 39 | return (bytes / info.size) * 100.0; 40 | } 41 | 42 | /// Updates the download progress for a specific receiver. 43 | /// 44 | /// Only updates if the new [bytes] value is greater than the current progress. 45 | void updateProgress( 46 | String receiverId, int bytes, ReceivableFileState newState) { 47 | final currentBytes = _downloadProgressBytes[receiverId] ?? 0; 48 | if (bytes > currentBytes) { 49 | _downloadProgressBytes[receiverId] = bytes; 50 | } 51 | // upate state of file 52 | if (newState != _state) { 53 | _state = newState; 54 | } 55 | } 56 | } 57 | 58 | /// Manages information about a file that can be received by the local client. 59 | class ReceivableFileInfo { 60 | /// Information about the file that can be received. 61 | final P2pFileInfo info; 62 | 63 | /// The current state of the file (e.g., idle, downloading, completed). 64 | ReceivableFileState state; 65 | 66 | /// The download progress percentage (0.0 to 100.0). 67 | double downloadProgressPercent; 68 | 69 | /// The local path where the file will be/is saved. 70 | String? savePath; 71 | 72 | /// Creates a [ReceivableFileInfo] instance. 73 | ReceivableFileInfo({ 74 | required this.info, 75 | this.state = ReceivableFileState.idle, 76 | this.downloadProgressPercent = 0.0, 77 | this.savePath, 78 | }); 79 | } 80 | 81 | /// Represents an update on the progress of a file download operation. 82 | class FileDownloadProgressUpdate { 83 | /// The ID of the file being downloaded. 84 | final String fileId; 85 | 86 | /// The download progress as a percentage (0.0 to 100.0). 87 | final double progressPercent; 88 | 89 | /// The number of bytes downloaded so far. 90 | final int bytesDownloaded; 91 | 92 | /// The total size of the file in bytes. 93 | final int totalSize; 94 | 95 | /// The local path where the file is being saved. 96 | final String savePath; 97 | 98 | /// Creates a [FileDownloadProgressUpdate] instance. 99 | FileDownloadProgressUpdate({ 100 | required this.fileId, 101 | required this.progressPercent, 102 | required this.bytesDownloaded, 103 | required this.totalSize, 104 | required this.savePath, 105 | }); 106 | 107 | @override 108 | String toString() => 109 | 'FileDownloadProgressUpdate(fileId: $fileId, progress: ${progressPercent.toStringAsFixed(1)}%, path: $savePath)'; 110 | } 111 | -------------------------------------------------------------------------------- /example/windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.14) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 12 | 13 | # Set fallback configurations for older versions of the flutter tool. 14 | if (NOT DEFINED FLUTTER_TARGET_PLATFORM) 15 | set(FLUTTER_TARGET_PLATFORM "windows-x64") 16 | endif() 17 | 18 | # === Flutter Library === 19 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 20 | 21 | # Published to parent scope for install step. 22 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 23 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 24 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 25 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 26 | 27 | list(APPEND FLUTTER_LIBRARY_HEADERS 28 | "flutter_export.h" 29 | "flutter_windows.h" 30 | "flutter_messenger.h" 31 | "flutter_plugin_registrar.h" 32 | "flutter_texture_registrar.h" 33 | ) 34 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 35 | add_library(flutter INTERFACE) 36 | target_include_directories(flutter INTERFACE 37 | "${EPHEMERAL_DIR}" 38 | ) 39 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 40 | add_dependencies(flutter flutter_assemble) 41 | 42 | # === Wrapper === 43 | list(APPEND CPP_WRAPPER_SOURCES_CORE 44 | "core_implementations.cc" 45 | "standard_codec.cc" 46 | ) 47 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 48 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 49 | "plugin_registrar.cc" 50 | ) 51 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 52 | list(APPEND CPP_WRAPPER_SOURCES_APP 53 | "flutter_engine.cc" 54 | "flutter_view_controller.cc" 55 | ) 56 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 57 | 58 | # Wrapper sources needed for a plugin. 59 | add_library(flutter_wrapper_plugin STATIC 60 | ${CPP_WRAPPER_SOURCES_CORE} 61 | ${CPP_WRAPPER_SOURCES_PLUGIN} 62 | ) 63 | apply_standard_settings(flutter_wrapper_plugin) 64 | set_target_properties(flutter_wrapper_plugin PROPERTIES 65 | POSITION_INDEPENDENT_CODE ON) 66 | set_target_properties(flutter_wrapper_plugin PROPERTIES 67 | CXX_VISIBILITY_PRESET hidden) 68 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 69 | target_include_directories(flutter_wrapper_plugin PUBLIC 70 | "${WRAPPER_ROOT}/include" 71 | ) 72 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 73 | 74 | # Wrapper sources needed for the runner. 75 | add_library(flutter_wrapper_app STATIC 76 | ${CPP_WRAPPER_SOURCES_CORE} 77 | ${CPP_WRAPPER_SOURCES_APP} 78 | ) 79 | apply_standard_settings(flutter_wrapper_app) 80 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 81 | target_include_directories(flutter_wrapper_app PUBLIC 82 | "${WRAPPER_ROOT}/include" 83 | ) 84 | add_dependencies(flutter_wrapper_app flutter_assemble) 85 | 86 | # === Flutter tool backend === 87 | # _phony_ is a non-existent file to force this command to run every time, 88 | # since currently there's no way to get a full input/output list from the 89 | # flutter tool. 90 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 91 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 92 | add_custom_command( 93 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 94 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 95 | ${CPP_WRAPPER_SOURCES_APP} 96 | ${PHONY_OUTPUT} 97 | COMMAND ${CMAKE_COMMAND} -E env 98 | ${FLUTTER_TOOL_ENVIRONMENT} 99 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 100 | ${FLUTTER_TARGET_PLATFORM} $ 101 | VERBATIM 102 | ) 103 | add_custom_target(flutter_assemble DEPENDS 104 | "${FLUTTER_LIBRARY}" 105 | ${FLUTTER_LIBRARY_HEADERS} 106 | ${CPP_WRAPPER_SOURCES_CORE} 107 | ${CPP_WRAPPER_SOURCES_PLUGIN} 108 | ${CPP_WRAPPER_SOURCES_APP} 109 | ) 110 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 28 | 30 | 31 | 32 | 34 | 37 | 39 | 40 | 41 | 42 | 43 | 44 | 49 | 58 | 62 | 66 | 67 | 68 | 69 | 70 | 71 | 73 | 76 | 77 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The Flutter tooling requires that developers have a version of Visual Studio 2 | # installed that includes CMake 3.14 or later. You should not increase this 3 | # version, as doing so will cause the plugin to fail to compile for some 4 | # customers of the plugin. 5 | cmake_minimum_required(VERSION 3.14) 6 | 7 | # Project-level configuration. 8 | set(PROJECT_NAME "flutter_p2p_connection") 9 | project(${PROJECT_NAME} LANGUAGES CXX) 10 | 11 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 12 | # versions of CMake. 13 | cmake_policy(VERSION 3.14...3.25) 14 | 15 | # This value is used when generating builds using this plugin, so it must 16 | # not be changed 17 | set(PLUGIN_NAME "flutter_p2p_connection_plugin") 18 | 19 | # Any new source files that you add to the plugin should be added here. 20 | list(APPEND PLUGIN_SOURCES 21 | "flutter_p2p_connection_plugin.cpp" 22 | "flutter_p2p_connection_plugin.h" 23 | ) 24 | 25 | # Find the C++/WinRT build support package. 26 | find_package(CppWinRT REQUIRED) 27 | 28 | # Define the plugin library target. Its name must not be changed (see comment 29 | # on PLUGIN_NAME above). 30 | add_library(${PLUGIN_NAME} SHARED 31 | "include/flutter_p2p_connection/flutter_p2p_connection_plugin_c_api.h" 32 | "flutter_p2p_connection_plugin_c_api.cpp" 33 | ${PLUGIN_SOURCES} 34 | ) 35 | 36 | # Apply a standard set of build settings that are configured in the 37 | # application-level CMakeLists.txt. This can be removed for plugins that want 38 | # full control over build settings. 39 | apply_standard_settings(${PLUGIN_NAME}) 40 | 41 | # Symbols are hidden by default to reduce the chance of accidental conflicts 42 | # between plugins. This should not be removed; any symbols that should be 43 | # exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. 44 | set_target_properties(${PLUGIN_NAME} PROPERTIES 45 | CXX_VISIBILITY_PRESET hidden) 46 | target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) 47 | 48 | # Source include directories and library dependencies. Add any plugin-specific 49 | # dependencies here. 50 | target_include_directories(${PLUGIN_NAME} INTERFACE 51 | "${CMAKE_CURRENT_SOURCE_DIR}/include") 52 | target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) 53 | target_link_libraries(${PLUGIN_NAME} PRIVATE CppWinRT::CppWinRT) 54 | 55 | target_precompile_headers(${PLUGIN_NAME} PRIVATE pch.h) 56 | 57 | # List of absolute paths to libraries that should be bundled with the plugin. 58 | # This list could contain prebuilt libraries, or libraries created by an 59 | # external build triggered from this build file. 60 | set(flutter_p2p_connection_bundled_libraries 61 | "" 62 | PARENT_SCOPE 63 | ) 64 | 65 | # === Tests === 66 | # These unit tests can be run from a terminal after building the example, or 67 | # from Visual Studio after opening the generated solution file. 68 | 69 | # Only enable test builds when building the example (which sets this variable) 70 | # so that plugin clients aren't building the tests. 71 | if (${include_${PROJECT_NAME}_tests}) 72 | set(TEST_RUNNER "${PROJECT_NAME}_test") 73 | enable_testing() 74 | 75 | # Add the Google Test dependency. 76 | include(FetchContent) 77 | FetchContent_Declare( 78 | googletest 79 | URL https://github.com/google/googletest/archive/release-1.11.0.zip 80 | ) 81 | # Prevent overriding the parent project's compiler/linker settings 82 | set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) 83 | # Disable install commands for gtest so it doesn't end up in the bundle. 84 | set(INSTALL_GTEST OFF CACHE BOOL "Disable installation of googletest" FORCE) 85 | FetchContent_MakeAvailable(googletest) 86 | 87 | # The plugin's C API is not very useful for unit testing, so build the sources 88 | # directly into the test binary rather than using the DLL. 89 | add_executable(${TEST_RUNNER} 90 | test/flutter_p2p_connection_plugin_test.cpp 91 | ${PLUGIN_SOURCES} 92 | ) 93 | apply_standard_settings(${TEST_RUNNER}) 94 | target_include_directories(${TEST_RUNNER} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") 95 | target_link_libraries(${TEST_RUNNER} PRIVATE flutter_wrapper_plugin) 96 | target_link_libraries(${TEST_RUNNER} PRIVATE gtest_main gmock) 97 | # flutter_wrapper_plugin has link dependencies on the Flutter DLL. 98 | add_custom_command(TARGET ${TEST_RUNNER} POST_BUILD 99 | COMMAND ${CMAKE_COMMAND} -E copy_if_different 100 | "${FLUTTER_LIBRARY}" $ 101 | ) 102 | 103 | # Enable automatic test discovery. 104 | include(GoogleTest) 105 | gtest_discover_tests(${TEST_RUNNER}) 106 | endif() 107 | -------------------------------------------------------------------------------- /example/windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.14) 3 | project(example LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "example") 8 | 9 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 10 | # versions of CMake. 11 | cmake_policy(VERSION 3.14...3.25) 12 | 13 | # Define build configuration option. 14 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 15 | if(IS_MULTICONFIG) 16 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 17 | CACHE STRING "" FORCE) 18 | else() 19 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 20 | set(CMAKE_BUILD_TYPE "Debug" CACHE 21 | STRING "Flutter build mode" FORCE) 22 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 23 | "Debug" "Profile" "Release") 24 | endif() 25 | endif() 26 | # Define settings for the Profile build mode. 27 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 28 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 29 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 30 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 31 | 32 | # Use Unicode for all projects. 33 | add_definitions(-DUNICODE -D_UNICODE) 34 | 35 | # Compilation settings that should be applied to most targets. 36 | # 37 | # Be cautious about adding new options here, as plugins use this function by 38 | # default. In most cases, you should add new options to specific targets instead 39 | # of modifying this function. 40 | function(APPLY_STANDARD_SETTINGS TARGET) 41 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 42 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 43 | target_compile_options(${TARGET} PRIVATE /EHsc) 44 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 45 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 46 | endfunction() 47 | 48 | # Flutter library and tool build rules. 49 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 50 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 51 | 52 | # Application build; see runner/CMakeLists.txt. 53 | add_subdirectory("runner") 54 | 55 | 56 | # Generated plugin build rules, which manage building the plugins and adding 57 | # them to the application. 58 | include(flutter/generated_plugins.cmake) 59 | 60 | 61 | # === Installation === 62 | # Support files are copied into place next to the executable, so that it can 63 | # run in place. This is done instead of making a separate bundle (as on Linux) 64 | # so that building and running from within Visual Studio will work. 65 | set(BUILD_BUNDLE_DIR "$") 66 | # Make the "install" step default, as it's required to run. 67 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 68 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 69 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 70 | endif() 71 | 72 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 73 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 74 | 75 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 76 | COMPONENT Runtime) 77 | 78 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 79 | COMPONENT Runtime) 80 | 81 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 82 | COMPONENT Runtime) 83 | 84 | if(PLUGIN_BUNDLED_LIBRARIES) 85 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 86 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 87 | COMPONENT Runtime) 88 | endif() 89 | 90 | # Copy the native assets provided by the build.dart from all packages. 91 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") 92 | install(DIRECTORY "${NATIVE_ASSETS_DIR}" 93 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 94 | COMPONENT Runtime) 95 | 96 | # Fully re-copy the assets directory on each build to avoid having stale files 97 | # from a previous install. 98 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 99 | install(CODE " 100 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 101 | " COMPONENT Runtime) 102 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 103 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 104 | 105 | # Install the AOT library on non-Debug builds only. 106 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 107 | CONFIGURATIONS Profile;Release 108 | COMPONENT Runtime) 109 | -------------------------------------------------------------------------------- /lib/src/transport/common/file_request_server_mixin.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'package:flutter/foundation.dart'; 3 | 4 | import 'transport_file_models.dart'; // For HostedFileInfo 5 | 6 | /// Mixin providing common file request handling logic for HTTP servers 7 | /// that serve files in the P2P network. 8 | mixin FileRequestServerMixin { 9 | /// A map of hosted files, where the key is the file ID. 10 | Map get hostedFiles; 11 | 12 | /// The username of the transport (host or client) for logging purposes. 13 | String get transportUsername; // For logging prefix 14 | static const String _logPrefixBase = "P2P FileServer"; 15 | 16 | /// Handles an incoming HTTP request for a file. 17 | /// 18 | /// This method processes requests to the `/file` endpoint, supporting 19 | /// full file downloads and byte range requests. 20 | Future handleFileRequest(HttpRequest request) async { 21 | final logPrefix = "$_logPrefixBase [$transportUsername]"; 22 | final fileId = request.uri.queryParameters['id']; 23 | 24 | if (fileId == null || fileId.isEmpty) { 25 | debugPrint("$logPrefix: File request missing ID."); 26 | request.response 27 | ..statusCode = HttpStatus.badRequest 28 | ..write('File ID parameter is required.') 29 | ..close(); 30 | return; 31 | } 32 | 33 | final hostedFile = hostedFiles[fileId]; 34 | if (hostedFile == null) { 35 | debugPrint( 36 | "$logPrefix: Requested file ID not found or not hosted: $fileId"); 37 | request.response 38 | ..statusCode = HttpStatus.notFound 39 | ..write('File not found or access denied.') 40 | ..close(); 41 | return; 42 | } 43 | 44 | final filePath = hostedFile.localPath; 45 | final file = File(filePath); 46 | if (!await file.exists()) { 47 | debugPrint( 48 | "$logPrefix: Hosted file path not found on disk: $filePath (ID: $fileId)"); 49 | hostedFiles.remove(fileId); 50 | request.response 51 | ..statusCode = HttpStatus.internalServerError 52 | ..write('File data is unavailable.') 53 | ..close(); 54 | return; 55 | } 56 | 57 | final fileStat = await file.stat(); 58 | final totalSize = fileStat.size; 59 | final response = request.response; 60 | 61 | response.headers.contentType = ContentType.binary; 62 | response.headers.add(HttpHeaders.contentDisposition, 63 | 'attachment; filename="${Uri.encodeComponent(hostedFile.info.name)}"'); 64 | response.headers.add(HttpHeaders.acceptRangesHeader, 'bytes'); 65 | 66 | final rangeHeader = request.headers.value(HttpHeaders.rangeHeader); 67 | int rangeStart = 0; 68 | int? rangeEnd; 69 | 70 | if (rangeHeader != null && rangeHeader.startsWith('bytes=')) { 71 | try { 72 | final rangeValues = rangeHeader.substring(6).split('-'); 73 | rangeStart = int.parse(rangeValues[0]); 74 | if (rangeValues[1].isNotEmpty) { 75 | rangeEnd = int.parse(rangeValues[1]); 76 | } 77 | 78 | if (rangeStart < 0 || 79 | rangeStart >= totalSize || 80 | (rangeEnd != null && 81 | (rangeEnd < rangeStart || rangeEnd >= totalSize))) { 82 | throw const FormatException('Invalid range'); 83 | } 84 | rangeEnd ??= totalSize - 1; 85 | final rangeLength = (rangeEnd - rangeStart) + 1; 86 | 87 | debugPrint( 88 | "$logPrefix: Serving range $rangeStart-$rangeEnd (length $rangeLength) for file $fileId"); 89 | response.statusCode = HttpStatus.partialContent; 90 | response.headers.contentLength = rangeLength; 91 | response.headers.add(HttpHeaders.contentRangeHeader, 92 | 'bytes $rangeStart-$rangeEnd/$totalSize'); 93 | final stream = file.openRead(rangeStart, rangeEnd + 1); 94 | await response.addStream(stream); 95 | } catch (e) { 96 | debugPrint("$logPrefix: Invalid Range header '$rangeHeader': $e"); 97 | response 98 | ..statusCode = HttpStatus.requestedRangeNotSatisfiable 99 | ..headers.add(HttpHeaders.contentRangeHeader, 'bytes */$totalSize') 100 | ..write('Invalid byte range requested.') 101 | ..close(); 102 | return; 103 | } 104 | } else { 105 | debugPrint( 106 | "$logPrefix: Serving full file $fileId (${hostedFile.info.name})"); 107 | response.statusCode = HttpStatus.ok; 108 | response.headers.contentLength = totalSize; 109 | final stream = file.openRead(); 110 | await response.addStream(stream); 111 | } 112 | 113 | try { 114 | await response.close(); 115 | debugPrint("$logPrefix: Finished sending file/range for $fileId."); 116 | } catch (e) { 117 | debugPrint("$logPrefix: Error closing response stream for $fileId: $e"); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /example/linux/my_application.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | #include 4 | #ifdef GDK_WINDOWING_X11 5 | #include 6 | #endif 7 | 8 | #include "flutter/generated_plugin_registrant.h" 9 | 10 | struct _MyApplication { 11 | GtkApplication parent_instance; 12 | char** dart_entrypoint_arguments; 13 | }; 14 | 15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) 16 | 17 | // Implements GApplication::activate. 18 | static void my_application_activate(GApplication* application) { 19 | MyApplication* self = MY_APPLICATION(application); 20 | GtkWindow* window = 21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); 22 | 23 | // Use a header bar when running in GNOME as this is the common style used 24 | // by applications and is the setup most users will be using (e.g. Ubuntu 25 | // desktop). 26 | // If running on X and not using GNOME then just use a traditional title bar 27 | // in case the window manager does more exotic layout, e.g. tiling. 28 | // If running on Wayland assume the header bar will work (may need changing 29 | // if future cases occur). 30 | gboolean use_header_bar = TRUE; 31 | #ifdef GDK_WINDOWING_X11 32 | GdkScreen* screen = gtk_window_get_screen(window); 33 | if (GDK_IS_X11_SCREEN(screen)) { 34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); 35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) { 36 | use_header_bar = FALSE; 37 | } 38 | } 39 | #endif 40 | if (use_header_bar) { 41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); 42 | gtk_widget_show(GTK_WIDGET(header_bar)); 43 | gtk_header_bar_set_title(header_bar, "example"); 44 | gtk_header_bar_set_show_close_button(header_bar, TRUE); 45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); 46 | } else { 47 | gtk_window_set_title(window, "example"); 48 | } 49 | 50 | gtk_window_set_default_size(window, 1280, 720); 51 | gtk_widget_show(GTK_WIDGET(window)); 52 | 53 | g_autoptr(FlDartProject) project = fl_dart_project_new(); 54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); 55 | 56 | FlView* view = fl_view_new(project); 57 | gtk_widget_show(GTK_WIDGET(view)); 58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); 59 | 60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view)); 61 | 62 | gtk_widget_grab_focus(GTK_WIDGET(view)); 63 | } 64 | 65 | // Implements GApplication::local_command_line. 66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { 67 | MyApplication* self = MY_APPLICATION(application); 68 | // Strip out the first argument as it is the binary name. 69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); 70 | 71 | g_autoptr(GError) error = nullptr; 72 | if (!g_application_register(application, nullptr, &error)) { 73 | g_warning("Failed to register: %s", error->message); 74 | *exit_status = 1; 75 | return TRUE; 76 | } 77 | 78 | g_application_activate(application); 79 | *exit_status = 0; 80 | 81 | return TRUE; 82 | } 83 | 84 | // Implements GApplication::startup. 85 | static void my_application_startup(GApplication* application) { 86 | //MyApplication* self = MY_APPLICATION(object); 87 | 88 | // Perform any actions required at application startup. 89 | 90 | G_APPLICATION_CLASS(my_application_parent_class)->startup(application); 91 | } 92 | 93 | // Implements GApplication::shutdown. 94 | static void my_application_shutdown(GApplication* application) { 95 | //MyApplication* self = MY_APPLICATION(object); 96 | 97 | // Perform any actions required at application shutdown. 98 | 99 | G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); 100 | } 101 | 102 | // Implements GObject::dispose. 103 | static void my_application_dispose(GObject* object) { 104 | MyApplication* self = MY_APPLICATION(object); 105 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); 106 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object); 107 | } 108 | 109 | static void my_application_class_init(MyApplicationClass* klass) { 110 | G_APPLICATION_CLASS(klass)->activate = my_application_activate; 111 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; 112 | G_APPLICATION_CLASS(klass)->startup = my_application_startup; 113 | G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; 114 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose; 115 | } 116 | 117 | static void my_application_init(MyApplication* self) {} 118 | 119 | MyApplication* my_application_new() { 120 | return MY_APPLICATION(g_object_new(my_application_get_type(), 121 | "application-id", APPLICATION_ID, 122 | "flags", G_APPLICATION_NON_UNIQUE, 123 | nullptr)); 124 | } 125 | -------------------------------------------------------------------------------- /android/src/main/kotlin/com/ugo/studio/plugins/flutter_p2p_connection/PermissionsManager.kt: -------------------------------------------------------------------------------- 1 | package com.ugo.studio.plugins.flutter_p2p_connection 2 | 3 | import android.Manifest 4 | import android.annotation.SuppressLint 5 | import android.app.Activity 6 | import android.content.Context 7 | import android.content.pm.PackageManager 8 | import android.os.Build 9 | import android.util.Log 10 | import androidx.core.app.ActivityCompat 11 | import androidx.core.content.ContextCompat 12 | 13 | import com.ugo.studio.plugins.flutter_p2p_connection.Constants 14 | import io.flutter.plugin.common.MethodChannel 15 | 16 | 17 | class PermissionsManager(private val applicationContext: Context) { 18 | 19 | private var activity: Activity? = null 20 | private val TAG = Constants.TAG 21 | 22 | fun updateActivity(activity: Activity?) { 23 | this.activity = activity 24 | } 25 | 26 | fun hasP2pPermissions(): Boolean { 27 | val fineLocationGranted = ContextCompat.checkSelfPermission( 28 | applicationContext, Manifest.permission.ACCESS_FINE_LOCATION 29 | ) == PackageManager.PERMISSION_GRANTED 30 | val changeWifiStateGranted = ContextCompat.checkSelfPermission( 31 | applicationContext, Manifest.permission.CHANGE_WIFI_STATE 32 | ) == PackageManager.PERMISSION_GRANTED 33 | 34 | var nearbyWifiGranted = true // Assume true for older APIs 35 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 36 | // Check if the app targets API 31+ 37 | val targetsApi31OrHigher = applicationContext.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.S 38 | if (targetsApi31OrHigher) { 39 | nearbyWifiGranted = ContextCompat.checkSelfPermission( 40 | applicationContext, Manifest.permission.NEARBY_WIFI_DEVICES 41 | ) == PackageManager.PERMISSION_GRANTED 42 | } 43 | } 44 | 45 | return fineLocationGranted && changeWifiStateGranted && nearbyWifiGranted 46 | } 47 | 48 | // Check for BLUETOOTH_CONNECT permission required on API 31+ if targeting API 31+ 49 | @SuppressLint("MissingPermission") // Lint complains even with the version check 50 | fun hasBluetoothConnectPermission(): Boolean { 51 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 52 | // Check if the app targets API 31+ 53 | val targetsApi31OrHigher = applicationContext.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.S 54 | if (targetsApi31OrHigher) { 55 | ContextCompat.checkSelfPermission( 56 | applicationContext, Manifest.permission.BLUETOOTH_CONNECT 57 | ) == PackageManager.PERMISSION_GRANTED 58 | } else { 59 | // App targets API 30 or lower, running on S+: BLUETOOTH/BLUETOOTH_ADMIN from Manifest suffice 60 | true // Assume Manifest permissions are sufficient for legacy apps on S+ 61 | } 62 | } else { 63 | // Running on older Android: BLUETOOTH/BLUETOOTH_ADMIN from Manifest suffice 64 | true // Assume Manifest permissions are sufficient 65 | } 66 | } 67 | 68 | fun checkP2pPermissions(result: MethodChannel.Result) { 69 | Log.d(TAG, "Checking Permissions (FINE_LOCATION, CHANGE_WIFI_STATE, NEARBY_WIFI_DEVICES if needed).") 70 | result.success(hasP2pPermissions()) 71 | } 72 | 73 | fun askP2pPermissions(result: MethodChannel.Result) { 74 | val currentActivity = activity 75 | if (currentActivity == null) { 76 | result.error("NO_ACTIVITY", "Activity is not available to request permissions", null) 77 | return 78 | } 79 | val permissionsToRequest = mutableListOf() 80 | if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 81 | permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION) 82 | } 83 | if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) { 84 | permissionsToRequest.add(Manifest.permission.CHANGE_WIFI_STATE) 85 | } 86 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 87 | val targetsApi31OrHigher = applicationContext.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.S 88 | if (targetsApi31OrHigher && ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.NEARBY_WIFI_DEVICES) != PackageManager.PERMISSION_GRANTED) { 89 | permissionsToRequest.add(Manifest.permission.NEARBY_WIFI_DEVICES) 90 | } 91 | } 92 | 93 | if (permissionsToRequest.isEmpty()) { 94 | Log.d(TAG, "P2P Permissions already granted.") 95 | result.success(true) 96 | return 97 | } 98 | Log.d(TAG, "Requesting P2P permissions: ${permissionsToRequest.joinToString()}") 99 | ActivityCompat.requestPermissions( 100 | currentActivity, 101 | permissionsToRequest.toTypedArray(), 102 | Constants.LOCATION_PERMISSION_REQUEST_CODE // Use Constant 103 | ) 104 | result.success(true) // Indicate request was made 105 | } 106 | } -------------------------------------------------------------------------------- /lib/flutter_p2p_connection_platform_interface.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter_p2p_connection/flutter_p2p_connection.dart'; 2 | import 'package:plugin_platform_interface/plugin_platform_interface.dart'; 3 | 4 | import 'flutter_p2p_connection_method_channel.dart'; 5 | 6 | abstract class FlutterP2pConnectionPlatform extends PlatformInterface { 7 | /// Constructs a FlutterP2pConnectionPlatform. 8 | FlutterP2pConnectionPlatform() : super(token: _token); 9 | 10 | static final Object _token = Object(); 11 | 12 | static FlutterP2pConnectionPlatform _instance = 13 | MethodChannelFlutterP2pConnection(); 14 | 15 | /// The default instance of [FlutterP2pConnectionPlatform] to use. 16 | /// 17 | /// Defaults to [MethodChannelFlutterP2pConnection]. 18 | static FlutterP2pConnectionPlatform get instance => _instance; 19 | 20 | /// Platform-specific implementations should set this with their own 21 | /// platform-specific class that extends [FlutterP2pConnectionPlatform] when 22 | /// they register themselves. 23 | static set instance(FlutterP2pConnectionPlatform instance) { 24 | PlatformInterface.verifyToken(instance, _token); 25 | _instance = instance; 26 | } 27 | 28 | Future getPlatformVersion() async { 29 | throw UnimplementedError('getPlatformVersion() has not been implemented.'); 30 | } 31 | 32 | Future getPlatformModel() async { 33 | throw UnimplementedError('getPlatformModel() has not been implemented.'); 34 | } 35 | 36 | Future initialize({ 37 | String? serviceUuid, 38 | bool? bondingRequired, 39 | bool? encryptionRequired, 40 | }) async { 41 | throw UnimplementedError('initialize() has not been implemented.'); 42 | } 43 | 44 | Future dispose() async { 45 | throw UnimplementedError('dispose() has not been implemented.'); 46 | } 47 | 48 | Future createHotspot() async { 49 | throw UnimplementedError('createHotspot() has not been implemented.'); 50 | } 51 | 52 | Future removeHotspot() async { 53 | throw UnimplementedError('removeHotspot() has not been implemented.'); 54 | } 55 | 56 | Future connectToHotspot(String ssid, String psk) async { 57 | throw UnimplementedError('connectToHotspot() has not been implemented.'); 58 | } 59 | 60 | Future disconnectFromHotspot() async { 61 | throw UnimplementedError( 62 | 'disconnectFromHotspot() has not been implemented.'); 63 | } 64 | 65 | Future startBleAdvertising(String ssid, String psk) async { 66 | throw UnimplementedError('startBleAdvertising() has not been implemented.'); 67 | } 68 | 69 | Future stopBleAdvertising() async { 70 | throw UnimplementedError('stopBleAdvertising() has not been implemented.'); 71 | } 72 | 73 | Future startBleScan() async { 74 | throw UnimplementedError('startBleScan() has not been implemented.'); 75 | } 76 | 77 | Future stopBleScan() async { 78 | throw UnimplementedError('stopBleScan() has not been implemented.'); 79 | } 80 | 81 | Future connectBleDevice(String deviceAddress) async { 82 | throw UnimplementedError('connectBleDevice() has not been implemented.'); 83 | } 84 | 85 | Future disconnectBleDevice(String deviceAddress) async { 86 | throw UnimplementedError('disconnectBleDevice() has not been implemented.'); 87 | } 88 | 89 | Future checkP2pPermissions() async { 90 | throw UnimplementedError('checkP2pPermissions() has not been implemented.'); 91 | } 92 | 93 | Future askP2pPermissions() async { 94 | throw UnimplementedError('askP2pPermissions() has not been implemented.'); 95 | } 96 | 97 | Future checkLocationEnabled() async { 98 | throw UnimplementedError( 99 | 'checkLocationEnabled() has not been implemented.'); 100 | } 101 | 102 | Future enableLocationServices() async { 103 | throw UnimplementedError( 104 | 'enableLocationServices() has not been implemented.'); 105 | } 106 | 107 | Future checkWifiEnabled() async { 108 | throw UnimplementedError('checkWifiEnabled() has not been implemented.'); 109 | } 110 | 111 | Future enableWifiServices() async { 112 | throw UnimplementedError('enableWifiServices() has not been implemented.'); 113 | } 114 | 115 | Future checkBluetoothEnabled() async { 116 | throw UnimplementedError( 117 | 'checkBluetoothEnabled() has not been implemented.'); 118 | } 119 | 120 | Future enableBluetoothServices() async { 121 | throw UnimplementedError( 122 | 'enableBluetoothServices() has not been implemented.'); 123 | } 124 | 125 | Stream streamHotspotInfo() { 126 | throw UnimplementedError('streamHotspotInfo() has not been implemented.'); 127 | } 128 | 129 | Stream streamHotspotClientState() { 130 | throw UnimplementedError( 131 | 'streamHotspotClientState() has not been implemented.'); 132 | } 133 | 134 | Stream streamBleConnectionState() { 135 | throw UnimplementedError( 136 | 'streamBleConnectionState() has not been implemented.'); 137 | } 138 | 139 | Stream> streamBleScanResult() { 140 | throw UnimplementedError('streamBleScanResult() has not been implemented.'); 141 | } 142 | 143 | Stream streamBleReceivedData() { 144 | throw UnimplementedError( 145 | 'streamBleReceivedData() has not been implemented.'); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /example/linux/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.10) 3 | project(runner LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "example") 8 | # The unique GTK application identifier for this application. See: 9 | # https://wiki.gnome.org/HowDoI/ChooseApplicationID 10 | set(APPLICATION_ID "com.ugo.studio.plugins.example") 11 | 12 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 13 | # versions of CMake. 14 | cmake_policy(SET CMP0063 NEW) 15 | 16 | # Load bundled libraries from the lib/ directory relative to the binary. 17 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") 18 | 19 | # Root filesystem for cross-building. 20 | if(FLUTTER_TARGET_PLATFORM_SYSROOT) 21 | set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) 22 | set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) 23 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 24 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) 25 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 26 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 27 | endif() 28 | 29 | # Define build configuration options. 30 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 31 | set(CMAKE_BUILD_TYPE "Debug" CACHE 32 | STRING "Flutter build mode" FORCE) 33 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 34 | "Debug" "Profile" "Release") 35 | endif() 36 | 37 | # Compilation settings that should be applied to most targets. 38 | # 39 | # Be cautious about adding new options here, as plugins use this function by 40 | # default. In most cases, you should add new options to specific targets instead 41 | # of modifying this function. 42 | function(APPLY_STANDARD_SETTINGS TARGET) 43 | target_compile_features(${TARGET} PUBLIC cxx_std_14) 44 | target_compile_options(${TARGET} PRIVATE -Wall -Werror) 45 | target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") 46 | target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") 47 | endfunction() 48 | 49 | # Flutter library and tool build rules. 50 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 51 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 52 | 53 | # System-level dependencies. 54 | find_package(PkgConfig REQUIRED) 55 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 56 | 57 | add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") 58 | 59 | # Define the application target. To change its name, change BINARY_NAME above, 60 | # not the value here, or `flutter run` will no longer work. 61 | # 62 | # Any new source files that you add to the application should be added here. 63 | add_executable(${BINARY_NAME} 64 | "main.cc" 65 | "my_application.cc" 66 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 67 | ) 68 | 69 | # Apply the standard set of build settings. This can be removed for applications 70 | # that need different build settings. 71 | apply_standard_settings(${BINARY_NAME}) 72 | 73 | # Add dependency libraries. Add any application-specific dependencies here. 74 | target_link_libraries(${BINARY_NAME} PRIVATE flutter) 75 | target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) 76 | 77 | # Run the Flutter tool portions of the build. This must not be removed. 78 | add_dependencies(${BINARY_NAME} flutter_assemble) 79 | 80 | # Only the install-generated bundle's copy of the executable will launch 81 | # correctly, since the resources must in the right relative locations. To avoid 82 | # people trying to run the unbundled copy, put it in a subdirectory instead of 83 | # the default top-level location. 84 | set_target_properties(${BINARY_NAME} 85 | PROPERTIES 86 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" 87 | ) 88 | 89 | 90 | # Generated plugin build rules, which manage building the plugins and adding 91 | # them to the application. 92 | include(flutter/generated_plugins.cmake) 93 | 94 | 95 | # === Installation === 96 | # By default, "installing" just makes a relocatable bundle in the build 97 | # directory. 98 | set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") 99 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 100 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 101 | endif() 102 | 103 | # Start with a clean build bundle directory every time. 104 | install(CODE " 105 | file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") 106 | " COMPONENT Runtime) 107 | 108 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 109 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") 110 | 111 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 112 | COMPONENT Runtime) 113 | 114 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 115 | COMPONENT Runtime) 116 | 117 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 118 | COMPONENT Runtime) 119 | 120 | foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) 121 | install(FILES "${bundled_library}" 122 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 123 | COMPONENT Runtime) 124 | endforeach(bundled_library) 125 | 126 | # Copy the native assets provided by the build.dart from all packages. 127 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") 128 | install(DIRECTORY "${NATIVE_ASSETS_DIR}" 129 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 130 | COMPONENT Runtime) 131 | 132 | # Fully re-copy the assets directory on each build to avoid having stale files 133 | # from a previous install. 134 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 135 | install(CODE " 136 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 137 | " COMPONENT Runtime) 138 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 139 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 140 | 141 | # Install the AOT library on non-Debug builds only. 142 | if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") 143 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 144 | COMPONENT Runtime) 145 | endif() 146 | -------------------------------------------------------------------------------- /lib/src/common/p2p_connection_base.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:flutter/foundation.dart'; 4 | import 'package:permission_handler/permission_handler.dart'; 5 | 6 | import '../../flutter_p2p_connection_platform_interface.dart'; 7 | 8 | /// Base class for common P2P connection functionalities. 9 | /// 10 | /// This class provides access to: 11 | /// - Utility methods for checking and requesting permissions and enabling services 12 | /// (Location, Wi-Fi, Bluetooth) required for P2P operations. 13 | /// - Device information like the model. 14 | class FlutterP2pConnectionBase { 15 | /// Optional custom user name for device. 16 | final String? username; 17 | 18 | /// Optional custom UUID for the BLE service. If null, a default UUID is used. 19 | final String? serviceUuid; 20 | 21 | /// Optional bonding by BLE service 22 | final bool? bondingRequired; 23 | 24 | /// Optional encryption by BLE service 25 | final bool? encryptionRequired; 26 | 27 | /// Constructor for [FlutterP2pConnectionBase]. 28 | const FlutterP2pConnectionBase({ 29 | this.serviceUuid, 30 | this.bondingRequired, 31 | this.encryptionRequired, 32 | this.username, 33 | }); 34 | 35 | /// Retrieves the model identifier of the current device. 36 | /// 37 | /// Useful for debugging or tailoring behavior based on the device. 38 | /// Returns a [Future] completing with the device model string. 39 | Future getDeviceModel() => 40 | FlutterP2pConnectionPlatform.instance.getPlatformModel(); 41 | 42 | /// Checks if location services are currently enabled on the device. 43 | /// 44 | /// Location is often required for Wi-Fi and BLE scanning on Android. 45 | /// Returns a [Future] completing with `true` if location is enabled, `false` otherwise. 46 | Future checkLocationEnabled() async => 47 | await FlutterP2pConnectionPlatform.instance.checkLocationEnabled(); 48 | 49 | /// Attempts to guide the user to system settings to enable location services. 50 | /// 51 | /// This typically opens the device's location settings screen. 52 | /// After the user potentially enables the service, it re-checks the status. 53 | /// Returns a [Future] completing with `true` if location is enabled after the 54 | /// attempt, `false` otherwise. Note that the user can choose not to enable it. 55 | Future enableLocationServices() async { 56 | await FlutterP2pConnectionPlatform.instance.enableLocationServices(); 57 | return await checkLocationEnabled(); 58 | } 59 | 60 | /// Checks if Wi-Fi is currently enabled on the device. 61 | /// 62 | /// Wi-Fi is essential for Wi-Fi Direct P2P connections. 63 | /// Returns a [Future] completing with `true` if Wi-Fi is enabled, `false` otherwise. 64 | Future checkWifiEnabled() async => 65 | await FlutterP2pConnectionPlatform.instance.checkWifiEnabled(); 66 | 67 | /// Attempts to guide the user to system settings to enable Wi-Fi. 68 | /// 69 | /// This typically opens the device's Wi-Fi settings screen. 70 | /// After the user potentially enables Wi-Fi, it re-checks the status. 71 | /// Returns a [Future] completing with `true` if Wi-Fi is enabled after the 72 | /// attempt, `false` otherwise. 73 | Future enableWifiServices() async { 74 | await FlutterP2pConnectionPlatform.instance.enableWifiServices(); 75 | return await checkWifiEnabled(); 76 | } 77 | 78 | /// Checks if Bluetooth is currently enabled on the device. 79 | /// 80 | /// Bluetooth is required for BLE discovery (scanning and advertising). 81 | /// Returns a [Future] completing with `true` if Bluetooth is enabled, `false` otherwise. 82 | Future checkBluetoothEnabled() async => 83 | await FlutterP2pConnectionPlatform.instance.checkBluetoothEnabled(); 84 | 85 | /// Attempts to guide the user to system settings to enable Bluetooth. 86 | /// 87 | /// This typically opens the device's Bluetooth settings screen. 88 | /// After the user potentially enables Bluetooth, it re-checks the status. 89 | /// Returns a [Future] completing with `true` if Bluetooth is enabled after the 90 | /// attempt, `false` otherwise. 91 | Future enableBluetoothServices() async { 92 | await FlutterP2pConnectionPlatform.instance.enableBluetoothServices(); 93 | return await checkBluetoothEnabled(); 94 | } 95 | 96 | /// Checks if all necessary Bluetooth permissions are granted. 97 | /// 98 | /// Returns a [Future] completing with `true` if all required Bluetooth permissions are granted, `false` otherwise. 99 | Future checkBluetoothPermissions() async { 100 | final List permissions = [ 101 | Permission.locationWhenInUse, 102 | Permission.bluetoothScan, 103 | Permission.bluetoothConnect, 104 | Permission.bluetoothAdvertise, 105 | ]; 106 | for (final perm in permissions) { 107 | final status = await perm.status; 108 | if (!status.isGranted && !status.isLimited) { 109 | debugPrint("Permission missing: $perm status: $status"); 110 | return false; 111 | } 112 | } 113 | return true; 114 | } 115 | 116 | /// Requests necessary Bluetooth and associated Location permissions from the user. 117 | /// 118 | /// Uses the `permission_handler` package to request permissions for scanning, 119 | /// connecting, advertising, and location (often needed for scanning). 120 | /// Returns a [Future] completing with `true` if all requested permissions are granted, `false` otherwise. 121 | Future askBluetoothPermissions() async { 122 | await [ 123 | Permission.locationWhenInUse, 124 | Permission.bluetooth, 125 | Permission.bluetoothScan, 126 | Permission.bluetoothAdvertise, 127 | Permission.bluetoothConnect, 128 | ].request(); 129 | return await checkBluetoothPermissions(); 130 | } 131 | 132 | /// Checks if all necessary P2P (Wi-Fi Direct) permissions are granted. 133 | /// 134 | /// Returns a [Future] completing with `true` if all required P2P permissions are granted, `false` otherwise. 135 | Future checkP2pPermissions() async => 136 | await FlutterP2pConnectionPlatform.instance.checkP2pPermissions(); 137 | 138 | /// Requests necessary P2P (Wi-Fi Direct) permissions from the user. 139 | /// 140 | /// Returns a [Future] completing with `true` if the permissions are granted after the request, `false` otherwise. 141 | Future askP2pPermissions() async { 142 | await FlutterP2pConnectionPlatform.instance.askP2pPermissions(); 143 | return await checkP2pPermissions(); 144 | } 145 | 146 | /// Checks if the necessary storage permissions are granted for file transfer. 147 | /// 148 | /// **Note:** Storage permission requirements have changed significantly in recent Android versions. 149 | /// Returns a [Future] completing with `true` if `Permission.storage` is granted, `false` otherwise. 150 | Future checkStoragePermission() async { 151 | // Consider Scoped Storage for Android 10+ 152 | return await Permission.storage.isGranted; 153 | } 154 | 155 | /// Requests storage permission(s) from the user, primarily for file transfer. 156 | /// 157 | /// Returns a [Future] completing with `true` if `Permission.storage` is granted after the request, `false` otherwise. 158 | Future askStoragePermission() async { 159 | // Consider Scoped Storage for Android 10+ 160 | final status = await Permission.storage.request(); 161 | return status.isGranted; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /android/src/main/kotlin/com/ugo/studio/plugins/flutter_p2p_connection/ServiceManager.kt: -------------------------------------------------------------------------------- 1 | package com.ugo.studio.plugins.flutter_p2p_connection 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.Activity 5 | import android.bluetooth.BluetoothAdapter 6 | import android.content.Context 7 | import android.content.Intent 8 | import android.location.LocationManager 9 | import android.net.wifi.WifiManager 10 | import android.os.Build 11 | import android.provider.Settings 12 | import android.util.Log 13 | 14 | import com.ugo.studio.plugins.flutter_p2p_connection.Constants 15 | import com.ugo.studio.plugins.flutter_p2p_connection.PermissionsManager 16 | import io.flutter.plugin.common.MethodChannel 17 | 18 | class ServiceManager( 19 | private val applicationContext: Context, 20 | private val permissionsManager: PermissionsManager, // Inject PermissionsManager 21 | private val bluetoothAdapter: BluetoothAdapter? // Inject adapter instance (can be null) 22 | ) { 23 | private var activity: Activity? = null 24 | private val TAG = Constants.TAG 25 | 26 | // Lazy initialization for managers that don't need injection 27 | private val wifiManager: WifiManager by lazy { 28 | applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager 29 | } 30 | private val locationManager: LocationManager by lazy { 31 | applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager 32 | } 33 | 34 | fun updateActivity(activity: Activity?) { 35 | this.activity = activity 36 | } 37 | 38 | // --- Location --- 39 | fun isLocationEnabled(): Boolean { 40 | return try { 41 | locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 42 | locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) 43 | } catch (e: Exception) { 44 | Log.e(TAG, "Error checking location provider status", e) 45 | false 46 | } 47 | } 48 | 49 | fun checkLocationEnabled(result: MethodChannel.Result) { 50 | result.success(isLocationEnabled()) 51 | } 52 | 53 | fun enableLocationServices(result: MethodChannel.Result) { 54 | val currentActivity = activity 55 | if (currentActivity == null) { 56 | result.error("NO_ACTIVITY", "Activity is not available to open location settings", null) 57 | return 58 | } 59 | try { 60 | val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) 61 | // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // Add only if necessary 62 | currentActivity.startActivity(intent) 63 | result.success(true) // Indicate settings were opened 64 | } catch (e: Exception) { 65 | Log.e(TAG, "Error opening location settings: ${e.message}", e) 66 | result.error("SETTINGS_ERROR", "Could not open location settings.", e.message) 67 | } 68 | } 69 | 70 | // --- Wi-Fi --- 71 | fun isWifiEnabled(): Boolean { 72 | return try { 73 | wifiManager.isWifiEnabled 74 | } catch (e: Exception) { 75 | Log.e(TAG, "Error checking Wi-Fi enabled state: ${e.message}", e) 76 | return false // Assume false if error occurs 77 | } 78 | } 79 | 80 | fun checkWifiEnabled(result: MethodChannel.Result) { 81 | result.success(isWifiEnabled()) 82 | } 83 | 84 | @SuppressLint("NewApi") // For Settings.Panel 85 | fun enableWifiServices(result: MethodChannel.Result) { 86 | val currentActivity = activity 87 | if (currentActivity == null) { 88 | result.error("NO_ACTIVITY", "Activity is not available to open Wi-Fi settings/panel", null) 89 | return 90 | } 91 | try { 92 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { 93 | val panelIntent = Intent(Settings.Panel.ACTION_WIFI) 94 | // panelIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // Add only if necessary 95 | currentActivity.startActivity(panelIntent) 96 | } else { 97 | // For older OS, go to general Wi-Fi settings 98 | val settingsIntent = Intent(Settings.ACTION_WIFI_SETTINGS) 99 | // settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // Add only if necessary 100 | currentActivity.startActivity(settingsIntent) 101 | } 102 | result.success(true) // Indicate settings/panel was opened 103 | } catch (e: Exception) { 104 | Log.e(TAG, "Error opening Wi-Fi settings/panel: ${e.message}", e) 105 | result.error("SETTINGS_ERROR", "Could not open Wi-Fi settings/panel.", e.message) 106 | } 107 | } 108 | 109 | // --- Bluetooth --- 110 | @SuppressLint("MissingPermission") // Permission check is done internally via helper 111 | fun isBluetoothEnabled(): Boolean { 112 | // Use the injected adapter instance 113 | val adapter = bluetoothAdapter ?: return false // Device doesn't support Bluetooth 114 | if (!permissionsManager.hasBluetoothConnectPermission()) { // Check needed permission (API 31+) 115 | Log.w(TAG, "Missing BLUETOOTH_CONNECT permission to check Bluetooth state (API 31+ requirement). Returning false.") 116 | return false 117 | } 118 | return try { 119 | adapter.isEnabled 120 | } catch (e: SecurityException) { // Catch specific SecurityException 121 | Log.e(TAG, "SecurityException checking Bluetooth state: ${e.message}", e) 122 | false 123 | } catch (e: Exception) { // Catch general exceptions 124 | Log.e(TAG, "Error checking Bluetooth enabled state: ${e.message}", e) 125 | false 126 | } 127 | } 128 | 129 | fun checkBluetoothEnabled(result: MethodChannel.Result) { 130 | result.success(isBluetoothEnabled()) // Calls the updated isBluetoothEnabled 131 | } 132 | 133 | @SuppressLint("MissingPermission") // Permission check is done internally for state, intent launch relies on system UI 134 | fun enableBluetoothServices(result: MethodChannel.Result) { 135 | val currentActivity = activity 136 | if (currentActivity == null) { 137 | result.error("NO_ACTIVITY", "Activity is not available to request Bluetooth enable", null) 138 | return 139 | } 140 | // Use the injected adapter instance 141 | val adapter = bluetoothAdapter 142 | if (adapter == null) { 143 | result.error("BLUETOOTH_UNAVAILABLE", "Device does not support Bluetooth.", null) 144 | return 145 | } 146 | 147 | // Check permission before checking state (as isEnabled requires it on S+) 148 | if (!permissionsManager.hasBluetoothConnectPermission()) { // Check needed permission (API 31+) 149 | result.error("PERMISSION_DENIED", "Missing BLUETOOTH_CONNECT permission (needed for check/enable on API 31+).", null) 150 | return 151 | } 152 | 153 | // Check if already enabled (now uses the potentially permitted isEnabled call) 154 | if (adapter.isEnabled) { 155 | Log.d(TAG, "Bluetooth is already enabled.") 156 | result.success(true) // Indicate it's already enabled 157 | return 158 | } 159 | 160 | // Create intent to request Bluetooth enable 161 | val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) 162 | try { 163 | // Launching ACTION_REQUEST_ENABLE implicitly uses BLUETOOTH_CONNECT on API 31+ 164 | // if the permission is declared in the manifest. No separate runtime check needed *here*. 165 | currentActivity.startActivity(enableBtIntent) 166 | // You usually don't need the result code from this intent; you check the adapter state again later if needed. 167 | result.success(true) // Indicate the request intent was successfully launched 168 | } catch (e: SecurityException) { 169 | Log.e(TAG, "SecurityException launching Bluetooth enable intent: ${e.message}", e) 170 | result.error("PERMISSION_ERROR", "Could not launch Bluetooth enable request due to permission issue (check manifest?).", e.message) 171 | } 172 | catch (e: Exception) { 173 | Log.e(TAG, "Error launching Bluetooth enable intent: ${e.message}", e) 174 | result.error("INTENT_ERROR", "Could not launch Bluetooth enable request.", e.message) 175 | } 176 | } 177 | } -------------------------------------------------------------------------------- /example/windows/runner/win32_window.cpp: -------------------------------------------------------------------------------- 1 | #include "win32_window.h" 2 | 3 | #include 4 | #include 5 | 6 | #include "resource.h" 7 | 8 | namespace { 9 | 10 | /// Window attribute that enables dark mode window decorations. 11 | /// 12 | /// Redefined in case the developer's machine has a Windows SDK older than 13 | /// version 10.0.22000.0. 14 | /// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute 15 | #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE 16 | #define DWMWA_USE_IMMERSIVE_DARK_MODE 20 17 | #endif 18 | 19 | constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; 20 | 21 | /// Registry key for app theme preference. 22 | /// 23 | /// A value of 0 indicates apps should use dark mode. A non-zero or missing 24 | /// value indicates apps should use light mode. 25 | constexpr const wchar_t kGetPreferredBrightnessRegKey[] = 26 | L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; 27 | constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; 28 | 29 | // The number of Win32Window objects that currently exist. 30 | static int g_active_window_count = 0; 31 | 32 | using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); 33 | 34 | // Scale helper to convert logical scaler values to physical using passed in 35 | // scale factor 36 | int Scale(int source, double scale_factor) { 37 | return static_cast(source * scale_factor); 38 | } 39 | 40 | // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. 41 | // This API is only needed for PerMonitor V1 awareness mode. 42 | void EnableFullDpiSupportIfAvailable(HWND hwnd) { 43 | HMODULE user32_module = LoadLibraryA("User32.dll"); 44 | if (!user32_module) { 45 | return; 46 | } 47 | auto enable_non_client_dpi_scaling = 48 | reinterpret_cast( 49 | GetProcAddress(user32_module, "EnableNonClientDpiScaling")); 50 | if (enable_non_client_dpi_scaling != nullptr) { 51 | enable_non_client_dpi_scaling(hwnd); 52 | } 53 | FreeLibrary(user32_module); 54 | } 55 | 56 | } // namespace 57 | 58 | // Manages the Win32Window's window class registration. 59 | class WindowClassRegistrar { 60 | public: 61 | ~WindowClassRegistrar() = default; 62 | 63 | // Returns the singleton registrar instance. 64 | static WindowClassRegistrar* GetInstance() { 65 | if (!instance_) { 66 | instance_ = new WindowClassRegistrar(); 67 | } 68 | return instance_; 69 | } 70 | 71 | // Returns the name of the window class, registering the class if it hasn't 72 | // previously been registered. 73 | const wchar_t* GetWindowClass(); 74 | 75 | // Unregisters the window class. Should only be called if there are no 76 | // instances of the window. 77 | void UnregisterWindowClass(); 78 | 79 | private: 80 | WindowClassRegistrar() = default; 81 | 82 | static WindowClassRegistrar* instance_; 83 | 84 | bool class_registered_ = false; 85 | }; 86 | 87 | WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; 88 | 89 | const wchar_t* WindowClassRegistrar::GetWindowClass() { 90 | if (!class_registered_) { 91 | WNDCLASS window_class{}; 92 | window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); 93 | window_class.lpszClassName = kWindowClassName; 94 | window_class.style = CS_HREDRAW | CS_VREDRAW; 95 | window_class.cbClsExtra = 0; 96 | window_class.cbWndExtra = 0; 97 | window_class.hInstance = GetModuleHandle(nullptr); 98 | window_class.hIcon = 99 | LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); 100 | window_class.hbrBackground = 0; 101 | window_class.lpszMenuName = nullptr; 102 | window_class.lpfnWndProc = Win32Window::WndProc; 103 | RegisterClass(&window_class); 104 | class_registered_ = true; 105 | } 106 | return kWindowClassName; 107 | } 108 | 109 | void WindowClassRegistrar::UnregisterWindowClass() { 110 | UnregisterClass(kWindowClassName, nullptr); 111 | class_registered_ = false; 112 | } 113 | 114 | Win32Window::Win32Window() { 115 | ++g_active_window_count; 116 | } 117 | 118 | Win32Window::~Win32Window() { 119 | --g_active_window_count; 120 | Destroy(); 121 | } 122 | 123 | bool Win32Window::Create(const std::wstring& title, 124 | const Point& origin, 125 | const Size& size) { 126 | Destroy(); 127 | 128 | const wchar_t* window_class = 129 | WindowClassRegistrar::GetInstance()->GetWindowClass(); 130 | 131 | const POINT target_point = {static_cast(origin.x), 132 | static_cast(origin.y)}; 133 | HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); 134 | UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); 135 | double scale_factor = dpi / 96.0; 136 | 137 | HWND window = CreateWindow( 138 | window_class, title.c_str(), WS_OVERLAPPEDWINDOW, 139 | Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), 140 | Scale(size.width, scale_factor), Scale(size.height, scale_factor), 141 | nullptr, nullptr, GetModuleHandle(nullptr), this); 142 | 143 | if (!window) { 144 | return false; 145 | } 146 | 147 | UpdateTheme(window); 148 | 149 | return OnCreate(); 150 | } 151 | 152 | bool Win32Window::Show() { 153 | return ShowWindow(window_handle_, SW_SHOWNORMAL); 154 | } 155 | 156 | // static 157 | LRESULT CALLBACK Win32Window::WndProc(HWND const window, 158 | UINT const message, 159 | WPARAM const wparam, 160 | LPARAM const lparam) noexcept { 161 | if (message == WM_NCCREATE) { 162 | auto window_struct = reinterpret_cast(lparam); 163 | SetWindowLongPtr(window, GWLP_USERDATA, 164 | reinterpret_cast(window_struct->lpCreateParams)); 165 | 166 | auto that = static_cast(window_struct->lpCreateParams); 167 | EnableFullDpiSupportIfAvailable(window); 168 | that->window_handle_ = window; 169 | } else if (Win32Window* that = GetThisFromHandle(window)) { 170 | return that->MessageHandler(window, message, wparam, lparam); 171 | } 172 | 173 | return DefWindowProc(window, message, wparam, lparam); 174 | } 175 | 176 | LRESULT 177 | Win32Window::MessageHandler(HWND hwnd, 178 | UINT const message, 179 | WPARAM const wparam, 180 | LPARAM const lparam) noexcept { 181 | switch (message) { 182 | case WM_DESTROY: 183 | window_handle_ = nullptr; 184 | Destroy(); 185 | if (quit_on_close_) { 186 | PostQuitMessage(0); 187 | } 188 | return 0; 189 | 190 | case WM_DPICHANGED: { 191 | auto newRectSize = reinterpret_cast(lparam); 192 | LONG newWidth = newRectSize->right - newRectSize->left; 193 | LONG newHeight = newRectSize->bottom - newRectSize->top; 194 | 195 | SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, 196 | newHeight, SWP_NOZORDER | SWP_NOACTIVATE); 197 | 198 | return 0; 199 | } 200 | case WM_SIZE: { 201 | RECT rect = GetClientArea(); 202 | if (child_content_ != nullptr) { 203 | // Size and position the child window. 204 | MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, 205 | rect.bottom - rect.top, TRUE); 206 | } 207 | return 0; 208 | } 209 | 210 | case WM_ACTIVATE: 211 | if (child_content_ != nullptr) { 212 | SetFocus(child_content_); 213 | } 214 | return 0; 215 | 216 | case WM_DWMCOLORIZATIONCOLORCHANGED: 217 | UpdateTheme(hwnd); 218 | return 0; 219 | } 220 | 221 | return DefWindowProc(window_handle_, message, wparam, lparam); 222 | } 223 | 224 | void Win32Window::Destroy() { 225 | OnDestroy(); 226 | 227 | if (window_handle_) { 228 | DestroyWindow(window_handle_); 229 | window_handle_ = nullptr; 230 | } 231 | if (g_active_window_count == 0) { 232 | WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); 233 | } 234 | } 235 | 236 | Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { 237 | return reinterpret_cast( 238 | GetWindowLongPtr(window, GWLP_USERDATA)); 239 | } 240 | 241 | void Win32Window::SetChildContent(HWND content) { 242 | child_content_ = content; 243 | SetParent(content, window_handle_); 244 | RECT frame = GetClientArea(); 245 | 246 | MoveWindow(content, frame.left, frame.top, frame.right - frame.left, 247 | frame.bottom - frame.top, true); 248 | 249 | SetFocus(child_content_); 250 | } 251 | 252 | RECT Win32Window::GetClientArea() { 253 | RECT frame; 254 | GetClientRect(window_handle_, &frame); 255 | return frame; 256 | } 257 | 258 | HWND Win32Window::GetHandle() { 259 | return window_handle_; 260 | } 261 | 262 | void Win32Window::SetQuitOnClose(bool quit_on_close) { 263 | quit_on_close_ = quit_on_close; 264 | } 265 | 266 | bool Win32Window::OnCreate() { 267 | // No-op; provided for subclasses. 268 | return true; 269 | } 270 | 271 | void Win32Window::OnDestroy() { 272 | // No-op; provided for subclasses. 273 | } 274 | 275 | void Win32Window::UpdateTheme(HWND const window) { 276 | DWORD light_mode; 277 | DWORD light_mode_size = sizeof(light_mode); 278 | LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, 279 | kGetPreferredBrightnessRegValue, 280 | RRF_RT_REG_DWORD, nullptr, &light_mode, 281 | &light_mode_size); 282 | 283 | if (result == ERROR_SUCCESS) { 284 | BOOL enable_dark_mode = light_mode == 0; 285 | DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, 286 | &enable_dark_mode, sizeof(enable_dark_mode)); 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /android/src/main/kotlin/com/ugo/studio/plugins/flutter_p2p_connection/DataUtils.kt: -------------------------------------------------------------------------------- 1 | package com.ugo.studio.plugins.flutter_p2p_connection 2 | 3 | import android.annotation.SuppressLint 4 | import android.net.ConnectivityManager 5 | import android.net.LinkProperties 6 | import android.net.Network 7 | import android.net.wifi.WifiConfiguration 8 | import android.net.wifi.WifiManager 9 | import android.util.Log 10 | import java.net.Inet4Address 11 | import java.net.InetAddress 12 | import java.net.NetworkInterface 13 | import java.util.Collections 14 | 15 | import com.ugo.studio.plugins.flutter_p2p_connection.Constants 16 | 17 | object DataUtils { 18 | private const val TAG = Constants.TAG // Use constant 19 | 20 | // Host's Hotspot Info Map 21 | fun createHotspotInfoMap(isActive: Boolean, config: WifiConfiguration?, ipAddress: String?, failureReason: Int? = null): Map { 22 | return mapOf( 23 | "isActive" to isActive, 24 | "ssid" to config?.SSID?.removePrefix("\"")?.removeSuffix("\""), 25 | "preSharedKey" to config?.preSharedKey?.removePrefix("\"")?.removeSuffix("\""), 26 | "hostIpAddress" to ipAddress, 27 | "failureReason" to failureReason 28 | ) 29 | } 30 | 31 | // Client's Connection State Map 32 | fun createClientStateMap(isActive: Boolean, gatewayIpAddress: String?, ipAddress: String?, connectedSsid: String?): Map { 33 | return mapOf( 34 | "isActive" to isActive, 35 | "hostGatewayIpAddress" to gatewayIpAddress, 36 | "hostIpAddress" to ipAddress, // Include host IP here too 37 | "hostSsid" to connectedSsid?.removePrefix("\"")?.removeSuffix("\"") // Ensure SSID is cleaned 38 | ) 39 | } 40 | 41 | // Helper to get client connection details (like gateway IP) using Network object 42 | fun getClientConnectionInfo(connectivityManager: ConnectivityManager, network: Network?): Map? { 43 | if (network == null) return null 44 | try { 45 | val linkProperties = connectivityManager.getLinkProperties(network) ?: return null 46 | val gatewayIp = getGatewayIpFromLinkProperties(linkProperties) 47 | // val clientIp = getClientIpFromLinkProperties(linkProperties) // Can add if needed 48 | return mapOf( 49 | "gatewayIpAddress" to gatewayIp 50 | // "clientIpAddress" to clientIp 51 | ) 52 | } catch (e: Exception) { 53 | Log.e(TAG, "Error getting client connection info: ${e.message}", e) 54 | return null 55 | } 56 | } 57 | 58 | // Helper to extract Gateway IP from LinkProperties 59 | fun getGatewayIpFromLinkProperties(linkProperties: LinkProperties?): String? { 60 | if (linkProperties == null) return null 61 | // Prioritize default route 62 | linkProperties.routes?.forEach { routeInfo -> 63 | if (routeInfo.isDefaultRoute && routeInfo.gateway != null) { 64 | val gwAddress = routeInfo.gateway?.hostAddress 65 | Log.d(TAG,"Found gateway IP (default route): $gwAddress") 66 | return gwAddress 67 | } 68 | } 69 | // Fallback: Look for the first IPv4 address on the interface that isn't the client's own IP 70 | // and assume the .1 address in that subnet is the gateway (common but not guaranteed) 71 | var clientIp: InetAddress? = null 72 | linkProperties.linkAddresses.forEach { linkAddress -> 73 | if (linkAddress.address is Inet4Address && !linkAddress.address.isLoopbackAddress) { 74 | clientIp = linkAddress.address // Find the client's likely IP first 75 | return@forEach // Found one, stop iterating link addresses for client IP 76 | } 77 | } 78 | 79 | if (clientIp != null) { 80 | val clientIpString = clientIp?.hostAddress 81 | Log.d(TAG, "Client's likely IP: $clientIpString") 82 | val parts = clientIpString?.split(".") 83 | if (parts?.size == 4) { 84 | val potentialGateway = "${parts[0]}.${parts[1]}.${parts[2]}.1" 85 | Log.w(TAG, "Could not find default route gateway. Guessing gateway: $potentialGateway") 86 | return potentialGateway // Fallback guess 87 | } 88 | } 89 | 90 | Log.w(TAG, "Could not determine gateway IP from LinkProperties.") 91 | return null 92 | } 93 | 94 | // Helper to get Gateway IP in Legacy mode 95 | @SuppressLint("Deprecated") 96 | fun getLegacyGatewayIpAddress(wifiManager: WifiManager): String? { 97 | try { 98 | val dhcpInfo = wifiManager.dhcpInfo ?: return null 99 | val gatewayInt = dhcpInfo.gateway 100 | if (gatewayInt == 0) return null 101 | val ipBytes = byteArrayOf( 102 | (gatewayInt and 0xff).toByte(), 103 | (gatewayInt shr 8 and 0xff).toByte(), 104 | (gatewayInt shr 16 and 0xff).toByte(), 105 | (gatewayInt shr 24 and 0xff).toByte() 106 | ) 107 | val gatewayAddress = InetAddress.getByAddress(ipBytes).hostAddress 108 | Log.d(TAG, "Legacy gateway IP: $gatewayAddress") 109 | return gatewayAddress 110 | } catch (e: Exception) { 111 | Log.e(TAG, "Error getting legacy gateway IP: ${e.message}", e) 112 | return null 113 | } 114 | } 115 | 116 | 117 | // Helper to find the Host's IP address when acting as hotspot or Client's view of it 118 | fun getHostIpAddress(): String? { 119 | var hotspotIp : String? = null 120 | var potentialIp : String? = null 121 | var fallbackIp : String? = null 122 | try { 123 | val interfaces: List = Collections.list(NetworkInterface.getNetworkInterfaces()) 124 | for (intf in interfaces) { 125 | if (!intf.isUp || intf.isLoopback || intf.isVirtual) continue // Skip down, loopback, virtual 126 | 127 | // Log all interfaces for debugging 128 | Log.d(TAG, "Checking interface: ${intf.name}, isUp: ${intf.isUp}") 129 | 130 | // Check for specific hotspot interface patterns 131 | val isP2pInterface = intf.name.contains("p2p-wlan", ignoreCase = true) 132 | val isApInterface = intf.name.contains("ap", ignoreCase = true) 133 | val isWlanInterface = intf.name.contains("wlan", ignoreCase = true) 134 | val isSwlanInterface = intf.name.contains("swlan", ignoreCase = true) // Samsung devices 135 | 136 | val addresses: List = Collections.list(intf.inetAddresses) 137 | for (addr in addresses) { 138 | if (!addr.isLoopbackAddress && addr is Inet4Address) { 139 | val ip = addr.hostAddress ?: continue 140 | Log.d(TAG, " Found IP: $ip on interface ${intf.name}") 141 | 142 | // Common hotspot IPs (192.168.43.1 for tethering, 192.168.49.1 for LOHS) 143 | if (ip == "192.168.43.1" || ip == "192.168.49.1") { 144 | Log.d(TAG, "Found common hotspot IP: $ip on interface ${intf.name}") 145 | return ip // Return immediately if common IP found 146 | } 147 | 148 | // Prioritize p2p-wlan interfaces for LocalOnlyHotspot 149 | if (isP2pInterface && ip.startsWith("192.168.")) { 150 | Log.d(TAG, "Found P2P hotspot IP: $ip on interface ${intf.name}") 151 | return ip // Return immediately for p2p interfaces 152 | } 153 | 154 | // Check for swlan (Samsung) or ap interfaces 155 | if ((isSwlanInterface || isApInterface) && ip.startsWith("192.168.") && hotspotIp == null) { 156 | Log.d(TAG, "Found hotspot IP on AP/SWLAN interface: $ip on interface ${intf.name}") 157 | hotspotIp = ip 158 | } 159 | 160 | // Store regular wlan IPs as potential only if they're in hotspot range 161 | if (isWlanInterface && ip.startsWith("192.168.") && 162 | (ip.startsWith("192.168.43.") || ip.startsWith("192.168.49.")) && potentialIp == null) { 163 | Log.d(TAG, "Found potential hotspot-range IP: $ip on interface ${intf.name}") 164 | potentialIp = ip 165 | } 166 | 167 | // Store any other 192.168.x.1 IP as last resort fallback 168 | if (ip.matches(Regex("192\\.168\\.\\d+\\.1")) && fallbackIp == null) { 169 | Log.d(TAG, "Found fallback gateway-like IP: $ip on interface ${intf.name}") 170 | fallbackIp = ip 171 | } 172 | } 173 | } 174 | } 175 | } catch (ex: Exception) { 176 | Log.e(TAG, "Exception while getting Host IP address: $ex") 177 | } 178 | 179 | // Return in order of preference 180 | if(hotspotIp != null) { 181 | Log.d(TAG, "Using hotspot IP: $hotspotIp") 182 | return hotspotIp 183 | } 184 | 185 | if(potentialIp != null) { 186 | Log.d(TAG, "Using potential hotspot-range IP: $potentialIp") 187 | return potentialIp 188 | } 189 | 190 | if(fallbackIp != null) { 191 | Log.d(TAG, "Using fallback gateway IP: $fallbackIp") 192 | return fallbackIp 193 | } 194 | 195 | Log.w(TAG, "Could not determine host IP address.") 196 | return null 197 | } 198 | } --------------------------------------------------------------------------------