From 767909a53d22a61ec21eab3b58c9bb4cb58c00d0 Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Thu, 1 Oct 2020 07:36:41 +0200 Subject: [PATCH 1/2] Connectivity Plus example: add Linux runner --- packages/connectivity_plus/example/.gitignore | 46 ++++++++ .../example/linux/.gitignore | 1 + .../example/linux/CMakeLists.txt | 106 ++++++++++++++++++ .../example/linux/flutter/CMakeLists.txt | 88 +++++++++++++++ .../flutter/generated_plugin_registrant.cc | 9 ++ .../flutter/generated_plugin_registrant.h | 13 +++ .../linux/flutter/generated_plugins.cmake | 15 +++ .../connectivity_plus/example/linux/main.cc | 10 ++ .../example/linux/my_application.cc | 46 ++++++++ .../example/linux/my_application.h | 18 +++ 10 files changed, 352 insertions(+) create mode 100644 packages/connectivity_plus/example/.gitignore create mode 100644 packages/connectivity_plus/example/linux/.gitignore create mode 100644 packages/connectivity_plus/example/linux/CMakeLists.txt create mode 100644 packages/connectivity_plus/example/linux/flutter/CMakeLists.txt create mode 100644 packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.cc create mode 100644 packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.h create mode 100644 packages/connectivity_plus/example/linux/flutter/generated_plugins.cmake create mode 100644 packages/connectivity_plus/example/linux/main.cc create mode 100644 packages/connectivity_plus/example/linux/my_application.cc create mode 100644 packages/connectivity_plus/example/linux/my_application.h diff --git a/packages/connectivity_plus/example/.gitignore b/packages/connectivity_plus/example/.gitignore new file mode 100644 index 0000000000..0fa6b675c0 --- /dev/null +++ b/packages/connectivity_plus/example/.gitignore @@ -0,0 +1,46 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Web related +lib/generated_plugin_registrant.dart + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/connectivity_plus/example/linux/.gitignore b/packages/connectivity_plus/example/linux/.gitignore new file mode 100644 index 0000000000..d3896c9844 --- /dev/null +++ b/packages/connectivity_plus/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/connectivity_plus/example/linux/CMakeLists.txt b/packages/connectivity_plus/example/linux/CMakeLists.txt new file mode 100644 index 0000000000..279007eb35 --- /dev/null +++ b/packages/connectivity_plus/example/linux/CMakeLists.txt @@ -0,0 +1,106 @@ +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +set(BINARY_NAME "example") +set(APPLICATION_ID "io.flutter.plugins.example") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Application build +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) +apply_standard_settings(${BINARY_NAME}) +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) +add_dependencies(${BINARY_NAME} flutter_assemble) +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/connectivity_plus/example/linux/flutter/CMakeLists.txt b/packages/connectivity_plus/example/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000000..4f48a7ced5 --- /dev/null +++ b/packages/connectivity_plus/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) +pkg_check_modules(BLKID REQUIRED IMPORTED_TARGET blkid) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO + PkgConfig::BLKID +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + linux-x64 ${CMAKE_BUILD_TYPE} +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.cc b/packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000000..d38195aa04 --- /dev/null +++ b/packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,9 @@ +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.h b/packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000000..9bf7478940 --- /dev/null +++ b/packages/connectivity_plus/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,13 @@ +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/connectivity_plus/example/linux/flutter/generated_plugins.cmake b/packages/connectivity_plus/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000000..51436ae8c9 --- /dev/null +++ b/packages/connectivity_plus/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,15 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) diff --git a/packages/connectivity_plus/example/linux/main.cc b/packages/connectivity_plus/example/linux/main.cc new file mode 100644 index 0000000000..058e6178fe --- /dev/null +++ b/packages/connectivity_plus/example/linux/main.cc @@ -0,0 +1,10 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + // Only X11 is currently supported. + // Wayland support is being developed: https://github.com/flutter/flutter/issues/57932. + gdk_set_allowed_backends("x11"); + + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/connectivity_plus/example/linux/my_application.cc b/packages/connectivity_plus/example/linux/my_application.cc new file mode 100644 index 0000000000..f28ca30940 --- /dev/null +++ b/packages/connectivity_plus/example/linux/my_application.cc @@ -0,0 +1,46 @@ +#include "my_application.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + nullptr)); +} diff --git a/packages/connectivity_plus/example/linux/my_application.h b/packages/connectivity_plus/example/linux/my_application.h new file mode 100644 index 0000000000..72271d5e41 --- /dev/null +++ b/packages/connectivity_plus/example/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ From d82bbec57f843f8769dd15bb0a53176527e0c608 Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Thu, 8 Oct 2020 17:44:24 +0200 Subject: [PATCH 2/2] Add Linux support to Connectivity Plus --- .../lib/connectivity_plus.dart | 24 +++- packages/connectivity_plus/pubspec.yaml | 3 + packages/connectivity_plus_linux/.gitignore | 47 +++++++ packages/connectivity_plus_linux/.metadata | 10 ++ packages/connectivity_plus_linux/CHANGELOG.md | 3 + packages/connectivity_plus_linux/LICENSE | 27 ++++ packages/connectivity_plus_linux/README.md | 12 ++ .../analysis_options.yaml | 1 + .../lib/connectivity_plus_linux.dart | 4 + .../lib/src/connectivity.dart | 125 ++++++++++++++++++ .../lib/src/network_manager.dart | 120 +++++++++++++++++ packages/connectivity_plus_linux/pubspec.yaml | 29 ++++ .../test/connectivity_plus_linux_test.dart | 47 +++++++ 13 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 packages/connectivity_plus_linux/.gitignore create mode 100644 packages/connectivity_plus_linux/.metadata create mode 100644 packages/connectivity_plus_linux/CHANGELOG.md create mode 100644 packages/connectivity_plus_linux/LICENSE create mode 100644 packages/connectivity_plus_linux/README.md create mode 100644 packages/connectivity_plus_linux/analysis_options.yaml create mode 100644 packages/connectivity_plus_linux/lib/connectivity_plus_linux.dart create mode 100644 packages/connectivity_plus_linux/lib/src/connectivity.dart create mode 100644 packages/connectivity_plus_linux/lib/src/network_manager.dart create mode 100644 packages/connectivity_plus_linux/pubspec.yaml create mode 100644 packages/connectivity_plus_linux/test/connectivity_plus_linux_test.dart diff --git a/packages/connectivity_plus/lib/connectivity_plus.dart b/packages/connectivity_plus/lib/connectivity_plus.dart index 8ef6c23a61..3bab8c0afd 100644 --- a/packages/connectivity_plus/lib/connectivity_plus.dart +++ b/packages/connectivity_plus/lib/connectivity_plus.dart @@ -3,9 +3,13 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:io' show Platform; import 'package:flutter/services.dart'; +import 'package:flutter/foundation.dart' show kIsWeb; import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart'; +import 'package:connectivity_plus_platform_interface/src/method_channel_connectivity.dart'; +import 'package:connectivity_plus_linux/connectivity_plus_linux.dart'; // Export enums from the platform_interface so plugin users can use them directly. export 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart' @@ -30,7 +34,25 @@ class Connectivity { static Connectivity _singleton; - static ConnectivityPlatform get _platform => ConnectivityPlatform.instance; + static bool _manualDartRegistrationNeeded = true; + + // This is to manually endorse Dart implementations until automatic + // registration of Dart plugins is implemented. For details see + // https://github.com/flutter/flutter/issues/52267. + static ConnectivityPlatform get _platform { + if (_manualDartRegistrationNeeded) { + // Only do the initial registration if it hasn't already been overridden + // with a non-default instance. + if (!kIsWeb && + ConnectivityPlatform.instance is MethodChannelConnectivity) { + if (Platform.isLinux) { + ConnectivityPlatform.instance = ConnectivityLinux(); + } + } + _manualDartRegistrationNeeded = false; + } + return ConnectivityPlatform.instance; + } /// Fires whenever the connectivity state changes. Stream get onConnectivityChanged { diff --git a/packages/connectivity_plus/pubspec.yaml b/packages/connectivity_plus/pubspec.yaml index f68db96246..d12a0955da 100644 --- a/packages/connectivity_plus/pubspec.yaml +++ b/packages/connectivity_plus/pubspec.yaml @@ -12,6 +12,8 @@ flutter: pluginClass: ConnectivityPlugin ios: pluginClass: FLTConnectivityPlusPlugin + linux: + default_package: connectivity_plus_linux macos: default_package: connectivity_plus_macos web: @@ -22,6 +24,7 @@ dependencies: sdk: flutter meta: ^1.0.5 connectivity_plus_platform_interface: ^0.3.0 + connectivity_plus_linux: ^0.1.0 connectivity_plus_macos: ^0.3.0 connectivity_plus_web: ^0.5.0 diff --git a/packages/connectivity_plus_linux/.gitignore b/packages/connectivity_plus_linux/.gitignore new file mode 100644 index 0000000000..88ce490e47 --- /dev/null +++ b/packages/connectivity_plus_linux/.gitignore @@ -0,0 +1,47 @@ +.DS_Store +.atom/ +.idea/ +.vscode/ + +.packages +.pub/ +.dart_tool/ +pubspec.lock +flutter_export_environment.sh + +examples/all_plugins/pubspec.yaml + +Podfile +Podfile.lock +Pods/ +.symlinks/ +**/Flutter/App.framework/ +**/Flutter/ephemeral/ +**/Flutter/Flutter.framework/ +**/Flutter/Generated.xcconfig +**/Flutter/flutter_assets/ + +ServiceDefinitions.json +xcuserdata/ +**/DerivedData/ + +local.properties +keystore.properties +.gradle/ +gradlew +gradlew.bat +gradle-wrapper.jar +.flutter-plugins-dependencies +*.iml + +generated_plugin_registrant.dart +GeneratedPluginRegistrant.h +GeneratedPluginRegistrant.m +GeneratedPluginRegistrant.java +GeneratedPluginRegistrant.swift +build/ +.flutter-plugins + +.project +.classpath +.settings diff --git a/packages/connectivity_plus_linux/.metadata b/packages/connectivity_plus_linux/.metadata new file mode 100644 index 0000000000..6b9d686e29 --- /dev/null +++ b/packages/connectivity_plus_linux/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 34541c30735bc1086335e13d69a7e0acdc0538c5 + channel: master + +project_type: package diff --git a/packages/connectivity_plus_linux/CHANGELOG.md b/packages/connectivity_plus_linux/CHANGELOG.md new file mode 100644 index 0000000000..f7950bb58c --- /dev/null +++ b/packages/connectivity_plus_linux/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.1.0 + +* Initial release for Linux. diff --git a/packages/connectivity_plus_linux/LICENSE b/packages/connectivity_plus_linux/LICENSE new file mode 100644 index 0000000000..0c91662b3f --- /dev/null +++ b/packages/connectivity_plus_linux/LICENSE @@ -0,0 +1,27 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/connectivity_plus_linux/README.md b/packages/connectivity_plus_linux/README.md new file mode 100644 index 0000000000..bdedb3d90d --- /dev/null +++ b/packages/connectivity_plus_linux/README.md @@ -0,0 +1,12 @@ +# Connectivity Plus Linux + +[![Flutter Community: connectivity_plus_linux](https://fluttercommunity.dev/_github/header/connectivity_plus_linux)](https://github.com/fluttercommunity/community) + +[![pub package](https://img.shields.io/pub/v/connectivity_plus_linux.svg)](https://pub.dev/packages/connectivity_plus_linux) + +The Linux implementation of [`connectivity_plus`](https://pub.dev/packages/connectivity_plus). + +## Usage + +This package is already included as part of the `connectivity_plus` package dependency, and will +be included when using `connectivity_plus` as normal. diff --git a/packages/connectivity_plus_linux/analysis_options.yaml b/packages/connectivity_plus_linux/analysis_options.yaml new file mode 100644 index 0000000000..486705dbf2 --- /dev/null +++ b/packages/connectivity_plus_linux/analysis_options.yaml @@ -0,0 +1 @@ +include: package:pedantic/analysis_options.1.9.0.yaml diff --git a/packages/connectivity_plus_linux/lib/connectivity_plus_linux.dart b/packages/connectivity_plus_linux/lib/connectivity_plus_linux.dart new file mode 100644 index 0000000000..8d035e5da7 --- /dev/null +++ b/packages/connectivity_plus_linux/lib/connectivity_plus_linux.dart @@ -0,0 +1,4 @@ +/// The Linux implementation of `connectivity_plus`. +library connectivity_plus_linux; + +export 'src/connectivity.dart'; diff --git a/packages/connectivity_plus_linux/lib/src/connectivity.dart b/packages/connectivity_plus_linux/lib/src/connectivity.dart new file mode 100644 index 0000000000..cddbd7f158 --- /dev/null +++ b/packages/connectivity_plus_linux/lib/src/connectivity.dart @@ -0,0 +1,125 @@ +import 'dart:async'; + +import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart'; +import 'package:meta/meta.dart'; + +import 'network_manager.dart'; + +typedef _DeviceGetter = Future Function(NMDevice device); +typedef _ConnectionGetter = Future Function(NMConnection connection); + +@visibleForTesting +typedef NetworkManagerFactory = NetworkManager Function(); + +/// The Linux implementation of ConnectivityPlatform. +class ConnectivityLinux extends ConnectivityPlatform { + /// Checks the connection status of the device. + @override + Future checkConnectivity() { + return _getConnectivity(_ref()).whenComplete(_deref); + } + + /// Obtains the wifi name (SSID) of the connected network + @override + Future getWifiName() { + return _getConnectionValue((connection) => connection.getId()); + } + + /// Obtains the IP address of the connected wifi network + @override + Future getWifiIP() { + return _getDeviceValue((device) => device.getIp4()); + } + + /// Obtains the wifi BSSID of the connected network. + @override + Future getWifiBSSID() { + return _getDeviceValue((device) { + return device + .asWirelessDevice() + .then((wireless) => wireless?.getHwAddress()); + }); + } + + Future _getDeviceValue(_DeviceGetter getter) { + return _getConnectionValue((connection) { + return connection.createDevice().then((device) { + return device != null ? getter(device) : null; + }); + }); + } + + Future _getConnectionValue(_ConnectionGetter getter) { + return _ref().createConnection().then((connection) { + return connection != null ? getter(connection) : null; + }).whenComplete(_deref); + } + + int _refCount = 0; + NetworkManager _manager; + StreamController _controller; + + /// Returns a Stream of ConnectivityResults changes. + @override + Stream get onConnectivityChanged { + _controller ??= StreamController.broadcast( + onListen: _startListenConnectivity, + onCancel: _deref, + ); + return _controller.stream; + } + + Future _getConnectivity(NetworkManager manager) { + return manager.getType().then((value) => value.toConnectivityResult()); + } + + void _startListenConnectivity() { + final manager = _ref(); + manager.getType().then((type) => _addConnectivity(type)); + manager.subscribeTypeChanged().listen((type) { + _addConnectivity(type); + }); + } + + void _addConnectivity(String type) { + _controller.add(type.toConnectivityResult()); + } + + NetworkManager _ref() { + _manager ??= createManager(); + ++_refCount; + return _manager; + } + + void _deref() { + // schedules an asynchronous disposal when the last reference is removed + if (--_refCount == 0) { + scheduleMicrotask(() { + if (_refCount == 0) { + _manager.dispose(); + _manager = null; + } + }); + } + } + + @visibleForTesting + NetworkManagerFactory createManager = () => NetworkManager.system(); +} + +extension _NMConnectivityType on String { + ConnectivityResult toConnectivityResult() { + if (isEmpty) { + return ConnectivityResult.none; + } + if (contains('wireless')) { + return ConnectivityResult.wifi; + } + // ### TODO: ethernet + //if (contains('ethernet')) { + // return ConnectivityResult.ethernet; + //} + // gsm, cdma, bluetooth, ... + return ConnectivityResult.mobile; + } +} diff --git a/packages/connectivity_plus_linux/lib/src/network_manager.dart b/packages/connectivity_plus_linux/lib/src/network_manager.dart new file mode 100644 index 0000000000..a130ecaf2e --- /dev/null +++ b/packages/connectivity_plus_linux/lib/src/network_manager.dart @@ -0,0 +1,120 @@ +import 'dart:async'; + +import 'package:dbus/dbus.dart'; + +const _kNetworkManager = 'org.freedesktop.NetworkManager'; +const _kActiveConnection = _kNetworkManager + '.Connection.Active'; +const _kDevice = _kNetworkManager + '.Device'; +const _kWireless = _kDevice + '.Wireless'; + +const _kPath = '/org/freedesktop/NetworkManager'; +const _kType = 'PrimaryConnectionType'; + +class NetworkManager extends DBusRemoteObject { + NetworkManager(DBusClient client) + : super(client, _kNetworkManager, DBusObjectPath(_kPath)); + + factory NetworkManager.system() => NetworkManager(DBusClient.system()); + void dispose() => client?.close(); + + Future getPath() => _getString('PrimaryConnection', fallback: '/'); + Future getType() => _getString(_kType); + + Future _getString(String path, {String fallback = ''}) { + return getProperty(_kNetworkManager, path) + .then((value) => (value as DBusString).value) + .catchError((error) => print(error)) + .then((value) => value ?? fallback); + } + + Stream subscribeTypeChanged() { + return subscribePropertiesChanged() + .where((event) => event.changedProperties.containsKey(_kType)) + .map((event) => (event.changedProperties[_kType] as DBusString).value); + } + + Future createConnection() { + return getPath().then((path) => NMConnection.fromPath(client, path)); + } +} + +class NMConnection extends DBusRemoteObject { + NMConnection(DBusClient client, {DBusObjectPath path}) + : super(client, _kNetworkManager, path); + + factory NMConnection.fromPath(DBusClient client, String path) { + if (path == '/') return null; + return NMConnection(client, path: DBusObjectPath(path)); + } + + Future getId() { + return getProperty(_kActiveConnection, 'Id') + .then((value) => (value as DBusString).value) + .catchError((error) => print(error)) + .then((value) => value ?? ''); + } + + Future> getDevices() { + return getProperty(_kActiveConnection, 'Devices') + .then((value) => (value as DBusArray) + .children + .map((child) => (child as DBusObjectPath).value) + .toList()) + .catchError((error) => print(error)) + .then((value) => value ?? []); + } + + Future createDevice() { + return getDevices().then((devices) { + if (devices.isEmpty) return null; + return NMDevice.fromPath(client, devices.first); + }); + } +} + +enum NMDeviceType { unknown, ethernet, wifi } + +extension NMDeviceInt on int { + int byteAt(int i) => (this >> (i * 8)) & 0xff; + String toIp4() => '${byteAt(0)}.${byteAt(1)}.${byteAt(2)}.${byteAt(3)}'; + NMDeviceType toType() => NMDeviceType.values[this]; +} + +class NMDevice extends DBusRemoteObject { + NMDevice(DBusClient client, {DBusObjectPath path}) + : super(client, _kNetworkManager, path); + + factory NMDevice.fromPath(DBusClient client, String path) { + return NMDevice(client, path: DBusObjectPath(path)); + } + + Future getIp4() { + return getProperty(_kDevice, 'Ip4Address') + .then((value) => (value as DBusUint32).value.toIp4()) + .catchError((error) => print(error)); + } + + Future getType() { + return getProperty(_kDevice, 'DeviceType') + .then((value) => (value as DBusUint32).value.toType()) + .catchError((error) => print(error)); + } + + Future asWirelessDevice() { + return getType().then((type) { + if (type != NMDeviceType.wifi) return null; + return NMWirelessDevice(client, path: path); + }); + } +} + +class NMWirelessDevice extends DBusRemoteObject { + NMWirelessDevice(DBusClient client, {DBusObjectPath path}) + : super(client, _kNetworkManager, path); + + Future getHwAddress() { + return getProperty(_kWireless, 'HwAddress') + .then((value) => (value as DBusString).value) + .catchError((error) => print(error)); + } +} diff --git a/packages/connectivity_plus_linux/pubspec.yaml b/packages/connectivity_plus_linux/pubspec.yaml new file mode 100644 index 0000000000..4f399d3eca --- /dev/null +++ b/packages/connectivity_plus_linux/pubspec.yaml @@ -0,0 +1,29 @@ +name: connectivity_plus_linux +description: Linux implementation of the connectivity_plus plugin +homepage: https://plus.fluttercommunity.dev/ +repository: https://github.com/fluttercommunity/plus_plugins/tree/main/packages/ +version: 0.1.0 + +environment: + sdk: ">=2.7.0 <3.0.0" + flutter: ">=1.17.0 <2.0.0" + +dependencies: + flutter: + sdk: flutter + connectivity_plus_platform_interface: ^0.2.0 + dbus: ^0.1.0 + meta: ^1.2.3 + +dev_dependencies: + flutter_test: + sdk: flutter + mockito: ^4.1.2 + pedantic: ^1.9.2 + +flutter: + plugin: + platforms: + linux: + dartPluginClass: ConnectivityLinux + pluginClass: none diff --git a/packages/connectivity_plus_linux/test/connectivity_plus_linux_test.dart b/packages/connectivity_plus_linux/test/connectivity_plus_linux_test.dart new file mode 100644 index 0000000000..5f60e8c6f0 --- /dev/null +++ b/packages/connectivity_plus_linux/test/connectivity_plus_linux_test.dart @@ -0,0 +1,47 @@ +import 'package:connectivity_plus_linux/src/connectivity.dart'; +import 'package:connectivity_plus_linux/src/network_manager.dart'; +import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; + +class MockNetworkManager extends Mock implements NetworkManager {} + +void main() { + test('wireless', () async { + final linux = ConnectivityLinux(); + linux.createManager = () { + final manager = MockNetworkManager(); + when(manager.getType()).thenAnswer((_) => Future.value('wireless')); + return manager; + }; + expect( + linux.checkConnectivity(), completion(equals(ConnectivityResult.wifi))); + }); + + test('no connectivity', () async { + final linux = ConnectivityLinux(); + linux.createManager = () { + final manager = MockNetworkManager(); + when(manager.getType()).thenAnswer((_) => Future.value('')); + return manager; + }; + expect( + linux.checkConnectivity(), completion(equals(ConnectivityResult.none))); + }); + + test('connectivity changes', () { + final linux = ConnectivityLinux(); + linux.createManager = () { + final manager = MockNetworkManager(); + when(manager.getType()).thenAnswer((_) { + return Future.value('wireless'); + }); + when(manager.subscribeTypeChanged()).thenAnswer((_) { + return Stream.value(''); + }); + return manager; + }; + expect(linux.onConnectivityChanged, + emitsInOrder([ConnectivityResult.wifi, ConnectivityResult.none])); + }); +}